From 82f2b1f66004450f9371345313038a70945c75cc Mon Sep 17 00:00:00 2001 From: Gregor Klevze Date: Wed, 6 May 2026 18:55:40 +0200 Subject: [PATCH] Add tests for featured thumbnail generation; apply Pint formatting and related edits --- .env.example | 3 +- .../Academy/AcademyLessonController.php | 28 +- .../Academy/AcademyPromptController.php | 2 +- .../Api/LatestCommentsApiController.php | 14 +- .../Auth/RegisteredUserController.php | 102 +- .../Community/LatestCommentsController.php | 14 +- app/Http/Controllers/News/NewsController.php | 37 +- .../Settings/AcademyAdminController.php | 554 +- .../Studio/StudioNewsMediaApiController.php | 95 +- .../Academy/UpsertAcademyLessonRequest.php | 82 +- .../UpsertAcademyPromptTemplateRequest.php | 1 + app/Models/AcademyLesson.php | 29 +- app/Services/Academy/AcademyAccessService.php | 122 +- app/Services/ArtworkService.php | 22 +- .../News/NewsArticleCommentService.php | 8 + app/Services/News/NewsService.php | 154 +- .../Captcha/TurnstileCaptchaProvider.php | 32 +- app/Services/Security/TurnstileVerifier.php | 19 +- .../Uploads/UploadDerivativesService.php | 24 +- bootstrap/app.php | 1 + .../ssr/assets/ArtworkShareModal-BnRQhiXq.js | 301 - .../ssr/assets/vendor-motion-Dg7DlHqj.js | 8068 ----- .../ssr/assets/vendor-realtime-BGlcW0gB.js | 9704 ------ .../ssr/assets/vendor-tiptap-BUUKoc3C.js | 27179 ---------------- bootstrap/ssr/ssr-manifest.json | 1067 +- bootstrap/ssr/ssr.js | 8110 +++-- config/horizon.php | 5 +- config/registration.php | 2 +- config/services.php | 2 + database/seeders/AcademyDemoSeeder.php | 34 +- package-lock.json | 274 +- package.json | 5 + resources/css/app.css | 882 +- resources/js/Layouts/AdminLayout.jsx | 28 +- resources/js/Pages/Academy/Show.jsx | 708 +- resources/js/Pages/Admin/Academy/CrudForm.jsx | 457 +- resources/js/components/Feed/PostCard.jsx | 6 +- resources/js/components/Feed/PostComposer.jsx | 6 +- .../js/components/forum/RichTextEditor.jsx | 1190 +- resources/js/nova.js | 2 +- resources/js/ssr.jsx | 13 +- resources/views/auth/register.blade.php | 31 +- resources/views/layouts/nova.blade.php | 23 +- .../views/layouts/nova/toolbar.blade.php | 2 +- resources/views/news/_article_card.blade.php | 2 +- resources/views/news/_sidebar.blade.php | 11 +- resources/views/news/archive.blade.php | 16 + resources/views/news/author.blade.php | 16 + resources/views/news/category.blade.php | 41 +- resources/views/news/index.blade.php | 49 +- resources/views/news/layout.blade.php | 4 + resources/views/news/show.blade.php | 59 +- resources/views/news/tag.blade.php | 16 + .../web/home/sections/artwork-card.blade.php | 139 +- .../home/sections/artwork-section.blade.php | 4 +- routes/api.php | 31 +- routes/web.php | 32 +- tests/Feature/Academy/AcademyFeatureTest.php | 101 +- tests/Feature/Admin/AcademyAdminTest.php | 233 +- ...teFeaturedArtworkThumbnailsCommandTest.php | 165 + .../Feature/Auth/RegistrationAntiSpamTest.php | 82 +- tests/Feature/Auth/RegistrationTest.php | 1 + tests/Feature/HomepageFeaturedMedalsTest.php | 83 +- tests/Feature/News/NewsPublicPagesTest.php | 216 + tests/Feature/Studio/StudioNewsPagesTest.php | 127 + 65 files changed, 11325 insertions(+), 49545 deletions(-) delete mode 100644 bootstrap/ssr/assets/ArtworkShareModal-BnRQhiXq.js delete mode 100644 bootstrap/ssr/assets/vendor-motion-Dg7DlHqj.js delete mode 100644 bootstrap/ssr/assets/vendor-realtime-BGlcW0gB.js delete mode 100644 bootstrap/ssr/assets/vendor-tiptap-BUUKoc3C.js create mode 100644 tests/Feature/Artworks/GenerateFeaturedArtworkThumbnailsCommandTest.php diff --git a/.env.example b/.env.example index cd120f1a..60cbfdac 100644 --- a/.env.example +++ b/.env.example @@ -298,7 +298,7 @@ REGISTRATION_IP_PER_DAY_LIMIT=20 REGISTRATION_EMAIL_PER_MINUTE_LIMIT=6 REGISTRATION_EMAIL_COOLDOWN_MINUTES=30 REGISTRATION_VERIFY_TOKEN_TTL_HOURS=24 -REGISTRATION_ENABLE_TURNSTILE=true +TURNSTILE_ENABLED=false REGISTRATION_DISPOSABLE_DOMAINS_ENABLED=true REGISTRATION_TURNSTILE_SUSPICIOUS_ATTEMPTS=2 REGISTRATION_TURNSTILE_ATTEMPT_WINDOW_MINUTES=30 @@ -306,6 +306,7 @@ REGISTRATION_EMAIL_GLOBAL_SEND_PER_MINUTE=30 REGISTRATION_MONTHLY_EMAIL_LIMIT=10000 TURNSTILE_SITE_KEY= TURNSTILE_SECRET_KEY= +TURNSTILE_FAIL_OPEN=false TURNSTILE_VERIFY_URL=https://challenges.cloudflare.com/turnstile/v0/siteverify TURNSTILE_TIMEOUT=5 diff --git a/app/Http/Controllers/Academy/AcademyLessonController.php b/app/Http/Controllers/Academy/AcademyLessonController.php index 3e8ae4fa..a2482741 100644 --- a/app/Http/Controllers/Academy/AcademyLessonController.php +++ b/app/Http/Controllers/Academy/AcademyLessonController.php @@ -19,8 +19,7 @@ final class AcademyLessonController extends Controller public function __construct( private readonly AcademyAccessService $access, private readonly AcademyCacheService $cache, - ) { - } + ) {} public function index(Request $request): Response { @@ -40,8 +39,8 @@ final class AcademyLessonController extends Controller if (filled($filters['q'] ?? null)) { $query->where(function ($builder) use ($filters): void { - $builder->where('title', 'like', '%' . $filters['q'] . '%') - ->orWhere('excerpt', 'like', '%' . $filters['q'] . '%'); + $builder->where('title', 'like', '%'.$filters['q'].'%') + ->orWhere('excerpt', 'like', '%'.$filters['q'].'%'); }); } @@ -81,17 +80,31 @@ final class AcademyLessonController extends Controller abort_unless((bool) config('academy.enabled', true), 404); $lesson = AcademyLesson::query() - ->with('category') + ->with(['category', 'activeBlocks.activeComparisonResults']) ->active() ->published() ->where('slug', $slug) ->firstOrFail(); $payload = $this->access->lessonPayload($lesson, $request->user(), true); + $relatedLessons = $lesson->category_id !== null + ? AcademyLesson::query() + ->with('category') + ->active() + ->published() + ->where('category_id', $lesson->category_id) + ->where('id', '!=', $lesson->id) + ->orderByDesc('published_at') + ->limit(6) + ->get() + ->map(fn (AcademyLesson $relatedLesson): array => $this->access->lessonPayload($relatedLesson, $request->user())) + ->values() + ->all() + : []; $canonical = route('academy.lessons.show', ['slug' => $lesson->slug]); $description = Str::limit(trim((string) ($lesson->seo_description ?? $lesson->excerpt ?? 'Skinbase Academy lesson.')), 160, '...'); $seo = app(SeoFactory::class)->collectionPage( - (string) ($lesson->seo_title ?? ($lesson->title . ' — Skinbase Academy')), + (string) ($lesson->seo_title ?? ($lesson->title.' — Skinbase Academy')), $description, $canonical, $lesson->cover_image, @@ -100,10 +113,11 @@ final class AcademyLessonController extends Controller return Inertia::render('Academy/Show', [ 'pageType' => 'lesson', 'item' => $payload, + 'relatedLessons' => $relatedLessons, 'seo' => $seo, 'pricingUrl' => route('academy.pricing'), 'completeUrl' => $request->user() ? route('academy.lessons.complete', ['lesson' => $lesson->id]) : null, 'completed' => $request->user()?->academyLessonProgress()->where('lesson_id', $lesson->id)->whereNotNull('completed_at')->exists() ?? false, ])->rootView('collections'); } -} \ No newline at end of file +} diff --git a/app/Http/Controllers/Academy/AcademyPromptController.php b/app/Http/Controllers/Academy/AcademyPromptController.php index 7bec97d7..f67b9a5f 100644 --- a/app/Http/Controllers/Academy/AcademyPromptController.php +++ b/app/Http/Controllers/Academy/AcademyPromptController.php @@ -100,7 +100,7 @@ final class AcademyPromptController extends Controller (string) ($prompt->seo_title ?? ($prompt->title . ' — Skinbase Academy')), $description, $canonical, - $prompt->preview_image, + $payload['preview_image'] ?? null, )->toArray(); return Inertia::render('Academy/Show', [ diff --git a/app/Http/Controllers/Api/LatestCommentsApiController.php b/app/Http/Controllers/Api/LatestCommentsApiController.php index 86a26d65..dcc7656f 100644 --- a/app/Http/Controllers/Api/LatestCommentsApiController.php +++ b/app/Http/Controllers/Api/LatestCommentsApiController.php @@ -30,7 +30,19 @@ class LatestCommentsApiController extends Controller return response()->json(['error' => 'Unauthenticated'], 401); } - $query = ArtworkComment::with(['user', 'user.profile', 'artwork']) + $query = ArtworkComment::query() + ->select([ + 'artwork_comments.id', + 'artwork_comments.artwork_id', + 'artwork_comments.user_id', + 'artwork_comments.content', + 'artwork_comments.created_at', + ]) + ->with([ + 'user:id,username,name', + 'user.profile:user_id,avatar_hash', + 'artwork:id,title,slug,hash,file_path,file_name', + ]) ->whereHas('artwork', function ($q) { $q->public()->published()->whereNull('deleted_at'); }) diff --git a/app/Http/Controllers/Auth/RegisteredUserController.php b/app/Http/Controllers/Auth/RegisteredUserController.php index 7bc7ee1f..5e76d4b1 100644 --- a/app/Http/Controllers/Auth/RegisteredUserController.php +++ b/app/Http/Controllers/Auth/RegisteredUserController.php @@ -17,6 +17,7 @@ use Illuminate\Http\Request; use Illuminate\Support\Facades\Hash; use Illuminate\Support\Facades\RateLimiter; use Illuminate\Support\Facades\Validator; +use Illuminate\Validation\ValidationException; use Illuminate\Support\Str; use Illuminate\View\View; @@ -37,10 +38,16 @@ class RegisteredUserController extends Controller */ public function create(Request $request): View { + $cspNonce = $this->resolveCspNonce($request); + return view('auth.register', [ 'prefillEmail' => (string) $request->query('email', ''), - 'requiresCaptcha' => $this->shouldRequireCaptcha($request->ip()), - 'captcha' => $this->captchaVerifier->frontendConfig(), + 'turnstile' => [ + 'enabled' => $this->turnstileVerifier->isEnabled(), + 'siteKey' => $this->turnstileVerifier->siteKey(), + 'scriptUrl' => $this->turnstileVerifier->scriptUrl(), + 'cspNonce' => $cspNonce, + ], ]); } @@ -62,25 +69,35 @@ class RegisteredUserController extends Controller */ public function store(Request $request): RedirectResponse { + $turnstileResponse = (string) ($request->input('turnstile_token') ?: $request->input('cf-turnstile-response', '')); + $rules = [ 'email' => ['required', 'string', 'lowercase', 'email', 'max:255'], 'website' => ['nullable', 'max:0'], + 'turnstile_token' => ['nullable', 'string'], + 'cf-turnstile-response' => [$this->turnstileVerifier->isEnabled() ? 'required_without:turnstile_token' : 'nullable', 'string'], ]; - $rules[$this->captchaVerifier->inputName()] = ['nullable', 'string']; $validator = Validator::make($request->all(), $rules); if ($validator->fails()) { + $errors = $validator->errors()->toArray(); + + if (array_key_exists('cf-turnstile-response', $errors) && ! array_key_exists('turnstile_token', $errors)) { + $errors['turnstile_token'] = $errors['cf-turnstile-response']; + unset($errors['cf-turnstile-response']); + } + $this->authAuditLogger->log( eventType: 'register', request: $request, status: 'failed', reason: 'validation_failed', identifier: (string) $request->input('email'), - metadata: ['fields' => array_keys($validator->errors()->toArray())], + metadata: ['fields' => array_keys($errors)], ); - $validator->validate(); + throw ValidationException::withMessages($errors); } $validated = $validator->validated(); @@ -90,32 +107,18 @@ class RegisteredUserController extends Controller $this->trackRegisterAttempt($ip); - if ($this->shouldRequireCaptcha($ip)) { - $verified = $this->captchaVerifier->verify( - (string) $request->input($this->captchaVerifier->inputName(), ''), - $ip + if ($this->turnstileVerifier->isEnabled() && ! $this->turnstileVerifier->verify($turnstileResponse, $ip)) { + $this->authAuditLogger->log( + eventType: 'register', + request: $request, + status: 'failed', + reason: 'captcha_failed', + identifier: $email, ); - if ($this->turnstileVerifier->isEnabled()) { - $verified = $this->turnstileVerifier->verify( - (string) $request->input($this->captchaVerifier->inputName(), ''), - $ip - ); - } - - if (! $verified) { - $this->authAuditLogger->log( - eventType: 'register', - request: $request, - status: 'failed', - reason: 'captcha_failed', - identifier: $email, - ); - - return back() - ->withInput($request->except('website')) - ->withErrors(['captcha' => 'Captcha verification failed. Please try again.']); - } + return back() + ->withInput($request->except('website', 'turnstile_token', 'cf-turnstile-response')) + ->withErrors(['turnstile_token' => 'Security verification failed. Please try again.']); } if ($this->disposableEmailService->isDisposableEmail($email)) { @@ -264,23 +267,6 @@ class RegisteredUserController extends Controller ]); } - private function shouldRequireCaptcha(?string $ip): bool - { - if (! $this->captchaVerifier->isEnabled()) { - if (! $this->turnstileVerifier->isEnabled()) { - return false; - } - - if (! (bool) config('registration.enable_turnstile', true)) { - return false; - } - - return $this->turnstileVerifier->isEnabled() && $this->shouldRequireCaptchaForIp($ip); - } - - return $this->shouldRequireCaptchaForIp($ip); - } - private function shouldRequireCaptchaForIp(?string $ip): bool { if (! $this->captchaVerifier->isEnabled() && ! $this->turnstileVerifier->isEnabled()) { @@ -387,4 +373,28 @@ class RegisteredUserController extends Controller return $remaining >= 0 ? 0 : abs((int) $remaining); } + + private function resolveCspNonce(Request $request): ?string + { + $candidates = [ + $request->attributes->get('csp_nonce'), + $request->attributes->get('cspNonce'), + $request->headers->get('X-CSP-Nonce'), + $request->server('HTTP_X_CSP_NONCE'), + ]; + + foreach ($candidates as $candidate) { + if (! is_string($candidate)) { + continue; + } + + $nonce = trim($candidate); + + if ($nonce !== '') { + return $nonce; + } + } + + return null; + } } diff --git a/app/Http/Controllers/Community/LatestCommentsController.php b/app/Http/Controllers/Community/LatestCommentsController.php index 03790de4..de7b276a 100644 --- a/app/Http/Controllers/Community/LatestCommentsController.php +++ b/app/Http/Controllers/Community/LatestCommentsController.php @@ -21,7 +21,19 @@ class LatestCommentsController extends Controller // Build initial (first-page, type=all) data for React SSR props $initialData = Cache::remember('comments.latest.all.page1', 120, function () { - return ArtworkComment::with(['user', 'user.profile', 'artwork']) + return ArtworkComment::query() + ->select([ + 'artwork_comments.id', + 'artwork_comments.artwork_id', + 'artwork_comments.user_id', + 'artwork_comments.content', + 'artwork_comments.created_at', + ]) + ->with([ + 'user:id,username,name', + 'user.profile:user_id,avatar_hash', + 'artwork:id,title,slug,hash,file_path,file_name', + ]) ->whereHas('artwork', function ($q) { $q->public()->published()->whereNull('deleted_at'); }) diff --git a/app/Http/Controllers/News/NewsController.php b/app/Http/Controllers/News/NewsController.php index 1bc2d3d5..8bc66520 100644 --- a/app/Http/Controllers/News/NewsController.php +++ b/app/Http/Controllers/News/NewsController.php @@ -3,7 +3,6 @@ namespace App\Http\Controllers\News; use App\Http\Controllers\Controller; -use App\Models\NewsArticleComment; use App\Models\User; use App\Services\News\NewsService; use Illuminate\Http\Request; @@ -147,40 +146,14 @@ class NewsController extends Controller // Track view (once per session / IP) $this->trackView($request, $article); - // Related articles (same category, excluding current) - $related = NewsArticle::with('author', 'category') - ->published() - ->when($article->category_id, fn ($q) => $q->where('category_id', $article->category_id)) - ->where('id', '!=', $article->id) - ->editorialOrder() - ->limit(config('news.related_limit', 4)) - ->get(); - - $comments = collect(); - $commentsCount = 0; - - if ($article->commentsAreEnabled()) { - $comments = NewsArticleComment::query() - ->where('article_id', $article->id) - ->whereNull('parent_id') - ->where('status', 'visible') - ->with(['user.profile']) - ->orderBy('created_at') - ->orderBy('id') - ->get(); - - $commentsCount = (int) NewsArticleComment::query() - ->where('article_id', $article->id) - ->where('status', 'visible') - ->count(); - } + $articleData = $this->news->publicArticleShowData($article, $request->user()); return view('news.show', [ 'article' => $article, - 'related' => $related, - 'relatedEntities' => $this->news->resolveRelatedEntities($article, $request->user()), - 'comments' => $comments, - 'commentsCount' => $commentsCount, + 'related' => $articleData['related'], + 'relatedEntities' => $articleData['relatedEntities'], + 'comments' => $articleData['comments'], + 'commentsCount' => $articleData['commentsCount'], ] + $this->sidebarData()); } diff --git a/app/Http/Controllers/Settings/AcademyAdminController.php b/app/Http/Controllers/Settings/AcademyAdminController.php index 8ddc49f5..f61079ca 100644 --- a/app/Http/Controllers/Settings/AcademyAdminController.php +++ b/app/Http/Controllers/Settings/AcademyAdminController.php @@ -11,26 +11,36 @@ use App\Http\Requests\Academy\UpsertAcademyChallengeRequest; use App\Http\Requests\Academy\UpsertAcademyLessonRequest; use App\Http\Requests\Academy\UpsertAcademyPromptPackRequest; use App\Http\Requests\Academy\UpsertAcademyPromptTemplateRequest; +use App\Models\AcademyAiComparisonResult; use App\Models\AcademyBadge; use App\Models\AcademyCategory; use App\Models\AcademyChallenge; use App\Models\AcademyChallengeSubmission; use App\Models\AcademyLesson; +use App\Models\AcademyLessonBlock; use App\Models\AcademyPromptPack; use App\Models\AcademyPromptPackItem; use App\Models\AcademyPromptTemplate; use App\Services\Academy\AcademyCacheService; use Illuminate\Database\Eloquent\Model; +use Illuminate\Http\JsonResponse; use Illuminate\Http\RedirectResponse; use Illuminate\Http\Request; +use Illuminate\Http\UploadedFile; +use Illuminate\Support\Facades\DB; +use Illuminate\Support\Facades\Storage; +use Illuminate\Support\Str; +use Illuminate\Validation\ValidationException; use Inertia\Inertia; use Inertia\Response; final class AcademyAdminController extends Controller { - public function __construct(private readonly AcademyCacheService $cache) - { - } + private const PROMPT_PREVIEW_WEBP_QUALITY = 84; + + private const PROMPT_PREVIEW_PREFIX = 'academy-prompts/previews'; + + public function __construct(private readonly AcademyCacheService $cache) {} public function dashboard(): Response { @@ -65,18 +75,30 @@ final class AcademyAdminController extends Controller public function categoriesCreate(): Response { - return $this->renderForm('categories', new AcademyCategory()); + return $this->renderForm('categories', new AcademyCategory); } public function categoriesStore(UpsertAcademyCategoryRequest $request): RedirectResponse { - $category = new AcademyCategory(); + $category = new AcademyCategory; $category->fill($request->validated())->save(); $this->cache->clearAll(); return redirect()->route('admin.academy.categories.edit', ['academyCategory' => $category])->with('success', 'Academy category created.'); } + public function categoriesStoreJson(UpsertAcademyCategoryRequest $request): JsonResponse + { + $category = new AcademyCategory; + $category->fill($request->validated())->save(); + $this->cache->clearAll(); + + return response()->json([ + 'success' => true, + 'category' => $this->serializeCategoryOption($category), + ]); + } + public function categoriesEdit(AcademyCategory $academyCategory): Response { return $this->renderForm('categories', $academyCategory); @@ -105,13 +127,19 @@ final class AcademyAdminController extends Controller public function lessonsCreate(): Response { - return $this->renderForm('lessons', new AcademyLesson()); + return $this->renderForm('lessons', new AcademyLesson); } public function lessonsStore(UpsertAcademyLessonRequest $request): RedirectResponse { - $lesson = new AcademyLesson(); - $lesson->fill($request->validated())->save(); + $lesson = DB::transaction(function () use ($request): AcademyLesson { + $lesson = new AcademyLesson; + $lesson->fill($this->persistLessonAttributes($request))->save(); + $this->syncLessonBlocks($lesson, $request->validated('blocks', [])); + + return $lesson; + }); + $this->cache->clearAll(); return redirect()->route('admin.academy.lessons.edit', ['academyLesson' => $lesson])->with('success', 'Academy lesson created.'); @@ -119,12 +147,18 @@ final class AcademyAdminController extends Controller public function lessonsEdit(AcademyLesson $academyLesson): Response { + $academyLesson->load(['blocks.comparisonResults']); + return $this->renderForm('lessons', $academyLesson); } public function lessonsUpdate(UpsertAcademyLessonRequest $request, AcademyLesson $academyLesson): RedirectResponse { - $academyLesson->fill($request->validated())->save(); + DB::transaction(function () use ($request, $academyLesson): void { + $academyLesson->fill($this->persistLessonAttributes($request, $academyLesson))->save(); + $this->syncLessonBlocks($academyLesson, $request->validated('blocks', [])); + }); + $this->cache->clearAll(); return redirect()->route('admin.academy.lessons.edit', ['academyLesson' => $academyLesson])->with('success', 'Academy lesson updated.'); @@ -132,6 +166,16 @@ final class AcademyAdminController extends Controller public function lessonsDestroy(AcademyLesson $academyLesson): RedirectResponse { + $academyLesson->load(['blocks.comparisonResults']); + + foreach ($academyLesson->blocks as $block) { + foreach ($block->comparisonResults as $result) { + $this->deleteStoredLessonMediaIfLocal($result->image_path); + $this->deleteStoredLessonMediaIfLocal($result->thumb_path); + } + } + + $this->deleteStoredLessonCoverIfLocal((string) $academyLesson->cover_image); $academyLesson->delete(); $this->cache->clearAll(); @@ -145,13 +189,13 @@ final class AcademyAdminController extends Controller public function promptsCreate(): Response { - return $this->renderForm('prompts', new AcademyPromptTemplate()); + return $this->renderForm('prompts', new AcademyPromptTemplate); } public function promptsStore(UpsertAcademyPromptTemplateRequest $request): RedirectResponse { - $prompt = new AcademyPromptTemplate(); - $prompt->fill($request->validated())->save(); + $prompt = new AcademyPromptTemplate; + $prompt->forceFill($this->persistPromptAttributes($request, $prompt))->save(); $this->cache->clearAll(); return redirect()->route('admin.academy.prompts.edit', ['academyPromptTemplate' => $prompt])->with('success', 'Academy prompt created.'); @@ -164,7 +208,7 @@ final class AcademyAdminController extends Controller public function promptsUpdate(UpsertAcademyPromptTemplateRequest $request, AcademyPromptTemplate $academyPromptTemplate): RedirectResponse { - $academyPromptTemplate->fill($request->validated())->save(); + $academyPromptTemplate->forceFill($this->persistPromptAttributes($request, $academyPromptTemplate))->save(); $this->cache->clearAll(); return redirect()->route('admin.academy.prompts.edit', ['academyPromptTemplate' => $academyPromptTemplate])->with('success', 'Academy prompt updated.'); @@ -185,12 +229,12 @@ final class AcademyAdminController extends Controller public function packsCreate(): Response { - return $this->renderForm('packs', new AcademyPromptPack()); + return $this->renderForm('packs', new AcademyPromptPack); } public function packsStore(UpsertAcademyPromptPackRequest $request): RedirectResponse { - $pack = new AcademyPromptPack(); + $pack = new AcademyPromptPack; $pack->fill(collect($request->validated())->except('prompt_ids')->all())->save(); $this->syncPackItems($pack, $request->validated('prompt_ids', [])); $this->cache->clearAll(); @@ -229,12 +273,12 @@ final class AcademyAdminController extends Controller public function challengesCreate(): Response { - return $this->renderForm('challenges', new AcademyChallenge()); + return $this->renderForm('challenges', new AcademyChallenge); } public function challengesStore(UpsertAcademyChallengeRequest $request): RedirectResponse { - $challenge = new AcademyChallenge(); + $challenge = new AcademyChallenge; $challenge->fill($request->validated())->save(); $this->cache->clearAll(); @@ -269,12 +313,12 @@ final class AcademyAdminController extends Controller public function badgesCreate(): Response { - return $this->renderForm('badges', new AcademyBadge()); + return $this->renderForm('badges', new AcademyBadge); } public function badgesStore(UpsertAcademyBadgeRequest $request): RedirectResponse { - $badge = new AcademyBadge(); + $badge = new AcademyBadge; $badge->fill($request->validated())->save(); return redirect()->route('admin.academy.badges.edit', ['academyBadge' => $badge])->with('success', 'Academy badge created.'); @@ -362,7 +406,7 @@ final class AcademyAdminController extends Controller 'subtitle' => $meta['subtitle'], 'items' => $items, 'columns' => $meta['columns'], - 'createUrl' => route($meta['route_base'] . '.create'), + 'createUrl' => route($meta['route_base'].'.create'), ]); } @@ -372,17 +416,44 @@ final class AcademyAdminController extends Controller return Inertia::render('Admin/Academy/CrudForm', [ 'resource' => $resource, - 'title' => $record->exists ? 'Edit ' . $meta['singular'] : 'Create ' . $meta['singular'], + 'title' => $record->exists ? 'Edit '.$meta['singular'] : 'Create '.$meta['singular'], 'subtitle' => $meta['subtitle'], 'fields' => $meta['fields'], 'record' => $this->serializeFormRecord($resource, $record), - 'submitUrl' => $record->exists ? route($meta['route_base'] . '.update', $this->routeParams($resource, $record)) : route($meta['route_base'] . '.store'), - 'indexUrl' => route($meta['route_base'] . '.index'), - 'destroyUrl' => $record->exists ? route($meta['route_base'] . '.destroy', $this->routeParams($resource, $record)) : null, + 'submitUrl' => $record->exists ? route($meta['route_base'].'.update', $this->routeParams($resource, $record)) : route($meta['route_base'].'.store'), + 'indexUrl' => route($meta['route_base'].'.index'), + 'destroyUrl' => $record->exists ? route($meta['route_base'].'.destroy', $this->routeParams($resource, $record)) : null, 'method' => $record->exists ? 'patch' : 'post', + 'editorContext' => $this->formEditorContext($resource), ]); } + private function formEditorContext(string $resource): array + { + if ($resource !== 'lessons') { + return []; + } + + return [ + 'coverUploadUrl' => route('api.studio.academy.lessons.media.upload'), + 'coverDeleteUrl' => route('api.studio.academy.lessons.media.destroy'), + 'bodyMediaUploadUrl' => route('api.studio.academy.lessons.media.upload'), + 'bodyMediaDeleteUrl' => route('api.studio.academy.lessons.media.destroy'), + 'bodyMediaAssetsUrl' => route('api.studio.academy.lessons.media.assets'), + 'coverCdnBaseUrl' => rtrim((string) config('cdn.files_url', 'https://files.skinbase.org'), '/'), + 'categories' => AcademyCategory::query() + ->where('type', 'lesson') + ->orderBy('order_num') + ->orderBy('name') + ->get() + ->map(fn (AcademyCategory $category): array => $this->serializeCategoryOption($category)) + ->values() + ->all(), + 'categoryStoreUrl' => route('api.academy.categories.store'), + 'categoryManageUrl' => route('admin.academy.categories.index'), + ]; + } + private function resourceMeta(string $resource): array { return match ($resource) { @@ -449,7 +520,7 @@ final class AcademyAdminController extends Controller ['name' => 'access_level', 'label' => 'Access', 'type' => 'select', 'options' => $this->accessOptions()], ['name' => 'aspect_ratio', 'label' => 'Aspect Ratio', 'type' => 'text'], ['name' => 'tags', 'label' => 'Tags', 'type' => 'csv'], - ['name' => 'preview_image', 'label' => 'Preview Image', 'type' => 'text'], + ['name' => 'preview_image', 'label' => 'Preview Image URL', 'type' => 'text'], ['name' => 'published_at', 'label' => 'Published At', 'type' => 'datetime-local'], ['name' => 'seo_title', 'label' => 'SEO Title', 'type' => 'text'], ['name' => 'seo_description', 'label' => 'SEO Description', 'type' => 'textarea'], @@ -526,7 +597,7 @@ final class AcademyAdminController extends Controller ['name' => 'active', 'label' => 'Active', 'type' => 'checkbox'], ], ], - default => throw new \InvalidArgumentException('Unknown Academy resource [' . $resource . '].'), + default => throw new \InvalidArgumentException('Unknown Academy resource ['.$resource.'].'), }; } @@ -616,6 +687,7 @@ final class AcademyAdminController extends Controller 'access_level' => (string) ($record->access_level ?? 'free'), 'lesson_type' => (string) ($record->lesson_type ?? 'article'), 'cover_image' => (string) ($record->cover_image ?? ''), + 'cover_image_url' => $this->resolveLessonCoverImageUrl((string) ($record->cover_image ?? '')), 'video_url' => (string) ($record->video_url ?? ''), 'reading_minutes' => (int) ($record->reading_minutes ?? 5), 'published_at' => optional($record->published_at)?->format('Y-m-d\TH:i'), @@ -623,6 +695,9 @@ final class AcademyAdminController extends Controller 'seo_description' => (string) ($record->seo_description ?? ''), 'featured' => (bool) ($record->featured ?? false), 'active' => (bool) ($record->active ?? true), + 'blocks' => $record instanceof AcademyLesson + ? $record->blocks->map(fn (AcademyLessonBlock $block): array => $this->serializeLessonBlock($block))->values()->all() + : [], ], 'prompts' => [ 'category_id' => $record->category_id, @@ -638,6 +713,8 @@ final class AcademyAdminController extends Controller 'aspect_ratio' => (string) ($record->aspect_ratio ?? ''), 'tags' => implode(', ', (array) ($record->tags ?? [])), 'preview_image' => (string) ($record->preview_image ?? ''), + 'preview_image_url' => $this->resolvePromptPreviewImageUrl((string) ($record->preview_image ?? '')), + 'preview_image_file' => null, 'published_at' => optional($record->published_at)?->format('Y-m-d\TH:i'), 'seo_title' => (string) ($record->seo_title ?? ''), 'seo_description' => (string) ($record->seo_description ?? ''), @@ -693,6 +770,429 @@ final class AcademyAdminController extends Controller }; } + /** + * @return array + */ + private function persistLessonAttributes(UpsertAcademyLessonRequest $request, ?AcademyLesson $lesson = null): array + { + $validated = $request->validated(); + unset($validated['blocks']); + $currentCoverImage = trim((string) ($lesson?->cover_image ?? '')); + $nextCoverImage = filled($validated['cover_image'] ?? null) + ? trim((string) $validated['cover_image']) + : null; + + if ($currentCoverImage !== '' && $currentCoverImage !== (string) $nextCoverImage) { + $this->deleteStoredLessonCoverIfLocal($currentCoverImage); + } + + $validated['cover_image'] = $nextCoverImage; + + // Auto-publish: if marked active but no published_at set, default to now. + if (! empty($validated['active']) && empty($validated['published_at'])) { + $validated['published_at'] = now(); + } + + return $validated; + } + + /** + * @param array> $blocks + */ + private function syncLessonBlocks(AcademyLesson $lesson, array $blocks): void + { + $lesson->loadMissing(['blocks.comparisonResults']); + + $existingBlocks = $lesson->blocks->keyBy(fn (AcademyLessonBlock $block): int => (int) $block->id); + $retainedBlockIds = []; + + foreach ($blocks as $index => $blockData) { + $blockId = isset($blockData['id']) ? (int) $blockData['id'] : null; + $block = $blockId !== null ? $existingBlocks->get($blockId) : null; + + if (! $block instanceof AcademyLessonBlock) { + $block = new AcademyLessonBlock; + $block->lesson()->associate($lesson); + } + + $payload = is_array($blockData['payload'] ?? null) ? $blockData['payload'] : []; + $block->fill([ + 'type' => (string) ($blockData['type'] ?? 'ai_comparison'), + 'title' => $this->nullableTrimmedString($blockData['title'] ?? null) ?? $this->nullableTrimmedString($payload['title'] ?? null), + 'payload' => $this->normalizeLessonBlockPayload($payload), + 'sort_order' => (int) ($blockData['sort_order'] ?? $index), + 'active' => (bool) ($blockData['active'] ?? true), + ]); + $block->save(); + + $retainedBlockIds[] = (int) $block->id; + $this->syncLessonBlockComparisonResults($block, is_array($blockData['comparison_results'] ?? null) ? $blockData['comparison_results'] : []); + } + + $lesson->blocks + ->filter(fn (AcademyLessonBlock $block): bool => ! in_array((int) $block->id, $retainedBlockIds, true)) + ->each(function (AcademyLessonBlock $block): void { + foreach ($block->comparisonResults as $result) { + $this->deleteStoredLessonMediaIfLocal($result->image_path); + $this->deleteStoredLessonMediaIfLocal($result->thumb_path); + } + + $block->delete(); + }); + } + + /** + * @param array> $results + */ + private function syncLessonBlockComparisonResults(AcademyLessonBlock $block, array $results): void + { + $existingResults = $block->comparisonResults->keyBy(fn (AcademyAiComparisonResult $result): int => (int) $result->id); + $retainedResultIds = []; + + foreach ($results as $index => $resultData) { + $resultId = isset($resultData['id']) ? (int) $resultData['id'] : null; + $result = $resultId !== null ? $existingResults->get($resultId) : null; + + if (! $result instanceof AcademyAiComparisonResult) { + $result = new AcademyAiComparisonResult; + $result->block()->associate($block); + } + + $previousImagePath = (string) ($result->image_path ?? ''); + $previousThumbPath = (string) ($result->thumb_path ?? ''); + $nextImagePath = $this->nullableTrimmedString($resultData['image_path'] ?? null); + $nextThumbPath = $this->nullableTrimmedString($resultData['thumb_path'] ?? null); + + $result->fill([ + 'provider' => $this->nullableTrimmedString($resultData['provider'] ?? null), + 'model_name' => $this->nullableTrimmedString($resultData['model_name'] ?? null), + 'image_path' => $nextImagePath, + 'thumb_path' => $nextThumbPath, + 'settings' => $this->nullableTrimmedString($resultData['settings'] ?? null), + 'strengths' => $this->nullableTrimmedString($resultData['strengths'] ?? null), + 'weaknesses' => $this->nullableTrimmedString($resultData['weaknesses'] ?? null), + 'best_for' => $this->nullableTrimmedString($resultData['best_for'] ?? null), + 'score' => $resultData['score'] ?? null, + 'sort_order' => (int) ($resultData['sort_order'] ?? $index), + 'active' => (bool) ($resultData['active'] ?? true), + ]); + $result->save(); + + if ($previousImagePath !== '' && $previousImagePath !== (string) $nextImagePath) { + $this->deleteStoredLessonMediaIfLocal($previousImagePath); + } + + if ($previousThumbPath !== '' && $previousThumbPath !== (string) $nextThumbPath) { + $this->deleteStoredLessonMediaIfLocal($previousThumbPath); + } + + $retainedResultIds[] = (int) $result->id; + } + + $block->comparisonResults + ->filter(fn (AcademyAiComparisonResult $result): bool => ! in_array((int) $result->id, $retainedResultIds, true)) + ->each(function (AcademyAiComparisonResult $result): void { + $this->deleteStoredLessonMediaIfLocal($result->image_path); + $this->deleteStoredLessonMediaIfLocal($result->thumb_path); + $result->delete(); + }); + } + + /** + * @param array $payload + * @return array + */ + private function normalizeLessonBlockPayload(array $payload): array + { + $criteria = collect($payload['criteria'] ?? []) + ->map(fn ($criterion): string => trim((string) $criterion)) + ->filter(static fn (string $criterion): bool => $criterion !== '') + ->values() + ->all(); + + return [ + 'title' => $this->nullableTrimmedString($payload['title'] ?? null), + 'intro' => $this->nullableTrimmedString($payload['intro'] ?? null), + 'prompt' => $this->nullableTrimmedString($payload['prompt'] ?? null), + 'negative_prompt' => $this->nullableTrimmedString($payload['negative_prompt'] ?? null), + 'aspect_ratio' => $this->nullableTrimmedString($payload['aspect_ratio'] ?? null), + 'criteria' => $criteria, + ]; + } + + /** + * @return array + */ + private function serializeLessonBlock(AcademyLessonBlock $block): array + { + $payload = is_array($block->payload) ? $block->payload : []; + + return [ + 'id' => (int) $block->id, + 'type' => (string) $block->type, + 'title' => (string) ($block->title ?? ''), + 'payload' => $this->normalizeLessonBlockPayload($payload), + 'sort_order' => (int) $block->sort_order, + 'active' => (bool) $block->active, + 'comparison_results' => $block->comparisonResults->map(fn (AcademyAiComparisonResult $result): array => [ + 'id' => (int) $result->id, + 'provider' => (string) ($result->provider ?? ''), + 'model_name' => (string) ($result->model_name ?? ''), + 'image_path' => (string) $result->image_path, + 'image_url' => $this->resolveLessonMediaUrl((string) $result->image_path), + 'thumb_path' => (string) ($result->thumb_path ?? ''), + 'thumb_url' => $this->resolveLessonMediaUrl((string) ($result->thumb_path ?? '')), + 'settings' => (string) ($result->settings ?? ''), + 'strengths' => (string) ($result->strengths ?? ''), + 'weaknesses' => (string) ($result->weaknesses ?? ''), + 'best_for' => (string) ($result->best_for ?? ''), + 'score' => $result->score, + 'sort_order' => (int) $result->sort_order, + 'active' => (bool) $result->active, + ])->values()->all(), + ]; + } + + /** + * @return array + */ + private function persistPromptAttributes(UpsertAcademyPromptTemplateRequest $request, ?AcademyPromptTemplate $prompt = null): array + { + $validated = $request->validated(); + unset($validated['preview_image_file']); + + $currentPreviewImage = (string) ($prompt?->preview_image ?? ''); + $previewImageFile = $this->promptPreviewImageUpload($request); + + if ($previewImageFile instanceof UploadedFile) { + $this->deleteStoredPromptPreviewIfLocal($currentPreviewImage); + $validated['preview_image'] = $this->storePromptPreviewImage($previewImageFile); + } else { + $validated['preview_image'] = filled($validated['preview_image'] ?? null) + ? trim((string) $validated['preview_image']) + : null; + } + + // Auto-publish: if marked active but no published_at set, default to now. + if (! empty($validated['active']) && empty($validated['published_at'])) { + $validated['published_at'] = now(); + } + + return $validated; + } + + private function promptPreviewImageUpload(UpsertAcademyPromptTemplateRequest $request): ?UploadedFile + { + $file = $request->file('preview_image_file'); + + if (! $file instanceof UploadedFile) { + return null; + } + + $pathName = trim((string) $file->getPathname()); + if ($file->isValid() && $pathName !== '' && is_file($pathName) && is_readable($pathName)) { + return $file; + } + + throw ValidationException::withMessages([ + 'preview_image_file' => $this->promptPreviewImageUploadErrorMessage($file), + ]); + } + + private function storePromptPreviewImage(UploadedFile $file): string + { + $pathName = trim((string) $file->getPathname()); + if ($pathName === '' || ! is_file($pathName) || ! is_readable($pathName)) { + throw ValidationException::withMessages([ + 'preview_image_file' => $this->promptPreviewImageUploadErrorMessage($file), + ]); + } + + if (! function_exists('imagecreatefromstring') || ! function_exists('imagewebp')) { + throw ValidationException::withMessages([ + 'preview_image_file' => 'The server is missing WebP image support. Enable the GD WebP extension to upload prompt preview images.', + ]); + } + + $binary = @file_get_contents($pathName); + if ($binary === false) { + throw ValidationException::withMessages([ + 'preview_image_file' => 'The uploaded preview image could not be opened for conversion. Please choose the file again and retry.', + ]); + } + + $image = @imagecreatefromstring($binary); + if (! $image instanceof \GdImage) { + throw ValidationException::withMessages([ + 'preview_image_file' => 'The uploaded preview image format could not be converted. Please use JPG, PNG, or WEBP.', + ]); + } + + try { + if (! imageistruecolor($image)) { + imagepalettetotruecolor($image); + } + + imagealphablending($image, true); + imagesavealpha($image, true); + + ob_start(); + $converted = imagewebp($image, null, self::PROMPT_PREVIEW_WEBP_QUALITY); + $webpBinary = ob_get_clean(); + + if (! $converted || ! is_string($webpBinary) || $webpBinary === '') { + throw ValidationException::withMessages([ + 'preview_image_file' => 'The uploaded preview image could not be converted to WebP. Please try a different image.', + ]); + } + + $storedPath = self::PROMPT_PREVIEW_PREFIX.'/'.pathinfo(Str::replace('\\', '/', $file->hashName()), PATHINFO_FILENAME).'.webp'; + Storage::disk($this->promptPreviewImageDisk())->put($storedPath, $webpBinary, ['visibility' => 'public']); + } finally { + imagedestroy($image); + } + + return $storedPath; + } + + private function deleteStoredPromptPreviewIfLocal(?string $path): void + { + $path = trim((string) $path); + if ($path === '' || str_starts_with($path, 'http://') || str_starts_with($path, 'https://') || str_starts_with($path, '/')) { + return; + } + + if (! str_starts_with($path, self::PROMPT_PREVIEW_PREFIX.'/')) { + return; + } + + $disk = $this->promptPreviewImageDisk(); + + if (Storage::disk($disk)->exists($path)) { + Storage::disk($disk)->delete($path); + } + } + + private function promptPreviewImageUploadErrorMessage(UploadedFile $file): string + { + return match ($file->getError()) { + UPLOAD_ERR_INI_SIZE, UPLOAD_ERR_FORM_SIZE => 'The uploaded preview image exceeds the server upload limit.', + UPLOAD_ERR_PARTIAL => 'The uploaded preview image was only partially received. Please retry the upload.', + UPLOAD_ERR_NO_TMP_DIR => 'The server upload temp directory is unavailable. Check PHP upload temp configuration.', + UPLOAD_ERR_CANT_WRITE => 'The server could not write the uploaded preview image to temporary storage.', + UPLOAD_ERR_EXTENSION => 'A PHP extension blocked the preview image upload.', + default => 'The uploaded preview image could not be read. Please choose the file again and retry.', + }; + } + + private function promptPreviewImageDisk(): string + { + return (string) config('uploads.object_storage.disk', 's3'); + } + + private function resolvePromptPreviewImageUrl(?string $previewImage): ?string + { + $previewImage = trim((string) $previewImage); + + if ($previewImage === '') { + return null; + } + + if (str_starts_with($previewImage, 'http://') || str_starts_with($previewImage, 'https://') || str_starts_with($previewImage, '/')) { + return $previewImage; + } + + return Storage::disk($this->promptPreviewImageDisk())->url($previewImage); + } + + private function resolveLessonMediaUrl(?string $path): ?string + { + $path = trim((string) $path); + + if ($path === '') { + return null; + } + + if (str_starts_with($path, 'http://') || str_starts_with($path, 'https://') || str_starts_with($path, '/')) { + return $path; + } + + return Storage::disk($this->promptPreviewImageDisk())->url($path); + } + + private function deleteStoredLessonCoverIfLocal(?string $path): void + { + $path = trim((string) $path); + if ($path === '' || str_starts_with($path, 'http://') || str_starts_with($path, 'https://') || str_starts_with($path, '/')) { + return; + } + + if (! str_starts_with($path, 'academy/lessons/covers/')) { + return; + } + + $disk = $this->promptPreviewImageDisk(); + + if (Storage::disk($disk)->exists($path)) { + Storage::disk($disk)->delete($path); + } + } + + private function deleteStoredLessonMediaIfLocal(?string $path): void + { + $path = trim((string) $path); + if ($path === '' || str_starts_with($path, 'http://') || str_starts_with($path, 'https://') || str_starts_with($path, '/')) { + return; + } + + if (! str_starts_with($path, 'academy/lessons/body/') && ! str_starts_with($path, 'academy/lessons/covers/')) { + return; + } + + $disk = $this->promptPreviewImageDisk(); + + if (Storage::disk($disk)->exists($path)) { + Storage::disk($disk)->delete($path); + } + } + + private function nullableTrimmedString(mixed $value): ?string + { + $trimmed = trim((string) $value); + + return $trimmed === '' ? null : $trimmed; + } + + private function resolveLessonCoverImageUrl(?string $coverImage): ?string + { + $coverImage = trim((string) $coverImage); + + if ($coverImage === '') { + return null; + } + + if (str_starts_with($coverImage, 'http://') || str_starts_with($coverImage, 'https://') || str_starts_with($coverImage, '/')) { + return $coverImage; + } + + return Storage::disk($this->promptPreviewImageDisk())->url($coverImage); + } + + private function serializeCategoryOption(AcademyCategory $category): array + { + return [ + 'id' => (int) $category->id, + 'value' => (int) $category->id, + 'label' => (string) $category->name, + 'name' => (string) $category->name, + 'slug' => (string) $category->slug, + 'description' => (string) ($category->description ?? ''), + 'order_num' => (int) ($category->order_num ?? 0), + 'active' => (bool) ($category->active ?? true), + 'edit_url' => route('admin.academy.categories.edit', ['academyCategory' => $category]), + ]; + } + private function routeParams(string $resource, Model $record): array { return match ($resource) { @@ -758,4 +1258,4 @@ final class AcademyAdminController extends Controller ]); } } -} \ No newline at end of file +} diff --git a/app/Http/Controllers/Studio/StudioNewsMediaApiController.php b/app/Http/Controllers/Studio/StudioNewsMediaApiController.php index 1c9d55e8..c7861177 100644 --- a/app/Http/Controllers/Studio/StudioNewsMediaApiController.php +++ b/app/Http/Controllers/Studio/StudioNewsMediaApiController.php @@ -5,42 +5,15 @@ declare(strict_types=1); namespace App\Http\Controllers\Studio; use App\Http\Controllers\Controller; +use App\Services\News\NewsCoverImageService; use Illuminate\Http\JsonResponse; use Illuminate\Http\Request; -use Illuminate\Http\UploadedFile; -use Illuminate\Support\Facades\Storage; -use Illuminate\Support\Str; -use Intervention\Image\Drivers\Gd\Driver as GdDriver; -use Intervention\Image\Drivers\Imagick\Driver as ImagickDriver; -use Intervention\Image\Encoders\WebpEncoder; -use Intervention\Image\ImageManager; use RuntimeException; final class StudioNewsMediaApiController extends Controller { - private const ALLOWED_MIME_TYPES = ['image/jpeg', 'image/png', 'image/webp']; - - private const MAX_FILE_SIZE_KB = 6144; - - private const MAX_WIDTH = 2200; - - private const MAX_HEIGHT = 1400; - - private const MIN_WIDTH = 1200; - - private const MIN_HEIGHT = 630; - - private ?ImageManager $manager = null; - - public function __construct() + public function __construct(private readonly NewsCoverImageService $covers) { - try { - $this->manager = extension_loaded('gd') - ? new ImageManager(new GdDriver()) - : new ImageManager(new ImagickDriver()); - } catch (\Throwable) { - $this->manager = null; - } } public function store(Request $request): JsonResponse @@ -52,26 +25,28 @@ final class StudioNewsMediaApiController extends Controller 'required', 'file', 'image', - 'max:' . self::MAX_FILE_SIZE_KB, + 'max:' . $this->covers->maxFileSizeKb(), 'mimes:jpg,jpeg,png,webp', 'mimetypes:image/jpeg,image/png,image/webp', ], ]); - /** @var UploadedFile $file */ $file = $validated['image']; try { - $stored = $this->storeMediaFile($file); + $stored = $this->covers->storeUploadedFile($file); return response()->json([ 'success' => true, 'path' => $stored['path'], - 'url' => $this->publicUrlForPath($stored['path']), + 'url' => $stored['url'], 'width' => $stored['width'], 'height' => $stored['height'], 'mime_type' => 'image/webp', 'size_bytes' => $stored['size_bytes'], + 'mobile_url' => $stored['mobile_url'], + 'desktop_url' => $stored['desktop_url'], + 'srcset' => $stored['srcset'], ]); } catch (RuntimeException $e) { return response()->json([ @@ -99,7 +74,7 @@ final class StudioNewsMediaApiController extends Controller 'path' => ['required', 'string', 'max:2048'], ]); - $this->deleteMediaFile((string) $validated['path']); + $this->covers->deleteManagedFiles((string) $validated['path']); return response()->json([ 'success' => true, @@ -176,56 +151,4 @@ final class StudioNewsMediaApiController extends Controller { abort_unless($request->user() && ($request->user()->isAdmin() || $request->user()->isModerator()), 403); } - - private function mediaDiskName(): string - { - return (string) config('uploads.object_storage.disk', 's3'); - } - - private function mediaPath(string $hash): string - { - return sprintf( - 'news/covers/%s/%s/%s.webp', - substr($hash, 0, 2), - substr($hash, 2, 2), - $hash, - ); - } - - private function publicUrlForPath(string $path): string - { - return rtrim((string) config('cdn.files_url', 'https://files.skinbase.org'), '/') . '/' . ltrim($path, '/'); - } - - private function deleteMediaFile(string $path): void - { - $trimmed = ltrim(trim($path), '/'); - - if ($trimmed === '' || ! Str::startsWith($trimmed, 'news/covers/')) { - return; - } - - Storage::disk($this->mediaDiskName())->delete($trimmed); - } - - private function assertImageManager(): void - { - if ($this->manager !== null) { - return; - } - - throw new RuntimeException('Image processing is not available on this environment.'); - } - - private function assertStorageIsAllowed(): void - { - if (! app()->environment('production')) { - return; - } - - $diskName = $this->mediaDiskName(); - if (in_array($diskName, ['local', 'public'], true)) { - throw new RuntimeException('Production news media storage must use object storage, not local/public disks.'); - } - } } \ No newline at end of file diff --git a/app/Http/Requests/Academy/UpsertAcademyLessonRequest.php b/app/Http/Requests/Academy/UpsertAcademyLessonRequest.php index f0e43538..27654db2 100644 --- a/app/Http/Requests/Academy/UpsertAcademyLessonRequest.php +++ b/app/Http/Requests/Academy/UpsertAcademyLessonRequest.php @@ -5,6 +5,7 @@ declare(strict_types=1); namespace App\Http\Requests\Academy; use Illuminate\Foundation\Http\FormRequest; +use Illuminate\Support\Arr; use Illuminate\Validation\Rule; class UpsertAcademyLessonRequest extends FormRequest @@ -16,10 +17,62 @@ class UpsertAcademyLessonRequest extends FormRequest protected function prepareForValidation(): void { + $blocks = collect($this->input('blocks', [])) + ->filter(static fn ($block): bool => is_array($block)) + ->map(function (array $block): array { + $payload = Arr::wrap($block['payload'] ?? []); + $criteria = collect($payload['criteria'] ?? []) + ->map(static fn ($criterion) => trim((string) $criterion)) + ->filter(static fn (string $criterion): bool => $criterion !== '') + ->values() + ->all(); + + $results = collect($block['comparison_results'] ?? []) + ->filter(static fn ($result): bool => is_array($result)) + ->map(function (array $result): array { + return [ + 'id' => filled($result['id'] ?? null) ? (int) $result['id'] : null, + 'provider' => $result['provider'] ?? null, + 'model_name' => $result['model_name'] ?? null, + 'image_path' => $result['image_path'] ?? null, + 'thumb_path' => $result['thumb_path'] ?? null, + 'settings' => $result['settings'] ?? null, + 'strengths' => $result['strengths'] ?? null, + 'weaknesses' => $result['weaknesses'] ?? null, + 'best_for' => $result['best_for'] ?? null, + 'score' => filled($result['score'] ?? null) ? (int) $result['score'] : null, + 'sort_order' => filled($result['sort_order'] ?? null) ? (int) $result['sort_order'] : 0, + 'active' => filter_var($result['active'] ?? true, FILTER_VALIDATE_BOOL, FILTER_NULL_ON_FAILURE) ?? true, + ]; + }) + ->values() + ->all(); + + return [ + 'id' => filled($block['id'] ?? null) ? (int) $block['id'] : null, + 'type' => (string) ($block['type'] ?? 'ai_comparison'), + 'title' => $block['title'] ?? null, + 'payload' => [ + 'title' => $payload['title'] ?? null, + 'intro' => $payload['intro'] ?? null, + 'prompt' => $payload['prompt'] ?? null, + 'negative_prompt' => $payload['negative_prompt'] ?? null, + 'aspect_ratio' => $payload['aspect_ratio'] ?? null, + 'criteria' => $criteria, + ], + 'sort_order' => filled($block['sort_order'] ?? null) ? (int) $block['sort_order'] : 0, + 'active' => filter_var($block['active'] ?? true, FILTER_VALIDATE_BOOL, FILTER_NULL_ON_FAILURE) ?? true, + 'comparison_results' => $results, + ]; + }) + ->values() + ->all(); + $this->merge([ 'reading_minutes' => $this->filled('reading_minutes') ? (int) $this->input('reading_minutes') : 5, 'featured' => $this->boolean('featured'), 'active' => $this->boolean('active', true), + 'blocks' => $blocks, ]); } @@ -44,6 +97,33 @@ class UpsertAcademyLessonRequest extends FormRequest 'published_at' => ['nullable', 'date'], 'seo_title' => ['nullable', 'string', 'max:180'], 'seo_description' => ['nullable', 'string', 'max:255'], + 'blocks' => ['nullable', 'array'], + 'blocks.*.id' => ['nullable', 'integer', 'exists:academy_lesson_blocks,id'], + 'blocks.*.type' => ['required', 'string', Rule::in(['ai_comparison'])], + 'blocks.*.title' => ['nullable', 'string', 'max:255'], + 'blocks.*.payload' => ['nullable', 'array'], + 'blocks.*.payload.title' => ['nullable', 'string', 'max:255'], + 'blocks.*.payload.intro' => ['nullable', 'string'], + 'blocks.*.payload.prompt' => ['nullable', 'string'], + 'blocks.*.payload.negative_prompt' => ['nullable', 'string'], + 'blocks.*.payload.aspect_ratio' => ['nullable', 'string', 'max:20'], + 'blocks.*.payload.criteria' => ['nullable', 'array'], + 'blocks.*.payload.criteria.*' => ['nullable', 'string', 'max:100'], + 'blocks.*.sort_order' => ['required', 'integer', 'min:0'], + 'blocks.*.active' => ['required', 'boolean'], + 'blocks.*.comparison_results' => ['nullable', 'array'], + 'blocks.*.comparison_results.*.id' => ['nullable', 'integer', 'exists:academy_ai_comparison_results,id'], + 'blocks.*.comparison_results.*.provider' => ['nullable', 'string', 'max:100'], + 'blocks.*.comparison_results.*.model_name' => ['nullable', 'string', 'max:150'], + 'blocks.*.comparison_results.*.image_path' => ['required', 'string', 'max:500'], + 'blocks.*.comparison_results.*.thumb_path' => ['nullable', 'string', 'max:500'], + 'blocks.*.comparison_results.*.settings' => ['nullable', 'string'], + 'blocks.*.comparison_results.*.strengths' => ['nullable', 'string'], + 'blocks.*.comparison_results.*.weaknesses' => ['nullable', 'string'], + 'blocks.*.comparison_results.*.best_for' => ['nullable', 'string'], + 'blocks.*.comparison_results.*.score' => ['nullable', 'integer', 'min:1', 'max:10'], + 'blocks.*.comparison_results.*.sort_order' => ['required', 'integer', 'min:0'], + 'blocks.*.comparison_results.*.active' => ['required', 'boolean'], ]; } -} \ No newline at end of file +} diff --git a/app/Http/Requests/Academy/UpsertAcademyPromptTemplateRequest.php b/app/Http/Requests/Academy/UpsertAcademyPromptTemplateRequest.php index 7b19a975..7f22fa14 100644 --- a/app/Http/Requests/Academy/UpsertAcademyPromptTemplateRequest.php +++ b/app/Http/Requests/Academy/UpsertAcademyPromptTemplateRequest.php @@ -45,6 +45,7 @@ class UpsertAcademyPromptTemplateRequest extends FormRequest 'tags.*' => ['string', 'max:60'], 'tool_notes' => ['nullable', 'array'], 'preview_image' => ['nullable', 'string', 'max:2048'], + 'preview_image_file' => ['nullable', 'file', 'image', 'mimes:jpg,jpeg,png,webp', 'max:5120'], 'featured' => ['required', 'boolean'], 'prompt_of_week' => ['required', 'boolean'], 'active' => ['required', 'boolean'], diff --git a/app/Models/AcademyLesson.php b/app/Models/AcademyLesson.php index f5658382..0886b035 100644 --- a/app/Models/AcademyLesson.php +++ b/app/Models/AcademyLesson.php @@ -14,6 +14,21 @@ class AcademyLesson extends Model { use SoftDeletes; + protected static function booted(): void + { + static::deleting(function (self $lesson): void { + $lesson->blocks()->with('comparisonResults')->get()->each(function (AcademyLessonBlock $block) use ($lesson): void { + if ($lesson->isForceDeleting()) { + $block->forceDelete(); + + return; + } + + $block->delete(); + }); + }); + } + protected $fillable = [ 'category_id', 'title', @@ -59,4 +74,16 @@ class AcademyLesson extends Model { return $this->hasMany(AcademyLessonProgress::class, 'lesson_id'); } -} \ No newline at end of file + + public function blocks(): HasMany + { + return $this->hasMany(AcademyLessonBlock::class, 'lesson_id') + ->orderBy('sort_order') + ->orderBy('id'); + } + + public function activeBlocks(): HasMany + { + return $this->blocks()->where('active', true); + } +} diff --git a/app/Services/Academy/AcademyAccessService.php b/app/Services/Academy/AcademyAccessService.php index 215c9ba1..b72b4882 100644 --- a/app/Services/Academy/AcademyAccessService.php +++ b/app/Services/Academy/AcademyAccessService.php @@ -4,11 +4,14 @@ declare(strict_types=1); namespace App\Services\Academy; +use App\Models\AcademyAiComparisonResult; use App\Models\AcademyChallenge; use App\Models\AcademyLesson; +use App\Models\AcademyLessonBlock; use App\Models\AcademyPromptPack; use App\Models\AcademyPromptTemplate; use App\Models\User; +use Illuminate\Support\Facades\Storage; use Illuminate\Support\Str; final class AcademyAccessService @@ -66,6 +69,7 @@ final class AcademyAccessService 'access_level' => (string) $lesson->access_level, 'lesson_type' => (string) $lesson->lesson_type, 'cover_image' => $lesson->cover_image, + 'cover_image_url' => $this->resolveLessonCoverImageUrl((string) ($lesson->cover_image ?? '')), 'video_url' => $authorized ? $lesson->video_url : null, 'reading_minutes' => (int) $lesson->reading_minutes, 'featured' => (bool) $lesson->featured, @@ -76,6 +80,9 @@ final class AcademyAccessService 'name' => (string) $lesson->category->name, 'slug' => (string) $lesson->category->slug, ] : null, + 'blocks' => ($authorized && $includeFull) + ? $lesson->activeBlocks->map(fn (AcademyLessonBlock $block): ?array => $this->lessonBlockPayload($block))->filter()->values()->all() + : [], 'locked' => ! $authorized, 'can_access' => $authorized, ]; @@ -100,7 +107,7 @@ final class AcademyAccessService 'aspect_ratio' => $prompt->aspect_ratio, 'tags' => array_values((array) ($prompt->tags ?? [])), 'tool_notes' => $authorized ? (array) ($prompt->tool_notes ?? []) : [], - 'preview_image' => $prompt->preview_image, + 'preview_image' => $this->resolvePreviewImageUrl((string) ($prompt->preview_image ?? '')), 'featured' => (bool) $prompt->featured, 'prompt_of_week' => (bool) $prompt->prompt_of_week, 'published_at' => $prompt->published_at?->toISOString(), @@ -204,6 +211,115 @@ final class AcademyAccessService $previewLength = max(1, $length - 1); } - return rtrim(mb_substr($plain, 0, $previewLength)) . '...'; + return rtrim(mb_substr($plain, 0, $previewLength)).'...'; } -} \ No newline at end of file + + private function resolvePreviewImageUrl(string $previewImage): ?string + { + $previewImage = trim($previewImage); + + if ($previewImage === '') { + return null; + } + + if (str_starts_with($previewImage, 'http://') || str_starts_with($previewImage, 'https://') || str_starts_with($previewImage, '/')) { + return $previewImage; + } + + return Storage::disk((string) config('uploads.object_storage.disk', 's3'))->url($previewImage); + } + + private function resolveLessonCoverImageUrl(string $coverImage): ?string + { + $coverImage = trim($coverImage); + + if ($coverImage === '') { + return null; + } + + if (str_starts_with($coverImage, 'http://') || str_starts_with($coverImage, 'https://') || str_starts_with($coverImage, '/')) { + return $coverImage; + } + + return Storage::disk((string) config('uploads.object_storage.disk', 's3'))->url($coverImage); + } + + private function resolveLessonMediaUrl(string $path): ?string + { + $path = trim($path); + + if ($path === '') { + return null; + } + + if (str_starts_with($path, 'http://') || str_starts_with($path, 'https://') || str_starts_with($path, '/')) { + return $path; + } + + return Storage::disk((string) config('uploads.object_storage.disk', 's3'))->url($path); + } + + /** + * @return array|null + */ + private function lessonBlockPayload(AcademyLessonBlock $block): ?array + { + if ($block->type !== 'ai_comparison') { + return null; + } + + $payload = is_array($block->payload) ? $block->payload : []; + $criteria = collect($payload['criteria'] ?? []) + ->map(static fn ($criterion): string => trim((string) $criterion)) + ->filter(static fn (string $criterion): bool => $criterion !== '') + ->values() + ->all(); + $results = $block->activeComparisonResults + ->map(fn (AcademyAiComparisonResult $result): array => [ + 'id' => (int) $result->id, + 'provider' => (string) ($result->provider ?? ''), + 'model_name' => (string) ($result->model_name ?? ''), + 'image_path' => (string) $result->image_path, + 'image_url' => $this->resolveLessonMediaUrl((string) $result->image_path), + 'thumb_path' => (string) ($result->thumb_path ?? ''), + 'thumb_url' => $this->resolveLessonMediaUrl((string) ($result->thumb_path ?? '')), + 'settings' => (string) ($result->settings ?? ''), + 'strengths' => (string) ($result->strengths ?? ''), + 'weaknesses' => (string) ($result->weaknesses ?? ''), + 'best_for' => (string) ($result->best_for ?? ''), + 'score' => $result->score, + 'sort_order' => (int) $result->sort_order, + 'active' => (bool) $result->active, + ]) + ->values() + ->all(); + + $hasPromptData = filled($payload['prompt'] ?? null) + || filled($payload['negative_prompt'] ?? null) + || filled($payload['intro'] ?? null) + || filled($payload['title'] ?? null) + || filled($payload['aspect_ratio'] ?? null) + || ! empty($criteria); + + if (! $hasPromptData && $results === []) { + return null; + } + + return [ + 'id' => (int) $block->id, + 'type' => (string) $block->type, + 'title' => (string) ($block->title ?? ($payload['title'] ?? '')), + 'payload' => [ + 'title' => (string) ($payload['title'] ?? ''), + 'intro' => (string) ($payload['intro'] ?? ''), + 'prompt' => (string) ($payload['prompt'] ?? ''), + 'negative_prompt' => (string) ($payload['negative_prompt'] ?? ''), + 'aspect_ratio' => (string) ($payload['aspect_ratio'] ?? ''), + 'criteria' => $criteria, + ], + 'sort_order' => (int) $block->sort_order, + 'active' => (bool) $block->active, + 'comparison_results' => $results, + ]; + } +} diff --git a/app/Services/ArtworkService.php b/app/Services/ArtworkService.php index d92363cd..8183a3ee 100644 --- a/app/Services/ArtworkService.php +++ b/app/Services/ArtworkService.php @@ -27,6 +27,8 @@ class ArtworkService { protected int $cacheTtl = 3600; // seconds + private ?bool $featureTypeColumnExists = null; + public function __construct( private readonly ContentTypeSlugResolver $contentTypeResolver, private readonly ArtworkMaturityService $maturity, @@ -340,7 +342,7 @@ class ArtworkService */ private function featuredBaseQuery(?int $type): Builder { - return Artwork::query() + $query = Artwork::query() ->select('artworks.*') ->join('artwork_features as af', 'af.artwork_id', '=', 'artworks.id') ->leftJoin('artwork_medal_stats as aas', 'aas.artwork_id', '=', 'artworks.id') @@ -349,10 +351,13 @@ class ArtworkService ->where(function ($query): void { $query->whereNull('af.expires_at') ->orWhere('af.expires_at', '>', now()); - }) - ->when($type !== null, function ($q) use ($type) { - $q->where('af.type', $type); }); + + if ($type !== null && $this->featuredTypeColumnExists()) { + $query->where('af.type', $type); + } + + return $query; } private function applyFeaturedEligibilityFilters(Builder $query): void @@ -384,6 +389,15 @@ class ArtworkService return $this->applyFeaturedOrdering($query); } + private function featuredTypeColumnExists(): bool + { + if ($this->featureTypeColumnExists === null) { + $this->featureTypeColumnExists = Schema::hasColumn('artwork_features', 'type'); + } + + return $this->featureTypeColumnExists; + } + private function featuredHeroSelectionQuery(?int $type): Builder { $query = $this->featuredBaseQuery($type); diff --git a/app/Services/News/NewsArticleCommentService.php b/app/Services/News/NewsArticleCommentService.php index 331d0552..f6ff5a49 100644 --- a/app/Services/News/NewsArticleCommentService.php +++ b/app/Services/News/NewsArticleCommentService.php @@ -12,6 +12,10 @@ use cPad\Plugins\News\Models\NewsArticle; final class NewsArticleCommentService { + public function __construct(private readonly NewsService $news) + { + } + public function create(NewsArticle $article, User $actor, string $body, ?NewsArticleComment $parent = null): NewsArticleComment { if (! $article->commentsAreEnabled()) { @@ -42,6 +46,8 @@ final class NewsArticleCommentService 'status' => 'visible', ]); + $this->news->invalidatePublicCache(); + return $comment->fresh(['user.profile', 'replies.user.profile']); } @@ -60,6 +66,8 @@ final class NewsArticleCommentService } $comment->delete(); + + $this->news->invalidatePublicCache(); } private function canDelete(NewsArticleComment $comment, NewsArticle $article, User $actor): bool diff --git a/app/Services/News/NewsService.php b/app/Services/News/NewsService.php index 5fff8c47..b43eb8ef 100644 --- a/app/Services/News/NewsService.php +++ b/app/Services/News/NewsService.php @@ -11,11 +11,15 @@ use App\Models\GroupChallenge; use App\Models\GroupEvent; use App\Models\GroupProject; use App\Models\GroupRelease; +use App\Models\NewsArticleComment; use App\Models\User; +use App\Support\News\NewsCoverImage; use App\Support\AvatarUrl; use Illuminate\Contracts\Pagination\LengthAwarePaginator; use Illuminate\Database\Eloquent\Builder; use Illuminate\Support\Carbon; +use Illuminate\Support\Facades\Cache; +use Illuminate\Support\Facades\Schema; use Illuminate\Support\Facades\Storage; use Illuminate\Support\Str; use cPad\Plugins\News\Models\NewsArticle; @@ -25,6 +29,8 @@ use cPad\Plugins\News\Models\NewsTag; final class NewsService { + private const PUBLIC_CACHE_VERSION_KEY = 'news.public.cache.version'; + public const RELATION_GROUP = 'group'; public const RELATION_ARTWORK = 'artwork'; public const RELATION_COLLECTION = 'collection'; @@ -45,6 +51,8 @@ final class NewsService self::RELATION_USER => 'Profile', ]; + private ?bool $artworkStatsViewsColumnExists = null; + public function articleTypeOptions(): array { return \collect(NewsArticle::TYPE_LABELS) @@ -98,15 +106,23 @@ final class NewsService public function sidebarData(): array { - return [ - 'categories' => NewsCategory::active()->withCount('publishedArticles')->ordered()->get(), - 'trending' => NewsArticle::published() - ->with('category') - ->orderByDesc('views') - ->limit(config('news.trending_limit', 5)) - ->get(['id', 'title', 'slug', 'views', 'published_at', 'category_id', 'type']), - 'tags' => NewsTag::whereHas('articles', fn ($query) => $query->published())->orderBy('name')->get(), - ]; + return Cache::remember($this->publicCacheKey('sidebar'), $this->publicCacheTtl(), function (): array { + return [ + 'categories' => NewsCategory::active()->withCount('publishedArticles')->ordered()->get(), + 'trending' => NewsArticle::published() + ->with('category') + ->orderByDesc('views') + ->limit(config('news.trending_limit', 5)) + ->get(['id', 'title', 'slug', 'views', 'published_at', 'category_id', 'type']), + 'tags' => NewsTag::query() + ->whereHas('articles', fn ($query) => $query->published()) + ->withCount(['articles as published_articles_count' => fn ($query) => $query->published()]) + ->orderByDesc('published_articles_count') + ->orderBy('name') + ->limit((int) config('news.sidebar_tags_limit', 18)) + ->get(), + ]; + }); } public function studioListing(array $filters = []): array @@ -169,6 +185,9 @@ final class NewsService 'content' => (string) ($article->content ?? ''), 'cover_image' => (string) ($article->cover_image ?? ''), 'cover_url' => $article->cover_url, + 'cover_mobile_url' => $article->cover_mobile_url, + 'cover_desktop_url' => $article->cover_desktop_url, + 'cover_srcset' => $article->cover_srcset, 'type' => (string) ($article->type ?? NewsArticle::TYPE_ANNOUNCEMENT), 'editorial_status' => (string) ($article->editorial_status ?? NewsArticle::EDITORIAL_STATUS_DRAFT), 'published_at' => \optional($article->published_at)?->toIso8601String(), @@ -214,6 +233,8 @@ final class NewsService public function deleteArticle(NewsArticle $article): void { $article->delete(); + + $this->invalidatePublicCache(); } public function publish(NewsArticle $article): NewsArticle @@ -224,6 +245,8 @@ final class NewsService 'published_at' => $article->published_at ?? \now(), ])->save(); + $this->invalidatePublicCache(); + return $article->fresh(['author', 'category', 'tags', 'relatedEntities']); } @@ -234,6 +257,8 @@ final class NewsService 'status' => 'draft', ])->save(); + $this->invalidatePublicCache(); + return $article->fresh(['author', 'category', 'tags', 'relatedEntities']); } @@ -241,6 +266,8 @@ final class NewsService { $article->forceFill(['is_featured' => ! $article->is_featured])->save(); + $this->invalidatePublicCache(); + return $article->fresh(['author', 'category', 'tags', 'relatedEntities']); } @@ -248,6 +275,8 @@ final class NewsService { $article->forceFill(['is_pinned' => ! (bool) $article->is_pinned])->save(); + $this->invalidatePublicCache(); + return $article->fresh(['author', 'category', 'tags', 'relatedEntities']); } @@ -280,6 +309,61 @@ final class NewsService ->all(); } + public function publicArticleShowData(NewsArticle $article, ?User $viewer = null): array + { + if ($viewer !== null) { + return $this->buildPublicArticleShowData($article, $viewer); + } + + return Cache::remember( + $this->publicCacheKey('article.show.' . $article->id), + $this->publicCacheTtl(), + fn (): array => $this->buildPublicArticleShowData($article, null), + ); + } + + private function buildPublicArticleShowData(NewsArticle $article, ?User $viewer = null): array + { + $related = NewsArticle::with('author', 'category') + ->published() + ->when($article->category_id, fn ($query) => $query->where('category_id', $article->category_id)) + ->where('id', '!=', $article->id) + ->editorialOrder() + ->limit(config('news.related_limit', 4)) + ->get(); + + $comments = collect(); + $commentsCount = 0; + + if ($article->commentsAreEnabled()) { + $comments = NewsArticleComment::query() + ->where('article_id', $article->id) + ->whereNull('parent_id') + ->where('status', 'visible') + ->with(['user.profile']) + ->orderBy('created_at') + ->orderBy('id') + ->get(); + + $commentsCount = (int) NewsArticleComment::query() + ->where('article_id', $article->id) + ->where('status', 'visible') + ->count(); + } + + return [ + 'related' => $related, + 'relatedEntities' => $this->resolveRelatedEntities($article, $viewer), + 'comments' => $comments, + 'commentsCount' => $commentsCount, + ]; + } + + public function invalidatePublicCache(): void + { + Cache::forever(self::PUBLIC_CACHE_VERSION_KEY, $this->publicCacheVersion() + 1); + } + public function syncRelations(NewsArticle $article, array $relations): void { $normalized = \collect($relations) @@ -311,6 +395,23 @@ final class NewsService 'sort_order' => $index, ]); } + + $this->invalidatePublicCache(); + } + + private function publicCacheKey(string $suffix): string + { + return 'news.public.v' . $this->publicCacheVersion() . '.' . $suffix; + } + + private function publicCacheTtl(): int + { + return max(60, (int) config('news.public_cache_ttl', 120)); + } + + private function publicCacheVersion(): int + { + return (int) Cache::get(self::PUBLIC_CACHE_VERSION_KEY, 1); } private function persistArticle(NewsArticle $article, User $editor, array $data): NewsArticle @@ -362,6 +463,8 @@ final class NewsService $article->tags()->sync($this->resolveArticleTagIds($data)); $this->syncRelations($article, $data['relations'] ?? []); + $this->invalidatePublicCache(); + return $article->fresh(['author.profile', 'category', 'tags', 'relatedEntities']); } @@ -376,6 +479,7 @@ final class NewsService 'editorial_status' => (string) ($article->editorial_status ?? NewsArticle::EDITORIAL_STATUS_DRAFT), 'published_at' => \optional($article->published_at)?->toIso8601String(), 'cover_url' => $article->cover_url, + 'cover_srcset' => $article->cover_srcset, 'author_name' => (string) ($article->author?->name ?? 'Skinbase'), 'category_name' => (string) ($article->category?->name ?? ''), 'is_featured' => (bool) $article->is_featured, @@ -485,13 +589,13 @@ final class NewsService private function deleteManagedCoverImage(string $path): void { - $trimmed = ltrim(trim($path), '/'); + $paths = NewsCoverImage::managedPaths($path); - if ($trimmed === '' || ! Str::startsWith($trimmed, 'news/covers/')) { + if ($paths === []) { return; } - Storage::disk((string) config('uploads.object_storage.disk', 's3'))->delete($trimmed); + Storage::disk((string) config('uploads.object_storage.disk', 's3'))->delete($paths); } private function searchGroups(string $query, ?User $viewer): array @@ -517,8 +621,9 @@ final class NewsService private function searchArtworks(string $query): array { - return Artwork::query() + $queryBuilder = Artwork::query() ->with(['user.profile']) + ->select('artworks.*') ->where('artwork_status', 'published') ->where('visibility', Artwork::VISIBILITY_PUBLIC) ->when($query !== '', function (Builder $builder) use ($query): void { @@ -528,8 +633,17 @@ final class NewsService ->orWhere('description', 'like', '%' . $query . '%'); }); }) - ->orderByDesc('views') - ->limit(8) + ->limit(8); + + if ($this->artworkStatsViewsAvailable()) { + $queryBuilder->leftJoin('artwork_stats as stats', 'stats.artwork_id', '=', 'artworks.id') + ->orderByRaw('COALESCE(stats.views, 0) DESC'); + } else { + $queryBuilder->orderByDesc('published_at'); + } + + return $queryBuilder + ->orderByDesc('artworks.id') ->get() ->map(fn (Artwork $artwork): ?array => $this->resolveArtworkPreview((int) $artwork->id, '')) ->filter() @@ -537,6 +651,16 @@ final class NewsService ->all(); } + private function artworkStatsViewsAvailable(): bool + { + if ($this->artworkStatsViewsColumnExists === null) { + $this->artworkStatsViewsColumnExists = Schema::hasTable('artwork_stats') + && Schema::hasColumn('artwork_stats', 'views'); + } + + return $this->artworkStatsViewsColumnExists; + } + private function searchCollections(string $query, ?User $viewer): array { return Collection::query() diff --git a/app/Services/Security/Captcha/TurnstileCaptchaProvider.php b/app/Services/Security/Captcha/TurnstileCaptchaProvider.php index f286610a..85d3765b 100644 --- a/app/Services/Security/Captcha/TurnstileCaptchaProvider.php +++ b/app/Services/Security/Captcha/TurnstileCaptchaProvider.php @@ -7,6 +7,10 @@ use Illuminate\Support\Facades\Log; class TurnstileCaptchaProvider implements CaptchaProviderInterface { + private const DEFAULT_VERIFY_URL = 'https://challenges.cloudflare.com/turnstile/v0/siteverify'; + + private const DEFAULT_SCRIPT_URL = 'https://challenges.cloudflare.com/turnstile/v0/api.js'; + public function name(): string { return 'turnstile'; @@ -14,7 +18,7 @@ class TurnstileCaptchaProvider implements CaptchaProviderInterface public function isEnabled(): bool { - return (bool) config('registration.enable_turnstile', true) + return (bool) config('services.turnstile.enabled', false) && $this->siteKey() !== '' && (string) config('services.turnstile.secret_key', '') !== ''; } @@ -31,7 +35,7 @@ class TurnstileCaptchaProvider implements CaptchaProviderInterface public function scriptUrl(): string { - return (string) config('services.turnstile.script_url', 'https://challenges.cloudflare.com/turnstile/v0/api.js'); + return (string) config('services.turnstile.script_url', self::DEFAULT_SCRIPT_URL); } public function verify(string $token, ?string $ip = null): bool @@ -47,23 +51,39 @@ class TurnstileCaptchaProvider implements CaptchaProviderInterface try { $response = Http::asForm() ->timeout((int) config('services.turnstile.timeout', 5)) - ->post((string) config('services.turnstile.verify_url', 'https://challenges.cloudflare.com/turnstile/v0/siteverify'), [ + ->post((string) config('services.turnstile.verify_url', self::DEFAULT_VERIFY_URL), [ 'secret' => (string) config('services.turnstile.secret_key', ''), 'response' => $token, - 'remoteip' => $ip, ]); if ($response->failed()) { + Log::info('turnstile verification rejected registration attempt', [ + 'ip' => $ip, + 'hostname' => data_get($response->json(), 'hostname'), + 'error_codes' => data_get($response->json(), 'error-codes', []), + ]); + return false; } - return (bool) data_get($response->json(), 'success', false); + $success = (bool) data_get($response->json(), 'success', false); + + if (! $success) { + Log::info('turnstile verification rejected registration attempt', [ + 'ip' => $ip, + 'hostname' => data_get($response->json(), 'hostname'), + 'error_codes' => data_get($response->json(), 'error-codes', []), + ]); + } + + return $success; } catch (\Throwable $exception) { Log::warning('turnstile verification request failed', [ 'message' => $exception->getMessage(), + 'ip' => $ip, ]); - return false; + return (bool) config('services.turnstile.fail_open', false); } } } diff --git a/app/Services/Security/TurnstileVerifier.php b/app/Services/Security/TurnstileVerifier.php index 29cd24a4..300fcbea 100644 --- a/app/Services/Security/TurnstileVerifier.php +++ b/app/Services/Security/TurnstileVerifier.php @@ -2,21 +2,32 @@ namespace App\Services\Security; +use App\Services\Security\Captcha\TurnstileCaptchaProvider; + class TurnstileVerifier { public function __construct( - private readonly CaptchaVerifier $captchaVerifier, + private readonly TurnstileCaptchaProvider $turnstileProvider, ) { } public function isEnabled(): bool { - return $this->captchaVerifier->provider() === 'turnstile' - && $this->captchaVerifier->isEnabled(); + return $this->turnstileProvider->isEnabled(); + } + + public function siteKey(): string + { + return $this->turnstileProvider->siteKey(); + } + + public function scriptUrl(): string + { + return $this->turnstileProvider->scriptUrl(); } public function verify(string $token, ?string $ip = null): bool { - return $this->captchaVerifier->verify($token, $ip); + return $this->turnstileProvider->verify($token, $ip); } } diff --git a/app/Services/Uploads/UploadDerivativesService.php b/app/Services/Uploads/UploadDerivativesService.php index aaa2c12c..c7dc9bb2 100644 --- a/app/Services/Uploads/UploadDerivativesService.php +++ b/app/Services/Uploads/UploadDerivativesService.php @@ -183,14 +183,32 @@ final class UploadDerivativesService * @return array */ public function generatePublicDerivatives(string $sourcePath, string $hash): array + { + return $this->generateSelectedPublicDerivatives( + $sourcePath, + $hash, + array_keys((array) config('uploads.derivatives', [])), + ); + } + + /** + * @param list $variants + * @return array + */ + public function generateSelectedPublicDerivatives(string $sourcePath, string $hash, array $variants): array { $this->assertImageAvailable(); $quality = (int) config('uploads.quality', 85); - $variants = (array) config('uploads.derivatives', []); + $configuredVariants = (array) config('uploads.derivatives', []); $written = []; - foreach ($variants as $variant => $options) { - $variant = (string) $variant; + foreach ($variants as $variant) { + $variant = strtolower(trim((string) $variant)); + if ($variant === '' || ! array_key_exists($variant, $configuredVariants)) { + continue; + } + + $options = (array) $configuredVariants[$variant]; if ($variant === 'sq') { $written[$variant] = $this->generateSquareDerivative($sourcePath, $hash); diff --git a/bootstrap/app.php b/bootstrap/app.php index 95247d83..457d2273 100644 --- a/bootstrap/app.php +++ b/bootstrap/app.php @@ -36,6 +36,7 @@ return Application::configure(basePath: dirname(__DIR__)) $middleware->web(append: [ \App\Http\Middleware\RedirectLegacyProfileSubdomain::class, + \App\Http\Middleware\TrackOnlineVisitor::class, \App\Http\Middleware\UpdateLastVisit::class, \App\Http\Middleware\HandleInertiaRequests::class, // Runs on every web request; no-ops for guests, redirects authenticated diff --git a/bootstrap/ssr/assets/ArtworkShareModal-BnRQhiXq.js b/bootstrap/ssr/assets/ArtworkShareModal-BnRQhiXq.js deleted file mode 100644 index 080ad90c..00000000 --- a/bootstrap/ssr/assets/ArtworkShareModal-BnRQhiXq.js +++ /dev/null @@ -1,301 +0,0 @@ -import { r as reactExports, a as reactDomExports, R as React } from "./vendor-tiptap-BUUKoc3C.js"; -import { S as ShareToast } from "../ssr.js"; -import "util"; -import "stream"; -import "path"; -import "http"; -import "https"; -import "url"; -import "fs"; -import "crypto"; -import "http2"; -import "assert"; -import "tty"; -import "os"; -import "zlib"; -import "events"; -import "node:process"; -import "node:path"; -import "node:url"; -import "./vendor-tooltip-CIQaDNlG.js"; -import "./vendor-realtime-BGlcW0gB.js"; -import "buffer"; -import "child_process"; -import "net"; -import "tls"; -import "./vendor-motion-Dg7DlHqj.js"; -import "process"; -import "async_hooks"; -const FeedShareArtworkModal = reactExports.lazy(() => import("../ssr.js").then((n) => n.a)); -function facebookUrl(url) { - return `https://www.facebook.com/sharer/sharer.php?u=${encodeURIComponent(url)}`; -} -function twitterUrl(url, title) { - return `https://twitter.com/intent/tweet?url=${encodeURIComponent(url)}&text=${encodeURIComponent(title)}`; -} -function pinterestUrl(url, imageUrl, title) { - return `https://pinterest.com/pin/create/button/?url=${encodeURIComponent(url)}&media=${encodeURIComponent(imageUrl)}&description=${encodeURIComponent(title)}`; -} -function emailUrl(url, title) { - return `mailto:?subject=${encodeURIComponent(title)}&body=${encodeURIComponent(url)}`; -} -function CopyIcon() { - return /* @__PURE__ */ React.createElement("svg", { xmlns: "http://www.w3.org/2000/svg", fill: "none", viewBox: "0 0 24 24", strokeWidth: 1.5, stroke: "currentColor", className: "h-5 w-5" }, /* @__PURE__ */ React.createElement("path", { strokeLinecap: "round", strokeLinejoin: "round", d: "M15.75 17.25v3.375c0 .621-.504 1.125-1.125 1.125h-9.75a1.125 1.125 0 0 1-1.125-1.125V7.875c0-.621.504-1.125 1.125-1.125H6.75a9.06 9.06 0 0 1 1.5.124m7.5 10.376h3.375c.621 0 1.125-.504 1.125-1.125V11.25c0-4.46-3.243-8.161-7.5-8.876a9.06 9.06 0 0 0-1.5-.124H9.375c-.621 0-1.125.504-1.125 1.125v3.5m7.5 10.375H9.375a1.125 1.125 0 0 1-1.125-1.125v-9.25m12 6.625v-1.875a3.375 3.375 0 0 0-3.375-3.375h-1.5a1.125 1.125 0 0 1-1.125-1.125v-1.5a3.375 3.375 0 0 0-3.375-3.375H9.75" })); -} -function CheckIcon() { - return /* @__PURE__ */ React.createElement("svg", { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 20 20", fill: "currentColor", className: "h-5 w-5 text-emerald-400" }, /* @__PURE__ */ React.createElement("path", { fillRule: "evenodd", d: "M16.704 4.153a.75.75 0 0 1 .143 1.052l-8 10.5a.75.75 0 0 1-1.127.075l-4.5-4.5a.75.75 0 0 1 1.06-1.06l3.894 3.893 7.48-9.817a.75.75 0 0 1 1.05-.143Z", clipRule: "evenodd" })); -} -function FacebookIcon() { - return /* @__PURE__ */ React.createElement("svg", { viewBox: "0 0 24 24", fill: "currentColor", className: "h-5 w-5" }, /* @__PURE__ */ React.createElement("path", { d: "M22 12c0-5.523-4.477-10-10-10S2 6.477 2 12c0 4.991 3.657 9.128 8.438 9.878v-6.987h-2.54V12h2.54V9.797c0-2.506 1.492-3.89 3.777-3.89 1.094 0 2.238.195 2.238.195v2.46h-1.26c-1.243 0-1.63.771-1.63 1.562V12h2.773l-.443 2.89h-2.33v6.988C18.343 21.128 22 16.991 22 12Z" })); -} -function XTwitterIcon() { - return /* @__PURE__ */ React.createElement("svg", { viewBox: "0 0 24 24", fill: "currentColor", className: "h-5 w-5" }, /* @__PURE__ */ React.createElement("path", { d: "M18.244 2.25h3.308l-7.227 8.26 8.502 11.24H16.17l-5.214-6.817L4.99 21.75H1.68l7.73-8.835L1.254 2.25H8.08l4.713 6.231 5.45-6.231Zm-1.161 17.52h1.833L7.084 4.126H5.117L17.083 19.77Z" })); -} -function PinterestIcon() { - return /* @__PURE__ */ React.createElement("svg", { viewBox: "0 0 24 24", fill: "currentColor", className: "h-5 w-5" }, /* @__PURE__ */ React.createElement("path", { d: "M12 2C6.477 2 2 6.477 2 12c0 4.236 2.636 7.855 6.356 9.312-.088-.791-.167-2.005.035-2.868.181-.78 1.172-4.97 1.172-4.97s-.299-.598-.299-1.482c0-1.388.806-2.425 1.808-2.425.853 0 1.265.64 1.265 1.408 0 .858-.546 2.14-.828 3.33-.236.995.5 1.807 1.482 1.807 1.778 0 3.144-1.874 3.144-4.58 0-2.393-1.72-4.068-4.177-4.068-2.845 0-4.515 2.135-4.515 4.34 0 .859.331 1.781.745 2.282a.3.3 0 0 1 .069.288l-.278 1.133c-.044.183-.145.222-.335.134-1.249-.581-2.03-2.407-2.03-3.874 0-3.154 2.292-6.052 6.608-6.052 3.469 0 6.165 2.472 6.165 5.776 0 3.447-2.173 6.22-5.19 6.22-1.013 0-1.965-.527-2.291-1.148l-.623 2.378c-.226.869-.835 1.958-1.244 2.621.937.29 1.931.446 2.962.446 5.523 0 10-4.477 10-10S17.523 2 12 2Z" })); -} -function EmailIcon() { - return /* @__PURE__ */ React.createElement("svg", { xmlns: "http://www.w3.org/2000/svg", fill: "none", viewBox: "0 0 24 24", strokeWidth: 1.5, stroke: "currentColor", className: "h-5 w-5" }, /* @__PURE__ */ React.createElement("path", { strokeLinecap: "round", strokeLinejoin: "round", d: "M21.75 6.75v10.5a2.25 2.25 0 0 1-2.25 2.25h-15a2.25 2.25 0 0 1-2.25-2.25V6.75m19.5 0A2.25 2.25 0 0 0 19.5 4.5h-15a2.25 2.25 0 0 0-2.25 2.25m19.5 0v.243a2.25 2.25 0 0 1-1.07 1.916l-7.5 4.615a2.25 2.25 0 0 1-2.36 0L3.32 8.91a2.25 2.25 0 0 1-1.07-1.916V6.75" })); -} -function EmbedIcon() { - return /* @__PURE__ */ React.createElement("svg", { xmlns: "http://www.w3.org/2000/svg", fill: "none", viewBox: "0 0 24 24", strokeWidth: 1.5, stroke: "currentColor", className: "h-5 w-5" }, /* @__PURE__ */ React.createElement("path", { strokeLinecap: "round", strokeLinejoin: "round", d: "M17.25 6.75 22.5 12l-5.25 5.25m-10.5 0L1.5 12l5.25-5.25m7.5-3-4.5 16.5" })); -} -function CloseIcon() { - return /* @__PURE__ */ React.createElement("svg", { xmlns: "http://www.w3.org/2000/svg", fill: "none", viewBox: "0 0 24 24", strokeWidth: 2, stroke: "currentColor", className: "h-5 w-5" }, /* @__PURE__ */ React.createElement("path", { strokeLinecap: "round", strokeLinejoin: "round", d: "M6 18 18 6M6 6l12 12" })); -} -function openShareWindow(url) { - window.open(url, "_blank", "noopener,noreferrer,width=600,height=500"); -} -function trackShare(artworkId, platform) { - const csrfToken = document.querySelector('meta[name="csrf-token"]')?.getAttribute("content"); - fetch(`/api/artworks/${artworkId}/share`, { - method: "POST", - headers: { "Content-Type": "application/json", "X-CSRF-TOKEN": csrfToken || "" }, - credentials: "same-origin", - body: JSON.stringify({ platform }) - }).catch(() => { - }); -} -function ArtworkShareModal({ open, onClose, artwork, shareUrl, isLoggedIn = false }) { - const backdropRef = reactExports.useRef(null); - const [linkCopied, setLinkCopied] = reactExports.useState(false); - const [embedCopied, setEmbedCopied] = reactExports.useState(false); - const [showEmbed, setShowEmbed] = reactExports.useState(false); - const [toastVisible, setToastVisible] = reactExports.useState(false); - const [toastMessage, setToastMessage] = reactExports.useState(""); - const [profileShareOpen, setProfileShareOpen] = reactExports.useState(false); - const url = shareUrl || artwork?.canonical_url || (typeof window !== "undefined" ? window.location.href : "#"); - const title = artwork?.title || "Artwork"; - const imageUrl = artwork?.thumbs?.xl?.url || artwork?.thumbs?.lg?.url || artwork?.thumbs?.md?.url || ""; - const thumbMdUrl = artwork?.thumbs?.md?.url || imageUrl; - const embedCode = ` - ${title.replace(/ -`; - reactExports.useEffect(() => { - if (open) { - document.body.style.overflow = "hidden"; - return () => { - document.body.style.overflow = ""; - }; - } - }, [open]); - reactExports.useEffect(() => { - if (!open) return; - const handler = (e) => { - if (e.key === "Escape") onClose(); - }; - window.addEventListener("keydown", handler); - return () => window.removeEventListener("keydown", handler); - }, [open, onClose]); - reactExports.useEffect(() => { - if (open) { - setLinkCopied(false); - setEmbedCopied(false); - setShowEmbed(false); - } - }, [open]); - const showToast = reactExports.useCallback((msg) => { - setToastMessage(msg); - setToastVisible(true); - }, []); - const handleCopyLink = async () => { - try { - await navigator.clipboard.writeText(url); - setLinkCopied(true); - showToast("Link copied!"); - trackShare(artwork?.id, "copy"); - setTimeout(() => setLinkCopied(false), 2500); - } catch { - } - }; - const handleCopyEmbed = async () => { - try { - await navigator.clipboard.writeText(embedCode); - setEmbedCopied(true); - showToast("Embed code copied!"); - trackShare(artwork?.id, "embed"); - setTimeout(() => setEmbedCopied(false), 2500); - } catch { - } - }; - const handlePlatformShare = (platform, shareLink) => { - openShareWindow(shareLink); - trackShare(artwork?.id, platform); - onClose(); - }; - if (!open) return null; - const SHARE_OPTIONS = [ - { - label: linkCopied ? "Copied!" : "Copy Link", - icon: linkCopied ? /* @__PURE__ */ React.createElement(CheckIcon, null) : /* @__PURE__ */ React.createElement(CopyIcon, null), - onClick: handleCopyLink, - className: linkCopied ? "border-emerald-500/40 bg-emerald-500/15 text-emerald-400" : "border-white/[0.08] bg-white/[0.04] text-white/70 hover:border-white/[0.15] hover:bg-white/[0.07] hover:text-white" - }, - { - label: "Facebook", - icon: /* @__PURE__ */ React.createElement(FacebookIcon, null), - onClick: () => handlePlatformShare("facebook", facebookUrl(url)), - className: "border-white/[0.08] bg-white/[0.04] text-white/70 hover:border-[#1877F2]/40 hover:bg-[#1877F2]/15 hover:text-[#1877F2]" - }, - { - label: "X (Twitter)", - icon: /* @__PURE__ */ React.createElement(XTwitterIcon, null), - onClick: () => handlePlatformShare("twitter", twitterUrl(url, title)), - className: "border-white/[0.08] bg-white/[0.04] text-white/70 hover:border-white/30 hover:bg-white/[0.10] hover:text-white" - }, - { - label: "Pinterest", - icon: /* @__PURE__ */ React.createElement(PinterestIcon, null), - onClick: () => handlePlatformShare("pinterest", pinterestUrl(url, imageUrl, title)), - className: "border-white/[0.08] bg-white/[0.04] text-white/70 hover:border-[#E60023]/40 hover:bg-[#E60023]/15 hover:text-[#E60023]" - }, - { - label: "Email", - icon: /* @__PURE__ */ React.createElement(EmailIcon, null), - onClick: () => { - window.location.href = emailUrl(url, title); - trackShare(artwork?.id, "email"); - }, - className: "border-white/[0.08] bg-white/[0.04] text-white/70 hover:border-white/[0.15] hover:bg-white/[0.07] hover:text-white" - }, - ...isLoggedIn ? [{ - label: "My Profile", - icon: /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-share-nodes h-5 w-5 text-[1.1rem]" }), - onClick: () => setProfileShareOpen(true), - className: "border-sky-500/30 bg-sky-500/10 text-sky-400 hover:border-sky-400/50 hover:bg-sky-500/20" - }] : [] - ]; - return reactDomExports.createPortal( - /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement( - "div", - { - ref: backdropRef, - onClick: (e) => { - if (e.target === backdropRef.current) onClose(); - }, - className: "fixed inset-0 z-[9999] flex items-center justify-center bg-black/60 backdrop-blur-sm p-4", - role: "dialog", - "aria-modal": "true", - "aria-label": "Share this artwork" - }, - /* @__PURE__ */ React.createElement("div", { className: "w-full max-w-md rounded-2xl border border-nova-700/50 bg-nova-900/80 shadow-2xl backdrop-blur-xl" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between border-b border-white/[0.06] px-6 py-4" }, /* @__PURE__ */ React.createElement("h3", { className: "text-base font-semibold text-white" }, "Share this artwork"), /* @__PURE__ */ React.createElement( - "button", - { - type: "button", - onClick: onClose, - className: "rounded-lg p-1.5 text-white/40 transition hover:bg-white/[0.06] hover:text-white/70", - "aria-label": "Close share dialog" - }, - /* @__PURE__ */ React.createElement(CloseIcon, null) - )), thumbMdUrl && /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-3 border-b border-white/[0.06] px-6 py-3" }, /* @__PURE__ */ React.createElement( - "img", - { - src: thumbMdUrl, - alt: title, - className: "h-14 w-14 rounded-lg object-cover", - loading: "lazy" - } - ), /* @__PURE__ */ React.createElement("div", { className: "min-w-0 flex-1" }, /* @__PURE__ */ React.createElement("p", { className: "truncate text-sm font-medium text-white" }, title), artwork?.user?.username && /* @__PURE__ */ React.createElement("p", { className: "truncate text-xs text-white/50" }, "by ", artwork.user.username))), /* @__PURE__ */ React.createElement("div", { className: "grid grid-cols-3 gap-2.5 px-6 py-5 sm:grid-cols-5" }, SHARE_OPTIONS.map((opt) => /* @__PURE__ */ React.createElement( - "button", - { - key: opt.label, - type: "button", - onClick: opt.onClick, - className: [ - "flex flex-col items-center gap-1.5 rounded-xl border px-2 py-3 text-xs font-medium transition-all duration-200", - opt.className - ].join(" ") - }, - opt.icon, - /* @__PURE__ */ React.createElement("span", { className: "truncate" }, opt.label) - ))), /* @__PURE__ */ React.createElement("div", { className: "border-t border-white/[0.06] px-6 py-4" }, /* @__PURE__ */ React.createElement( - "button", - { - type: "button", - onClick: () => setShowEmbed(!showEmbed), - className: "flex items-center gap-2 text-sm font-medium text-white/60 transition hover:text-white/80" - }, - /* @__PURE__ */ React.createElement(EmbedIcon, null), - showEmbed ? "Hide Embed Code" : "Embed Code", - /* @__PURE__ */ React.createElement( - "svg", - { - xmlns: "http://www.w3.org/2000/svg", - viewBox: "0 0 16 16", - fill: "currentColor", - className: `h-3.5 w-3.5 transition-transform duration-200 ${showEmbed ? "rotate-180" : ""}` - }, - /* @__PURE__ */ React.createElement("path", { fillRule: "evenodd", d: "M4.22 6.22a.75.75 0 0 1 1.06 0L8 8.94l2.72-2.72a.75.75 0 1 1 1.06 1.06l-3.25 3.25a.75.75 0 0 1-1.06 0L4.22 7.28a.75.75 0 0 1 0-1.06Z", clipRule: "evenodd" }) - ) - ), showEmbed && /* @__PURE__ */ React.createElement("div", { className: "mt-3 space-y-2" }, /* @__PURE__ */ React.createElement( - "textarea", - { - readOnly: true, - value: embedCode, - rows: 3, - className: "w-full resize-none rounded-xl border border-white/[0.08] bg-white/[0.03] px-4 py-3 font-mono text-xs text-white/70 outline-none focus:border-white/[0.15]", - onClick: (e) => e.target.select() - } - ), /* @__PURE__ */ React.createElement( - "button", - { - type: "button", - onClick: handleCopyEmbed, - className: [ - "inline-flex items-center gap-1.5 rounded-full border px-4 py-1.5 text-xs font-medium transition-all duration-200", - embedCopied ? "border-emerald-500/40 bg-emerald-500/15 text-emerald-400" : "border-white/[0.08] bg-white/[0.04] text-white/60 hover:border-white/[0.15] hover:text-white/80" - ].join(" ") - }, - embedCopied ? /* @__PURE__ */ React.createElement(CheckIcon, null) : /* @__PURE__ */ React.createElement(CopyIcon, null), - embedCopied ? "Copied!" : "Copy Embed" - )))) - ), /* @__PURE__ */ React.createElement( - ShareToast, - { - message: toastMessage, - visible: toastVisible, - onHide: () => setToastVisible(false) - } - ), profileShareOpen && /* @__PURE__ */ React.createElement(reactExports.Suspense, { fallback: null }, /* @__PURE__ */ React.createElement( - FeedShareArtworkModal, - { - isOpen: profileShareOpen, - onClose: () => setProfileShareOpen(false), - preselectedArtwork: artwork?.id ? { - id: artwork.id, - title: artwork.title, - thumb_url: artwork.thumbs?.md?.url ?? artwork.thumbs?.lg?.url ?? null, - user: artwork.user ?? null - } : null, - onShared: () => { - setProfileShareOpen(false); - showToast("Shared to your profile!"); - } - } - ))), - document.body - ); -} -export { - ArtworkShareModal as default -}; diff --git a/bootstrap/ssr/assets/vendor-motion-Dg7DlHqj.js b/bootstrap/ssr/assets/vendor-motion-Dg7DlHqj.js deleted file mode 100644 index 5cb433e5..00000000 --- a/bootstrap/ssr/assets/vendor-motion-Dg7DlHqj.js +++ /dev/null @@ -1,8068 +0,0 @@ -import { r as reactExports, j as jsxRuntimeExports } from "./vendor-tiptap-BUUKoc3C.js"; -const LayoutGroupContext = reactExports.createContext({}); -function useConstant(init) { - const ref = reactExports.useRef(null); - if (ref.current === null) { - ref.current = init(); - } - return ref.current; -} -const isBrowser$1 = typeof window !== "undefined"; -const useIsomorphicLayoutEffect = isBrowser$1 ? reactExports.useLayoutEffect : reactExports.useEffect; -const PresenceContext = /* @__PURE__ */ reactExports.createContext(null); -function addUniqueItem(arr, item) { - if (arr.indexOf(item) === -1) - arr.push(item); -} -function removeItem(arr, item) { - const index = arr.indexOf(item); - if (index > -1) - arr.splice(index, 1); -} -const clamp = (min, max, v) => { - if (v > max) - return max; - if (v < min) - return min; - return v; -}; -function formatErrorMessage(message, errorCode) { - return errorCode ? `${message}. For more information and steps for solving, visit https://motion.dev/troubleshooting/${errorCode}` : message; -} -let warning = () => { -}; -let invariant = () => { -}; -if (typeof process !== "undefined" && process.env?.NODE_ENV !== "production") { - warning = (check, message, errorCode) => { - if (!check && typeof console !== "undefined") { - console.warn(formatErrorMessage(message, errorCode)); - } - }; - invariant = (check, message, errorCode) => { - if (!check) { - throw new Error(formatErrorMessage(message, errorCode)); - } - }; -} -const MotionGlobalConfig = {}; -const isNumericalString = (v) => /^-?(?:\d+(?:\.\d+)?|\.\d+)$/u.test(v); -function isObject(value) { - return typeof value === "object" && value !== null; -} -const isZeroValueString = (v) => /^0[^.\s]+$/u.test(v); -// @__NO_SIDE_EFFECTS__ -function memo(callback) { - let result; - return () => { - if (result === void 0) - result = callback(); - return result; - }; -} -const noop = /* @__NO_SIDE_EFFECTS__ */ (any) => any; -const combineFunctions = (a, b) => (v) => b(a(v)); -const pipe = (...transformers) => transformers.reduce(combineFunctions); -const progress = /* @__NO_SIDE_EFFECTS__ */ (from, to, value) => { - const toFromDifference = to - from; - return toFromDifference === 0 ? 1 : (value - from) / toFromDifference; -}; -class SubscriptionManager { - constructor() { - this.subscriptions = []; - } - add(handler) { - addUniqueItem(this.subscriptions, handler); - return () => removeItem(this.subscriptions, handler); - } - notify(a, b, c) { - const numSubscriptions = this.subscriptions.length; - if (!numSubscriptions) - return; - if (numSubscriptions === 1) { - this.subscriptions[0](a, b, c); - } else { - for (let i = 0; i < numSubscriptions; i++) { - const handler = this.subscriptions[i]; - handler && handler(a, b, c); - } - } - } - getSize() { - return this.subscriptions.length; - } - clear() { - this.subscriptions.length = 0; - } -} -const secondsToMilliseconds = /* @__NO_SIDE_EFFECTS__ */ (seconds) => seconds * 1e3; -const millisecondsToSeconds = /* @__NO_SIDE_EFFECTS__ */ (milliseconds) => milliseconds / 1e3; -function velocityPerSecond(velocity, frameDuration) { - return frameDuration ? velocity * (1e3 / frameDuration) : 0; -} -const warned = /* @__PURE__ */ new Set(); -function warnOnce(condition, message, errorCode) { - if (condition || warned.has(message)) - return; - console.warn(formatErrorMessage(message, errorCode)); - warned.add(message); -} -const calcBezier = (t, a1, a2) => (((1 - 3 * a2 + 3 * a1) * t + (3 * a2 - 6 * a1)) * t + 3 * a1) * t; -const subdivisionPrecision = 1e-7; -const subdivisionMaxIterations = 12; -function binarySubdivide(x, lowerBound, upperBound, mX1, mX2) { - let currentX; - let currentT; - let i = 0; - do { - currentT = lowerBound + (upperBound - lowerBound) / 2; - currentX = calcBezier(currentT, mX1, mX2) - x; - if (currentX > 0) { - upperBound = currentT; - } else { - lowerBound = currentT; - } - } while (Math.abs(currentX) > subdivisionPrecision && ++i < subdivisionMaxIterations); - return currentT; -} -function cubicBezier(mX1, mY1, mX2, mY2) { - if (mX1 === mY1 && mX2 === mY2) - return noop; - const getTForX = (aX) => binarySubdivide(aX, 0, 1, mX1, mX2); - return (t) => t === 0 || t === 1 ? t : calcBezier(getTForX(t), mY1, mY2); -} -const mirrorEasing = (easing) => (p) => p <= 0.5 ? easing(2 * p) / 2 : (2 - easing(2 * (1 - p))) / 2; -const reverseEasing = (easing) => (p) => 1 - easing(1 - p); -const backOut = /* @__PURE__ */ cubicBezier(0.33, 1.53, 0.69, 0.99); -const backIn = /* @__PURE__ */ reverseEasing(backOut); -const backInOut = /* @__PURE__ */ mirrorEasing(backIn); -const anticipate = (p) => p >= 1 ? 1 : (p *= 2) < 1 ? 0.5 * backIn(p) : 0.5 * (2 - Math.pow(2, -10 * (p - 1))); -const circIn = (p) => 1 - Math.sin(Math.acos(p)); -const circOut = reverseEasing(circIn); -const circInOut = mirrorEasing(circIn); -const easeIn = /* @__PURE__ */ cubicBezier(0.42, 0, 1, 1); -const easeOut = /* @__PURE__ */ cubicBezier(0, 0, 0.58, 1); -const easeInOut = /* @__PURE__ */ cubicBezier(0.42, 0, 0.58, 1); -const isEasingArray = (ease2) => { - return Array.isArray(ease2) && typeof ease2[0] !== "number"; -}; -const isBezierDefinition = (easing) => Array.isArray(easing) && typeof easing[0] === "number"; -const easingLookup = { - linear: noop, - easeIn, - easeInOut, - easeOut, - circIn, - circInOut, - circOut, - backIn, - backInOut, - backOut, - anticipate -}; -const isValidEasing = (easing) => { - return typeof easing === "string"; -}; -const easingDefinitionToFunction = (definition) => { - if (isBezierDefinition(definition)) { - invariant(definition.length === 4, `Cubic bezier arrays must contain four numerical values.`, "cubic-bezier-length"); - const [x1, y1, x2, y2] = definition; - return cubicBezier(x1, y1, x2, y2); - } else if (isValidEasing(definition)) { - invariant(easingLookup[definition] !== void 0, `Invalid easing type '${definition}'`, "invalid-easing-type"); - return easingLookup[definition]; - } - return definition; -}; -const stepsOrder = [ - "setup", - // Compute - "read", - // Read - "resolveKeyframes", - // Write/Read/Write/Read - "preUpdate", - // Compute - "update", - // Compute - "preRender", - // Compute - "render", - // Write - "postRender" - // Compute -]; -function createRenderStep(runNextFrame, stepName) { - let thisFrame = /* @__PURE__ */ new Set(); - let nextFrame = /* @__PURE__ */ new Set(); - let isProcessing = false; - let flushNextFrame = false; - const toKeepAlive = /* @__PURE__ */ new WeakSet(); - let latestFrameData = { - delta: 0, - timestamp: 0, - isProcessing: false - }; - function triggerCallback(callback) { - if (toKeepAlive.has(callback)) { - step.schedule(callback); - runNextFrame(); - } - callback(latestFrameData); - } - const step = { - /** - * Schedule a process to run on the next frame. - */ - schedule: (callback, keepAlive = false, immediate = false) => { - const addToCurrentFrame = immediate && isProcessing; - const queue = addToCurrentFrame ? thisFrame : nextFrame; - if (keepAlive) - toKeepAlive.add(callback); - queue.add(callback); - return callback; - }, - /** - * Cancel the provided callback from running on the next frame. - */ - cancel: (callback) => { - nextFrame.delete(callback); - toKeepAlive.delete(callback); - }, - /** - * Execute all schedule callbacks. - */ - process: (frameData2) => { - latestFrameData = frameData2; - if (isProcessing) { - flushNextFrame = true; - return; - } - isProcessing = true; - const prevFrame = thisFrame; - thisFrame = nextFrame; - nextFrame = prevFrame; - thisFrame.forEach(triggerCallback); - thisFrame.clear(); - isProcessing = false; - if (flushNextFrame) { - flushNextFrame = false; - step.process(frameData2); - } - } - }; - return step; -} -const maxElapsed = 40; -function createRenderBatcher(scheduleNextBatch, allowKeepAlive) { - let runNextFrame = false; - let useDefaultElapsed = true; - const state = { - delta: 0, - timestamp: 0, - isProcessing: false - }; - const flagRunNextFrame = () => runNextFrame = true; - const steps = stepsOrder.reduce((acc, key) => { - acc[key] = createRenderStep(flagRunNextFrame); - return acc; - }, {}); - const { setup, read, resolveKeyframes, preUpdate, update, preRender, render, postRender } = steps; - const processBatch = () => { - const useManualTiming = MotionGlobalConfig.useManualTiming; - const timestamp = useManualTiming ? state.timestamp : performance.now(); - runNextFrame = false; - if (!useManualTiming) { - state.delta = useDefaultElapsed ? 1e3 / 60 : Math.max(Math.min(timestamp - state.timestamp, maxElapsed), 1); - } - state.timestamp = timestamp; - state.isProcessing = true; - setup.process(state); - read.process(state); - resolveKeyframes.process(state); - preUpdate.process(state); - update.process(state); - preRender.process(state); - render.process(state); - postRender.process(state); - state.isProcessing = false; - if (runNextFrame && allowKeepAlive) { - useDefaultElapsed = false; - scheduleNextBatch(processBatch); - } - }; - const wake = () => { - runNextFrame = true; - useDefaultElapsed = true; - if (!state.isProcessing) { - scheduleNextBatch(processBatch); - } - }; - const schedule = stepsOrder.reduce((acc, key) => { - const step = steps[key]; - acc[key] = (process2, keepAlive = false, immediate = false) => { - if (!runNextFrame) - wake(); - return step.schedule(process2, keepAlive, immediate); - }; - return acc; - }, {}); - const cancel = (process2) => { - for (let i = 0; i < stepsOrder.length; i++) { - steps[stepsOrder[i]].cancel(process2); - } - }; - return { schedule, cancel, state, steps }; -} -const { schedule: frame, cancel: cancelFrame, state: frameData, steps: frameSteps } = /* @__PURE__ */ createRenderBatcher(typeof requestAnimationFrame !== "undefined" ? requestAnimationFrame : noop, true); -let now; -function clearTime() { - now = void 0; -} -const time = { - now: () => { - if (now === void 0) { - time.set(frameData.isProcessing || MotionGlobalConfig.useManualTiming ? frameData.timestamp : performance.now()); - } - return now; - }, - set: (newTime) => { - now = newTime; - queueMicrotask(clearTime); - } -}; -const checkStringStartsWith = (token) => (key) => typeof key === "string" && key.startsWith(token); -const isCSSVariableName = /* @__PURE__ */ checkStringStartsWith("--"); -const startsAsVariableToken = /* @__PURE__ */ checkStringStartsWith("var(--"); -const isCSSVariableToken = (value) => { - const startsWithToken = startsAsVariableToken(value); - if (!startsWithToken) - return false; - return singleCssVariableRegex.test(value.split("/*")[0].trim()); -}; -const singleCssVariableRegex = /var\(--(?:[\w-]+\s*|[\w-]+\s*,(?:\s*[^)(\s]|\s*\((?:[^)(]|\([^)(]*\))*\))+\s*)\)$/iu; -function containsCSSVariable(value) { - if (typeof value !== "string") - return false; - return value.split("/*")[0].includes("var(--"); -} -const number = { - test: (v) => typeof v === "number", - parse: parseFloat, - transform: (v) => v -}; -const alpha = { - ...number, - transform: (v) => clamp(0, 1, v) -}; -const scale = { - ...number, - default: 1 -}; -const sanitize = (v) => Math.round(v * 1e5) / 1e5; -const floatRegex = /-?(?:\d+(?:\.\d+)?|\.\d+)/gu; -function isNullish(v) { - return v == null; -} -const singleColorRegex = /^(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))$/iu; -const isColorString = (type, testProp) => (v) => { - return Boolean(typeof v === "string" && singleColorRegex.test(v) && v.startsWith(type) || testProp && !isNullish(v) && Object.prototype.hasOwnProperty.call(v, testProp)); -}; -const splitColor = (aName, bName, cName) => (v) => { - if (typeof v !== "string") - return v; - const [a, b, c, alpha2] = v.match(floatRegex); - return { - [aName]: parseFloat(a), - [bName]: parseFloat(b), - [cName]: parseFloat(c), - alpha: alpha2 !== void 0 ? parseFloat(alpha2) : 1 - }; -}; -const clampRgbUnit = (v) => clamp(0, 255, v); -const rgbUnit = { - ...number, - transform: (v) => Math.round(clampRgbUnit(v)) -}; -const rgba = { - test: /* @__PURE__ */ isColorString("rgb", "red"), - parse: /* @__PURE__ */ splitColor("red", "green", "blue"), - transform: ({ red, green, blue, alpha: alpha$1 = 1 }) => "rgba(" + rgbUnit.transform(red) + ", " + rgbUnit.transform(green) + ", " + rgbUnit.transform(blue) + ", " + sanitize(alpha.transform(alpha$1)) + ")" -}; -function parseHex(v) { - let r = ""; - let g = ""; - let b = ""; - let a = ""; - if (v.length > 5) { - r = v.substring(1, 3); - g = v.substring(3, 5); - b = v.substring(5, 7); - a = v.substring(7, 9); - } else { - r = v.substring(1, 2); - g = v.substring(2, 3); - b = v.substring(3, 4); - a = v.substring(4, 5); - r += r; - g += g; - b += b; - a += a; - } - return { - red: parseInt(r, 16), - green: parseInt(g, 16), - blue: parseInt(b, 16), - alpha: a ? parseInt(a, 16) / 255 : 1 - }; -} -const hex = { - test: /* @__PURE__ */ isColorString("#"), - parse: parseHex, - transform: rgba.transform -}; -const createUnitType = /* @__NO_SIDE_EFFECTS__ */ (unit) => ({ - test: (v) => typeof v === "string" && v.endsWith(unit) && v.split(" ").length === 1, - parse: parseFloat, - transform: (v) => `${v}${unit}` -}); -const degrees = /* @__PURE__ */ createUnitType("deg"); -const percent = /* @__PURE__ */ createUnitType("%"); -const px = /* @__PURE__ */ createUnitType("px"); -const vh = /* @__PURE__ */ createUnitType("vh"); -const vw = /* @__PURE__ */ createUnitType("vw"); -const progressPercentage = /* @__PURE__ */ (() => ({ - ...percent, - parse: (v) => percent.parse(v) / 100, - transform: (v) => percent.transform(v * 100) -}))(); -const hsla = { - test: /* @__PURE__ */ isColorString("hsl", "hue"), - parse: /* @__PURE__ */ splitColor("hue", "saturation", "lightness"), - transform: ({ hue, saturation, lightness, alpha: alpha$1 = 1 }) => { - return "hsla(" + Math.round(hue) + ", " + percent.transform(sanitize(saturation)) + ", " + percent.transform(sanitize(lightness)) + ", " + sanitize(alpha.transform(alpha$1)) + ")"; - } -}; -const color = { - test: (v) => rgba.test(v) || hex.test(v) || hsla.test(v), - parse: (v) => { - if (rgba.test(v)) { - return rgba.parse(v); - } else if (hsla.test(v)) { - return hsla.parse(v); - } else { - return hex.parse(v); - } - }, - transform: (v) => { - return typeof v === "string" ? v : v.hasOwnProperty("red") ? rgba.transform(v) : hsla.transform(v); - }, - getAnimatableNone: (v) => { - const parsed = color.parse(v); - parsed.alpha = 0; - return color.transform(parsed); - } -}; -const colorRegex = /(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))/giu; -function test(v) { - return isNaN(v) && typeof v === "string" && (v.match(floatRegex)?.length || 0) + (v.match(colorRegex)?.length || 0) > 0; -} -const NUMBER_TOKEN = "number"; -const COLOR_TOKEN = "color"; -const VAR_TOKEN = "var"; -const VAR_FUNCTION_TOKEN = "var("; -const SPLIT_TOKEN = "${}"; -const complexRegex = /var\s*\(\s*--(?:[\w-]+\s*|[\w-]+\s*,(?:\s*[^)(\s]|\s*\((?:[^)(]|\([^)(]*\))*\))+\s*)\)|#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\)|-?(?:\d+(?:\.\d+)?|\.\d+)/giu; -function analyseComplexValue(value) { - const originalValue = value.toString(); - const values = []; - const indexes = { - color: [], - number: [], - var: [] - }; - const types = []; - let i = 0; - const tokenised = originalValue.replace(complexRegex, (parsedValue) => { - if (color.test(parsedValue)) { - indexes.color.push(i); - types.push(COLOR_TOKEN); - values.push(color.parse(parsedValue)); - } else if (parsedValue.startsWith(VAR_FUNCTION_TOKEN)) { - indexes.var.push(i); - types.push(VAR_TOKEN); - values.push(parsedValue); - } else { - indexes.number.push(i); - types.push(NUMBER_TOKEN); - values.push(parseFloat(parsedValue)); - } - ++i; - return SPLIT_TOKEN; - }); - const split = tokenised.split(SPLIT_TOKEN); - return { values, split, indexes, types }; -} -function parseComplexValue(v) { - return analyseComplexValue(v).values; -} -function buildTransformer({ split, types }) { - const numSections = split.length; - return (v) => { - let output = ""; - for (let i = 0; i < numSections; i++) { - output += split[i]; - if (v[i] !== void 0) { - const type = types[i]; - if (type === NUMBER_TOKEN) { - output += sanitize(v[i]); - } else if (type === COLOR_TOKEN) { - output += color.transform(v[i]); - } else { - output += v[i]; - } - } - } - return output; - }; -} -function createTransformer(source) { - return buildTransformer(analyseComplexValue(source)); -} -const convertNumbersToZero = (v) => typeof v === "number" ? 0 : color.test(v) ? color.getAnimatableNone(v) : v; -const convertToZero = (value, splitBefore) => { - if (typeof value === "number") { - return splitBefore?.trim().endsWith("/") ? value : 0; - } - return convertNumbersToZero(value); -}; -function getAnimatableNone$1(v) { - const info = analyseComplexValue(v); - const transformer = buildTransformer(info); - return transformer(info.values.map((value, i) => convertToZero(value, info.split[i]))); -} -const complex = { - test, - parse: parseComplexValue, - createTransformer, - getAnimatableNone: getAnimatableNone$1 -}; -function hueToRgb(p, q, t) { - if (t < 0) - t += 1; - if (t > 1) - t -= 1; - if (t < 1 / 6) - return p + (q - p) * 6 * t; - if (t < 1 / 2) - return q; - if (t < 2 / 3) - return p + (q - p) * (2 / 3 - t) * 6; - return p; -} -function hslaToRgba({ hue, saturation, lightness, alpha: alpha2 }) { - hue /= 360; - saturation /= 100; - lightness /= 100; - let red = 0; - let green = 0; - let blue = 0; - if (!saturation) { - red = green = blue = lightness; - } else { - const q = lightness < 0.5 ? lightness * (1 + saturation) : lightness + saturation - lightness * saturation; - const p = 2 * lightness - q; - red = hueToRgb(p, q, hue + 1 / 3); - green = hueToRgb(p, q, hue); - blue = hueToRgb(p, q, hue - 1 / 3); - } - return { - red: Math.round(red * 255), - green: Math.round(green * 255), - blue: Math.round(blue * 255), - alpha: alpha2 - }; -} -function mixImmediate(a, b) { - return (p) => p > 0 ? b : a; -} -const mixNumber$1 = (from, to, progress2) => { - return from + (to - from) * progress2; -}; -const mixLinearColor = (from, to, v) => { - const fromExpo = from * from; - const expo = v * (to * to - fromExpo) + fromExpo; - return expo < 0 ? 0 : Math.sqrt(expo); -}; -const colorTypes = [hex, rgba, hsla]; -const getColorType = (v) => colorTypes.find((type) => type.test(v)); -function asRGBA(color2) { - const type = getColorType(color2); - warning(Boolean(type), `'${color2}' is not an animatable color. Use the equivalent color code instead.`, "color-not-animatable"); - if (!Boolean(type)) - return false; - let model = type.parse(color2); - if (type === hsla) { - model = hslaToRgba(model); - } - return model; -} -const mixColor = (from, to) => { - const fromRGBA = asRGBA(from); - const toRGBA = asRGBA(to); - if (!fromRGBA || !toRGBA) { - return mixImmediate(from, to); - } - const blended = { ...fromRGBA }; - return (v) => { - blended.red = mixLinearColor(fromRGBA.red, toRGBA.red, v); - blended.green = mixLinearColor(fromRGBA.green, toRGBA.green, v); - blended.blue = mixLinearColor(fromRGBA.blue, toRGBA.blue, v); - blended.alpha = mixNumber$1(fromRGBA.alpha, toRGBA.alpha, v); - return rgba.transform(blended); - }; -}; -const invisibleValues = /* @__PURE__ */ new Set(["none", "hidden"]); -function mixVisibility(origin, target) { - if (invisibleValues.has(origin)) { - return (p) => p <= 0 ? origin : target; - } else { - return (p) => p >= 1 ? target : origin; - } -} -function mixNumber(a, b) { - return (p) => mixNumber$1(a, b, p); -} -function getMixer(a) { - if (typeof a === "number") { - return mixNumber; - } else if (typeof a === "string") { - return isCSSVariableToken(a) ? mixImmediate : color.test(a) ? mixColor : mixComplex; - } else if (Array.isArray(a)) { - return mixArray; - } else if (typeof a === "object") { - return color.test(a) ? mixColor : mixObject; - } - return mixImmediate; -} -function mixArray(a, b) { - const output = [...a]; - const numValues = output.length; - const blendValue = a.map((v, i) => getMixer(v)(v, b[i])); - return (p) => { - for (let i = 0; i < numValues; i++) { - output[i] = blendValue[i](p); - } - return output; - }; -} -function mixObject(a, b) { - const output = { ...a, ...b }; - const blendValue = {}; - for (const key in output) { - if (a[key] !== void 0 && b[key] !== void 0) { - blendValue[key] = getMixer(a[key])(a[key], b[key]); - } - } - return (v) => { - for (const key in blendValue) { - output[key] = blendValue[key](v); - } - return output; - }; -} -function matchOrder(origin, target) { - const orderedOrigin = []; - const pointers = { color: 0, var: 0, number: 0 }; - for (let i = 0; i < target.values.length; i++) { - const type = target.types[i]; - const originIndex = origin.indexes[type][pointers[type]]; - const originValue = origin.values[originIndex] ?? 0; - orderedOrigin[i] = originValue; - pointers[type]++; - } - return orderedOrigin; -} -const mixComplex = (origin, target) => { - const template = complex.createTransformer(target); - const originStats = analyseComplexValue(origin); - const targetStats = analyseComplexValue(target); - const canInterpolate = originStats.indexes.var.length === targetStats.indexes.var.length && originStats.indexes.color.length === targetStats.indexes.color.length && originStats.indexes.number.length >= targetStats.indexes.number.length; - if (canInterpolate) { - if (invisibleValues.has(origin) && !targetStats.values.length || invisibleValues.has(target) && !originStats.values.length) { - return mixVisibility(origin, target); - } - return pipe(mixArray(matchOrder(originStats, targetStats), targetStats.values), template); - } else { - warning(true, `Complex values '${origin}' and '${target}' too different to mix. Ensure all colors are of the same type, and that each contains the same quantity of number and color values. Falling back to instant transition.`, "complex-values-different"); - return mixImmediate(origin, target); - } -}; -function mix(from, to, p) { - if (typeof from === "number" && typeof to === "number" && typeof p === "number") { - return mixNumber$1(from, to, p); - } - const mixer = getMixer(from); - return mixer(from, to); -} -const frameloopDriver = (update) => { - const passTimestamp = ({ timestamp }) => update(timestamp); - return { - start: (keepAlive = true) => frame.update(passTimestamp, keepAlive), - stop: () => cancelFrame(passTimestamp), - /** - * If we're processing this frame we can use the - * framelocked timestamp to keep things in sync. - */ - now: () => frameData.isProcessing ? frameData.timestamp : time.now() - }; -}; -const generateLinearEasing = (easing, duration, resolution = 10) => { - let points = ""; - const numPoints = Math.max(Math.round(duration / resolution), 2); - for (let i = 0; i < numPoints; i++) { - points += Math.round(easing(i / (numPoints - 1)) * 1e4) / 1e4 + ", "; - } - return `linear(${points.substring(0, points.length - 2)})`; -}; -const maxGeneratorDuration = 2e4; -function calcGeneratorDuration(generator) { - let duration = 0; - const timeStep = 50; - let state = generator.next(duration); - while (!state.done && duration < maxGeneratorDuration) { - duration += timeStep; - state = generator.next(duration); - } - return duration >= maxGeneratorDuration ? Infinity : duration; -} -function createGeneratorEasing(options, scale2 = 100, createGenerator) { - const generator = createGenerator({ ...options, keyframes: [0, scale2] }); - const duration = Math.min(calcGeneratorDuration(generator), maxGeneratorDuration); - return { - type: "keyframes", - ease: (progress2) => { - return generator.next(duration * progress2).value / scale2; - }, - duration: /* @__PURE__ */ millisecondsToSeconds(duration) - }; -} -const springDefaults = { - // Default spring physics - stiffness: 100, - damping: 10, - mass: 1, - velocity: 0, - // Default duration/bounce-based options - duration: 800, - // in ms - bounce: 0.3, - visualDuration: 0.3, - // in seconds - // Rest thresholds - restSpeed: { - granular: 0.01, - default: 2 - }, - restDelta: { - granular: 5e-3, - default: 0.5 - }, - // Limits - minDuration: 0.01, - // in seconds - maxDuration: 10, - // in seconds - minDamping: 0.05, - maxDamping: 1 -}; -function calcAngularFreq(undampedFreq, dampingRatio) { - return undampedFreq * Math.sqrt(1 - dampingRatio * dampingRatio); -} -const rootIterations = 12; -function approximateRoot(envelope, derivative, initialGuess) { - let result = initialGuess; - for (let i = 1; i < rootIterations; i++) { - result = result - envelope(result) / derivative(result); - } - return result; -} -const safeMin = 1e-3; -function findSpring({ duration = springDefaults.duration, bounce = springDefaults.bounce, velocity = springDefaults.velocity, mass = springDefaults.mass }) { - let envelope; - let derivative; - warning(duration <= /* @__PURE__ */ secondsToMilliseconds(springDefaults.maxDuration), "Spring duration must be 10 seconds or less", "spring-duration-limit"); - let dampingRatio = 1 - bounce; - dampingRatio = clamp(springDefaults.minDamping, springDefaults.maxDamping, dampingRatio); - duration = clamp(springDefaults.minDuration, springDefaults.maxDuration, /* @__PURE__ */ millisecondsToSeconds(duration)); - if (dampingRatio < 1) { - envelope = (undampedFreq2) => { - const exponentialDecay = undampedFreq2 * dampingRatio; - const delta = exponentialDecay * duration; - const a = exponentialDecay - velocity; - const b = calcAngularFreq(undampedFreq2, dampingRatio); - const c = Math.exp(-delta); - return safeMin - a / b * c; - }; - derivative = (undampedFreq2) => { - const exponentialDecay = undampedFreq2 * dampingRatio; - const delta = exponentialDecay * duration; - const d = delta * velocity + velocity; - const e = Math.pow(dampingRatio, 2) * Math.pow(undampedFreq2, 2) * duration; - const f = Math.exp(-delta); - const g = calcAngularFreq(Math.pow(undampedFreq2, 2), dampingRatio); - const factor = -envelope(undampedFreq2) + safeMin > 0 ? -1 : 1; - return factor * ((d - e) * f) / g; - }; - } else { - envelope = (undampedFreq2) => { - const a = Math.exp(-undampedFreq2 * duration); - const b = (undampedFreq2 - velocity) * duration + 1; - return -safeMin + a * b; - }; - derivative = (undampedFreq2) => { - const a = Math.exp(-undampedFreq2 * duration); - const b = (velocity - undampedFreq2) * (duration * duration); - return a * b; - }; - } - const initialGuess = 5 / duration; - const undampedFreq = approximateRoot(envelope, derivative, initialGuess); - duration = /* @__PURE__ */ secondsToMilliseconds(duration); - if (isNaN(undampedFreq)) { - return { - stiffness: springDefaults.stiffness, - damping: springDefaults.damping, - duration - }; - } else { - const stiffness = Math.pow(undampedFreq, 2) * mass; - return { - stiffness, - damping: dampingRatio * 2 * Math.sqrt(mass * stiffness), - duration - }; - } -} -const durationKeys = ["duration", "bounce"]; -const physicsKeys = ["stiffness", "damping", "mass"]; -function isSpringType(options, keys) { - return keys.some((key) => options[key] !== void 0); -} -function getSpringOptions(options) { - let springOptions = { - velocity: springDefaults.velocity, - stiffness: springDefaults.stiffness, - damping: springDefaults.damping, - mass: springDefaults.mass, - isResolvedFromDuration: false, - ...options - }; - if (!isSpringType(options, physicsKeys) && isSpringType(options, durationKeys)) { - springOptions.velocity = 0; - if (options.visualDuration) { - const visualDuration = options.visualDuration; - const root = 2 * Math.PI / (visualDuration * 1.2); - const stiffness = root * root; - const damping = 2 * clamp(0.05, 1, 1 - (options.bounce || 0)) * Math.sqrt(stiffness); - springOptions = { - ...springOptions, - mass: springDefaults.mass, - stiffness, - damping - }; - } else { - const derived = findSpring({ ...options, velocity: 0 }); - springOptions = { - ...springOptions, - ...derived, - mass: springDefaults.mass - }; - springOptions.isResolvedFromDuration = true; - } - } - return springOptions; -} -function spring(optionsOrVisualDuration = springDefaults.visualDuration, bounce = springDefaults.bounce) { - const options = typeof optionsOrVisualDuration !== "object" ? { - visualDuration: optionsOrVisualDuration, - keyframes: [0, 1], - bounce - } : optionsOrVisualDuration; - let { restSpeed, restDelta } = options; - const origin = options.keyframes[0]; - const target = options.keyframes[options.keyframes.length - 1]; - const state = { done: false, value: origin }; - const { stiffness, damping, mass, duration, velocity, isResolvedFromDuration } = getSpringOptions({ - ...options, - velocity: -/* @__PURE__ */ millisecondsToSeconds(options.velocity || 0) - }); - const initialVelocity = velocity || 0; - const dampingRatio = damping / (2 * Math.sqrt(stiffness * mass)); - const initialDelta = target - origin; - const undampedAngularFreq = /* @__PURE__ */ millisecondsToSeconds(Math.sqrt(stiffness / mass)); - const isGranularScale = Math.abs(initialDelta) < 5; - restSpeed || (restSpeed = isGranularScale ? springDefaults.restSpeed.granular : springDefaults.restSpeed.default); - restDelta || (restDelta = isGranularScale ? springDefaults.restDelta.granular : springDefaults.restDelta.default); - let resolveSpring; - let resolveVelocity; - let angularFreq; - let A; - let sinCoeff; - let cosCoeff; - if (dampingRatio < 1) { - angularFreq = calcAngularFreq(undampedAngularFreq, dampingRatio); - A = (initialVelocity + dampingRatio * undampedAngularFreq * initialDelta) / angularFreq; - resolveSpring = (t) => { - const envelope = Math.exp(-dampingRatio * undampedAngularFreq * t); - return target - envelope * (A * Math.sin(angularFreq * t) + initialDelta * Math.cos(angularFreq * t)); - }; - sinCoeff = dampingRatio * undampedAngularFreq * A + initialDelta * angularFreq; - cosCoeff = dampingRatio * undampedAngularFreq * initialDelta - A * angularFreq; - resolveVelocity = (t) => { - const envelope = Math.exp(-dampingRatio * undampedAngularFreq * t); - return envelope * (sinCoeff * Math.sin(angularFreq * t) + cosCoeff * Math.cos(angularFreq * t)); - }; - } else if (dampingRatio === 1) { - resolveSpring = (t) => target - Math.exp(-undampedAngularFreq * t) * (initialDelta + (initialVelocity + undampedAngularFreq * initialDelta) * t); - const C = initialVelocity + undampedAngularFreq * initialDelta; - resolveVelocity = (t) => Math.exp(-undampedAngularFreq * t) * (undampedAngularFreq * C * t - initialVelocity); - } else { - const dampedAngularFreq = undampedAngularFreq * Math.sqrt(dampingRatio * dampingRatio - 1); - resolveSpring = (t) => { - const envelope = Math.exp(-dampingRatio * undampedAngularFreq * t); - const freqForT = Math.min(dampedAngularFreq * t, 300); - return target - envelope * ((initialVelocity + dampingRatio * undampedAngularFreq * initialDelta) * Math.sinh(freqForT) + dampedAngularFreq * initialDelta * Math.cosh(freqForT)) / dampedAngularFreq; - }; - const P = (initialVelocity + dampingRatio * undampedAngularFreq * initialDelta) / dampedAngularFreq; - const sinhCoeff = dampingRatio * undampedAngularFreq * P - initialDelta * dampedAngularFreq; - const coshCoeff = dampingRatio * undampedAngularFreq * initialDelta - P * dampedAngularFreq; - resolveVelocity = (t) => { - const envelope = Math.exp(-dampingRatio * undampedAngularFreq * t); - const freqForT = Math.min(dampedAngularFreq * t, 300); - return envelope * (sinhCoeff * Math.sinh(freqForT) + coshCoeff * Math.cosh(freqForT)); - }; - } - const generator = { - calculatedDuration: isResolvedFromDuration ? duration || null : null, - velocity: (t) => /* @__PURE__ */ secondsToMilliseconds(resolveVelocity(t)), - next: (t) => { - if (!isResolvedFromDuration && dampingRatio < 1) { - const envelope = Math.exp(-dampingRatio * undampedAngularFreq * t); - const sin = Math.sin(angularFreq * t); - const cos = Math.cos(angularFreq * t); - const current2 = target - envelope * (A * sin + initialDelta * cos); - const currentVelocity = /* @__PURE__ */ secondsToMilliseconds(envelope * (sinCoeff * sin + cosCoeff * cos)); - state.done = Math.abs(currentVelocity) <= restSpeed && Math.abs(target - current2) <= restDelta; - state.value = state.done ? target : current2; - return state; - } - const current = resolveSpring(t); - if (!isResolvedFromDuration) { - const currentVelocity = /* @__PURE__ */ secondsToMilliseconds(resolveVelocity(t)); - state.done = Math.abs(currentVelocity) <= restSpeed && Math.abs(target - current) <= restDelta; - } else { - state.done = t >= duration; - } - state.value = state.done ? target : current; - return state; - }, - toString: () => { - const calculatedDuration = Math.min(calcGeneratorDuration(generator), maxGeneratorDuration); - const easing = generateLinearEasing((progress2) => generator.next(calculatedDuration * progress2).value, calculatedDuration, 30); - return calculatedDuration + "ms " + easing; - }, - toTransition: () => { - } - }; - return generator; -} -spring.applyToOptions = (options) => { - const generatorOptions = createGeneratorEasing(options, 100, spring); - options.ease = generatorOptions.ease; - options.duration = /* @__PURE__ */ secondsToMilliseconds(generatorOptions.duration); - options.type = "keyframes"; - return options; -}; -const velocitySampleDuration = 5; -function getGeneratorVelocity(resolveValue, t, current) { - const prevT = Math.max(t - velocitySampleDuration, 0); - return velocityPerSecond(current - resolveValue(prevT), t - prevT); -} -function inertia({ keyframes: keyframes2, velocity = 0, power = 0.8, timeConstant = 325, bounceDamping = 10, bounceStiffness = 500, modifyTarget, min, max, restDelta = 0.5, restSpeed }) { - const origin = keyframes2[0]; - const state = { - done: false, - value: origin - }; - const isOutOfBounds = (v) => min !== void 0 && v < min || max !== void 0 && v > max; - const nearestBoundary = (v) => { - if (min === void 0) - return max; - if (max === void 0) - return min; - return Math.abs(min - v) < Math.abs(max - v) ? min : max; - }; - let amplitude = power * velocity; - const ideal = origin + amplitude; - const target = modifyTarget === void 0 ? ideal : modifyTarget(ideal); - if (target !== ideal) - amplitude = target - origin; - const calcDelta = (t) => -amplitude * Math.exp(-t / timeConstant); - const calcLatest = (t) => target + calcDelta(t); - const applyFriction = (t) => { - const delta = calcDelta(t); - const latest = calcLatest(t); - state.done = Math.abs(delta) <= restDelta; - state.value = state.done ? target : latest; - }; - let timeReachedBoundary; - let spring$1; - const checkCatchBoundary = (t) => { - if (!isOutOfBounds(state.value)) - return; - timeReachedBoundary = t; - spring$1 = spring({ - keyframes: [state.value, nearestBoundary(state.value)], - velocity: getGeneratorVelocity(calcLatest, t, state.value), - // TODO: This should be passing * 1000 - damping: bounceDamping, - stiffness: bounceStiffness, - restDelta, - restSpeed - }); - }; - checkCatchBoundary(0); - return { - calculatedDuration: null, - next: (t) => { - let hasUpdatedFrame = false; - if (!spring$1 && timeReachedBoundary === void 0) { - hasUpdatedFrame = true; - applyFriction(t); - checkCatchBoundary(t); - } - if (timeReachedBoundary !== void 0 && t >= timeReachedBoundary) { - return spring$1.next(t - timeReachedBoundary); - } else { - !hasUpdatedFrame && applyFriction(t); - return state; - } - } - }; -} -function createMixers(output, ease2, customMixer) { - const mixers = []; - const mixerFactory = customMixer || MotionGlobalConfig.mix || mix; - const numMixers = output.length - 1; - for (let i = 0; i < numMixers; i++) { - let mixer = mixerFactory(output[i], output[i + 1]); - if (ease2) { - const easingFunction = Array.isArray(ease2) ? ease2[i] || noop : ease2; - mixer = pipe(easingFunction, mixer); - } - mixers.push(mixer); - } - return mixers; -} -function interpolate(input, output, { clamp: isClamp = true, ease: ease2, mixer } = {}) { - const inputLength = input.length; - invariant(inputLength === output.length, "Both input and output ranges must be the same length", "range-length"); - if (inputLength === 1) - return () => output[0]; - if (inputLength === 2 && output[0] === output[1]) - return () => output[1]; - const isZeroDeltaRange = input[0] === input[1]; - if (input[0] > input[inputLength - 1]) { - input = [...input].reverse(); - output = [...output].reverse(); - } - const mixers = createMixers(output, ease2, mixer); - const numMixers = mixers.length; - const interpolator = (v) => { - if (isZeroDeltaRange && v < input[0]) - return output[0]; - let i = 0; - if (numMixers > 1) { - for (; i < input.length - 2; i++) { - if (v < input[i + 1]) - break; - } - } - const progressInRange = /* @__PURE__ */ progress(input[i], input[i + 1], v); - return mixers[i](progressInRange); - }; - return isClamp ? (v) => interpolator(clamp(input[0], input[inputLength - 1], v)) : interpolator; -} -function fillOffset(offset, remaining) { - const min = offset[offset.length - 1]; - for (let i = 1; i <= remaining; i++) { - const offsetProgress = /* @__PURE__ */ progress(0, remaining, i); - offset.push(mixNumber$1(min, 1, offsetProgress)); - } -} -function defaultOffset(arr) { - const offset = [0]; - fillOffset(offset, arr.length - 1); - return offset; -} -function convertOffsetToTimes(offset, duration) { - return offset.map((o) => o * duration); -} -function defaultEasing(values, easing) { - return values.map(() => easing || easeInOut).splice(0, values.length - 1); -} -function keyframes({ duration = 300, keyframes: keyframeValues, times, ease: ease2 = "easeInOut" }) { - const easingFunctions = isEasingArray(ease2) ? ease2.map(easingDefinitionToFunction) : easingDefinitionToFunction(ease2); - const state = { - done: false, - value: keyframeValues[0] - }; - const absoluteTimes = convertOffsetToTimes( - // Only use the provided offsets if they're the correct length - // TODO Maybe we should warn here if there's a length mismatch - times && times.length === keyframeValues.length ? times : defaultOffset(keyframeValues), - duration - ); - const mapTimeToKeyframe = interpolate(absoluteTimes, keyframeValues, { - ease: Array.isArray(easingFunctions) ? easingFunctions : defaultEasing(keyframeValues, easingFunctions) - }); - return { - calculatedDuration: duration, - next: (t) => { - state.value = mapTimeToKeyframe(t); - state.done = t >= duration; - return state; - } - }; -} -const isNotNull = (value) => value !== null; -function getFinalKeyframe(keyframes2, { repeat, repeatType = "loop" }, finalKeyframe, speed = 1) { - const resolvedKeyframes = keyframes2.filter(isNotNull); - const useFirstKeyframe = speed < 0 || repeat && repeatType !== "loop" && repeat % 2 === 1; - const index = useFirstKeyframe ? 0 : resolvedKeyframes.length - 1; - return !index || finalKeyframe === void 0 ? resolvedKeyframes[index] : finalKeyframe; -} -const transitionTypeMap = { - decay: inertia, - inertia, - tween: keyframes, - keyframes, - spring -}; -function replaceTransitionType(transition) { - if (typeof transition.type === "string") { - transition.type = transitionTypeMap[transition.type]; - } -} -class WithPromise { - constructor() { - this.updateFinished(); - } - get finished() { - return this._finished; - } - updateFinished() { - this._finished = new Promise((resolve) => { - this.resolve = resolve; - }); - } - notifyFinished() { - this.resolve(); - } - /** - * Allows the animation to be awaited. - * - * @deprecated Use `finished` instead. - */ - then(onResolve, onReject) { - return this.finished.then(onResolve, onReject); - } -} -const percentToProgress = (percent2) => percent2 / 100; -class JSAnimation extends WithPromise { - constructor(options) { - super(); - this.state = "idle"; - this.startTime = null; - this.isStopped = false; - this.currentTime = 0; - this.holdTime = null; - this.playbackSpeed = 1; - this.delayState = { - done: false, - value: void 0 - }; - this.stop = () => { - const { motionValue: motionValue2 } = this.options; - if (motionValue2 && motionValue2.updatedAt !== time.now()) { - this.tick(time.now()); - } - this.isStopped = true; - if (this.state === "idle") - return; - this.teardown(); - this.options.onStop?.(); - }; - this.options = options; - this.initAnimation(); - this.play(); - if (options.autoplay === false) - this.pause(); - } - initAnimation() { - const { options } = this; - replaceTransitionType(options); - const { type = keyframes, repeat = 0, repeatDelay = 0, repeatType, velocity = 0 } = options; - let { keyframes: keyframes$1 } = options; - const generatorFactory = type || keyframes; - if (process.env.NODE_ENV !== "production" && generatorFactory !== keyframes) { - invariant(keyframes$1.length <= 2, `Only two keyframes currently supported with spring and inertia animations. Trying to animate ${keyframes$1}`, "spring-two-frames"); - } - if (generatorFactory !== keyframes && typeof keyframes$1[0] !== "number") { - this.mixKeyframes = pipe(percentToProgress, mix(keyframes$1[0], keyframes$1[1])); - keyframes$1 = [0, 100]; - } - const generator = generatorFactory({ ...options, keyframes: keyframes$1 }); - if (repeatType === "mirror") { - this.mirroredGenerator = generatorFactory({ - ...options, - keyframes: [...keyframes$1].reverse(), - velocity: -velocity - }); - } - if (generator.calculatedDuration === null) { - generator.calculatedDuration = calcGeneratorDuration(generator); - } - const { calculatedDuration } = generator; - this.calculatedDuration = calculatedDuration; - this.resolvedDuration = calculatedDuration + repeatDelay; - this.totalDuration = this.resolvedDuration * (repeat + 1) - repeatDelay; - this.generator = generator; - } - updateTime(timestamp) { - const animationTime = Math.round(timestamp - this.startTime) * this.playbackSpeed; - if (this.holdTime !== null) { - this.currentTime = this.holdTime; - } else { - this.currentTime = animationTime; - } - } - tick(timestamp, sample = false) { - const { generator, totalDuration, mixKeyframes, mirroredGenerator, resolvedDuration, calculatedDuration } = this; - if (this.startTime === null) - return generator.next(0); - const { delay: delay2 = 0, keyframes: keyframes2, repeat, repeatType, repeatDelay, type, onUpdate, finalKeyframe } = this.options; - if (this.speed > 0) { - this.startTime = Math.min(this.startTime, timestamp); - } else if (this.speed < 0) { - this.startTime = Math.min(timestamp - totalDuration / this.speed, this.startTime); - } - if (sample) { - this.currentTime = timestamp; - } else { - this.updateTime(timestamp); - } - const timeWithoutDelay = this.currentTime - delay2 * (this.playbackSpeed >= 0 ? 1 : -1); - const isInDelayPhase = this.playbackSpeed >= 0 ? timeWithoutDelay < 0 : timeWithoutDelay > totalDuration; - this.currentTime = Math.max(timeWithoutDelay, 0); - if (this.state === "finished" && this.holdTime === null) { - this.currentTime = totalDuration; - } - let elapsed = this.currentTime; - let frameGenerator = generator; - if (repeat) { - const progress2 = Math.min(this.currentTime, totalDuration) / resolvedDuration; - let currentIteration = Math.floor(progress2); - let iterationProgress = progress2 % 1; - if (!iterationProgress && progress2 >= 1) { - iterationProgress = 1; - } - iterationProgress === 1 && currentIteration--; - currentIteration = Math.min(currentIteration, repeat + 1); - const isOddIteration = Boolean(currentIteration % 2); - if (isOddIteration) { - if (repeatType === "reverse") { - iterationProgress = 1 - iterationProgress; - if (repeatDelay) { - iterationProgress -= repeatDelay / resolvedDuration; - } - } else if (repeatType === "mirror") { - frameGenerator = mirroredGenerator; - } - } - elapsed = clamp(0, 1, iterationProgress) * resolvedDuration; - } - let state; - if (isInDelayPhase) { - this.delayState.value = keyframes2[0]; - state = this.delayState; - } else { - state = frameGenerator.next(elapsed); - } - if (mixKeyframes && !isInDelayPhase) { - state.value = mixKeyframes(state.value); - } - let { done } = state; - if (!isInDelayPhase && calculatedDuration !== null) { - done = this.playbackSpeed >= 0 ? this.currentTime >= totalDuration : this.currentTime <= 0; - } - const isAnimationFinished = this.holdTime === null && (this.state === "finished" || this.state === "running" && done); - if (isAnimationFinished && type !== inertia) { - state.value = getFinalKeyframe(keyframes2, this.options, finalKeyframe, this.speed); - } - if (onUpdate) { - onUpdate(state.value); - } - if (isAnimationFinished) { - this.finish(); - } - return state; - } - /** - * Allows the returned animation to be awaited or promise-chained. Currently - * resolves when the animation finishes at all but in a future update could/should - * reject if its cancels. - */ - then(resolve, reject) { - return this.finished.then(resolve, reject); - } - get duration() { - return /* @__PURE__ */ millisecondsToSeconds(this.calculatedDuration); - } - get iterationDuration() { - const { delay: delay2 = 0 } = this.options || {}; - return this.duration + /* @__PURE__ */ millisecondsToSeconds(delay2); - } - get time() { - return /* @__PURE__ */ millisecondsToSeconds(this.currentTime); - } - set time(newTime) { - newTime = /* @__PURE__ */ secondsToMilliseconds(newTime); - this.currentTime = newTime; - if (this.startTime === null || this.holdTime !== null || this.playbackSpeed === 0) { - this.holdTime = newTime; - } else if (this.driver) { - this.startTime = this.driver.now() - newTime / this.playbackSpeed; - } - if (this.driver) { - this.driver.start(false); - } else { - this.startTime = 0; - this.state = "paused"; - this.holdTime = newTime; - this.tick(newTime); - } - } - /** - * Returns the generator's velocity at the current time in units/second. - * Uses the analytical derivative when available (springs), avoiding - * the MotionValue's frame-dependent velocity estimation. - */ - getGeneratorVelocity() { - const t = this.currentTime; - if (t <= 0) - return this.options.velocity || 0; - if (this.generator.velocity) { - return this.generator.velocity(t); - } - const current = this.generator.next(t).value; - return getGeneratorVelocity((s) => this.generator.next(s).value, t, current); - } - get speed() { - return this.playbackSpeed; - } - set speed(newSpeed) { - const hasChanged = this.playbackSpeed !== newSpeed; - if (hasChanged && this.driver) { - this.updateTime(time.now()); - } - this.playbackSpeed = newSpeed; - if (hasChanged && this.driver) { - this.time = /* @__PURE__ */ millisecondsToSeconds(this.currentTime); - } - } - play() { - if (this.isStopped) - return; - const { driver = frameloopDriver, startTime } = this.options; - if (!this.driver) { - this.driver = driver((timestamp) => this.tick(timestamp)); - } - this.options.onPlay?.(); - const now2 = this.driver.now(); - if (this.state === "finished") { - this.updateFinished(); - this.startTime = now2; - } else if (this.holdTime !== null) { - this.startTime = now2 - this.holdTime; - } else if (!this.startTime) { - this.startTime = startTime ?? now2; - } - if (this.state === "finished" && this.speed < 0) { - this.startTime += this.calculatedDuration; - } - this.holdTime = null; - this.state = "running"; - this.driver.start(); - } - pause() { - this.state = "paused"; - this.updateTime(time.now()); - this.holdTime = this.currentTime; - } - complete() { - if (this.state !== "running") { - this.play(); - } - this.state = "finished"; - this.holdTime = null; - } - finish() { - this.notifyFinished(); - this.teardown(); - this.state = "finished"; - this.options.onComplete?.(); - } - cancel() { - this.holdTime = null; - this.startTime = 0; - this.tick(0); - this.teardown(); - this.options.onCancel?.(); - } - teardown() { - this.state = "idle"; - this.stopDriver(); - this.startTime = this.holdTime = null; - } - stopDriver() { - if (!this.driver) - return; - this.driver.stop(); - this.driver = void 0; - } - sample(sampleTime) { - this.startTime = 0; - return this.tick(sampleTime, true); - } - attachTimeline(timeline) { - if (this.options.allowFlatten) { - this.options.type = "keyframes"; - this.options.ease = "linear"; - this.initAnimation(); - } - this.driver?.stop(); - return timeline.observe(this); - } -} -function fillWildcards(keyframes2) { - for (let i = 1; i < keyframes2.length; i++) { - keyframes2[i] ?? (keyframes2[i] = keyframes2[i - 1]); - } -} -const radToDeg = (rad) => rad * 180 / Math.PI; -const rotate = (v) => { - const angle = radToDeg(Math.atan2(v[1], v[0])); - return rebaseAngle(angle); -}; -const matrix2dParsers = { - x: 4, - y: 5, - translateX: 4, - translateY: 5, - scaleX: 0, - scaleY: 3, - scale: (v) => (Math.abs(v[0]) + Math.abs(v[3])) / 2, - rotate, - rotateZ: rotate, - skewX: (v) => radToDeg(Math.atan(v[1])), - skewY: (v) => radToDeg(Math.atan(v[2])), - skew: (v) => (Math.abs(v[1]) + Math.abs(v[2])) / 2 -}; -const rebaseAngle = (angle) => { - angle = angle % 360; - if (angle < 0) - angle += 360; - return angle; -}; -const rotateZ = rotate; -const scaleX = (v) => Math.sqrt(v[0] * v[0] + v[1] * v[1]); -const scaleY = (v) => Math.sqrt(v[4] * v[4] + v[5] * v[5]); -const matrix3dParsers = { - x: 12, - y: 13, - z: 14, - translateX: 12, - translateY: 13, - translateZ: 14, - scaleX, - scaleY, - scale: (v) => (scaleX(v) + scaleY(v)) / 2, - rotateX: (v) => rebaseAngle(radToDeg(Math.atan2(v[6], v[5]))), - rotateY: (v) => rebaseAngle(radToDeg(Math.atan2(-v[2], v[0]))), - rotateZ, - rotate: rotateZ, - skewX: (v) => radToDeg(Math.atan(v[4])), - skewY: (v) => radToDeg(Math.atan(v[1])), - skew: (v) => (Math.abs(v[1]) + Math.abs(v[4])) / 2 -}; -function defaultTransformValue(name) { - return name.includes("scale") ? 1 : 0; -} -function parseValueFromTransform(transform, name) { - if (!transform || transform === "none") { - return defaultTransformValue(name); - } - const matrix3dMatch = transform.match(/^matrix3d\(([-\d.e\s,]+)\)$/u); - let parsers; - let match; - if (matrix3dMatch) { - parsers = matrix3dParsers; - match = matrix3dMatch; - } else { - const matrix2dMatch = transform.match(/^matrix\(([-\d.e\s,]+)\)$/u); - parsers = matrix2dParsers; - match = matrix2dMatch; - } - if (!match) { - return defaultTransformValue(name); - } - const valueParser = parsers[name]; - const values = match[1].split(",").map(convertTransformToNumber); - return typeof valueParser === "function" ? valueParser(values) : values[valueParser]; -} -const readTransformValue = (instance, name) => { - const { transform = "none" } = getComputedStyle(instance); - return parseValueFromTransform(transform, name); -}; -function convertTransformToNumber(value) { - return parseFloat(value.trim()); -} -const transformPropOrder = [ - "transformPerspective", - "x", - "y", - "z", - "translateX", - "translateY", - "translateZ", - "scale", - "scaleX", - "scaleY", - "rotate", - "rotateX", - "rotateY", - "rotateZ", - "skew", - "skewX", - "skewY" -]; -const transformProps = /* @__PURE__ */ (() => new Set(transformPropOrder))(); -const isNumOrPxType = (v) => v === number || v === px; -const transformKeys = /* @__PURE__ */ new Set(["x", "y", "z"]); -const nonTranslationalTransformKeys = transformPropOrder.filter((key) => !transformKeys.has(key)); -function removeNonTranslationalTransform(visualElement) { - const removedTransforms = []; - nonTranslationalTransformKeys.forEach((key) => { - const value = visualElement.getValue(key); - if (value !== void 0) { - removedTransforms.push([key, value.get()]); - value.set(key.startsWith("scale") ? 1 : 0); - } - }); - return removedTransforms; -} -const positionalValues = { - // Dimensions - width: ({ x }, { paddingLeft = "0", paddingRight = "0", boxSizing }) => { - const width = x.max - x.min; - return boxSizing === "border-box" ? width : width - parseFloat(paddingLeft) - parseFloat(paddingRight); - }, - height: ({ y }, { paddingTop = "0", paddingBottom = "0", boxSizing }) => { - const height = y.max - y.min; - return boxSizing === "border-box" ? height : height - parseFloat(paddingTop) - parseFloat(paddingBottom); - }, - top: (_bbox, { top }) => parseFloat(top), - left: (_bbox, { left }) => parseFloat(left), - bottom: ({ y }, { top }) => parseFloat(top) + (y.max - y.min), - right: ({ x }, { left }) => parseFloat(left) + (x.max - x.min), - // Transform - x: (_bbox, { transform }) => parseValueFromTransform(transform, "x"), - y: (_bbox, { transform }) => parseValueFromTransform(transform, "y") -}; -positionalValues.translateX = positionalValues.x; -positionalValues.translateY = positionalValues.y; -const toResolve = /* @__PURE__ */ new Set(); -let isScheduled = false; -let anyNeedsMeasurement = false; -let isForced = false; -function measureAllKeyframes() { - if (anyNeedsMeasurement) { - const resolversToMeasure = Array.from(toResolve).filter((resolver) => resolver.needsMeasurement); - const elementsToMeasure = new Set(resolversToMeasure.map((resolver) => resolver.element)); - const transformsToRestore = /* @__PURE__ */ new Map(); - elementsToMeasure.forEach((element) => { - const removedTransforms = removeNonTranslationalTransform(element); - if (!removedTransforms.length) - return; - transformsToRestore.set(element, removedTransforms); - element.render(); - }); - resolversToMeasure.forEach((resolver) => resolver.measureInitialState()); - elementsToMeasure.forEach((element) => { - element.render(); - const restore = transformsToRestore.get(element); - if (restore) { - restore.forEach(([key, value]) => { - element.getValue(key)?.set(value); - }); - } - }); - resolversToMeasure.forEach((resolver) => resolver.measureEndState()); - resolversToMeasure.forEach((resolver) => { - if (resolver.suspendedScrollY !== void 0) { - window.scrollTo(0, resolver.suspendedScrollY); - } - }); - } - anyNeedsMeasurement = false; - isScheduled = false; - toResolve.forEach((resolver) => resolver.complete(isForced)); - toResolve.clear(); -} -function readAllKeyframes() { - toResolve.forEach((resolver) => { - resolver.readKeyframes(); - if (resolver.needsMeasurement) { - anyNeedsMeasurement = true; - } - }); -} -function flushKeyframeResolvers() { - isForced = true; - readAllKeyframes(); - measureAllKeyframes(); - isForced = false; -} -class KeyframeResolver { - constructor(unresolvedKeyframes, onComplete, name, motionValue2, element, isAsync = false) { - this.state = "pending"; - this.isAsync = false; - this.needsMeasurement = false; - this.unresolvedKeyframes = [...unresolvedKeyframes]; - this.onComplete = onComplete; - this.name = name; - this.motionValue = motionValue2; - this.element = element; - this.isAsync = isAsync; - } - scheduleResolve() { - this.state = "scheduled"; - if (this.isAsync) { - toResolve.add(this); - if (!isScheduled) { - isScheduled = true; - frame.read(readAllKeyframes); - frame.resolveKeyframes(measureAllKeyframes); - } - } else { - this.readKeyframes(); - this.complete(); - } - } - readKeyframes() { - const { unresolvedKeyframes, name, element, motionValue: motionValue2 } = this; - if (unresolvedKeyframes[0] === null) { - const currentValue = motionValue2?.get(); - const finalKeyframe = unresolvedKeyframes[unresolvedKeyframes.length - 1]; - if (currentValue !== void 0) { - unresolvedKeyframes[0] = currentValue; - } else if (element && name) { - const valueAsRead = element.readValue(name, finalKeyframe); - if (valueAsRead !== void 0 && valueAsRead !== null) { - unresolvedKeyframes[0] = valueAsRead; - } - } - if (unresolvedKeyframes[0] === void 0) { - unresolvedKeyframes[0] = finalKeyframe; - } - if (motionValue2 && currentValue === void 0) { - motionValue2.set(unresolvedKeyframes[0]); - } - } - fillWildcards(unresolvedKeyframes); - } - setFinalKeyframe() { - } - measureInitialState() { - } - renderEndStyles() { - } - measureEndState() { - } - complete(isForcedComplete = false) { - this.state = "complete"; - this.onComplete(this.unresolvedKeyframes, this.finalKeyframe, isForcedComplete); - toResolve.delete(this); - } - cancel() { - if (this.state === "scheduled") { - toResolve.delete(this); - this.state = "pending"; - } - } - resume() { - if (this.state === "pending") - this.scheduleResolve(); - } -} -const isCSSVar = (name) => name.startsWith("--"); -function setStyle(element, name, value) { - isCSSVar(name) ? element.style.setProperty(name, value) : element.style[name] = value; -} -const supportsFlags = {}; -function memoSupports(callback, supportsFlag) { - const memoized = /* @__PURE__ */ memo(callback); - return () => supportsFlags[supportsFlag] ?? memoized(); -} -const supportsScrollTimeline = /* @__PURE__ */ memoSupports(() => window.ScrollTimeline !== void 0, "scrollTimeline"); -const supportsLinearEasing = /* @__PURE__ */ memoSupports(() => { - try { - document.createElement("div").animate({ opacity: 0 }, { easing: "linear(0, 1)" }); - } catch (e) { - return false; - } - return true; -}, "linearEasing"); -const cubicBezierAsString = ([a, b, c, d]) => `cubic-bezier(${a}, ${b}, ${c}, ${d})`; -const supportedWaapiEasing = { - linear: "linear", - ease: "ease", - easeIn: "ease-in", - easeOut: "ease-out", - easeInOut: "ease-in-out", - circIn: /* @__PURE__ */ cubicBezierAsString([0, 0.65, 0.55, 1]), - circOut: /* @__PURE__ */ cubicBezierAsString([0.55, 0, 1, 0.45]), - backIn: /* @__PURE__ */ cubicBezierAsString([0.31, 0.01, 0.66, -0.59]), - backOut: /* @__PURE__ */ cubicBezierAsString([0.33, 1.53, 0.69, 0.99]) -}; -function mapEasingToNativeEasing(easing, duration) { - if (!easing) { - return void 0; - } else if (typeof easing === "function") { - return supportsLinearEasing() ? generateLinearEasing(easing, duration) : "ease-out"; - } else if (isBezierDefinition(easing)) { - return cubicBezierAsString(easing); - } else if (Array.isArray(easing)) { - return easing.map((segmentEasing) => mapEasingToNativeEasing(segmentEasing, duration) || supportedWaapiEasing.easeOut); - } else { - return supportedWaapiEasing[easing]; - } -} -function startWaapiAnimation(element, valueName, keyframes2, { delay: delay2 = 0, duration = 300, repeat = 0, repeatType = "loop", ease: ease2 = "easeOut", times } = {}, pseudoElement = void 0) { - const keyframeOptions = { - [valueName]: keyframes2 - }; - if (times) - keyframeOptions.offset = times; - const easing = mapEasingToNativeEasing(ease2, duration); - if (Array.isArray(easing)) - keyframeOptions.easing = easing; - const options = { - delay: delay2, - duration, - easing: !Array.isArray(easing) ? easing : "linear", - fill: "both", - iterations: repeat + 1, - direction: repeatType === "reverse" ? "alternate" : "normal" - }; - if (pseudoElement) - options.pseudoElement = pseudoElement; - const animation = element.animate(keyframeOptions, options); - return animation; -} -function isGenerator(type) { - return typeof type === "function" && "applyToOptions" in type; -} -function applyGeneratorOptions({ type, ...options }) { - if (isGenerator(type) && supportsLinearEasing()) { - return type.applyToOptions(options); - } else { - options.duration ?? (options.duration = 300); - options.ease ?? (options.ease = "easeOut"); - } - return options; -} -class NativeAnimation extends WithPromise { - constructor(options) { - super(); - this.finishedTime = null; - this.isStopped = false; - this.manualStartTime = null; - if (!options) - return; - const { element, name, keyframes: keyframes2, pseudoElement, allowFlatten = false, finalKeyframe, onComplete } = options; - this.isPseudoElement = Boolean(pseudoElement); - this.allowFlatten = allowFlatten; - this.options = options; - invariant(typeof options.type !== "string", `Mini animate() doesn't support "type" as a string.`, "mini-spring"); - const transition = applyGeneratorOptions(options); - this.animation = startWaapiAnimation(element, name, keyframes2, transition, pseudoElement); - if (transition.autoplay === false) { - this.animation.pause(); - } - this.animation.onfinish = () => { - this.finishedTime = this.time; - if (!pseudoElement) { - const keyframe = getFinalKeyframe(keyframes2, this.options, finalKeyframe, this.speed); - if (this.updateMotionValue) { - this.updateMotionValue(keyframe); - } - setStyle(element, name, keyframe); - this.animation.cancel(); - } - onComplete?.(); - this.notifyFinished(); - }; - } - play() { - if (this.isStopped) - return; - this.manualStartTime = null; - this.animation.play(); - if (this.state === "finished") { - this.updateFinished(); - } - } - pause() { - this.animation.pause(); - } - complete() { - this.animation.finish?.(); - } - cancel() { - try { - this.animation.cancel(); - } catch (e) { - } - } - stop() { - if (this.isStopped) - return; - this.isStopped = true; - const { state } = this; - if (state === "idle" || state === "finished") { - return; - } - if (this.updateMotionValue) { - this.updateMotionValue(); - } else { - this.commitStyles(); - } - if (!this.isPseudoElement) - this.cancel(); - } - /** - * WAAPI doesn't natively have any interruption capabilities. - * - * In this method, we commit styles back to the DOM before cancelling - * the animation. - * - * This is designed to be overridden by NativeAnimationExtended, which - * will create a renderless JS animation and sample it twice to calculate - * its current value, "previous" value, and therefore allow - * Motion to also correctly calculate velocity for any subsequent animation - * while deferring the commit until the next animation frame. - */ - commitStyles() { - const element = this.options?.element; - if (!this.isPseudoElement && element?.isConnected) { - this.animation.commitStyles?.(); - } - } - get duration() { - const duration = this.animation.effect?.getComputedTiming?.().duration || 0; - return /* @__PURE__ */ millisecondsToSeconds(Number(duration)); - } - get iterationDuration() { - const { delay: delay2 = 0 } = this.options || {}; - return this.duration + /* @__PURE__ */ millisecondsToSeconds(delay2); - } - get time() { - return /* @__PURE__ */ millisecondsToSeconds(Number(this.animation.currentTime) || 0); - } - set time(newTime) { - const wasFinished = this.finishedTime !== null; - this.manualStartTime = null; - this.finishedTime = null; - this.animation.currentTime = /* @__PURE__ */ secondsToMilliseconds(newTime); - if (wasFinished) { - this.animation.pause(); - } - } - /** - * The playback speed of the animation. - * 1 = normal speed, 2 = double speed, 0.5 = half speed. - */ - get speed() { - return this.animation.playbackRate; - } - set speed(newSpeed) { - if (newSpeed < 0) - this.finishedTime = null; - this.animation.playbackRate = newSpeed; - } - get state() { - return this.finishedTime !== null ? "finished" : this.animation.playState; - } - get startTime() { - return this.manualStartTime ?? Number(this.animation.startTime); - } - set startTime(newStartTime) { - this.manualStartTime = this.animation.startTime = newStartTime; - } - /** - * Attaches a timeline to the animation, for instance the `ScrollTimeline`. - */ - attachTimeline({ timeline, rangeStart, rangeEnd, observe }) { - if (this.allowFlatten) { - this.animation.effect?.updateTiming({ easing: "linear" }); - } - this.animation.onfinish = null; - if (timeline && supportsScrollTimeline()) { - this.animation.timeline = timeline; - if (rangeStart) - this.animation.rangeStart = rangeStart; - if (rangeEnd) - this.animation.rangeEnd = rangeEnd; - return noop; - } else { - return observe(this); - } - } -} -const unsupportedEasingFunctions = { - anticipate, - backInOut, - circInOut -}; -function isUnsupportedEase(key) { - return key in unsupportedEasingFunctions; -} -function replaceStringEasing(transition) { - if (typeof transition.ease === "string" && isUnsupportedEase(transition.ease)) { - transition.ease = unsupportedEasingFunctions[transition.ease]; - } -} -const sampleDelta = 10; -class NativeAnimationExtended extends NativeAnimation { - constructor(options) { - replaceStringEasing(options); - replaceTransitionType(options); - super(options); - if (options.startTime !== void 0 && options.autoplay !== false) { - this.startTime = options.startTime; - } - this.options = options; - } - /** - * WAAPI doesn't natively have any interruption capabilities. - * - * Rather than read committed styles back out of the DOM, we can - * create a renderless JS animation and sample it twice to calculate - * its current value, "previous" value, and therefore allow - * Motion to calculate velocity for any subsequent animation. - */ - updateMotionValue(value) { - const { motionValue: motionValue2, onUpdate, onComplete, element, ...options } = this.options; - if (!motionValue2) - return; - if (value !== void 0) { - motionValue2.set(value); - return; - } - const sampleAnimation = new JSAnimation({ - ...options, - autoplay: false - }); - const sampleTime = Math.max(sampleDelta, time.now() - this.startTime); - const delta = clamp(0, sampleDelta, sampleTime - sampleDelta); - const current = sampleAnimation.sample(sampleTime).value; - const { name } = this.options; - if (element && name) - setStyle(element, name, current); - motionValue2.setWithVelocity(sampleAnimation.sample(Math.max(0, sampleTime - delta)).value, current, delta); - sampleAnimation.stop(); - } -} -const isAnimatable = (value, name) => { - if (name === "zIndex") - return false; - if (typeof value === "number" || Array.isArray(value)) - return true; - if (typeof value === "string" && // It's animatable if we have a string - (complex.test(value) || value === "0") && // And it contains numbers and/or colors - !value.startsWith("url(")) { - return true; - } - return false; -}; -function hasKeyframesChanged(keyframes2) { - const current = keyframes2[0]; - if (keyframes2.length === 1) - return true; - for (let i = 0; i < keyframes2.length; i++) { - if (keyframes2[i] !== current) - return true; - } -} -function canAnimate(keyframes2, name, type, velocity) { - const originKeyframe = keyframes2[0]; - if (originKeyframe === null) { - return false; - } - if (name === "display" || name === "visibility") - return true; - const targetKeyframe = keyframes2[keyframes2.length - 1]; - const isOriginAnimatable = isAnimatable(originKeyframe, name); - const isTargetAnimatable = isAnimatable(targetKeyframe, name); - warning(isOriginAnimatable === isTargetAnimatable, `You are trying to animate ${name} from "${originKeyframe}" to "${targetKeyframe}". "${isOriginAnimatable ? targetKeyframe : originKeyframe}" is not an animatable value.`, "value-not-animatable"); - if (!isOriginAnimatable || !isTargetAnimatable) { - return false; - } - return hasKeyframesChanged(keyframes2) || (type === "spring" || isGenerator(type)) && velocity; -} -function makeAnimationInstant(options) { - options.duration = 0; - options.type = "keyframes"; -} -const acceleratedValues = /* @__PURE__ */ new Set([ - "opacity", - "clipPath", - "filter", - "transform" - // TODO: Can be accelerated but currently disabled until https://issues.chromium.org/issues/41491098 is resolved - // or until we implement support for linear() easing. - // "background-color" -]); -const browserColorFunctions = /^(?:oklch|oklab|lab|lch|color|color-mix|light-dark)\(/; -function hasBrowserOnlyColors(keyframes2) { - for (let i = 0; i < keyframes2.length; i++) { - if (typeof keyframes2[i] === "string" && browserColorFunctions.test(keyframes2[i])) { - return true; - } - } - return false; -} -const colorProperties = /* @__PURE__ */ new Set([ - "color", - "backgroundColor", - "outlineColor", - "fill", - "stroke", - "borderColor", - "borderTopColor", - "borderRightColor", - "borderBottomColor", - "borderLeftColor" -]); -const supportsWaapi = /* @__PURE__ */ memo(() => Object.hasOwnProperty.call(Element.prototype, "animate")); -function supportsBrowserAnimation(options) { - const { motionValue: motionValue2, name, repeatDelay, repeatType, damping, type, keyframes: keyframes2 } = options; - const subject = motionValue2?.owner?.current; - if (!(subject instanceof HTMLElement)) { - return false; - } - const { onUpdate, transformTemplate } = motionValue2.owner.getProps(); - return supportsWaapi() && name && /** - * Force WAAPI for color properties with browser-only color formats - * (oklch, oklab, lab, lch, etc.) that the JS animation path can't parse. - */ - (acceleratedValues.has(name) || colorProperties.has(name) && hasBrowserOnlyColors(keyframes2)) && (name !== "transform" || !transformTemplate) && /** - * If we're outputting values to onUpdate then we can't use WAAPI as there's - * no way to read the value from WAAPI every frame. - */ - !onUpdate && !repeatDelay && repeatType !== "mirror" && damping !== 0 && type !== "inertia"; -} -const MAX_RESOLVE_DELAY = 40; -class AsyncMotionValueAnimation extends WithPromise { - constructor({ autoplay = true, delay: delay2 = 0, type = "keyframes", repeat = 0, repeatDelay = 0, repeatType = "loop", keyframes: keyframes2, name, motionValue: motionValue2, element, ...options }) { - super(); - this.stop = () => { - if (this._animation) { - this._animation.stop(); - this.stopTimeline?.(); - } - this.keyframeResolver?.cancel(); - }; - this.createdAt = time.now(); - const optionsWithDefaults = { - autoplay, - delay: delay2, - type, - repeat, - repeatDelay, - repeatType, - name, - motionValue: motionValue2, - element, - ...options - }; - const KeyframeResolver$1 = element?.KeyframeResolver || KeyframeResolver; - this.keyframeResolver = new KeyframeResolver$1(keyframes2, (resolvedKeyframes, finalKeyframe, forced) => this.onKeyframesResolved(resolvedKeyframes, finalKeyframe, optionsWithDefaults, !forced), name, motionValue2, element); - this.keyframeResolver?.scheduleResolve(); - } - onKeyframesResolved(keyframes2, finalKeyframe, options, sync) { - this.keyframeResolver = void 0; - const { name, type, velocity, delay: delay2, isHandoff, onUpdate } = options; - this.resolvedAt = time.now(); - let canAnimateValue = true; - if (!canAnimate(keyframes2, name, type, velocity)) { - canAnimateValue = false; - if (MotionGlobalConfig.instantAnimations || !delay2) { - onUpdate?.(getFinalKeyframe(keyframes2, options, finalKeyframe)); - } - keyframes2[0] = keyframes2[keyframes2.length - 1]; - makeAnimationInstant(options); - options.repeat = 0; - } - const startTime = sync ? !this.resolvedAt ? this.createdAt : this.resolvedAt - this.createdAt > MAX_RESOLVE_DELAY ? this.resolvedAt : this.createdAt : void 0; - const resolvedOptions = { - startTime, - finalKeyframe, - ...options, - keyframes: keyframes2 - }; - const useWaapi = canAnimateValue && !isHandoff && supportsBrowserAnimation(resolvedOptions); - const element = resolvedOptions.motionValue?.owner?.current; - let animation; - if (useWaapi) { - try { - animation = new NativeAnimationExtended({ - ...resolvedOptions, - element - }); - } catch { - animation = new JSAnimation(resolvedOptions); - } - } else { - animation = new JSAnimation(resolvedOptions); - } - animation.finished.then(() => { - this.notifyFinished(); - }).catch(noop); - if (this.pendingTimeline) { - this.stopTimeline = animation.attachTimeline(this.pendingTimeline); - this.pendingTimeline = void 0; - } - this._animation = animation; - } - get finished() { - if (!this._animation) { - return this._finished; - } else { - return this.animation.finished; - } - } - then(onResolve, _onReject) { - return this.finished.finally(onResolve).then(() => { - }); - } - get animation() { - if (!this._animation) { - this.keyframeResolver?.resume(); - flushKeyframeResolvers(); - } - return this._animation; - } - get duration() { - return this.animation.duration; - } - get iterationDuration() { - return this.animation.iterationDuration; - } - get time() { - return this.animation.time; - } - set time(newTime) { - this.animation.time = newTime; - } - get speed() { - return this.animation.speed; - } - get state() { - return this.animation.state; - } - set speed(newSpeed) { - this.animation.speed = newSpeed; - } - get startTime() { - return this.animation.startTime; - } - attachTimeline(timeline) { - if (this._animation) { - this.stopTimeline = this.animation.attachTimeline(timeline); - } else { - this.pendingTimeline = timeline; - } - return () => this.stop(); - } - play() { - this.animation.play(); - } - pause() { - this.animation.pause(); - } - complete() { - this.animation.complete(); - } - cancel() { - if (this._animation) { - this.animation.cancel(); - } - this.keyframeResolver?.cancel(); - } -} -function calcChildStagger(children, child, delayChildren, staggerChildren = 0, staggerDirection = 1) { - const index = Array.from(children).sort((a, b) => a.sortNodePosition(b)).indexOf(child); - const numChildren = children.size; - const maxStaggerDuration = (numChildren - 1) * staggerChildren; - const delayIsFunction = typeof delayChildren === "function"; - return delayIsFunction ? delayChildren(index, numChildren) : staggerDirection === 1 ? index * staggerChildren : maxStaggerDuration - index * staggerChildren; -} -const splitCSSVariableRegex = ( - // eslint-disable-next-line redos-detector/no-unsafe-regex -- false positive, as it can match a lot of words - /^var\(--(?:([\w-]+)|([\w-]+), ?([a-zA-Z\d ()%#.,-]+))\)/u -); -function parseCSSVariable(current) { - const match = splitCSSVariableRegex.exec(current); - if (!match) - return [,]; - const [, token1, token2, fallback] = match; - return [`--${token1 ?? token2}`, fallback]; -} -const maxDepth = 4; -function getVariableValue(current, element, depth = 1) { - invariant(depth <= maxDepth, `Max CSS variable fallback depth detected in property "${current}". This may indicate a circular fallback dependency.`, "max-css-var-depth"); - const [token, fallback] = parseCSSVariable(current); - if (!token) - return; - const resolved = window.getComputedStyle(element).getPropertyValue(token); - if (resolved) { - const trimmed = resolved.trim(); - return isNumericalString(trimmed) ? parseFloat(trimmed) : trimmed; - } - return isCSSVariableToken(fallback) ? getVariableValue(fallback, element, depth + 1) : fallback; -} -const underDampedSpring = { - type: "spring", - stiffness: 500, - damping: 25, - restSpeed: 10 -}; -const criticallyDampedSpring = (target) => ({ - type: "spring", - stiffness: 550, - damping: target === 0 ? 2 * Math.sqrt(550) : 30, - restSpeed: 10 -}); -const keyframesTransition = { - type: "keyframes", - duration: 0.8 -}; -const ease = { - type: "keyframes", - ease: [0.25, 0.1, 0.35, 1], - duration: 0.3 -}; -const getDefaultTransition = (valueKey, { keyframes: keyframes2 }) => { - if (keyframes2.length > 2) { - return keyframesTransition; - } else if (transformProps.has(valueKey)) { - return valueKey.startsWith("scale") ? criticallyDampedSpring(keyframes2[1]) : underDampedSpring; - } - return ease; -}; -function resolveTransition(transition, parentTransition) { - if (transition?.inherit && parentTransition) { - const { inherit: _, ...rest } = transition; - return { ...parentTransition, ...rest }; - } - return transition; -} -function getValueTransition(transition, key) { - const valueTransition = transition?.[key] ?? transition?.["default"] ?? transition; - if (valueTransition !== transition) { - return resolveTransition(valueTransition, transition); - } - return valueTransition; -} -const orchestrationKeys = /* @__PURE__ */ new Set([ - "when", - "delay", - "delayChildren", - "staggerChildren", - "staggerDirection", - "repeat", - "repeatType", - "repeatDelay", - "from", - "elapsed" -]); -function isTransitionDefined(transition) { - for (const key in transition) { - if (!orchestrationKeys.has(key)) - return true; - } - return false; -} -const animateMotionValue = (name, value, target, transition = {}, element, isHandoff) => (onComplete) => { - const valueTransition = getValueTransition(transition, name) || {}; - const delay2 = valueTransition.delay || transition.delay || 0; - let { elapsed = 0 } = transition; - elapsed = elapsed - /* @__PURE__ */ secondsToMilliseconds(delay2); - const options = { - keyframes: Array.isArray(target) ? target : [null, target], - ease: "easeOut", - velocity: value.getVelocity(), - ...valueTransition, - delay: -elapsed, - onUpdate: (v) => { - value.set(v); - valueTransition.onUpdate && valueTransition.onUpdate(v); - }, - onComplete: () => { - onComplete(); - valueTransition.onComplete && valueTransition.onComplete(); - }, - name, - motionValue: value, - element: isHandoff ? void 0 : element - }; - if (!isTransitionDefined(valueTransition)) { - Object.assign(options, getDefaultTransition(name, options)); - } - options.duration && (options.duration = /* @__PURE__ */ secondsToMilliseconds(options.duration)); - options.repeatDelay && (options.repeatDelay = /* @__PURE__ */ secondsToMilliseconds(options.repeatDelay)); - if (options.from !== void 0) { - options.keyframes[0] = options.from; - } - let shouldSkip = false; - if (options.type === false || options.duration === 0 && !options.repeatDelay) { - makeAnimationInstant(options); - if (options.delay === 0) { - shouldSkip = true; - } - } - if (MotionGlobalConfig.instantAnimations || MotionGlobalConfig.skipAnimations || element?.shouldSkipAnimations) { - shouldSkip = true; - makeAnimationInstant(options); - options.delay = 0; - } - options.allowFlatten = !valueTransition.type && !valueTransition.ease; - if (shouldSkip && !isHandoff && value.get() !== void 0) { - const finalKeyframe = getFinalKeyframe(options.keyframes, valueTransition); - if (finalKeyframe !== void 0) { - frame.update(() => { - options.onUpdate(finalKeyframe); - options.onComplete(); - }); - return; - } - } - return valueTransition.isSync ? new JSAnimation(options) : new AsyncMotionValueAnimation(options); -}; -function getValueState(visualElement) { - const state = [{}, {}]; - visualElement?.values.forEach((value, key) => { - state[0][key] = value.get(); - state[1][key] = value.getVelocity(); - }); - return state; -} -function resolveVariantFromProps(props, definition, custom, visualElement) { - if (typeof definition === "function") { - const [current, velocity] = getValueState(visualElement); - definition = definition(custom !== void 0 ? custom : props.custom, current, velocity); - } - if (typeof definition === "string") { - definition = props.variants && props.variants[definition]; - } - if (typeof definition === "function") { - const [current, velocity] = getValueState(visualElement); - definition = definition(custom !== void 0 ? custom : props.custom, current, velocity); - } - return definition; -} -function resolveVariant(visualElement, definition, custom) { - const props = visualElement.getProps(); - return resolveVariantFromProps(props, definition, custom !== void 0 ? custom : props.custom, visualElement); -} -const positionalKeys = /* @__PURE__ */ new Set([ - "width", - "height", - "top", - "left", - "right", - "bottom", - ...transformPropOrder -]); -const MAX_VELOCITY_DELTA = 30; -const isFloat = (value) => { - return !isNaN(parseFloat(value)); -}; -class MotionValue { - /** - * @param init - The initiating value - * @param config - Optional configuration options - * - * - `transformer`: A function to transform incoming values with. - */ - constructor(init, options = {}) { - this.canTrackVelocity = null; - this.events = {}; - this.updateAndNotify = (v) => { - const currentTime = time.now(); - if (this.updatedAt !== currentTime) { - this.setPrevFrameValue(); - } - this.prev = this.current; - this.setCurrent(v); - if (this.current !== this.prev) { - this.events.change?.notify(this.current); - if (this.dependents) { - for (const dependent of this.dependents) { - dependent.dirty(); - } - } - } - }; - this.hasAnimated = false; - this.setCurrent(init); - this.owner = options.owner; - } - setCurrent(current) { - this.current = current; - this.updatedAt = time.now(); - if (this.canTrackVelocity === null && current !== void 0) { - this.canTrackVelocity = isFloat(this.current); - } - } - setPrevFrameValue(prevFrameValue = this.current) { - this.prevFrameValue = prevFrameValue; - this.prevUpdatedAt = this.updatedAt; - } - /** - * Adds a function that will be notified when the `MotionValue` is updated. - * - * It returns a function that, when called, will cancel the subscription. - * - * When calling `onChange` inside a React component, it should be wrapped with the - * `useEffect` hook. As it returns an unsubscribe function, this should be returned - * from the `useEffect` function to ensure you don't add duplicate subscribers.. - * - * ```jsx - * export const MyComponent = () => { - * const x = useMotionValue(0) - * const y = useMotionValue(0) - * const opacity = useMotionValue(1) - * - * useEffect(() => { - * function updateOpacity() { - * const maxXY = Math.max(x.get(), y.get()) - * const newOpacity = transform(maxXY, [0, 100], [1, 0]) - * opacity.set(newOpacity) - * } - * - * const unsubscribeX = x.on("change", updateOpacity) - * const unsubscribeY = y.on("change", updateOpacity) - * - * return () => { - * unsubscribeX() - * unsubscribeY() - * } - * }, []) - * - * return - * } - * ``` - * - * @param subscriber - A function that receives the latest value. - * @returns A function that, when called, will cancel this subscription. - * - * @deprecated - */ - onChange(subscription) { - if (process.env.NODE_ENV !== "production") { - warnOnce(false, `value.onChange(callback) is deprecated. Switch to value.on("change", callback).`); - } - return this.on("change", subscription); - } - on(eventName, callback) { - if (!this.events[eventName]) { - this.events[eventName] = new SubscriptionManager(); - } - const unsubscribe = this.events[eventName].add(callback); - if (eventName === "change") { - return () => { - unsubscribe(); - frame.read(() => { - if (!this.events.change.getSize()) { - this.stop(); - } - }); - }; - } - return unsubscribe; - } - clearListeners() { - for (const eventManagers in this.events) { - this.events[eventManagers].clear(); - } - } - /** - * Attaches a passive effect to the `MotionValue`. - */ - attach(passiveEffect, stopPassiveEffect) { - this.passiveEffect = passiveEffect; - this.stopPassiveEffect = stopPassiveEffect; - } - /** - * Sets the state of the `MotionValue`. - * - * @remarks - * - * ```jsx - * const x = useMotionValue(0) - * x.set(10) - * ``` - * - * @param latest - Latest value to set. - * @param render - Whether to notify render subscribers. Defaults to `true` - * - * @public - */ - set(v) { - if (!this.passiveEffect) { - this.updateAndNotify(v); - } else { - this.passiveEffect(v, this.updateAndNotify); - } - } - setWithVelocity(prev, current, delta) { - this.set(current); - this.prev = void 0; - this.prevFrameValue = prev; - this.prevUpdatedAt = this.updatedAt - delta; - } - /** - * Set the state of the `MotionValue`, stopping any active animations, - * effects, and resets velocity to `0`. - */ - jump(v, endAnimation = true) { - this.updateAndNotify(v); - this.prev = v; - this.prevUpdatedAt = this.prevFrameValue = void 0; - endAnimation && this.stop(); - if (this.stopPassiveEffect) - this.stopPassiveEffect(); - } - dirty() { - this.events.change?.notify(this.current); - } - addDependent(dependent) { - if (!this.dependents) { - this.dependents = /* @__PURE__ */ new Set(); - } - this.dependents.add(dependent); - } - removeDependent(dependent) { - if (this.dependents) { - this.dependents.delete(dependent); - } - } - /** - * Returns the latest state of `MotionValue` - * - * @returns - The latest state of `MotionValue` - * - * @public - */ - get() { - return this.current; - } - /** - * @public - */ - getPrevious() { - return this.prev; - } - /** - * Returns the latest velocity of `MotionValue` - * - * @returns - The latest velocity of `MotionValue`. Returns `0` if the state is non-numerical. - * - * @public - */ - getVelocity() { - const currentTime = time.now(); - if (!this.canTrackVelocity || this.prevFrameValue === void 0 || currentTime - this.updatedAt > MAX_VELOCITY_DELTA) { - return 0; - } - const delta = Math.min(this.updatedAt - this.prevUpdatedAt, MAX_VELOCITY_DELTA); - return velocityPerSecond(parseFloat(this.current) - parseFloat(this.prevFrameValue), delta); - } - /** - * Registers a new animation to control this `MotionValue`. Only one - * animation can drive a `MotionValue` at one time. - * - * ```jsx - * value.start() - * ``` - * - * @param animation - A function that starts the provided animation - */ - start(startAnimation) { - this.stop(); - return new Promise((resolve) => { - this.hasAnimated = true; - this.animation = startAnimation(resolve); - if (this.events.animationStart) { - this.events.animationStart.notify(); - } - }).then(() => { - if (this.events.animationComplete) { - this.events.animationComplete.notify(); - } - this.clearAnimation(); - }); - } - /** - * Stop the currently active animation. - * - * @public - */ - stop() { - if (this.animation) { - this.animation.stop(); - if (this.events.animationCancel) { - this.events.animationCancel.notify(); - } - } - this.clearAnimation(); - } - /** - * Returns `true` if this value is currently animating. - * - * @public - */ - isAnimating() { - return !!this.animation; - } - clearAnimation() { - delete this.animation; - } - /** - * Destroy and clean up subscribers to this `MotionValue`. - * - * The `MotionValue` hooks like `useMotionValue` and `useTransform` automatically - * handle the lifecycle of the returned `MotionValue`, so this method is only necessary if you've manually - * created a `MotionValue` via the `motionValue` function. - * - * @public - */ - destroy() { - this.dependents?.clear(); - this.events.destroy?.notify(); - this.clearListeners(); - this.stop(); - if (this.stopPassiveEffect) { - this.stopPassiveEffect(); - } - } -} -function motionValue(init, options) { - return new MotionValue(init, options); -} -const isKeyframesTarget = (v) => { - return Array.isArray(v); -}; -function setMotionValue(visualElement, key, value) { - if (visualElement.hasValue(key)) { - visualElement.getValue(key).set(value); - } else { - visualElement.addValue(key, motionValue(value)); - } -} -function resolveFinalValueInKeyframes(v) { - return isKeyframesTarget(v) ? v[v.length - 1] || 0 : v; -} -function setTarget(visualElement, definition) { - const resolved = resolveVariant(visualElement, definition); - let { transitionEnd = {}, transition = {}, ...target } = resolved || {}; - target = { ...target, ...transitionEnd }; - for (const key in target) { - const value = resolveFinalValueInKeyframes(target[key]); - setMotionValue(visualElement, key, value); - } -} -const isMotionValue = (value) => Boolean(value && value.getVelocity); -function isWillChangeMotionValue(value) { - return Boolean(isMotionValue(value) && value.add); -} -function addValueToWillChange(visualElement, key) { - const willChange = visualElement.getValue("willChange"); - if (isWillChangeMotionValue(willChange)) { - return willChange.add(key); - } else if (!willChange && MotionGlobalConfig.WillChange) { - const newWillChange = new MotionGlobalConfig.WillChange("auto"); - visualElement.addValue("willChange", newWillChange); - newWillChange.add(key); - } -} -function camelToDash(str) { - return str.replace(/([A-Z])/g, (match) => `-${match.toLowerCase()}`); -} -const optimizedAppearDataId = "framerAppearId"; -const optimizedAppearDataAttribute = "data-" + camelToDash(optimizedAppearDataId); -function getOptimisedAppearId(visualElement) { - return visualElement.props[optimizedAppearDataAttribute]; -} -function shouldBlockAnimation({ protectedKeys, needsAnimating }, key) { - const shouldBlock = protectedKeys.hasOwnProperty(key) && needsAnimating[key] !== true; - needsAnimating[key] = false; - return shouldBlock; -} -function animateTarget(visualElement, targetAndTransition, { delay: delay2 = 0, transitionOverride, type } = {}) { - let { transition, transitionEnd, ...target } = targetAndTransition; - const defaultTransition = visualElement.getDefaultTransition(); - transition = transition ? resolveTransition(transition, defaultTransition) : defaultTransition; - const reduceMotion = transition?.reduceMotion; - if (transitionOverride) - transition = transitionOverride; - const animations2 = []; - const animationTypeState = type && visualElement.animationState && visualElement.animationState.getState()[type]; - for (const key in target) { - const value = visualElement.getValue(key, visualElement.latestValues[key] ?? null); - const valueTarget = target[key]; - if (valueTarget === void 0 || animationTypeState && shouldBlockAnimation(animationTypeState, key)) { - continue; - } - const valueTransition = { - delay: delay2, - ...getValueTransition(transition || {}, key) - }; - const currentValue = value.get(); - if (currentValue !== void 0 && !value.isAnimating() && !Array.isArray(valueTarget) && valueTarget === currentValue && !valueTransition.velocity) { - frame.update(() => value.set(valueTarget)); - continue; - } - let isHandoff = false; - if (window.MotionHandoffAnimation) { - const appearId = getOptimisedAppearId(visualElement); - if (appearId) { - const startTime = window.MotionHandoffAnimation(appearId, key, frame); - if (startTime !== null) { - valueTransition.startTime = startTime; - isHandoff = true; - } - } - } - addValueToWillChange(visualElement, key); - const shouldReduceMotion = reduceMotion ?? visualElement.shouldReduceMotion; - value.start(animateMotionValue(key, value, valueTarget, shouldReduceMotion && positionalKeys.has(key) ? { type: false } : valueTransition, visualElement, isHandoff)); - const animation = value.animation; - if (animation) { - animations2.push(animation); - } - } - if (transitionEnd) { - const applyTransitionEnd = () => frame.update(() => { - transitionEnd && setTarget(visualElement, transitionEnd); - }); - if (animations2.length) { - Promise.all(animations2).then(applyTransitionEnd); - } else { - applyTransitionEnd(); - } - } - return animations2; -} -function animateVariant(visualElement, variant, options = {}) { - const resolved = resolveVariant(visualElement, variant, options.type === "exit" ? visualElement.presenceContext?.custom : void 0); - let { transition = visualElement.getDefaultTransition() || {} } = resolved || {}; - if (options.transitionOverride) { - transition = options.transitionOverride; - } - const getAnimation = resolved ? () => Promise.all(animateTarget(visualElement, resolved, options)) : () => Promise.resolve(); - const getChildAnimations = visualElement.variantChildren && visualElement.variantChildren.size ? (forwardDelay = 0) => { - const { delayChildren = 0, staggerChildren, staggerDirection } = transition; - return animateChildren(visualElement, variant, forwardDelay, delayChildren, staggerChildren, staggerDirection, options); - } : () => Promise.resolve(); - const { when } = transition; - if (when) { - const [first, last] = when === "beforeChildren" ? [getAnimation, getChildAnimations] : [getChildAnimations, getAnimation]; - return first().then(() => last()); - } else { - return Promise.all([getAnimation(), getChildAnimations(options.delay)]); - } -} -function animateChildren(visualElement, variant, delay2 = 0, delayChildren = 0, staggerChildren = 0, staggerDirection = 1, options) { - const animations2 = []; - for (const child of visualElement.variantChildren) { - child.notify("AnimationStart", variant); - animations2.push(animateVariant(child, variant, { - ...options, - delay: delay2 + (typeof delayChildren === "function" ? 0 : delayChildren) + calcChildStagger(visualElement.variantChildren, child, delayChildren, staggerChildren, staggerDirection) - }).then(() => child.notify("AnimationComplete", variant))); - } - return Promise.all(animations2); -} -function animateVisualElement(visualElement, definition, options = {}) { - visualElement.notify("AnimationStart", definition); - let animation; - if (Array.isArray(definition)) { - const animations2 = definition.map((variant) => animateVariant(visualElement, variant, options)); - animation = Promise.all(animations2); - } else if (typeof definition === "string") { - animation = animateVariant(visualElement, definition, options); - } else { - const resolvedDefinition = typeof definition === "function" ? resolveVariant(visualElement, definition, options.custom) : definition; - animation = Promise.all(animateTarget(visualElement, resolvedDefinition, options)); - } - return animation.then(() => { - visualElement.notify("AnimationComplete", definition); - }); -} -const auto = { - test: (v) => v === "auto", - parse: (v) => v -}; -const testValueType = (v) => (type) => type.test(v); -const dimensionValueTypes = [number, px, percent, degrees, vw, vh, auto]; -const findDimensionValueType = (v) => dimensionValueTypes.find(testValueType(v)); -function isNone(value) { - if (typeof value === "number") { - return value === 0; - } else if (value !== null) { - return value === "none" || value === "0" || isZeroValueString(value); - } else { - return true; - } -} -const maxDefaults = /* @__PURE__ */ new Set(["brightness", "contrast", "saturate", "opacity"]); -function applyDefaultFilter(v) { - const [name, value] = v.slice(0, -1).split("("); - if (name === "drop-shadow") - return v; - const [number2] = value.match(floatRegex) || []; - if (!number2) - return v; - const unit = value.replace(number2, ""); - let defaultValue = maxDefaults.has(name) ? 1 : 0; - if (number2 !== value) - defaultValue *= 100; - return name + "(" + defaultValue + unit + ")"; -} -const functionRegex = /\b([a-z-]*)\(.*?\)/gu; -const filter = { - ...complex, - getAnimatableNone: (v) => { - const functions = v.match(functionRegex); - return functions ? functions.map(applyDefaultFilter).join(" ") : v; - } -}; -const mask = { - ...complex, - getAnimatableNone: (v) => { - const parsed = complex.parse(v); - const transformer = complex.createTransformer(v); - return transformer(parsed.map((v2) => typeof v2 === "number" ? 0 : typeof v2 === "object" ? { ...v2, alpha: 1 } : v2)); - } -}; -const int = { - ...number, - transform: Math.round -}; -const transformValueTypes = { - rotate: degrees, - rotateX: degrees, - rotateY: degrees, - rotateZ: degrees, - scale, - scaleX: scale, - scaleY: scale, - scaleZ: scale, - skew: degrees, - skewX: degrees, - skewY: degrees, - distance: px, - translateX: px, - translateY: px, - translateZ: px, - x: px, - y: px, - z: px, - perspective: px, - transformPerspective: px, - opacity: alpha, - originX: progressPercentage, - originY: progressPercentage, - originZ: px -}; -const numberValueTypes = { - // Border props - borderWidth: px, - borderTopWidth: px, - borderRightWidth: px, - borderBottomWidth: px, - borderLeftWidth: px, - borderRadius: px, - borderTopLeftRadius: px, - borderTopRightRadius: px, - borderBottomRightRadius: px, - borderBottomLeftRadius: px, - // Positioning props - width: px, - maxWidth: px, - height: px, - maxHeight: px, - top: px, - right: px, - bottom: px, - left: px, - inset: px, - insetBlock: px, - insetBlockStart: px, - insetBlockEnd: px, - insetInline: px, - insetInlineStart: px, - insetInlineEnd: px, - // Spacing props - padding: px, - paddingTop: px, - paddingRight: px, - paddingBottom: px, - paddingLeft: px, - paddingBlock: px, - paddingBlockStart: px, - paddingBlockEnd: px, - paddingInline: px, - paddingInlineStart: px, - paddingInlineEnd: px, - margin: px, - marginTop: px, - marginRight: px, - marginBottom: px, - marginLeft: px, - marginBlock: px, - marginBlockStart: px, - marginBlockEnd: px, - marginInline: px, - marginInlineStart: px, - marginInlineEnd: px, - // Typography - fontSize: px, - // Misc - backgroundPositionX: px, - backgroundPositionY: px, - ...transformValueTypes, - zIndex: int, - // SVG - fillOpacity: alpha, - strokeOpacity: alpha, - numOctaves: int -}; -const defaultValueTypes = { - ...numberValueTypes, - // Color props - color, - backgroundColor: color, - outlineColor: color, - fill: color, - stroke: color, - // Border props - borderColor: color, - borderTopColor: color, - borderRightColor: color, - borderBottomColor: color, - borderLeftColor: color, - filter, - WebkitFilter: filter, - mask, - WebkitMask: mask -}; -const getDefaultValueType = (key) => defaultValueTypes[key]; -const customTypes = /* @__PURE__ */ new Set([filter, mask]); -function getAnimatableNone(key, value) { - let defaultValueType = getDefaultValueType(key); - if (!customTypes.has(defaultValueType)) - defaultValueType = complex; - return defaultValueType.getAnimatableNone ? defaultValueType.getAnimatableNone(value) : void 0; -} -const invalidTemplates = /* @__PURE__ */ new Set(["auto", "none", "0"]); -function makeNoneKeyframesAnimatable(unresolvedKeyframes, noneKeyframeIndexes, name) { - let i = 0; - let animatableTemplate = void 0; - while (i < unresolvedKeyframes.length && !animatableTemplate) { - const keyframe = unresolvedKeyframes[i]; - if (typeof keyframe === "string" && !invalidTemplates.has(keyframe) && analyseComplexValue(keyframe).values.length) { - animatableTemplate = unresolvedKeyframes[i]; - } - i++; - } - if (animatableTemplate && name) { - for (const noneIndex of noneKeyframeIndexes) { - unresolvedKeyframes[noneIndex] = getAnimatableNone(name, animatableTemplate); - } - } -} -class DOMKeyframesResolver extends KeyframeResolver { - constructor(unresolvedKeyframes, onComplete, name, motionValue2, element) { - super(unresolvedKeyframes, onComplete, name, motionValue2, element, true); - } - readKeyframes() { - const { unresolvedKeyframes, element, name } = this; - if (!element || !element.current) - return; - super.readKeyframes(); - for (let i = 0; i < unresolvedKeyframes.length; i++) { - let keyframe = unresolvedKeyframes[i]; - if (typeof keyframe === "string") { - keyframe = keyframe.trim(); - if (isCSSVariableToken(keyframe)) { - const resolved = getVariableValue(keyframe, element.current); - if (resolved !== void 0) { - unresolvedKeyframes[i] = resolved; - } - if (i === unresolvedKeyframes.length - 1) { - this.finalKeyframe = keyframe; - } - } - } - } - this.resolveNoneKeyframes(); - if (!positionalKeys.has(name) || unresolvedKeyframes.length !== 2) { - return; - } - const [origin, target] = unresolvedKeyframes; - const originType = findDimensionValueType(origin); - const targetType = findDimensionValueType(target); - const originHasVar = containsCSSVariable(origin); - const targetHasVar = containsCSSVariable(target); - if (originHasVar !== targetHasVar && positionalValues[name]) { - this.needsMeasurement = true; - return; - } - if (originType === targetType) - return; - if (isNumOrPxType(originType) && isNumOrPxType(targetType)) { - for (let i = 0; i < unresolvedKeyframes.length; i++) { - const value = unresolvedKeyframes[i]; - if (typeof value === "string") { - unresolvedKeyframes[i] = parseFloat(value); - } - } - } else if (positionalValues[name]) { - this.needsMeasurement = true; - } - } - resolveNoneKeyframes() { - const { unresolvedKeyframes, name } = this; - const noneKeyframeIndexes = []; - for (let i = 0; i < unresolvedKeyframes.length; i++) { - if (unresolvedKeyframes[i] === null || isNone(unresolvedKeyframes[i])) { - noneKeyframeIndexes.push(i); - } - } - if (noneKeyframeIndexes.length) { - makeNoneKeyframesAnimatable(unresolvedKeyframes, noneKeyframeIndexes, name); - } - } - measureInitialState() { - const { element, unresolvedKeyframes, name } = this; - if (!element || !element.current) - return; - if (name === "height") { - this.suspendedScrollY = window.pageYOffset; - } - this.measuredOrigin = positionalValues[name](element.measureViewportBox(), window.getComputedStyle(element.current)); - unresolvedKeyframes[0] = this.measuredOrigin; - const measureKeyframe = unresolvedKeyframes[unresolvedKeyframes.length - 1]; - if (measureKeyframe !== void 0) { - element.getValue(name, measureKeyframe).jump(measureKeyframe, false); - } - } - measureEndState() { - const { element, name, unresolvedKeyframes } = this; - if (!element || !element.current) - return; - const value = element.getValue(name); - value && value.jump(this.measuredOrigin, false); - const finalKeyframeIndex = unresolvedKeyframes.length - 1; - const finalKeyframe = unresolvedKeyframes[finalKeyframeIndex]; - unresolvedKeyframes[finalKeyframeIndex] = positionalValues[name](element.measureViewportBox(), window.getComputedStyle(element.current)); - if (finalKeyframe !== null && this.finalKeyframe === void 0) { - this.finalKeyframe = finalKeyframe; - } - if (this.removedTransforms?.length) { - this.removedTransforms.forEach(([unsetTransformName, unsetTransformValue]) => { - element.getValue(unsetTransformName).set(unsetTransformValue); - }); - } - this.resolveNoneKeyframes(); - } -} -function resolveElements(elementOrSelector, scope, selectorCache) { - if (elementOrSelector == null) { - return []; - } - if (elementOrSelector instanceof EventTarget) { - return [elementOrSelector]; - } else if (typeof elementOrSelector === "string") { - let root = document; - const elements = selectorCache?.[elementOrSelector] ?? root.querySelectorAll(elementOrSelector); - return elements ? Array.from(elements) : []; - } - return Array.from(elementOrSelector).filter((element) => element != null); -} -const getValueAsType = (value, type) => { - return type && typeof value === "number" ? type.transform(value) : value; -}; -function isHTMLElement(element) { - return isObject(element) && "offsetHeight" in element && !("ownerSVGElement" in element); -} -const { schedule: microtask } = /* @__PURE__ */ createRenderBatcher(queueMicrotask, false); -const isDragging = { - x: false, - y: false -}; -function isDragActive() { - return isDragging.x || isDragging.y; -} -function setDragLock(axis) { - if (axis === "x" || axis === "y") { - if (isDragging[axis]) { - return null; - } else { - isDragging[axis] = true; - return () => { - isDragging[axis] = false; - }; - } - } else { - if (isDragging.x || isDragging.y) { - return null; - } else { - isDragging.x = isDragging.y = true; - return () => { - isDragging.x = isDragging.y = false; - }; - } - } -} -function setupGesture(elementOrSelector, options) { - const elements = resolveElements(elementOrSelector); - const gestureAbortController = new AbortController(); - const eventOptions = { - passive: true, - ...options, - signal: gestureAbortController.signal - }; - const cancel = () => gestureAbortController.abort(); - return [elements, eventOptions, cancel]; -} -function isValidHover(event) { - return !(event.pointerType === "touch" || isDragActive()); -} -function hover(elementOrSelector, onHoverStart, options = {}) { - const [elements, eventOptions, cancel] = setupGesture(elementOrSelector, options); - elements.forEach((element) => { - let isPressed = false; - let deferredHoverEnd = false; - let hoverEndCallback; - const removePointerLeave = () => { - element.removeEventListener("pointerleave", onPointerLeave); - }; - const endHover = (event) => { - if (hoverEndCallback) { - hoverEndCallback(event); - hoverEndCallback = void 0; - } - removePointerLeave(); - }; - const onPointerUp = (event) => { - isPressed = false; - window.removeEventListener("pointerup", onPointerUp); - window.removeEventListener("pointercancel", onPointerUp); - if (deferredHoverEnd) { - deferredHoverEnd = false; - endHover(event); - } - }; - const onPointerDown = () => { - isPressed = true; - window.addEventListener("pointerup", onPointerUp, eventOptions); - window.addEventListener("pointercancel", onPointerUp, eventOptions); - }; - const onPointerLeave = (leaveEvent) => { - if (leaveEvent.pointerType === "touch") - return; - if (isPressed) { - deferredHoverEnd = true; - return; - } - endHover(leaveEvent); - }; - const onPointerEnter = (enterEvent) => { - if (!isValidHover(enterEvent)) - return; - deferredHoverEnd = false; - const onHoverEnd = onHoverStart(element, enterEvent); - if (typeof onHoverEnd !== "function") - return; - hoverEndCallback = onHoverEnd; - element.addEventListener("pointerleave", onPointerLeave, eventOptions); - }; - element.addEventListener("pointerenter", onPointerEnter, eventOptions); - element.addEventListener("pointerdown", onPointerDown, eventOptions); - }); - return cancel; -} -const isNodeOrChild = (parent, child) => { - if (!child) { - return false; - } else if (parent === child) { - return true; - } else { - return isNodeOrChild(parent, child.parentElement); - } -}; -const isPrimaryPointer = (event) => { - if (event.pointerType === "mouse") { - return typeof event.button !== "number" || event.button <= 0; - } else { - return event.isPrimary !== false; - } -}; -const keyboardAccessibleElements = /* @__PURE__ */ new Set([ - "BUTTON", - "INPUT", - "SELECT", - "TEXTAREA", - "A" -]); -function isElementKeyboardAccessible(element) { - return keyboardAccessibleElements.has(element.tagName) || element.isContentEditable === true; -} -const textInputElements = /* @__PURE__ */ new Set(["INPUT", "SELECT", "TEXTAREA"]); -function isElementTextInput(element) { - return textInputElements.has(element.tagName) || element.isContentEditable === true; -} -const isPressing = /* @__PURE__ */ new WeakSet(); -function filterEvents(callback) { - return (event) => { - if (event.key !== "Enter") - return; - callback(event); - }; -} -function firePointerEvent(target, type) { - target.dispatchEvent(new PointerEvent("pointer" + type, { isPrimary: true, bubbles: true })); -} -const enableKeyboardPress = (focusEvent, eventOptions) => { - const element = focusEvent.currentTarget; - if (!element) - return; - const handleKeydown = filterEvents(() => { - if (isPressing.has(element)) - return; - firePointerEvent(element, "down"); - const handleKeyup = filterEvents(() => { - firePointerEvent(element, "up"); - }); - const handleBlur = () => firePointerEvent(element, "cancel"); - element.addEventListener("keyup", handleKeyup, eventOptions); - element.addEventListener("blur", handleBlur, eventOptions); - }); - element.addEventListener("keydown", handleKeydown, eventOptions); - element.addEventListener("blur", () => element.removeEventListener("keydown", handleKeydown), eventOptions); -}; -function isValidPressEvent(event) { - return isPrimaryPointer(event) && !isDragActive(); -} -const claimedPointerDownEvents = /* @__PURE__ */ new WeakSet(); -function press(targetOrSelector, onPressStart, options = {}) { - const [targets, eventOptions, cancelEvents] = setupGesture(targetOrSelector, options); - const startPress = (startEvent) => { - const target = startEvent.currentTarget; - if (!isValidPressEvent(startEvent)) - return; - if (claimedPointerDownEvents.has(startEvent)) - return; - isPressing.add(target); - if (options.stopPropagation) { - claimedPointerDownEvents.add(startEvent); - } - const onPressEnd = onPressStart(target, startEvent); - const onPointerEnd = (endEvent, success) => { - window.removeEventListener("pointerup", onPointerUp); - window.removeEventListener("pointercancel", onPointerCancel); - if (isPressing.has(target)) { - isPressing.delete(target); - } - if (!isValidPressEvent(endEvent)) { - return; - } - if (typeof onPressEnd === "function") { - onPressEnd(endEvent, { success }); - } - }; - const onPointerUp = (upEvent) => { - onPointerEnd(upEvent, target === window || target === document || options.useGlobalTarget || isNodeOrChild(target, upEvent.target)); - }; - const onPointerCancel = (cancelEvent) => { - onPointerEnd(cancelEvent, false); - }; - window.addEventListener("pointerup", onPointerUp, eventOptions); - window.addEventListener("pointercancel", onPointerCancel, eventOptions); - }; - targets.forEach((target) => { - const pointerDownTarget = options.useGlobalTarget ? window : target; - pointerDownTarget.addEventListener("pointerdown", startPress, eventOptions); - if (isHTMLElement(target)) { - target.addEventListener("focus", (event) => enableKeyboardPress(event, eventOptions)); - if (!isElementKeyboardAccessible(target) && !target.hasAttribute("tabindex")) { - target.tabIndex = 0; - } - } - }); - return cancelEvents; -} -function isSVGElement(element) { - return isObject(element) && "ownerSVGElement" in element; -} -const resizeHandlers = /* @__PURE__ */ new WeakMap(); -let observer; -const getSize = (borderBoxAxis, svgAxis, htmlAxis) => (target, borderBoxSize) => { - if (borderBoxSize && borderBoxSize[0]) { - return borderBoxSize[0][borderBoxAxis + "Size"]; - } else if (isSVGElement(target) && "getBBox" in target) { - return target.getBBox()[svgAxis]; - } else { - return target[htmlAxis]; - } -}; -const getWidth = /* @__PURE__ */ getSize("inline", "width", "offsetWidth"); -const getHeight = /* @__PURE__ */ getSize("block", "height", "offsetHeight"); -function notifyTarget({ target, borderBoxSize }) { - resizeHandlers.get(target)?.forEach((handler) => { - handler(target, { - get width() { - return getWidth(target, borderBoxSize); - }, - get height() { - return getHeight(target, borderBoxSize); - } - }); - }); -} -function notifyAll(entries) { - entries.forEach(notifyTarget); -} -function createResizeObserver() { - if (typeof ResizeObserver === "undefined") - return; - observer = new ResizeObserver(notifyAll); -} -function resizeElement(target, handler) { - if (!observer) - createResizeObserver(); - const elements = resolveElements(target); - elements.forEach((element) => { - let elementHandlers = resizeHandlers.get(element); - if (!elementHandlers) { - elementHandlers = /* @__PURE__ */ new Set(); - resizeHandlers.set(element, elementHandlers); - } - elementHandlers.add(handler); - observer?.observe(element); - }); - return () => { - elements.forEach((element) => { - const elementHandlers = resizeHandlers.get(element); - elementHandlers?.delete(handler); - if (!elementHandlers?.size) { - observer?.unobserve(element); - } - }); - }; -} -const windowCallbacks = /* @__PURE__ */ new Set(); -let windowResizeHandler; -function createWindowResizeHandler() { - windowResizeHandler = () => { - const info = { - get width() { - return window.innerWidth; - }, - get height() { - return window.innerHeight; - } - }; - windowCallbacks.forEach((callback) => callback(info)); - }; - window.addEventListener("resize", windowResizeHandler); -} -function resizeWindow(callback) { - windowCallbacks.add(callback); - if (!windowResizeHandler) - createWindowResizeHandler(); - return () => { - windowCallbacks.delete(callback); - if (!windowCallbacks.size && typeof windowResizeHandler === "function") { - window.removeEventListener("resize", windowResizeHandler); - windowResizeHandler = void 0; - } - }; -} -function resize(a, b) { - return typeof a === "function" ? resizeWindow(a) : resizeElement(a, b); -} -function isSVGSVGElement(element) { - return isSVGElement(element) && element.tagName === "svg"; -} -const valueTypes = [...dimensionValueTypes, color, complex]; -const findValueType = (v) => valueTypes.find(testValueType(v)); -const createAxisDelta = () => ({ - translate: 0, - scale: 1, - origin: 0, - originPoint: 0 -}); -const createDelta = () => ({ - x: createAxisDelta(), - y: createAxisDelta() -}); -const createAxis = () => ({ min: 0, max: 0 }); -const createBox = () => ({ - x: createAxis(), - y: createAxis() -}); -const visualElementStore = /* @__PURE__ */ new WeakMap(); -function isAnimationControls(v) { - return v !== null && typeof v === "object" && typeof v.start === "function"; -} -function isVariantLabel(v) { - return typeof v === "string" || Array.isArray(v); -} -const variantPriorityOrder = [ - "animate", - "whileInView", - "whileFocus", - "whileHover", - "whileTap", - "whileDrag", - "exit" -]; -const variantProps = ["initial", ...variantPriorityOrder]; -function isControllingVariants(props) { - return isAnimationControls(props.animate) || variantProps.some((name) => isVariantLabel(props[name])); -} -function isVariantNode(props) { - return Boolean(isControllingVariants(props) || props.variants); -} -function updateMotionValuesFromProps(element, next, prev) { - for (const key in next) { - const nextValue = next[key]; - const prevValue = prev[key]; - if (isMotionValue(nextValue)) { - element.addValue(key, nextValue); - } else if (isMotionValue(prevValue)) { - element.addValue(key, motionValue(nextValue, { owner: element })); - } else if (prevValue !== nextValue) { - if (element.hasValue(key)) { - const existingValue = element.getValue(key); - if (existingValue.liveStyle === true) { - existingValue.jump(nextValue); - } else if (!existingValue.hasAnimated) { - existingValue.set(nextValue); - } - } else { - const latestValue = element.getStaticValue(key); - element.addValue(key, motionValue(latestValue !== void 0 ? latestValue : nextValue, { owner: element })); - } - } - } - for (const key in prev) { - if (next[key] === void 0) - element.removeValue(key); - } - return next; -} -const prefersReducedMotion = { current: null }; -const hasReducedMotionListener = { current: false }; -const isBrowser = typeof window !== "undefined"; -function initPrefersReducedMotion() { - hasReducedMotionListener.current = true; - if (!isBrowser) - return; - if (window.matchMedia) { - const motionMediaQuery = window.matchMedia("(prefers-reduced-motion)"); - const setReducedMotionPreferences = () => prefersReducedMotion.current = motionMediaQuery.matches; - motionMediaQuery.addEventListener("change", setReducedMotionPreferences); - setReducedMotionPreferences(); - } else { - prefersReducedMotion.current = false; - } -} -const propEventHandlers = [ - "AnimationStart", - "AnimationComplete", - "Update", - "BeforeLayoutMeasure", - "LayoutMeasure", - "LayoutAnimationStart", - "LayoutAnimationComplete" -]; -let featureDefinitions = {}; -function setFeatureDefinitions(definitions) { - featureDefinitions = definitions; -} -function getFeatureDefinitions() { - return featureDefinitions; -} -class VisualElement { - /** - * This method takes React props and returns found MotionValues. For example, HTML - * MotionValues will be found within the style prop, whereas for Three.js within attribute arrays. - * - * This isn't an abstract method as it needs calling in the constructor, but it is - * intended to be one. - */ - scrapeMotionValuesFromProps(_props, _prevProps, _visualElement) { - return {}; - } - constructor({ parent, props, presenceContext, reducedMotionConfig, skipAnimations, blockInitialAnimation, visualState }, options = {}) { - this.current = null; - this.children = /* @__PURE__ */ new Set(); - this.isVariantNode = false; - this.isControllingVariants = false; - this.shouldReduceMotion = null; - this.shouldSkipAnimations = false; - this.values = /* @__PURE__ */ new Map(); - this.KeyframeResolver = KeyframeResolver; - this.features = {}; - this.valueSubscriptions = /* @__PURE__ */ new Map(); - this.prevMotionValues = {}; - this.hasBeenMounted = false; - this.events = {}; - this.propEventSubscriptions = {}; - this.notifyUpdate = () => this.notify("Update", this.latestValues); - this.render = () => { - if (!this.current) - return; - this.triggerBuild(); - this.renderInstance(this.current, this.renderState, this.props.style, this.projection); - }; - this.renderScheduledAt = 0; - this.scheduleRender = () => { - const now2 = time.now(); - if (this.renderScheduledAt < now2) { - this.renderScheduledAt = now2; - frame.render(this.render, false, true); - } - }; - const { latestValues, renderState } = visualState; - this.latestValues = latestValues; - this.baseTarget = { ...latestValues }; - this.initialValues = props.initial ? { ...latestValues } : {}; - this.renderState = renderState; - this.parent = parent; - this.props = props; - this.presenceContext = presenceContext; - this.depth = parent ? parent.depth + 1 : 0; - this.reducedMotionConfig = reducedMotionConfig; - this.skipAnimationsConfig = skipAnimations; - this.options = options; - this.blockInitialAnimation = Boolean(blockInitialAnimation); - this.isControllingVariants = isControllingVariants(props); - this.isVariantNode = isVariantNode(props); - if (this.isVariantNode) { - this.variantChildren = /* @__PURE__ */ new Set(); - } - this.manuallyAnimateOnMount = Boolean(parent && parent.current); - const { willChange, ...initialMotionValues } = this.scrapeMotionValuesFromProps(props, {}, this); - for (const key in initialMotionValues) { - const value = initialMotionValues[key]; - if (latestValues[key] !== void 0 && isMotionValue(value)) { - value.set(latestValues[key]); - } - } - } - mount(instance) { - if (this.hasBeenMounted) { - for (const key in this.initialValues) { - this.values.get(key)?.jump(this.initialValues[key]); - this.latestValues[key] = this.initialValues[key]; - } - } - this.current = instance; - visualElementStore.set(instance, this); - if (this.projection && !this.projection.instance) { - this.projection.mount(instance); - } - if (this.parent && this.isVariantNode && !this.isControllingVariants) { - this.removeFromVariantTree = this.parent.addVariantChild(this); - } - this.values.forEach((value, key) => this.bindToMotionValue(key, value)); - if (this.reducedMotionConfig === "never") { - this.shouldReduceMotion = false; - } else if (this.reducedMotionConfig === "always") { - this.shouldReduceMotion = true; - } else { - if (!hasReducedMotionListener.current) { - initPrefersReducedMotion(); - } - this.shouldReduceMotion = prefersReducedMotion.current; - } - if (process.env.NODE_ENV !== "production") { - warnOnce(this.shouldReduceMotion !== true, "You have Reduced Motion enabled on your device. Animations may not appear as expected.", "reduced-motion-disabled"); - } - this.shouldSkipAnimations = this.skipAnimationsConfig ?? false; - this.parent?.addChild(this); - this.update(this.props, this.presenceContext); - this.hasBeenMounted = true; - } - unmount() { - this.projection && this.projection.unmount(); - cancelFrame(this.notifyUpdate); - cancelFrame(this.render); - this.valueSubscriptions.forEach((remove) => remove()); - this.valueSubscriptions.clear(); - this.removeFromVariantTree && this.removeFromVariantTree(); - this.parent?.removeChild(this); - for (const key in this.events) { - this.events[key].clear(); - } - for (const key in this.features) { - const feature = this.features[key]; - if (feature) { - feature.unmount(); - feature.isMounted = false; - } - } - this.current = null; - } - addChild(child) { - this.children.add(child); - this.enteringChildren ?? (this.enteringChildren = /* @__PURE__ */ new Set()); - this.enteringChildren.add(child); - } - removeChild(child) { - this.children.delete(child); - this.enteringChildren && this.enteringChildren.delete(child); - } - bindToMotionValue(key, value) { - if (this.valueSubscriptions.has(key)) { - this.valueSubscriptions.get(key)(); - } - if (value.accelerate && acceleratedValues.has(key) && this.current instanceof HTMLElement) { - const { factory, keyframes: keyframes2, times, ease: ease2, duration } = value.accelerate; - const animation = new NativeAnimation({ - element: this.current, - name: key, - keyframes: keyframes2, - times, - ease: ease2, - duration: /* @__PURE__ */ secondsToMilliseconds(duration) - }); - const cleanup = factory(animation); - this.valueSubscriptions.set(key, () => { - cleanup(); - animation.cancel(); - }); - return; - } - const valueIsTransform = transformProps.has(key); - if (valueIsTransform && this.onBindTransform) { - this.onBindTransform(); - } - const removeOnChange = value.on("change", (latestValue) => { - this.latestValues[key] = latestValue; - this.props.onUpdate && frame.preRender(this.notifyUpdate); - if (valueIsTransform && this.projection) { - this.projection.isTransformDirty = true; - } - this.scheduleRender(); - }); - let removeSyncCheck; - if (typeof window !== "undefined" && window.MotionCheckAppearSync) { - removeSyncCheck = window.MotionCheckAppearSync(this, key, value); - } - this.valueSubscriptions.set(key, () => { - removeOnChange(); - if (removeSyncCheck) - removeSyncCheck(); - if (value.owner) - value.stop(); - }); - } - sortNodePosition(other) { - if (!this.current || !this.sortInstanceNodePosition || this.type !== other.type) { - return 0; - } - return this.sortInstanceNodePosition(this.current, other.current); - } - updateFeatures() { - let key = "animation"; - for (key in featureDefinitions) { - const featureDefinition = featureDefinitions[key]; - if (!featureDefinition) - continue; - const { isEnabled, Feature: FeatureConstructor } = featureDefinition; - if (!this.features[key] && FeatureConstructor && isEnabled(this.props)) { - this.features[key] = new FeatureConstructor(this); - } - if (this.features[key]) { - const feature = this.features[key]; - if (feature.isMounted) { - feature.update(); - } else { - feature.mount(); - feature.isMounted = true; - } - } - } - } - triggerBuild() { - this.build(this.renderState, this.latestValues, this.props); - } - /** - * Measure the current viewport box with or without transforms. - * Only measures axis-aligned boxes, rotate and skew must be manually - * removed with a re-render to work. - */ - measureViewportBox() { - return this.current ? this.measureInstanceViewportBox(this.current, this.props) : createBox(); - } - getStaticValue(key) { - return this.latestValues[key]; - } - setStaticValue(key, value) { - this.latestValues[key] = value; - } - /** - * Update the provided props. Ensure any newly-added motion values are - * added to our map, old ones removed, and listeners updated. - */ - update(props, presenceContext) { - if (props.transformTemplate || this.props.transformTemplate) { - this.scheduleRender(); - } - this.prevProps = this.props; - this.props = props; - this.prevPresenceContext = this.presenceContext; - this.presenceContext = presenceContext; - for (let i = 0; i < propEventHandlers.length; i++) { - const key = propEventHandlers[i]; - if (this.propEventSubscriptions[key]) { - this.propEventSubscriptions[key](); - delete this.propEventSubscriptions[key]; - } - const listenerName = "on" + key; - const listener = props[listenerName]; - if (listener) { - this.propEventSubscriptions[key] = this.on(key, listener); - } - } - this.prevMotionValues = updateMotionValuesFromProps(this, this.scrapeMotionValuesFromProps(props, this.prevProps || {}, this), this.prevMotionValues); - if (this.handleChildMotionValue) { - this.handleChildMotionValue(); - } - } - getProps() { - return this.props; - } - /** - * Returns the variant definition with a given name. - */ - getVariant(name) { - return this.props.variants ? this.props.variants[name] : void 0; - } - /** - * Returns the defined default transition on this component. - */ - getDefaultTransition() { - return this.props.transition; - } - getTransformPagePoint() { - return this.props.transformPagePoint; - } - getClosestVariantNode() { - return this.isVariantNode ? this : this.parent ? this.parent.getClosestVariantNode() : void 0; - } - /** - * Add a child visual element to our set of children. - */ - addVariantChild(child) { - const closestVariantNode = this.getClosestVariantNode(); - if (closestVariantNode) { - closestVariantNode.variantChildren && closestVariantNode.variantChildren.add(child); - return () => closestVariantNode.variantChildren.delete(child); - } - } - /** - * Add a motion value and bind it to this visual element. - */ - addValue(key, value) { - const existingValue = this.values.get(key); - if (value !== existingValue) { - if (existingValue) - this.removeValue(key); - this.bindToMotionValue(key, value); - this.values.set(key, value); - this.latestValues[key] = value.get(); - } - } - /** - * Remove a motion value and unbind any active subscriptions. - */ - removeValue(key) { - this.values.delete(key); - const unsubscribe = this.valueSubscriptions.get(key); - if (unsubscribe) { - unsubscribe(); - this.valueSubscriptions.delete(key); - } - delete this.latestValues[key]; - this.removeValueFromRenderState(key, this.renderState); - } - /** - * Check whether we have a motion value for this key - */ - hasValue(key) { - return this.values.has(key); - } - getValue(key, defaultValue) { - if (this.props.values && this.props.values[key]) { - return this.props.values[key]; - } - let value = this.values.get(key); - if (value === void 0 && defaultValue !== void 0) { - value = motionValue(defaultValue === null ? void 0 : defaultValue, { owner: this }); - this.addValue(key, value); - } - return value; - } - /** - * If we're trying to animate to a previously unencountered value, - * we need to check for it in our state and as a last resort read it - * directly from the instance (which might have performance implications). - */ - readValue(key, target) { - let value = this.latestValues[key] !== void 0 || !this.current ? this.latestValues[key] : this.getBaseTargetFromProps(this.props, key) ?? this.readValueFromInstance(this.current, key, this.options); - if (value !== void 0 && value !== null) { - if (typeof value === "string" && (isNumericalString(value) || isZeroValueString(value))) { - value = parseFloat(value); - } else if (!findValueType(value) && complex.test(target)) { - value = getAnimatableNone(key, target); - } - this.setBaseTarget(key, isMotionValue(value) ? value.get() : value); - } - return isMotionValue(value) ? value.get() : value; - } - /** - * Set the base target to later animate back to. This is currently - * only hydrated on creation and when we first read a value. - */ - setBaseTarget(key, value) { - this.baseTarget[key] = value; - } - /** - * Find the base target for a value thats been removed from all animation - * props. - */ - getBaseTarget(key) { - const { initial } = this.props; - let valueFromInitial; - if (typeof initial === "string" || typeof initial === "object") { - const variant = resolveVariantFromProps(this.props, initial, this.presenceContext?.custom); - if (variant) { - valueFromInitial = variant[key]; - } - } - if (initial && valueFromInitial !== void 0) { - return valueFromInitial; - } - const target = this.getBaseTargetFromProps(this.props, key); - if (target !== void 0 && !isMotionValue(target)) - return target; - return this.initialValues[key] !== void 0 && valueFromInitial === void 0 ? void 0 : this.baseTarget[key]; - } - on(eventName, callback) { - if (!this.events[eventName]) { - this.events[eventName] = new SubscriptionManager(); - } - return this.events[eventName].add(callback); - } - notify(eventName, ...args) { - if (this.events[eventName]) { - this.events[eventName].notify(...args); - } - } - scheduleRenderMicrotask() { - microtask.render(this.render); - } -} -class DOMVisualElement extends VisualElement { - constructor() { - super(...arguments); - this.KeyframeResolver = DOMKeyframesResolver; - } - sortInstanceNodePosition(a, b) { - return a.compareDocumentPosition(b) & 2 ? 1 : -1; - } - getBaseTargetFromProps(props, key) { - const style = props.style; - return style ? style[key] : void 0; - } - removeValueFromRenderState(key, { vars, style }) { - delete vars[key]; - delete style[key]; - } - handleChildMotionValue() { - if (this.childSubscription) { - this.childSubscription(); - delete this.childSubscription; - } - const { children } = this.props; - if (isMotionValue(children)) { - this.childSubscription = children.on("change", (latest) => { - if (this.current) { - this.current.textContent = `${latest}`; - } - }); - } - } -} -class Feature { - constructor(node) { - this.isMounted = false; - this.node = node; - } - update() { - } -} -function convertBoundingBoxToBox({ top, left, right, bottom }) { - return { - x: { min: left, max: right }, - y: { min: top, max: bottom } - }; -} -function convertBoxToBoundingBox({ x, y }) { - return { top: y.min, right: x.max, bottom: y.max, left: x.min }; -} -function transformBoxPoints(point, transformPoint2) { - if (!transformPoint2) - return point; - const topLeft = transformPoint2({ x: point.left, y: point.top }); - const bottomRight = transformPoint2({ x: point.right, y: point.bottom }); - return { - top: topLeft.y, - left: topLeft.x, - bottom: bottomRight.y, - right: bottomRight.x - }; -} -function isIdentityScale(scale2) { - return scale2 === void 0 || scale2 === 1; -} -function hasScale({ scale: scale2, scaleX: scaleX2, scaleY: scaleY2 }) { - return !isIdentityScale(scale2) || !isIdentityScale(scaleX2) || !isIdentityScale(scaleY2); -} -function hasTransform(values) { - return hasScale(values) || has2DTranslate(values) || values.z || values.rotate || values.rotateX || values.rotateY || values.skewX || values.skewY; -} -function has2DTranslate(values) { - return is2DTranslate(values.x) || is2DTranslate(values.y); -} -function is2DTranslate(value) { - return value && value !== "0%"; -} -function scalePoint(point, scale2, originPoint) { - const distanceFromOrigin = point - originPoint; - const scaled = scale2 * distanceFromOrigin; - return originPoint + scaled; -} -function applyPointDelta(point, translate, scale2, originPoint, boxScale) { - if (boxScale !== void 0) { - point = scalePoint(point, boxScale, originPoint); - } - return scalePoint(point, scale2, originPoint) + translate; -} -function applyAxisDelta(axis, translate = 0, scale2 = 1, originPoint, boxScale) { - axis.min = applyPointDelta(axis.min, translate, scale2, originPoint, boxScale); - axis.max = applyPointDelta(axis.max, translate, scale2, originPoint, boxScale); -} -function applyBoxDelta(box, { x, y }) { - applyAxisDelta(box.x, x.translate, x.scale, x.originPoint); - applyAxisDelta(box.y, y.translate, y.scale, y.originPoint); -} -const TREE_SCALE_SNAP_MIN = 0.999999999999; -const TREE_SCALE_SNAP_MAX = 1.0000000000001; -function applyTreeDeltas(box, treeScale, treePath, isSharedTransition = false) { - const treeLength = treePath.length; - if (!treeLength) - return; - treeScale.x = treeScale.y = 1; - let node; - let delta; - for (let i = 0; i < treeLength; i++) { - node = treePath[i]; - delta = node.projectionDelta; - const { visualElement } = node.options; - if (visualElement && visualElement.props.style && visualElement.props.style.display === "contents") { - continue; - } - if (isSharedTransition && node.options.layoutScroll && node.scroll && node !== node.root) { - translateAxis(box.x, -node.scroll.offset.x); - translateAxis(box.y, -node.scroll.offset.y); - } - if (delta) { - treeScale.x *= delta.x.scale; - treeScale.y *= delta.y.scale; - applyBoxDelta(box, delta); - } - if (isSharedTransition && hasTransform(node.latestValues)) { - transformBox(box, node.latestValues, node.layout?.layoutBox); - } - } - if (treeScale.x < TREE_SCALE_SNAP_MAX && treeScale.x > TREE_SCALE_SNAP_MIN) { - treeScale.x = 1; - } - if (treeScale.y < TREE_SCALE_SNAP_MAX && treeScale.y > TREE_SCALE_SNAP_MIN) { - treeScale.y = 1; - } -} -function translateAxis(axis, distance2) { - axis.min += distance2; - axis.max += distance2; -} -function transformAxis(axis, axisTranslate, axisScale, boxScale, axisOrigin = 0.5) { - const originPoint = mixNumber$1(axis.min, axis.max, axisOrigin); - applyAxisDelta(axis, axisTranslate, axisScale, originPoint, boxScale); -} -function resolveAxisTranslate(value, axis) { - if (typeof value === "string") { - return parseFloat(value) / 100 * (axis.max - axis.min); - } - return value; -} -function transformBox(box, transform, sourceBox) { - const resolveBox = sourceBox ?? box; - transformAxis(box.x, resolveAxisTranslate(transform.x, resolveBox.x), transform.scaleX, transform.scale, transform.originX); - transformAxis(box.y, resolveAxisTranslate(transform.y, resolveBox.y), transform.scaleY, transform.scale, transform.originY); -} -function measureViewportBox(instance, transformPoint2) { - return convertBoundingBoxToBox(transformBoxPoints(instance.getBoundingClientRect(), transformPoint2)); -} -function measurePageBox(element, rootProjectionNode2, transformPagePoint) { - const viewportBox = measureViewportBox(element, transformPagePoint); - const { scroll } = rootProjectionNode2; - if (scroll) { - translateAxis(viewportBox.x, scroll.offset.x); - translateAxis(viewportBox.y, scroll.offset.y); - } - return viewportBox; -} -const translateAlias = { - x: "translateX", - y: "translateY", - z: "translateZ", - transformPerspective: "perspective" -}; -const numTransforms = transformPropOrder.length; -function buildTransform(latestValues, transform, transformTemplate) { - let transformString = ""; - let transformIsDefault = true; - for (let i = 0; i < numTransforms; i++) { - const key = transformPropOrder[i]; - const value = latestValues[key]; - if (value === void 0) - continue; - let valueIsDefault = true; - if (typeof value === "number") { - valueIsDefault = value === (key.startsWith("scale") ? 1 : 0); - } else { - const parsed = parseFloat(value); - valueIsDefault = key.startsWith("scale") ? parsed === 1 : parsed === 0; - } - if (!valueIsDefault || transformTemplate) { - const valueAsType = getValueAsType(value, numberValueTypes[key]); - if (!valueIsDefault) { - transformIsDefault = false; - const transformName = translateAlias[key] || key; - transformString += `${transformName}(${valueAsType}) `; - } - if (transformTemplate) { - transform[key] = valueAsType; - } - } - } - transformString = transformString.trim(); - if (transformTemplate) { - transformString = transformTemplate(transform, transformIsDefault ? "" : transformString); - } else if (transformIsDefault) { - transformString = "none"; - } - return transformString; -} -function buildHTMLStyles(state, latestValues, transformTemplate) { - const { style, vars, transformOrigin } = state; - let hasTransform2 = false; - let hasTransformOrigin = false; - for (const key in latestValues) { - const value = latestValues[key]; - if (transformProps.has(key)) { - hasTransform2 = true; - continue; - } else if (isCSSVariableName(key)) { - vars[key] = value; - continue; - } else { - const valueAsType = getValueAsType(value, numberValueTypes[key]); - if (key.startsWith("origin")) { - hasTransformOrigin = true; - transformOrigin[key] = valueAsType; - } else { - style[key] = valueAsType; - } - } - } - if (!latestValues.transform) { - if (hasTransform2 || transformTemplate) { - style.transform = buildTransform(latestValues, state.transform, transformTemplate); - } else if (style.transform) { - style.transform = "none"; - } - } - if (hasTransformOrigin) { - const { originX = "50%", originY = "50%", originZ = 0 } = transformOrigin; - style.transformOrigin = `${originX} ${originY} ${originZ}`; - } -} -function renderHTML(element, { style, vars }, styleProp, projection) { - const elementStyle = element.style; - let key; - for (key in style) { - elementStyle[key] = style[key]; - } - projection?.applyProjectionStyles(elementStyle, styleProp); - for (key in vars) { - elementStyle.setProperty(key, vars[key]); - } -} -function pixelsToPercent(pixels, axis) { - if (axis.max === axis.min) - return 0; - return pixels / (axis.max - axis.min) * 100; -} -const correctBorderRadius = { - correct: (latest, node) => { - if (!node.target) - return latest; - if (typeof latest === "string") { - if (px.test(latest)) { - latest = parseFloat(latest); - } else { - return latest; - } - } - const x = pixelsToPercent(latest, node.target.x); - const y = pixelsToPercent(latest, node.target.y); - return `${x}% ${y}%`; - } -}; -const correctBoxShadow = { - correct: (latest, { treeScale, projectionDelta }) => { - const original = latest; - const shadow = complex.parse(latest); - if (shadow.length > 5) - return original; - const template = complex.createTransformer(latest); - const offset = typeof shadow[0] !== "number" ? 1 : 0; - const xScale = projectionDelta.x.scale * treeScale.x; - const yScale = projectionDelta.y.scale * treeScale.y; - shadow[0 + offset] /= xScale; - shadow[1 + offset] /= yScale; - const averageScale = mixNumber$1(xScale, yScale, 0.5); - if (typeof shadow[2 + offset] === "number") - shadow[2 + offset] /= averageScale; - if (typeof shadow[3 + offset] === "number") - shadow[3 + offset] /= averageScale; - return template(shadow); - } -}; -const scaleCorrectors = { - borderRadius: { - ...correctBorderRadius, - applyTo: [ - "borderTopLeftRadius", - "borderTopRightRadius", - "borderBottomLeftRadius", - "borderBottomRightRadius" - ] - }, - borderTopLeftRadius: correctBorderRadius, - borderTopRightRadius: correctBorderRadius, - borderBottomLeftRadius: correctBorderRadius, - borderBottomRightRadius: correctBorderRadius, - boxShadow: correctBoxShadow -}; -function isForcedMotionValue(key, { layout: layout2, layoutId }) { - return transformProps.has(key) || key.startsWith("origin") || (layout2 || layoutId !== void 0) && (!!scaleCorrectors[key] || key === "opacity"); -} -function scrapeMotionValuesFromProps$1(props, prevProps, visualElement) { - const style = props.style; - const prevStyle = prevProps?.style; - const newValues = {}; - if (!style) - return newValues; - for (const key in style) { - if (isMotionValue(style[key]) || prevStyle && isMotionValue(prevStyle[key]) || isForcedMotionValue(key, props) || visualElement?.getValue(key)?.liveStyle !== void 0) { - newValues[key] = style[key]; - } - } - return newValues; -} -function getComputedStyle$1(element) { - return window.getComputedStyle(element); -} -class HTMLVisualElement extends DOMVisualElement { - constructor() { - super(...arguments); - this.type = "html"; - this.renderInstance = renderHTML; - } - readValueFromInstance(instance, key) { - if (transformProps.has(key)) { - return this.projection?.isProjecting ? defaultTransformValue(key) : readTransformValue(instance, key); - } else { - const computedStyle = getComputedStyle$1(instance); - const value = (isCSSVariableName(key) ? computedStyle.getPropertyValue(key) : computedStyle[key]) || 0; - return typeof value === "string" ? value.trim() : value; - } - } - measureInstanceViewportBox(instance, { transformPagePoint }) { - return measureViewportBox(instance, transformPagePoint); - } - build(renderState, latestValues, props) { - buildHTMLStyles(renderState, latestValues, props.transformTemplate); - } - scrapeMotionValuesFromProps(props, prevProps, visualElement) { - return scrapeMotionValuesFromProps$1(props, prevProps, visualElement); - } -} -const dashKeys = { - offset: "stroke-dashoffset", - array: "stroke-dasharray" -}; -const camelKeys = { - offset: "strokeDashoffset", - array: "strokeDasharray" -}; -function buildSVGPath(attrs, length, spacing = 1, offset = 0, useDashCase = true) { - attrs.pathLength = 1; - const keys = useDashCase ? dashKeys : camelKeys; - attrs[keys.offset] = `${-offset}`; - attrs[keys.array] = `${length} ${spacing}`; -} -const cssMotionPathProperties = [ - "offsetDistance", - "offsetPath", - "offsetRotate", - "offsetAnchor" -]; -function buildSVGAttrs(state, { - attrX, - attrY, - attrScale, - pathLength, - pathSpacing = 1, - pathOffset = 0, - // This is object creation, which we try to avoid per-frame. - ...latest -}, isSVGTag2, transformTemplate, styleProp) { - buildHTMLStyles(state, latest, transformTemplate); - if (isSVGTag2) { - if (state.style.viewBox) { - state.attrs.viewBox = state.style.viewBox; - } - return; - } - state.attrs = state.style; - state.style = {}; - const { attrs, style } = state; - if (attrs.transform) { - style.transform = attrs.transform; - delete attrs.transform; - } - if (style.transform || attrs.transformOrigin) { - style.transformOrigin = attrs.transformOrigin ?? "50% 50%"; - delete attrs.transformOrigin; - } - if (style.transform) { - style.transformBox = styleProp?.transformBox ?? "fill-box"; - delete attrs.transformBox; - } - for (const key of cssMotionPathProperties) { - if (attrs[key] !== void 0) { - style[key] = attrs[key]; - delete attrs[key]; - } - } - if (attrX !== void 0) - attrs.x = attrX; - if (attrY !== void 0) - attrs.y = attrY; - if (attrScale !== void 0) - attrs.scale = attrScale; - if (pathLength !== void 0) { - buildSVGPath(attrs, pathLength, pathSpacing, pathOffset, false); - } -} -const camelCaseAttributes = /* @__PURE__ */ new Set([ - "baseFrequency", - "diffuseConstant", - "kernelMatrix", - "kernelUnitLength", - "keySplines", - "keyTimes", - "limitingConeAngle", - "markerHeight", - "markerWidth", - "numOctaves", - "targetX", - "targetY", - "surfaceScale", - "specularConstant", - "specularExponent", - "stdDeviation", - "tableValues", - "viewBox", - "gradientTransform", - "pathLength", - "startOffset", - "textLength", - "lengthAdjust" -]); -const isSVGTag = (tag) => typeof tag === "string" && tag.toLowerCase() === "svg"; -function renderSVG(element, renderState, _styleProp, projection) { - renderHTML(element, renderState, void 0, projection); - for (const key in renderState.attrs) { - element.setAttribute(!camelCaseAttributes.has(key) ? camelToDash(key) : key, renderState.attrs[key]); - } -} -function scrapeMotionValuesFromProps(props, prevProps, visualElement) { - const newValues = scrapeMotionValuesFromProps$1(props, prevProps, visualElement); - for (const key in props) { - if (isMotionValue(props[key]) || isMotionValue(prevProps[key])) { - const targetKey = transformPropOrder.indexOf(key) !== -1 ? "attr" + key.charAt(0).toUpperCase() + key.substring(1) : key; - newValues[targetKey] = props[key]; - } - } - return newValues; -} -class SVGVisualElement extends DOMVisualElement { - constructor() { - super(...arguments); - this.type = "svg"; - this.isSVGTag = false; - this.measureInstanceViewportBox = createBox; - } - getBaseTargetFromProps(props, key) { - return props[key]; - } - readValueFromInstance(instance, key) { - if (transformProps.has(key)) { - const defaultType = getDefaultValueType(key); - return defaultType ? defaultType.default || 0 : 0; - } - key = !camelCaseAttributes.has(key) ? camelToDash(key) : key; - return instance.getAttribute(key); - } - scrapeMotionValuesFromProps(props, prevProps, visualElement) { - return scrapeMotionValuesFromProps(props, prevProps, visualElement); - } - build(renderState, latestValues, props) { - buildSVGAttrs(renderState, latestValues, this.isSVGTag, props.transformTemplate, props.style); - } - renderInstance(instance, renderState, styleProp, projection) { - renderSVG(instance, renderState, styleProp, projection); - } - mount(instance) { - this.isSVGTag = isSVGTag(instance.tagName); - super.mount(instance); - } -} -const numVariantProps = variantProps.length; -function getVariantContext(visualElement) { - if (!visualElement) - return void 0; - if (!visualElement.isControllingVariants) { - const context2 = visualElement.parent ? getVariantContext(visualElement.parent) || {} : {}; - if (visualElement.props.initial !== void 0) { - context2.initial = visualElement.props.initial; - } - return context2; - } - const context = {}; - for (let i = 0; i < numVariantProps; i++) { - const name = variantProps[i]; - const prop = visualElement.props[name]; - if (isVariantLabel(prop) || prop === false) { - context[name] = prop; - } - } - return context; -} -function shallowCompare(next, prev) { - if (!Array.isArray(prev)) - return false; - const prevLength = prev.length; - if (prevLength !== next.length) - return false; - for (let i = 0; i < prevLength; i++) { - if (prev[i] !== next[i]) - return false; - } - return true; -} -const reversePriorityOrder = [...variantPriorityOrder].reverse(); -const numAnimationTypes = variantPriorityOrder.length; -function createAnimateFunction(visualElement) { - return (animations2) => { - return Promise.all(animations2.map(({ animation, options }) => animateVisualElement(visualElement, animation, options))); - }; -} -function createAnimationState(visualElement) { - let animate = createAnimateFunction(visualElement); - let state = createState(); - let isInitialRender = true; - let wasReset = false; - const buildResolvedTypeValues = (type) => (acc, definition) => { - const resolved = resolveVariant(visualElement, definition, type === "exit" ? visualElement.presenceContext?.custom : void 0); - if (resolved) { - const { transition, transitionEnd, ...target } = resolved; - acc = { ...acc, ...target, ...transitionEnd }; - } - return acc; - }; - function setAnimateFunction(makeAnimator) { - animate = makeAnimator(visualElement); - } - function animateChanges(changedActiveType) { - const { props } = visualElement; - const context = getVariantContext(visualElement.parent) || {}; - const animations2 = []; - const removedKeys = /* @__PURE__ */ new Set(); - let encounteredKeys = {}; - let removedVariantIndex = Infinity; - for (let i = 0; i < numAnimationTypes; i++) { - const type = reversePriorityOrder[i]; - const typeState = state[type]; - const prop = props[type] !== void 0 ? props[type] : context[type]; - const propIsVariant = isVariantLabel(prop); - const activeDelta = type === changedActiveType ? typeState.isActive : null; - if (activeDelta === false) - removedVariantIndex = i; - let isInherited = prop === context[type] && prop !== props[type] && propIsVariant; - if (isInherited && (isInitialRender || wasReset) && visualElement.manuallyAnimateOnMount) { - isInherited = false; - } - typeState.protectedKeys = { ...encounteredKeys }; - if ( - // If it isn't active and hasn't *just* been set as inactive - !typeState.isActive && activeDelta === null || // If we didn't and don't have any defined prop for this animation type - !prop && !typeState.prevProp || // Or if the prop doesn't define an animation - isAnimationControls(prop) || typeof prop === "boolean" - ) { - continue; - } - if (type === "exit" && typeState.isActive && activeDelta !== true) { - if (typeState.prevResolvedValues) { - encounteredKeys = { - ...encounteredKeys, - ...typeState.prevResolvedValues - }; - } - continue; - } - const variantDidChange = checkVariantsDidChange(typeState.prevProp, prop); - let shouldAnimateType = variantDidChange || // If we're making this variant active, we want to always make it active - type === changedActiveType && typeState.isActive && !isInherited && propIsVariant || // If we removed a higher-priority variant (i is in reverse order) - i > removedVariantIndex && propIsVariant; - let handledRemovedValues = false; - const definitionList = Array.isArray(prop) ? prop : [prop]; - let resolvedValues = definitionList.reduce(buildResolvedTypeValues(type), {}); - if (activeDelta === false) - resolvedValues = {}; - const { prevResolvedValues = {} } = typeState; - const allKeys = { - ...prevResolvedValues, - ...resolvedValues - }; - const markToAnimate = (key) => { - shouldAnimateType = true; - if (removedKeys.has(key)) { - handledRemovedValues = true; - removedKeys.delete(key); - } - typeState.needsAnimating[key] = true; - const motionValue2 = visualElement.getValue(key); - if (motionValue2) - motionValue2.liveStyle = false; - }; - for (const key in allKeys) { - const next = resolvedValues[key]; - const prev = prevResolvedValues[key]; - if (encounteredKeys.hasOwnProperty(key)) - continue; - let valueHasChanged = false; - if (isKeyframesTarget(next) && isKeyframesTarget(prev)) { - valueHasChanged = !shallowCompare(next, prev); - } else { - valueHasChanged = next !== prev; - } - if (valueHasChanged) { - if (next !== void 0 && next !== null) { - markToAnimate(key); - } else { - removedKeys.add(key); - } - } else if (next !== void 0 && removedKeys.has(key)) { - markToAnimate(key); - } else { - typeState.protectedKeys[key] = true; - } - } - typeState.prevProp = prop; - typeState.prevResolvedValues = resolvedValues; - if (typeState.isActive) { - encounteredKeys = { ...encounteredKeys, ...resolvedValues }; - } - if ((isInitialRender || wasReset) && visualElement.blockInitialAnimation) { - shouldAnimateType = false; - } - const willAnimateViaParent = isInherited && variantDidChange; - const needsAnimating = !willAnimateViaParent || handledRemovedValues; - if (shouldAnimateType && needsAnimating) { - animations2.push(...definitionList.map((animation) => { - const options = { type }; - if (typeof animation === "string" && (isInitialRender || wasReset) && !willAnimateViaParent && visualElement.manuallyAnimateOnMount && visualElement.parent) { - const { parent } = visualElement; - const parentVariant = resolveVariant(parent, animation); - if (parent.enteringChildren && parentVariant) { - const { delayChildren } = parentVariant.transition || {}; - options.delay = calcChildStagger(parent.enteringChildren, visualElement, delayChildren); - } - } - return { - animation, - options - }; - })); - } - } - if (removedKeys.size) { - const fallbackAnimation = {}; - if (typeof props.initial !== "boolean") { - const initialTransition = resolveVariant(visualElement, Array.isArray(props.initial) ? props.initial[0] : props.initial); - if (initialTransition && initialTransition.transition) { - fallbackAnimation.transition = initialTransition.transition; - } - } - removedKeys.forEach((key) => { - const fallbackTarget = visualElement.getBaseTarget(key); - const motionValue2 = visualElement.getValue(key); - if (motionValue2) - motionValue2.liveStyle = true; - fallbackAnimation[key] = fallbackTarget ?? null; - }); - animations2.push({ animation: fallbackAnimation }); - } - let shouldAnimate = Boolean(animations2.length); - if (isInitialRender && (props.initial === false || props.initial === props.animate) && !visualElement.manuallyAnimateOnMount) { - shouldAnimate = false; - } - isInitialRender = false; - wasReset = false; - return shouldAnimate ? animate(animations2) : Promise.resolve(); - } - function setActive(type, isActive) { - if (state[type].isActive === isActive) - return Promise.resolve(); - visualElement.variantChildren?.forEach((child) => child.animationState?.setActive(type, isActive)); - state[type].isActive = isActive; - const animations2 = animateChanges(type); - for (const key in state) { - state[key].protectedKeys = {}; - } - return animations2; - } - return { - animateChanges, - setActive, - setAnimateFunction, - getState: () => state, - reset: () => { - state = createState(); - wasReset = true; - } - }; -} -function checkVariantsDidChange(prev, next) { - if (typeof next === "string") { - return next !== prev; - } else if (Array.isArray(next)) { - return !shallowCompare(next, prev); - } - return false; -} -function createTypeState(isActive = false) { - return { - isActive, - protectedKeys: {}, - needsAnimating: {}, - prevResolvedValues: {} - }; -} -function createState() { - return { - animate: createTypeState(true), - whileInView: createTypeState(), - whileHover: createTypeState(), - whileTap: createTypeState(), - whileDrag: createTypeState(), - whileFocus: createTypeState(), - exit: createTypeState() - }; -} -function copyAxisInto(axis, originAxis) { - axis.min = originAxis.min; - axis.max = originAxis.max; -} -function copyBoxInto(box, originBox) { - copyAxisInto(box.x, originBox.x); - copyAxisInto(box.y, originBox.y); -} -function copyAxisDeltaInto(delta, originDelta) { - delta.translate = originDelta.translate; - delta.scale = originDelta.scale; - delta.originPoint = originDelta.originPoint; - delta.origin = originDelta.origin; -} -const SCALE_PRECISION = 1e-4; -const SCALE_MIN = 1 - SCALE_PRECISION; -const SCALE_MAX = 1 + SCALE_PRECISION; -const TRANSLATE_PRECISION = 0.01; -const TRANSLATE_MIN = 0 - TRANSLATE_PRECISION; -const TRANSLATE_MAX = 0 + TRANSLATE_PRECISION; -function calcLength(axis) { - return axis.max - axis.min; -} -function isNear(value, target, maxDistance) { - return Math.abs(value - target) <= maxDistance; -} -function calcAxisDelta(delta, source, target, origin = 0.5) { - delta.origin = origin; - delta.originPoint = mixNumber$1(source.min, source.max, delta.origin); - delta.scale = calcLength(target) / calcLength(source); - delta.translate = mixNumber$1(target.min, target.max, delta.origin) - delta.originPoint; - if (delta.scale >= SCALE_MIN && delta.scale <= SCALE_MAX || isNaN(delta.scale)) { - delta.scale = 1; - } - if (delta.translate >= TRANSLATE_MIN && delta.translate <= TRANSLATE_MAX || isNaN(delta.translate)) { - delta.translate = 0; - } -} -function calcBoxDelta(delta, source, target, origin) { - calcAxisDelta(delta.x, source.x, target.x, origin ? origin.originX : void 0); - calcAxisDelta(delta.y, source.y, target.y, origin ? origin.originY : void 0); -} -function calcRelativeAxis(target, relative, parent, anchor = 0) { - const anchorPoint = anchor ? mixNumber$1(parent.min, parent.max, anchor) : parent.min; - target.min = anchorPoint + relative.min; - target.max = target.min + calcLength(relative); -} -function calcRelativeBox(target, relative, parent, anchor) { - calcRelativeAxis(target.x, relative.x, parent.x, anchor?.x); - calcRelativeAxis(target.y, relative.y, parent.y, anchor?.y); -} -function calcRelativeAxisPosition(target, layout2, parent, anchor = 0) { - const anchorPoint = anchor ? mixNumber$1(parent.min, parent.max, anchor) : parent.min; - target.min = layout2.min - anchorPoint; - target.max = target.min + calcLength(layout2); -} -function calcRelativePosition(target, layout2, parent, anchor) { - calcRelativeAxisPosition(target.x, layout2.x, parent.x, anchor?.x); - calcRelativeAxisPosition(target.y, layout2.y, parent.y, anchor?.y); -} -function removePointDelta(point, translate, scale2, originPoint, boxScale) { - point -= translate; - point = scalePoint(point, 1 / scale2, originPoint); - if (boxScale !== void 0) { - point = scalePoint(point, 1 / boxScale, originPoint); - } - return point; -} -function removeAxisDelta(axis, translate = 0, scale2 = 1, origin = 0.5, boxScale, originAxis = axis, sourceAxis = axis) { - if (percent.test(translate)) { - translate = parseFloat(translate); - const relativeProgress = mixNumber$1(sourceAxis.min, sourceAxis.max, translate / 100); - translate = relativeProgress - sourceAxis.min; - } - if (typeof translate !== "number") - return; - let originPoint = mixNumber$1(originAxis.min, originAxis.max, origin); - if (axis === originAxis) - originPoint -= translate; - axis.min = removePointDelta(axis.min, translate, scale2, originPoint, boxScale); - axis.max = removePointDelta(axis.max, translate, scale2, originPoint, boxScale); -} -function removeAxisTransforms(axis, transforms, [key, scaleKey, originKey], origin, sourceAxis) { - removeAxisDelta(axis, transforms[key], transforms[scaleKey], transforms[originKey], transforms.scale, origin, sourceAxis); -} -const xKeys = ["x", "scaleX", "originX"]; -const yKeys = ["y", "scaleY", "originY"]; -function removeBoxTransforms(box, transforms, originBox, sourceBox) { - removeAxisTransforms(box.x, transforms, xKeys, originBox ? originBox.x : void 0, sourceBox ? sourceBox.x : void 0); - removeAxisTransforms(box.y, transforms, yKeys, originBox ? originBox.y : void 0, sourceBox ? sourceBox.y : void 0); -} -function isAxisDeltaZero(delta) { - return delta.translate === 0 && delta.scale === 1; -} -function isDeltaZero(delta) { - return isAxisDeltaZero(delta.x) && isAxisDeltaZero(delta.y); -} -function axisEquals(a, b) { - return a.min === b.min && a.max === b.max; -} -function boxEquals(a, b) { - return axisEquals(a.x, b.x) && axisEquals(a.y, b.y); -} -function axisEqualsRounded(a, b) { - return Math.round(a.min) === Math.round(b.min) && Math.round(a.max) === Math.round(b.max); -} -function boxEqualsRounded(a, b) { - return axisEqualsRounded(a.x, b.x) && axisEqualsRounded(a.y, b.y); -} -function aspectRatio(box) { - return calcLength(box.x) / calcLength(box.y); -} -function axisDeltaEquals(a, b) { - return a.translate === b.translate && a.scale === b.scale && a.originPoint === b.originPoint; -} -function eachAxis(callback) { - return [callback("x"), callback("y")]; -} -function buildProjectionTransform(delta, treeScale, latestTransform) { - let transform = ""; - const xTranslate = delta.x.translate / treeScale.x; - const yTranslate = delta.y.translate / treeScale.y; - const zTranslate = latestTransform?.z || 0; - if (xTranslate || yTranslate || zTranslate) { - transform = `translate3d(${xTranslate}px, ${yTranslate}px, ${zTranslate}px) `; - } - if (treeScale.x !== 1 || treeScale.y !== 1) { - transform += `scale(${1 / treeScale.x}, ${1 / treeScale.y}) `; - } - if (latestTransform) { - const { transformPerspective, rotate: rotate2, rotateX, rotateY, skewX, skewY } = latestTransform; - if (transformPerspective) - transform = `perspective(${transformPerspective}px) ${transform}`; - if (rotate2) - transform += `rotate(${rotate2}deg) `; - if (rotateX) - transform += `rotateX(${rotateX}deg) `; - if (rotateY) - transform += `rotateY(${rotateY}deg) `; - if (skewX) - transform += `skewX(${skewX}deg) `; - if (skewY) - transform += `skewY(${skewY}deg) `; - } - const elementScaleX = delta.x.scale * treeScale.x; - const elementScaleY = delta.y.scale * treeScale.y; - if (elementScaleX !== 1 || elementScaleY !== 1) { - transform += `scale(${elementScaleX}, ${elementScaleY})`; - } - return transform || "none"; -} -const borderLabels = [ - "borderTopLeftRadius", - "borderTopRightRadius", - "borderBottomLeftRadius", - "borderBottomRightRadius" -]; -const numBorders = borderLabels.length; -const asNumber = (value) => typeof value === "string" ? parseFloat(value) : value; -const isPx = (value) => typeof value === "number" || px.test(value); -function mixValues(target, follow, lead, progress2, shouldCrossfadeOpacity, isOnlyMember) { - if (shouldCrossfadeOpacity) { - target.opacity = mixNumber$1(0, lead.opacity ?? 1, easeCrossfadeIn(progress2)); - target.opacityExit = mixNumber$1(follow.opacity ?? 1, 0, easeCrossfadeOut(progress2)); - } else if (isOnlyMember) { - target.opacity = mixNumber$1(follow.opacity ?? 1, lead.opacity ?? 1, progress2); - } - for (let i = 0; i < numBorders; i++) { - const borderLabel = borderLabels[i]; - let followRadius = getRadius(follow, borderLabel); - let leadRadius = getRadius(lead, borderLabel); - if (followRadius === void 0 && leadRadius === void 0) - continue; - followRadius || (followRadius = 0); - leadRadius || (leadRadius = 0); - const canMix = followRadius === 0 || leadRadius === 0 || isPx(followRadius) === isPx(leadRadius); - if (canMix) { - target[borderLabel] = Math.max(mixNumber$1(asNumber(followRadius), asNumber(leadRadius), progress2), 0); - if (percent.test(leadRadius) || percent.test(followRadius)) { - target[borderLabel] += "%"; - } - } else { - target[borderLabel] = leadRadius; - } - } - if (follow.rotate || lead.rotate) { - target.rotate = mixNumber$1(follow.rotate || 0, lead.rotate || 0, progress2); - } -} -function getRadius(values, radiusName) { - return values[radiusName] !== void 0 ? values[radiusName] : values.borderRadius; -} -const easeCrossfadeIn = /* @__PURE__ */ compress(0, 0.5, circOut); -const easeCrossfadeOut = /* @__PURE__ */ compress(0.5, 0.95, noop); -function compress(min, max, easing) { - return (p) => { - if (p < min) - return 0; - if (p > max) - return 1; - return easing(/* @__PURE__ */ progress(min, max, p)); - }; -} -function animateSingleValue(value, keyframes2, options) { - const motionValue$1 = isMotionValue(value) ? value : motionValue(value); - motionValue$1.start(animateMotionValue("", motionValue$1, keyframes2, options)); - return motionValue$1.animation; -} -function addDomEvent(target, eventName, handler, options = { passive: true }) { - target.addEventListener(eventName, handler, options); - return () => target.removeEventListener(eventName, handler); -} -const compareByDepth = (a, b) => a.depth - b.depth; -class FlatTree { - constructor() { - this.children = []; - this.isDirty = false; - } - add(child) { - addUniqueItem(this.children, child); - this.isDirty = true; - } - remove(child) { - removeItem(this.children, child); - this.isDirty = true; - } - forEach(callback) { - this.isDirty && this.children.sort(compareByDepth); - this.isDirty = false; - this.children.forEach(callback); - } -} -function delay(callback, timeout) { - const start = time.now(); - const checkElapsed = ({ timestamp }) => { - const elapsed = timestamp - start; - if (elapsed >= timeout) { - cancelFrame(checkElapsed); - callback(elapsed - timeout); - } - }; - frame.setup(checkElapsed, true); - return () => cancelFrame(checkElapsed); -} -function resolveMotionValue(value) { - return isMotionValue(value) ? value.get() : value; -} -class NodeStack { - constructor() { - this.members = []; - } - add(node) { - addUniqueItem(this.members, node); - for (let i = this.members.length - 1; i >= 0; i--) { - const member = this.members[i]; - if (member === node || member === this.lead || member === this.prevLead) - continue; - const inst = member.instance; - if ((!inst || inst.isConnected === false) && !member.snapshot) { - removeItem(this.members, member); - member.unmount(); - } - } - node.scheduleRender(); - } - remove(node) { - removeItem(this.members, node); - if (node === this.prevLead) - this.prevLead = void 0; - if (node === this.lead) { - const prevLead = this.members[this.members.length - 1]; - if (prevLead) - this.promote(prevLead); - } - } - relegate(node) { - for (let i = this.members.indexOf(node) - 1; i >= 0; i--) { - const member = this.members[i]; - if (member.isPresent !== false && member.instance?.isConnected !== false) { - this.promote(member); - return true; - } - } - return false; - } - promote(node, preserveFollowOpacity) { - const prevLead = this.lead; - if (node === prevLead) - return; - this.prevLead = prevLead; - this.lead = node; - node.show(); - if (prevLead) { - prevLead.updateSnapshot(); - node.scheduleRender(); - const { layoutDependency: prevDep } = prevLead.options; - const { layoutDependency: nextDep } = node.options; - if (prevDep === void 0 || prevDep !== nextDep) { - node.resumeFrom = prevLead; - if (preserveFollowOpacity) - prevLead.preserveOpacity = true; - if (prevLead.snapshot) { - node.snapshot = prevLead.snapshot; - node.snapshot.latestValues = prevLead.animationValues || prevLead.latestValues; - } - if (node.root?.isUpdating) - node.isLayoutDirty = true; - } - if (node.options.crossfade === false) - prevLead.hide(); - } - } - exitAnimationComplete() { - this.members.forEach((member) => { - member.options.onExitComplete?.(); - member.resumingFrom?.options.onExitComplete?.(); - }); - } - scheduleRender() { - this.members.forEach((member) => member.instance && member.scheduleRender(false)); - } - removeLeadSnapshot() { - if (this.lead?.snapshot) - this.lead.snapshot = void 0; - } -} -const globalProjectionState = { - /** - * Global flag as to whether the tree has animated since the last time - * we resized the window - */ - hasAnimatedSinceResize: true, - /** - * We set this to true once, on the first update. Any nodes added to the tree beyond that - * update will be given a `data-projection-id` attribute. - */ - hasEverUpdated: false -}; -const transformAxes = ["", "X", "Y", "Z"]; -const animationTarget = 1e3; -let id$1 = 0; -function resetDistortingTransform(key, visualElement, values, sharedAnimationValues) { - const { latestValues } = visualElement; - if (latestValues[key]) { - values[key] = latestValues[key]; - visualElement.setStaticValue(key, 0); - if (sharedAnimationValues) { - sharedAnimationValues[key] = 0; - } - } -} -function cancelTreeOptimisedTransformAnimations(projectionNode) { - projectionNode.hasCheckedOptimisedAppear = true; - if (projectionNode.root === projectionNode) - return; - const { visualElement } = projectionNode.options; - if (!visualElement) - return; - const appearId = getOptimisedAppearId(visualElement); - if (window.MotionHasOptimisedAnimation(appearId, "transform")) { - const { layout: layout2, layoutId } = projectionNode.options; - window.MotionCancelOptimisedAnimation(appearId, "transform", frame, !(layout2 || layoutId)); - } - const { parent } = projectionNode; - if (parent && !parent.hasCheckedOptimisedAppear) { - cancelTreeOptimisedTransformAnimations(parent); - } -} -function createProjectionNode$1({ attachResizeListener, defaultParent, measureScroll, checkIsScrollRoot, resetTransform }) { - return class ProjectionNode { - constructor(latestValues = {}, parent = defaultParent?.()) { - this.id = id$1++; - this.animationId = 0; - this.animationCommitId = 0; - this.children = /* @__PURE__ */ new Set(); - this.options = {}; - this.isTreeAnimating = false; - this.isAnimationBlocked = false; - this.isLayoutDirty = false; - this.isProjectionDirty = false; - this.isSharedProjectionDirty = false; - this.isTransformDirty = false; - this.updateManuallyBlocked = false; - this.updateBlockedByResize = false; - this.isUpdating = false; - this.isSVG = false; - this.needsReset = false; - this.shouldResetTransform = false; - this.hasCheckedOptimisedAppear = false; - this.treeScale = { x: 1, y: 1 }; - this.eventHandlers = /* @__PURE__ */ new Map(); - this.hasTreeAnimated = false; - this.layoutVersion = 0; - this.updateScheduled = false; - this.scheduleUpdate = () => this.update(); - this.projectionUpdateScheduled = false; - this.checkUpdateFailed = () => { - if (this.isUpdating) { - this.isUpdating = false; - this.clearAllSnapshots(); - } - }; - this.updateProjection = () => { - this.projectionUpdateScheduled = false; - this.nodes.forEach(propagateDirtyNodes); - this.nodes.forEach(resolveTargetDelta); - this.nodes.forEach(calcProjection); - this.nodes.forEach(cleanDirtyNodes); - }; - this.resolvedRelativeTargetAt = 0; - this.linkedParentVersion = 0; - this.hasProjected = false; - this.isVisible = true; - this.animationProgress = 0; - this.sharedNodes = /* @__PURE__ */ new Map(); - this.latestValues = latestValues; - this.root = parent ? parent.root || parent : this; - this.path = parent ? [...parent.path, parent] : []; - this.parent = parent; - this.depth = parent ? parent.depth + 1 : 0; - for (let i = 0; i < this.path.length; i++) { - this.path[i].shouldResetTransform = true; - } - if (this.root === this) - this.nodes = new FlatTree(); - } - addEventListener(name, handler) { - if (!this.eventHandlers.has(name)) { - this.eventHandlers.set(name, new SubscriptionManager()); - } - return this.eventHandlers.get(name).add(handler); - } - notifyListeners(name, ...args) { - const subscriptionManager = this.eventHandlers.get(name); - subscriptionManager && subscriptionManager.notify(...args); - } - hasListeners(name) { - return this.eventHandlers.has(name); - } - /** - * Lifecycles - */ - mount(instance) { - if (this.instance) - return; - this.isSVG = isSVGElement(instance) && !isSVGSVGElement(instance); - this.instance = instance; - const { layoutId, layout: layout2, visualElement } = this.options; - if (visualElement && !visualElement.current) { - visualElement.mount(instance); - } - this.root.nodes.add(this); - this.parent && this.parent.children.add(this); - if (this.root.hasTreeAnimated && (layout2 || layoutId)) { - this.isLayoutDirty = true; - } - if (attachResizeListener) { - let cancelDelay; - let innerWidth = 0; - const resizeUnblockUpdate = () => this.root.updateBlockedByResize = false; - frame.read(() => { - innerWidth = window.innerWidth; - }); - attachResizeListener(instance, () => { - const newInnerWidth = window.innerWidth; - if (newInnerWidth === innerWidth) - return; - innerWidth = newInnerWidth; - this.root.updateBlockedByResize = true; - cancelDelay && cancelDelay(); - cancelDelay = delay(resizeUnblockUpdate, 250); - if (globalProjectionState.hasAnimatedSinceResize) { - globalProjectionState.hasAnimatedSinceResize = false; - this.nodes.forEach(finishAnimation); - } - }); - } - if (layoutId) { - this.root.registerSharedNode(layoutId, this); - } - if (this.options.animate !== false && visualElement && (layoutId || layout2)) { - this.addEventListener("didUpdate", ({ delta, hasLayoutChanged, hasRelativeLayoutChanged, layout: newLayout }) => { - if (this.isTreeAnimationBlocked()) { - this.target = void 0; - this.relativeTarget = void 0; - return; - } - const layoutTransition = this.options.transition || visualElement.getDefaultTransition() || defaultLayoutTransition; - const { onLayoutAnimationStart, onLayoutAnimationComplete } = visualElement.getProps(); - const hasTargetChanged = !this.targetLayout || !boxEqualsRounded(this.targetLayout, newLayout); - const hasOnlyRelativeTargetChanged = !hasLayoutChanged && hasRelativeLayoutChanged; - if (this.options.layoutRoot || this.resumeFrom || hasOnlyRelativeTargetChanged || hasLayoutChanged && (hasTargetChanged || !this.currentAnimation)) { - if (this.resumeFrom) { - this.resumingFrom = this.resumeFrom; - this.resumingFrom.resumingFrom = void 0; - } - const animationOptions = { - ...getValueTransition(layoutTransition, "layout"), - onPlay: onLayoutAnimationStart, - onComplete: onLayoutAnimationComplete - }; - if (visualElement.shouldReduceMotion || this.options.layoutRoot) { - animationOptions.delay = 0; - animationOptions.type = false; - } - this.startAnimation(animationOptions); - this.setAnimationOrigin(delta, hasOnlyRelativeTargetChanged); - } else { - if (!hasLayoutChanged) { - finishAnimation(this); - } - if (this.isLead() && this.options.onExitComplete) { - this.options.onExitComplete(); - } - } - this.targetLayout = newLayout; - }); - } - } - unmount() { - this.options.layoutId && this.willUpdate(); - this.root.nodes.remove(this); - const stack = this.getStack(); - stack && stack.remove(this); - this.parent && this.parent.children.delete(this); - this.instance = void 0; - this.eventHandlers.clear(); - cancelFrame(this.updateProjection); - } - // only on the root - blockUpdate() { - this.updateManuallyBlocked = true; - } - unblockUpdate() { - this.updateManuallyBlocked = false; - } - isUpdateBlocked() { - return this.updateManuallyBlocked || this.updateBlockedByResize; - } - isTreeAnimationBlocked() { - return this.isAnimationBlocked || this.parent && this.parent.isTreeAnimationBlocked() || false; - } - // Note: currently only running on root node - startUpdate() { - if (this.isUpdateBlocked()) - return; - this.isUpdating = true; - this.nodes && this.nodes.forEach(resetSkewAndRotation); - this.animationId++; - } - getTransformTemplate() { - const { visualElement } = this.options; - return visualElement && visualElement.getProps().transformTemplate; - } - willUpdate(shouldNotifyListeners = true) { - this.root.hasTreeAnimated = true; - if (this.root.isUpdateBlocked()) { - this.options.onExitComplete && this.options.onExitComplete(); - return; - } - if (window.MotionCancelOptimisedAnimation && !this.hasCheckedOptimisedAppear) { - cancelTreeOptimisedTransformAnimations(this); - } - !this.root.isUpdating && this.root.startUpdate(); - if (this.isLayoutDirty) - return; - this.isLayoutDirty = true; - for (let i = 0; i < this.path.length; i++) { - const node = this.path[i]; - node.shouldResetTransform = true; - if (typeof node.latestValues.x === "string" || typeof node.latestValues.y === "string") { - node.isLayoutDirty = true; - } - node.updateScroll("snapshot"); - if (node.options.layoutRoot) { - node.willUpdate(false); - } - } - const { layoutId, layout: layout2 } = this.options; - if (layoutId === void 0 && !layout2) - return; - const transformTemplate = this.getTransformTemplate(); - this.prevTransformTemplateValue = transformTemplate ? transformTemplate(this.latestValues, "") : void 0; - this.updateSnapshot(); - shouldNotifyListeners && this.notifyListeners("willUpdate"); - } - update() { - this.updateScheduled = false; - const updateWasBlocked = this.isUpdateBlocked(); - if (updateWasBlocked) { - const wasBlockedByResize = this.updateBlockedByResize; - this.unblockUpdate(); - this.updateBlockedByResize = false; - this.clearAllSnapshots(); - if (wasBlockedByResize) { - this.nodes.forEach(forceLayoutMeasure); - } - this.nodes.forEach(clearMeasurements); - return; - } - if (this.animationId <= this.animationCommitId) { - this.nodes.forEach(clearIsLayoutDirty); - return; - } - this.animationCommitId = this.animationId; - if (!this.isUpdating) { - this.nodes.forEach(clearIsLayoutDirty); - } else { - this.isUpdating = false; - this.nodes.forEach(ensureDraggedNodesSnapshotted); - this.nodes.forEach(resetTransformStyle); - this.nodes.forEach(updateLayout); - this.nodes.forEach(notifyLayoutUpdate); - } - this.clearAllSnapshots(); - const now2 = time.now(); - frameData.delta = clamp(0, 1e3 / 60, now2 - frameData.timestamp); - frameData.timestamp = now2; - frameData.isProcessing = true; - frameSteps.update.process(frameData); - frameSteps.preRender.process(frameData); - frameSteps.render.process(frameData); - frameData.isProcessing = false; - } - didUpdate() { - if (!this.updateScheduled) { - this.updateScheduled = true; - microtask.read(this.scheduleUpdate); - } - } - clearAllSnapshots() { - this.nodes.forEach(clearSnapshot); - this.sharedNodes.forEach(removeLeadSnapshots); - } - scheduleUpdateProjection() { - if (!this.projectionUpdateScheduled) { - this.projectionUpdateScheduled = true; - frame.preRender(this.updateProjection, false, true); - } - } - scheduleCheckAfterUnmount() { - frame.postRender(() => { - if (this.isLayoutDirty) { - this.root.didUpdate(); - } else { - this.root.checkUpdateFailed(); - } - }); - } - /** - * Update measurements - */ - updateSnapshot() { - if (this.snapshot || !this.instance) - return; - this.snapshot = this.measure(); - if (this.snapshot && !calcLength(this.snapshot.measuredBox.x) && !calcLength(this.snapshot.measuredBox.y)) { - this.snapshot = void 0; - } - } - updateLayout() { - if (!this.instance) - return; - this.updateScroll(); - if (!(this.options.alwaysMeasureLayout && this.isLead()) && !this.isLayoutDirty) { - return; - } - if (this.resumeFrom && !this.resumeFrom.instance) { - for (let i = 0; i < this.path.length; i++) { - const node = this.path[i]; - node.updateScroll(); - } - } - const prevLayout = this.layout; - this.layout = this.measure(false); - this.layoutVersion++; - if (!this.layoutCorrected) - this.layoutCorrected = createBox(); - this.isLayoutDirty = false; - this.projectionDelta = void 0; - this.notifyListeners("measure", this.layout.layoutBox); - const { visualElement } = this.options; - visualElement && visualElement.notify("LayoutMeasure", this.layout.layoutBox, prevLayout ? prevLayout.layoutBox : void 0); - } - updateScroll(phase = "measure") { - let needsMeasurement = Boolean(this.options.layoutScroll && this.instance); - if (this.scroll && this.scroll.animationId === this.root.animationId && this.scroll.phase === phase) { - needsMeasurement = false; - } - if (needsMeasurement && this.instance) { - const isRoot = checkIsScrollRoot(this.instance); - this.scroll = { - animationId: this.root.animationId, - phase, - isRoot, - offset: measureScroll(this.instance), - wasRoot: this.scroll ? this.scroll.isRoot : isRoot - }; - } - } - resetTransform() { - if (!resetTransform) - return; - const isResetRequested = this.isLayoutDirty || this.shouldResetTransform || this.options.alwaysMeasureLayout; - const hasProjection = this.projectionDelta && !isDeltaZero(this.projectionDelta); - const transformTemplate = this.getTransformTemplate(); - const transformTemplateValue = transformTemplate ? transformTemplate(this.latestValues, "") : void 0; - const transformTemplateHasChanged = transformTemplateValue !== this.prevTransformTemplateValue; - if (isResetRequested && this.instance && (hasProjection || hasTransform(this.latestValues) || transformTemplateHasChanged)) { - resetTransform(this.instance, transformTemplateValue); - this.shouldResetTransform = false; - this.scheduleRender(); - } - } - measure(removeTransform = true) { - const pageBox = this.measurePageBox(); - let layoutBox = this.removeElementScroll(pageBox); - if (removeTransform) { - layoutBox = this.removeTransform(layoutBox); - } - roundBox(layoutBox); - return { - animationId: this.root.animationId, - measuredBox: pageBox, - layoutBox, - latestValues: {}, - source: this.id - }; - } - measurePageBox() { - const { visualElement } = this.options; - if (!visualElement) - return createBox(); - const box = visualElement.measureViewportBox(); - const wasInScrollRoot = this.scroll?.wasRoot || this.path.some(checkNodeWasScrollRoot); - if (!wasInScrollRoot) { - const { scroll } = this.root; - if (scroll) { - translateAxis(box.x, scroll.offset.x); - translateAxis(box.y, scroll.offset.y); - } - } - return box; - } - removeElementScroll(box) { - const boxWithoutScroll = createBox(); - copyBoxInto(boxWithoutScroll, box); - if (this.scroll?.wasRoot) { - return boxWithoutScroll; - } - for (let i = 0; i < this.path.length; i++) { - const node = this.path[i]; - const { scroll, options } = node; - if (node !== this.root && scroll && options.layoutScroll) { - if (scroll.wasRoot) { - copyBoxInto(boxWithoutScroll, box); - } - translateAxis(boxWithoutScroll.x, scroll.offset.x); - translateAxis(boxWithoutScroll.y, scroll.offset.y); - } - } - return boxWithoutScroll; - } - applyTransform(box, transformOnly = false, output) { - const withTransforms = output || createBox(); - copyBoxInto(withTransforms, box); - for (let i = 0; i < this.path.length; i++) { - const node = this.path[i]; - if (!transformOnly && node.options.layoutScroll && node.scroll && node !== node.root) { - translateAxis(withTransforms.x, -node.scroll.offset.x); - translateAxis(withTransforms.y, -node.scroll.offset.y); - } - if (!hasTransform(node.latestValues)) - continue; - transformBox(withTransforms, node.latestValues, node.layout?.layoutBox); - } - if (hasTransform(this.latestValues)) { - transformBox(withTransforms, this.latestValues, this.layout?.layoutBox); - } - return withTransforms; - } - removeTransform(box) { - const boxWithoutTransform = createBox(); - copyBoxInto(boxWithoutTransform, box); - for (let i = 0; i < this.path.length; i++) { - const node = this.path[i]; - if (!hasTransform(node.latestValues)) - continue; - let sourceBox; - if (node.instance) { - hasScale(node.latestValues) && node.updateSnapshot(); - sourceBox = createBox(); - copyBoxInto(sourceBox, node.measurePageBox()); - } - removeBoxTransforms(boxWithoutTransform, node.latestValues, node.snapshot?.layoutBox, sourceBox); - } - if (hasTransform(this.latestValues)) { - removeBoxTransforms(boxWithoutTransform, this.latestValues); - } - return boxWithoutTransform; - } - setTargetDelta(delta) { - this.targetDelta = delta; - this.root.scheduleUpdateProjection(); - this.isProjectionDirty = true; - } - setOptions(options) { - this.options = { - ...this.options, - ...options, - crossfade: options.crossfade !== void 0 ? options.crossfade : true - }; - } - clearMeasurements() { - this.scroll = void 0; - this.layout = void 0; - this.snapshot = void 0; - this.prevTransformTemplateValue = void 0; - this.targetDelta = void 0; - this.target = void 0; - this.isLayoutDirty = false; - } - forceRelativeParentToResolveTarget() { - if (!this.relativeParent) - return; - if (this.relativeParent.resolvedRelativeTargetAt !== frameData.timestamp) { - this.relativeParent.resolveTargetDelta(true); - } - } - resolveTargetDelta(forceRecalculation = false) { - const lead = this.getLead(); - this.isProjectionDirty || (this.isProjectionDirty = lead.isProjectionDirty); - this.isTransformDirty || (this.isTransformDirty = lead.isTransformDirty); - this.isSharedProjectionDirty || (this.isSharedProjectionDirty = lead.isSharedProjectionDirty); - const isShared = Boolean(this.resumingFrom) || this !== lead; - const canSkip = !(forceRecalculation || isShared && this.isSharedProjectionDirty || this.isProjectionDirty || this.parent?.isProjectionDirty || this.attemptToResolveRelativeTarget || this.root.updateBlockedByResize); - if (canSkip) - return; - const { layout: layout2, layoutId } = this.options; - if (!this.layout || !(layout2 || layoutId)) - return; - this.resolvedRelativeTargetAt = frameData.timestamp; - const relativeParent = this.getClosestProjectingParent(); - if (relativeParent && this.linkedParentVersion !== relativeParent.layoutVersion && !relativeParent.options.layoutRoot) { - this.removeRelativeTarget(); - } - if (!this.targetDelta && !this.relativeTarget) { - if (this.options.layoutAnchor !== false && relativeParent && relativeParent.layout) { - this.createRelativeTarget(relativeParent, this.layout.layoutBox, relativeParent.layout.layoutBox); - } else { - this.removeRelativeTarget(); - } - } - if (!this.relativeTarget && !this.targetDelta) - return; - if (!this.target) { - this.target = createBox(); - this.targetWithTransforms = createBox(); - } - if (this.relativeTarget && this.relativeTargetOrigin && this.relativeParent && this.relativeParent.target) { - this.forceRelativeParentToResolveTarget(); - calcRelativeBox(this.target, this.relativeTarget, this.relativeParent.target, this.options.layoutAnchor || void 0); - } else if (this.targetDelta) { - if (Boolean(this.resumingFrom)) { - this.applyTransform(this.layout.layoutBox, false, this.target); - } else { - copyBoxInto(this.target, this.layout.layoutBox); - } - applyBoxDelta(this.target, this.targetDelta); - } else { - copyBoxInto(this.target, this.layout.layoutBox); - } - if (this.attemptToResolveRelativeTarget) { - this.attemptToResolveRelativeTarget = false; - if (this.options.layoutAnchor !== false && relativeParent && Boolean(relativeParent.resumingFrom) === Boolean(this.resumingFrom) && !relativeParent.options.layoutScroll && relativeParent.target && this.animationProgress !== 1) { - this.createRelativeTarget(relativeParent, this.target, relativeParent.target); - } else { - this.relativeParent = this.relativeTarget = void 0; - } - } - } - getClosestProjectingParent() { - if (!this.parent || hasScale(this.parent.latestValues) || has2DTranslate(this.parent.latestValues)) { - return void 0; - } - if (this.parent.isProjecting()) { - return this.parent; - } else { - return this.parent.getClosestProjectingParent(); - } - } - isProjecting() { - return Boolean((this.relativeTarget || this.targetDelta || this.options.layoutRoot) && this.layout); - } - createRelativeTarget(relativeParent, layout2, parentLayout) { - this.relativeParent = relativeParent; - this.linkedParentVersion = relativeParent.layoutVersion; - this.forceRelativeParentToResolveTarget(); - this.relativeTarget = createBox(); - this.relativeTargetOrigin = createBox(); - calcRelativePosition(this.relativeTargetOrigin, layout2, parentLayout, this.options.layoutAnchor || void 0); - copyBoxInto(this.relativeTarget, this.relativeTargetOrigin); - } - removeRelativeTarget() { - this.relativeParent = this.relativeTarget = void 0; - } - calcProjection() { - const lead = this.getLead(); - const isShared = Boolean(this.resumingFrom) || this !== lead; - let canSkip = true; - if (this.isProjectionDirty || this.parent?.isProjectionDirty) { - canSkip = false; - } - if (isShared && (this.isSharedProjectionDirty || this.isTransformDirty)) { - canSkip = false; - } - if (this.resolvedRelativeTargetAt === frameData.timestamp) { - canSkip = false; - } - if (canSkip) - return; - const { layout: layout2, layoutId } = this.options; - this.isTreeAnimating = Boolean(this.parent && this.parent.isTreeAnimating || this.currentAnimation || this.pendingAnimation); - if (!this.isTreeAnimating) { - this.targetDelta = this.relativeTarget = void 0; - } - if (!this.layout || !(layout2 || layoutId)) - return; - copyBoxInto(this.layoutCorrected, this.layout.layoutBox); - const prevTreeScaleX = this.treeScale.x; - const prevTreeScaleY = this.treeScale.y; - applyTreeDeltas(this.layoutCorrected, this.treeScale, this.path, isShared); - if (lead.layout && !lead.target && (this.treeScale.x !== 1 || this.treeScale.y !== 1)) { - lead.target = lead.layout.layoutBox; - lead.targetWithTransforms = createBox(); - } - const { target } = lead; - if (!target) { - if (this.prevProjectionDelta) { - this.createProjectionDeltas(); - this.scheduleRender(); - } - return; - } - if (!this.projectionDelta || !this.prevProjectionDelta) { - this.createProjectionDeltas(); - } else { - copyAxisDeltaInto(this.prevProjectionDelta.x, this.projectionDelta.x); - copyAxisDeltaInto(this.prevProjectionDelta.y, this.projectionDelta.y); - } - calcBoxDelta(this.projectionDelta, this.layoutCorrected, target, this.latestValues); - if (this.treeScale.x !== prevTreeScaleX || this.treeScale.y !== prevTreeScaleY || !axisDeltaEquals(this.projectionDelta.x, this.prevProjectionDelta.x) || !axisDeltaEquals(this.projectionDelta.y, this.prevProjectionDelta.y)) { - this.hasProjected = true; - this.scheduleRender(); - this.notifyListeners("projectionUpdate", target); - } - } - hide() { - this.isVisible = false; - } - show() { - this.isVisible = true; - } - scheduleRender(notifyAll2 = true) { - this.options.visualElement?.scheduleRender(); - if (notifyAll2) { - const stack = this.getStack(); - stack && stack.scheduleRender(); - } - if (this.resumingFrom && !this.resumingFrom.instance) { - this.resumingFrom = void 0; - } - } - createProjectionDeltas() { - this.prevProjectionDelta = createDelta(); - this.projectionDelta = createDelta(); - this.projectionDeltaWithTransform = createDelta(); - } - setAnimationOrigin(delta, hasOnlyRelativeTargetChanged = false) { - const snapshot = this.snapshot; - const snapshotLatestValues = snapshot ? snapshot.latestValues : {}; - const mixedValues = { ...this.latestValues }; - const targetDelta = createDelta(); - if (!this.relativeParent || !this.relativeParent.options.layoutRoot) { - this.relativeTarget = this.relativeTargetOrigin = void 0; - } - this.attemptToResolveRelativeTarget = !hasOnlyRelativeTargetChanged; - const relativeLayout = createBox(); - const snapshotSource = snapshot ? snapshot.source : void 0; - const layoutSource = this.layout ? this.layout.source : void 0; - const isSharedLayoutAnimation = snapshotSource !== layoutSource; - const stack = this.getStack(); - const isOnlyMember = !stack || stack.members.length <= 1; - const shouldCrossfadeOpacity = Boolean(isSharedLayoutAnimation && !isOnlyMember && this.options.crossfade === true && !this.path.some(hasOpacityCrossfade)); - this.animationProgress = 0; - let prevRelativeTarget; - this.mixTargetDelta = (latest) => { - const progress2 = latest / 1e3; - mixAxisDelta(targetDelta.x, delta.x, progress2); - mixAxisDelta(targetDelta.y, delta.y, progress2); - this.setTargetDelta(targetDelta); - if (this.relativeTarget && this.relativeTargetOrigin && this.layout && this.relativeParent && this.relativeParent.layout) { - calcRelativePosition(relativeLayout, this.layout.layoutBox, this.relativeParent.layout.layoutBox, this.options.layoutAnchor || void 0); - mixBox(this.relativeTarget, this.relativeTargetOrigin, relativeLayout, progress2); - if (prevRelativeTarget && boxEquals(this.relativeTarget, prevRelativeTarget)) { - this.isProjectionDirty = false; - } - if (!prevRelativeTarget) - prevRelativeTarget = createBox(); - copyBoxInto(prevRelativeTarget, this.relativeTarget); - } - if (isSharedLayoutAnimation) { - this.animationValues = mixedValues; - mixValues(mixedValues, snapshotLatestValues, this.latestValues, progress2, shouldCrossfadeOpacity, isOnlyMember); - } - this.root.scheduleUpdateProjection(); - this.scheduleRender(); - this.animationProgress = progress2; - }; - this.mixTargetDelta(this.options.layoutRoot ? 1e3 : 0); - } - startAnimation(options) { - this.notifyListeners("animationStart"); - this.currentAnimation?.stop(); - this.resumingFrom?.currentAnimation?.stop(); - if (this.pendingAnimation) { - cancelFrame(this.pendingAnimation); - this.pendingAnimation = void 0; - } - this.pendingAnimation = frame.update(() => { - globalProjectionState.hasAnimatedSinceResize = true; - this.motionValue || (this.motionValue = motionValue(0)); - this.motionValue.jump(0, false); - this.currentAnimation = animateSingleValue(this.motionValue, [0, 1e3], { - ...options, - velocity: 0, - isSync: true, - onUpdate: (latest) => { - this.mixTargetDelta(latest); - options.onUpdate && options.onUpdate(latest); - }, - onStop: () => { - }, - onComplete: () => { - options.onComplete && options.onComplete(); - this.completeAnimation(); - } - }); - if (this.resumingFrom) { - this.resumingFrom.currentAnimation = this.currentAnimation; - } - this.pendingAnimation = void 0; - }); - } - completeAnimation() { - if (this.resumingFrom) { - this.resumingFrom.currentAnimation = void 0; - this.resumingFrom.preserveOpacity = void 0; - } - const stack = this.getStack(); - stack && stack.exitAnimationComplete(); - this.resumingFrom = this.currentAnimation = this.animationValues = void 0; - this.notifyListeners("animationComplete"); - } - finishAnimation() { - if (this.currentAnimation) { - this.mixTargetDelta && this.mixTargetDelta(animationTarget); - this.currentAnimation.stop(); - } - this.completeAnimation(); - } - applyTransformsToTarget() { - const lead = this.getLead(); - let { targetWithTransforms, target, layout: layout2, latestValues } = lead; - if (!targetWithTransforms || !target || !layout2) - return; - if (this !== lead && this.layout && layout2 && shouldAnimatePositionOnly(this.options.animationType, this.layout.layoutBox, layout2.layoutBox)) { - target = this.target || createBox(); - const xLength = calcLength(this.layout.layoutBox.x); - target.x.min = lead.target.x.min; - target.x.max = target.x.min + xLength; - const yLength = calcLength(this.layout.layoutBox.y); - target.y.min = lead.target.y.min; - target.y.max = target.y.min + yLength; - } - copyBoxInto(targetWithTransforms, target); - transformBox(targetWithTransforms, latestValues); - calcBoxDelta(this.projectionDeltaWithTransform, this.layoutCorrected, targetWithTransforms, latestValues); - } - registerSharedNode(layoutId, node) { - if (!this.sharedNodes.has(layoutId)) { - this.sharedNodes.set(layoutId, new NodeStack()); - } - const stack = this.sharedNodes.get(layoutId); - stack.add(node); - const config = node.options.initialPromotionConfig; - node.promote({ - transition: config ? config.transition : void 0, - preserveFollowOpacity: config && config.shouldPreserveFollowOpacity ? config.shouldPreserveFollowOpacity(node) : void 0 - }); - } - isLead() { - const stack = this.getStack(); - return stack ? stack.lead === this : true; - } - getLead() { - const { layoutId } = this.options; - return layoutId ? this.getStack()?.lead || this : this; - } - getPrevLead() { - const { layoutId } = this.options; - return layoutId ? this.getStack()?.prevLead : void 0; - } - getStack() { - const { layoutId } = this.options; - if (layoutId) - return this.root.sharedNodes.get(layoutId); - } - promote({ needsReset, transition, preserveFollowOpacity } = {}) { - const stack = this.getStack(); - if (stack) - stack.promote(this, preserveFollowOpacity); - if (needsReset) { - this.projectionDelta = void 0; - this.needsReset = true; - } - if (transition) - this.setOptions({ transition }); - } - relegate() { - const stack = this.getStack(); - if (stack) { - return stack.relegate(this); - } else { - return false; - } - } - resetSkewAndRotation() { - const { visualElement } = this.options; - if (!visualElement) - return; - let hasDistortingTransform = false; - const { latestValues } = visualElement; - if (latestValues.z || latestValues.rotate || latestValues.rotateX || latestValues.rotateY || latestValues.rotateZ || latestValues.skewX || latestValues.skewY) { - hasDistortingTransform = true; - } - if (!hasDistortingTransform) - return; - const resetValues = {}; - if (latestValues.z) { - resetDistortingTransform("z", visualElement, resetValues, this.animationValues); - } - for (let i = 0; i < transformAxes.length; i++) { - resetDistortingTransform(`rotate${transformAxes[i]}`, visualElement, resetValues, this.animationValues); - resetDistortingTransform(`skew${transformAxes[i]}`, visualElement, resetValues, this.animationValues); - } - visualElement.render(); - for (const key in resetValues) { - visualElement.setStaticValue(key, resetValues[key]); - if (this.animationValues) { - this.animationValues[key] = resetValues[key]; - } - } - visualElement.scheduleRender(); - } - applyProjectionStyles(targetStyle, styleProp) { - if (!this.instance || this.isSVG) - return; - if (!this.isVisible) { - targetStyle.visibility = "hidden"; - return; - } - const transformTemplate = this.getTransformTemplate(); - if (this.needsReset) { - this.needsReset = false; - targetStyle.visibility = ""; - targetStyle.opacity = ""; - targetStyle.pointerEvents = resolveMotionValue(styleProp?.pointerEvents) || ""; - targetStyle.transform = transformTemplate ? transformTemplate(this.latestValues, "") : "none"; - return; - } - const lead = this.getLead(); - if (!this.projectionDelta || !this.layout || !lead.target) { - if (this.options.layoutId) { - targetStyle.opacity = this.latestValues.opacity !== void 0 ? this.latestValues.opacity : 1; - targetStyle.pointerEvents = resolveMotionValue(styleProp?.pointerEvents) || ""; - } - if (this.hasProjected && !hasTransform(this.latestValues)) { - targetStyle.transform = transformTemplate ? transformTemplate({}, "") : "none"; - this.hasProjected = false; - } - return; - } - targetStyle.visibility = ""; - const valuesToRender = lead.animationValues || lead.latestValues; - this.applyTransformsToTarget(); - let transform = buildProjectionTransform(this.projectionDeltaWithTransform, this.treeScale, valuesToRender); - if (transformTemplate) { - transform = transformTemplate(valuesToRender, transform); - } - targetStyle.transform = transform; - const { x, y } = this.projectionDelta; - targetStyle.transformOrigin = `${x.origin * 100}% ${y.origin * 100}% 0`; - if (lead.animationValues) { - targetStyle.opacity = lead === this ? valuesToRender.opacity ?? this.latestValues.opacity ?? 1 : this.preserveOpacity ? this.latestValues.opacity : valuesToRender.opacityExit; - } else { - targetStyle.opacity = lead === this ? valuesToRender.opacity !== void 0 ? valuesToRender.opacity : "" : valuesToRender.opacityExit !== void 0 ? valuesToRender.opacityExit : 0; - } - for (const key in scaleCorrectors) { - if (valuesToRender[key] === void 0) - continue; - const { correct, applyTo, isCSSVariable } = scaleCorrectors[key]; - const corrected = transform === "none" ? valuesToRender[key] : correct(valuesToRender[key], lead); - if (applyTo) { - const num = applyTo.length; - for (let i = 0; i < num; i++) { - targetStyle[applyTo[i]] = corrected; - } - } else { - if (isCSSVariable) { - this.options.visualElement.renderState.vars[key] = corrected; - } else { - targetStyle[key] = corrected; - } - } - } - if (this.options.layoutId) { - targetStyle.pointerEvents = lead === this ? resolveMotionValue(styleProp?.pointerEvents) || "" : "none"; - } - } - clearSnapshot() { - this.resumeFrom = this.snapshot = void 0; - } - // Only run on root - resetTree() { - this.root.nodes.forEach((node) => node.currentAnimation?.stop()); - this.root.nodes.forEach(clearMeasurements); - this.root.sharedNodes.clear(); - } - }; -} -function updateLayout(node) { - node.updateLayout(); -} -function notifyLayoutUpdate(node) { - const snapshot = node.resumeFrom?.snapshot || node.snapshot; - if (node.isLead() && node.layout && snapshot && node.hasListeners("didUpdate")) { - const { layoutBox: layout2, measuredBox: measuredLayout } = node.layout; - const { animationType } = node.options; - const isShared = snapshot.source !== node.layout.source; - if (animationType === "size") { - eachAxis((axis) => { - const axisSnapshot = isShared ? snapshot.measuredBox[axis] : snapshot.layoutBox[axis]; - const length = calcLength(axisSnapshot); - axisSnapshot.min = layout2[axis].min; - axisSnapshot.max = axisSnapshot.min + length; - }); - } else if (animationType === "x" || animationType === "y") { - const snapAxis = animationType === "x" ? "y" : "x"; - copyAxisInto(isShared ? snapshot.measuredBox[snapAxis] : snapshot.layoutBox[snapAxis], layout2[snapAxis]); - } else if (shouldAnimatePositionOnly(animationType, snapshot.layoutBox, layout2)) { - eachAxis((axis) => { - const axisSnapshot = isShared ? snapshot.measuredBox[axis] : snapshot.layoutBox[axis]; - const length = calcLength(layout2[axis]); - axisSnapshot.max = axisSnapshot.min + length; - if (node.relativeTarget && !node.currentAnimation) { - node.isProjectionDirty = true; - node.relativeTarget[axis].max = node.relativeTarget[axis].min + length; - } - }); - } - const layoutDelta = createDelta(); - calcBoxDelta(layoutDelta, layout2, snapshot.layoutBox); - const visualDelta = createDelta(); - if (isShared) { - calcBoxDelta(visualDelta, node.applyTransform(measuredLayout, true), snapshot.measuredBox); - } else { - calcBoxDelta(visualDelta, layout2, snapshot.layoutBox); - } - const hasLayoutChanged = !isDeltaZero(layoutDelta); - let hasRelativeLayoutChanged = false; - if (!node.resumeFrom) { - const relativeParent = node.getClosestProjectingParent(); - if (relativeParent && !relativeParent.resumeFrom) { - const { snapshot: parentSnapshot, layout: parentLayout } = relativeParent; - if (parentSnapshot && parentLayout) { - const anchor = node.options.layoutAnchor || void 0; - const relativeSnapshot = createBox(); - calcRelativePosition(relativeSnapshot, snapshot.layoutBox, parentSnapshot.layoutBox, anchor); - const relativeLayout = createBox(); - calcRelativePosition(relativeLayout, layout2, parentLayout.layoutBox, anchor); - if (!boxEqualsRounded(relativeSnapshot, relativeLayout)) { - hasRelativeLayoutChanged = true; - } - if (relativeParent.options.layoutRoot) { - node.relativeTarget = relativeLayout; - node.relativeTargetOrigin = relativeSnapshot; - node.relativeParent = relativeParent; - } - } - } - } - node.notifyListeners("didUpdate", { - layout: layout2, - snapshot, - delta: visualDelta, - layoutDelta, - hasLayoutChanged, - hasRelativeLayoutChanged - }); - } else if (node.isLead()) { - const { onExitComplete } = node.options; - onExitComplete && onExitComplete(); - } - node.options.transition = void 0; -} -function propagateDirtyNodes(node) { - if (!node.parent) - return; - if (!node.isProjecting()) { - node.isProjectionDirty = node.parent.isProjectionDirty; - } - node.isSharedProjectionDirty || (node.isSharedProjectionDirty = Boolean(node.isProjectionDirty || node.parent.isProjectionDirty || node.parent.isSharedProjectionDirty)); - node.isTransformDirty || (node.isTransformDirty = node.parent.isTransformDirty); -} -function cleanDirtyNodes(node) { - node.isProjectionDirty = node.isSharedProjectionDirty = node.isTransformDirty = false; -} -function clearSnapshot(node) { - node.clearSnapshot(); -} -function clearMeasurements(node) { - node.clearMeasurements(); -} -function forceLayoutMeasure(node) { - node.isLayoutDirty = true; - node.updateLayout(); -} -function clearIsLayoutDirty(node) { - node.isLayoutDirty = false; -} -function ensureDraggedNodesSnapshotted(node) { - if (node.isAnimationBlocked && node.layout && !node.isLayoutDirty) { - node.snapshot = node.layout; - node.isLayoutDirty = true; - } -} -function resetTransformStyle(node) { - const { visualElement } = node.options; - if (visualElement && visualElement.getProps().onBeforeLayoutMeasure) { - visualElement.notify("BeforeLayoutMeasure"); - } - node.resetTransform(); -} -function finishAnimation(node) { - node.finishAnimation(); - node.targetDelta = node.relativeTarget = node.target = void 0; - node.isProjectionDirty = true; -} -function resolveTargetDelta(node) { - node.resolveTargetDelta(); -} -function calcProjection(node) { - node.calcProjection(); -} -function resetSkewAndRotation(node) { - node.resetSkewAndRotation(); -} -function removeLeadSnapshots(stack) { - stack.removeLeadSnapshot(); -} -function mixAxisDelta(output, delta, p) { - output.translate = mixNumber$1(delta.translate, 0, p); - output.scale = mixNumber$1(delta.scale, 1, p); - output.origin = delta.origin; - output.originPoint = delta.originPoint; -} -function mixAxis(output, from, to, p) { - output.min = mixNumber$1(from.min, to.min, p); - output.max = mixNumber$1(from.max, to.max, p); -} -function mixBox(output, from, to, p) { - mixAxis(output.x, from.x, to.x, p); - mixAxis(output.y, from.y, to.y, p); -} -function hasOpacityCrossfade(node) { - return node.animationValues && node.animationValues.opacityExit !== void 0; -} -const defaultLayoutTransition = { - duration: 0.45, - ease: [0.4, 0, 0.1, 1] -}; -const userAgentContains = (string) => typeof navigator !== "undefined" && navigator.userAgent && navigator.userAgent.toLowerCase().includes(string); -const roundPoint = userAgentContains("applewebkit/") && !userAgentContains("chrome/") ? Math.round : noop; -function roundAxis(axis) { - axis.min = roundPoint(axis.min); - axis.max = roundPoint(axis.max); -} -function roundBox(box) { - roundAxis(box.x); - roundAxis(box.y); -} -function shouldAnimatePositionOnly(animationType, snapshot, layout2) { - return animationType === "position" || animationType === "preserve-aspect" && !isNear(aspectRatio(snapshot), aspectRatio(layout2), 0.2); -} -function checkNodeWasScrollRoot(node) { - return node !== node.root && node.scroll?.wasRoot; -} -const DocumentProjectionNode = createProjectionNode$1({ - attachResizeListener: (ref, notify) => addDomEvent(ref, "resize", notify), - measureScroll: () => ({ - x: document.documentElement.scrollLeft || document.body?.scrollLeft || 0, - y: document.documentElement.scrollTop || document.body?.scrollTop || 0 - }), - checkIsScrollRoot: () => true -}); -const rootProjectionNode = { - current: void 0 -}; -const HTMLProjectionNode = createProjectionNode$1({ - measureScroll: (instance) => ({ - x: instance.scrollLeft, - y: instance.scrollTop - }), - defaultParent: () => { - if (!rootProjectionNode.current) { - const documentNode = new DocumentProjectionNode({}); - documentNode.mount(window); - documentNode.setOptions({ layoutScroll: true }); - rootProjectionNode.current = documentNode; - } - return rootProjectionNode.current; - }, - resetTransform: (instance, value) => { - instance.style.transform = value !== void 0 ? value : "none"; - }, - checkIsScrollRoot: (instance) => Boolean(window.getComputedStyle(instance).position === "fixed") -}); -const MotionConfigContext = reactExports.createContext({ - transformPagePoint: (p) => p, - isStatic: false, - reducedMotion: "never" -}); -function setRef(ref, value) { - if (typeof ref === "function") { - return ref(value); - } else if (ref !== null && ref !== void 0) { - ref.current = value; - } -} -function composeRefs(...refs) { - return (node) => { - let hasCleanup = false; - const cleanups = refs.map((ref) => { - const cleanup = setRef(ref, node); - if (!hasCleanup && typeof cleanup === "function") { - hasCleanup = true; - } - return cleanup; - }); - if (hasCleanup) { - return () => { - for (let i = 0; i < cleanups.length; i++) { - const cleanup = cleanups[i]; - if (typeof cleanup === "function") { - cleanup(); - } else { - setRef(refs[i], null); - } - } - }; - } - }; -} -function useComposedRefs(...refs) { - return reactExports.useCallback(composeRefs(...refs), refs); -} -class PopChildMeasure extends reactExports.Component { - getSnapshotBeforeUpdate(prevProps) { - const element = this.props.childRef.current; - if (isHTMLElement(element) && prevProps.isPresent && !this.props.isPresent && this.props.pop !== false) { - const parent = element.offsetParent; - const parentWidth = isHTMLElement(parent) ? parent.offsetWidth || 0 : 0; - const parentHeight = isHTMLElement(parent) ? parent.offsetHeight || 0 : 0; - const computedStyle = getComputedStyle(element); - const size = this.props.sizeRef.current; - size.height = parseFloat(computedStyle.height); - size.width = parseFloat(computedStyle.width); - size.top = element.offsetTop; - size.left = element.offsetLeft; - size.right = parentWidth - size.width - size.left; - size.bottom = parentHeight - size.height - size.top; - } - return null; - } - /** - * Required with getSnapshotBeforeUpdate to stop React complaining. - */ - componentDidUpdate() { - } - render() { - return this.props.children; - } -} -function PopChild({ children, isPresent, anchorX, anchorY, root, pop }) { - const id2 = reactExports.useId(); - const ref = reactExports.useRef(null); - const size = reactExports.useRef({ - width: 0, - height: 0, - top: 0, - left: 0, - right: 0, - bottom: 0 - }); - const { nonce } = reactExports.useContext(MotionConfigContext); - const childRef = children.props?.ref ?? children?.ref; - const composedRef = useComposedRefs(ref, childRef); - reactExports.useInsertionEffect(() => { - const { width, height, top, left, right, bottom } = size.current; - if (isPresent || pop === false || !ref.current || !width || !height) - return; - const x = anchorX === "left" ? `left: ${left}` : `right: ${right}`; - const y = anchorY === "bottom" ? `bottom: ${bottom}` : `top: ${top}`; - ref.current.dataset.motionPopId = id2; - const style = document.createElement("style"); - if (nonce) - style.nonce = nonce; - const parent = root ?? document.head; - parent.appendChild(style); - if (style.sheet) { - style.sheet.insertRule(` - [data-motion-pop-id="${id2}"] { - position: absolute !important; - width: ${width}px !important; - height: ${height}px !important; - ${x}px !important; - ${y}px !important; - } - `); - } - return () => { - ref.current?.removeAttribute("data-motion-pop-id"); - if (parent.contains(style)) { - parent.removeChild(style); - } - }; - }, [isPresent]); - return jsxRuntimeExports.jsx(PopChildMeasure, { isPresent, childRef: ref, sizeRef: size, pop, children: pop === false ? children : reactExports.cloneElement(children, { ref: composedRef }) }); -} -const PresenceChild = ({ children, initial, isPresent, onExitComplete, custom, presenceAffectsLayout, mode, anchorX, anchorY, root }) => { - const presenceChildren = useConstant(newChildrenMap); - const id2 = reactExports.useId(); - let isReusedContext = true; - let context = reactExports.useMemo(() => { - isReusedContext = false; - return { - id: id2, - initial, - isPresent, - custom, - onExitComplete: (childId) => { - presenceChildren.set(childId, true); - for (const isComplete of presenceChildren.values()) { - if (!isComplete) - return; - } - onExitComplete && onExitComplete(); - }, - register: (childId) => { - presenceChildren.set(childId, false); - return () => presenceChildren.delete(childId); - } - }; - }, [isPresent, presenceChildren, onExitComplete]); - if (presenceAffectsLayout && isReusedContext) { - context = { ...context }; - } - reactExports.useMemo(() => { - presenceChildren.forEach((_, key) => presenceChildren.set(key, false)); - }, [isPresent]); - reactExports.useEffect(() => { - !isPresent && !presenceChildren.size && onExitComplete && onExitComplete(); - }, [isPresent]); - children = jsxRuntimeExports.jsx(PopChild, { pop: mode === "popLayout", isPresent, anchorX, anchorY, root, children }); - return jsxRuntimeExports.jsx(PresenceContext.Provider, { value: context, children }); -}; -function newChildrenMap() { - return /* @__PURE__ */ new Map(); -} -function usePresence(subscribe = true) { - const context = reactExports.useContext(PresenceContext); - if (context === null) - return [true, null]; - const { isPresent, onExitComplete, register } = context; - const id2 = reactExports.useId(); - reactExports.useEffect(() => { - if (subscribe) { - return register(id2); - } - }, [subscribe]); - const safeToRemove = reactExports.useCallback(() => subscribe && onExitComplete && onExitComplete(id2), [id2, onExitComplete, subscribe]); - return !isPresent && onExitComplete ? [false, safeToRemove] : [true]; -} -const getChildKey = (child) => child.key || ""; -function onlyElements(children) { - const filtered = []; - reactExports.Children.forEach(children, (child) => { - if (reactExports.isValidElement(child)) - filtered.push(child); - }); - return filtered; -} -const AnimatePresence = ({ children, custom, initial = true, onExitComplete, presenceAffectsLayout = true, mode = "sync", propagate = false, anchorX = "left", anchorY = "top", root }) => { - const [isParentPresent, safeToRemove] = usePresence(propagate); - const presentChildren = reactExports.useMemo(() => onlyElements(children), [children]); - const presentKeys = propagate && !isParentPresent ? [] : presentChildren.map(getChildKey); - const isInitialRender = reactExports.useRef(true); - const pendingPresentChildren = reactExports.useRef(presentChildren); - const exitComplete = useConstant(() => /* @__PURE__ */ new Map()); - const exitingComponents = reactExports.useRef(/* @__PURE__ */ new Set()); - const [diffedChildren, setDiffedChildren] = reactExports.useState(presentChildren); - const [renderedChildren, setRenderedChildren] = reactExports.useState(presentChildren); - useIsomorphicLayoutEffect(() => { - isInitialRender.current = false; - pendingPresentChildren.current = presentChildren; - for (let i = 0; i < renderedChildren.length; i++) { - const key = getChildKey(renderedChildren[i]); - if (!presentKeys.includes(key)) { - if (exitComplete.get(key) !== true) { - exitComplete.set(key, false); - } - } else { - exitComplete.delete(key); - exitingComponents.current.delete(key); - } - } - }, [renderedChildren, presentKeys.length, presentKeys.join("-")]); - const exitingChildren = []; - if (presentChildren !== diffedChildren) { - let nextChildren = [...presentChildren]; - for (let i = 0; i < renderedChildren.length; i++) { - const child = renderedChildren[i]; - const key = getChildKey(child); - if (!presentKeys.includes(key)) { - nextChildren.splice(i, 0, child); - exitingChildren.push(child); - } - } - if (mode === "wait" && exitingChildren.length) { - nextChildren = exitingChildren; - } - setRenderedChildren(onlyElements(nextChildren)); - setDiffedChildren(presentChildren); - return null; - } - if (process.env.NODE_ENV !== "production" && mode === "wait" && renderedChildren.length > 1) { - console.warn(`You're attempting to animate multiple children within AnimatePresence, but its mode is set to "wait". This will lead to odd visual behaviour.`); - } - const { forceRender } = reactExports.useContext(LayoutGroupContext); - return jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment, { children: renderedChildren.map((child) => { - const key = getChildKey(child); - const isPresent = propagate && !isParentPresent ? false : presentChildren === renderedChildren || presentKeys.includes(key); - const onExit = () => { - if (exitingComponents.current.has(key)) { - return; - } - if (exitComplete.has(key)) { - exitingComponents.current.add(key); - exitComplete.set(key, true); - } else { - return; - } - let isEveryExitComplete = true; - exitComplete.forEach((isExitComplete) => { - if (!isExitComplete) - isEveryExitComplete = false; - }); - if (isEveryExitComplete) { - forceRender?.(); - setRenderedChildren(pendingPresentChildren.current); - propagate && safeToRemove?.(); - onExitComplete && onExitComplete(); - } - }; - return jsxRuntimeExports.jsx(PresenceChild, { isPresent, initial: !isInitialRender.current || initial ? void 0 : false, custom, presenceAffectsLayout, mode, root, onExitComplete: isPresent ? void 0 : onExit, anchorX, anchorY, children: child }, key); - }) }); -}; -const LazyContext = reactExports.createContext({ strict: false }); -const featureProps = { - animation: [ - "animate", - "variants", - "whileHover", - "whileTap", - "exit", - "whileInView", - "whileFocus", - "whileDrag" - ], - exit: ["exit"], - drag: ["drag", "dragControls"], - focus: ["whileFocus"], - hover: ["whileHover", "onHoverStart", "onHoverEnd"], - tap: ["whileTap", "onTap", "onTapStart", "onTapCancel"], - pan: ["onPan", "onPanStart", "onPanSessionStart", "onPanEnd"], - inView: ["whileInView", "onViewportEnter", "onViewportLeave"], - layout: ["layout", "layoutId"] -}; -let isInitialized = false; -function initFeatureDefinitions() { - if (isInitialized) - return; - const initialFeatureDefinitions = {}; - for (const key in featureProps) { - initialFeatureDefinitions[key] = { - isEnabled: (props) => featureProps[key].some((name) => !!props[name]) - }; - } - setFeatureDefinitions(initialFeatureDefinitions); - isInitialized = true; -} -function getInitializedFeatureDefinitions() { - initFeatureDefinitions(); - return getFeatureDefinitions(); -} -function loadFeatures(features) { - const featureDefinitions2 = getInitializedFeatureDefinitions(); - for (const key in features) { - featureDefinitions2[key] = { - ...featureDefinitions2[key], - ...features[key] - }; - } - setFeatureDefinitions(featureDefinitions2); -} -const validMotionProps = /* @__PURE__ */ new Set([ - "animate", - "exit", - "variants", - "initial", - "style", - "values", - "variants", - "transition", - "transformTemplate", - "custom", - "inherit", - "onBeforeLayoutMeasure", - "onAnimationStart", - "onAnimationComplete", - "onUpdate", - "onDragStart", - "onDrag", - "onDragEnd", - "onMeasureDragConstraints", - "onDirectionLock", - "onDragTransitionEnd", - "_dragX", - "_dragY", - "onHoverStart", - "onHoverEnd", - "onViewportEnter", - "onViewportLeave", - "globalTapTarget", - "propagate", - "ignoreStrict", - "viewport" -]); -function isValidMotionProp(key) { - return key.startsWith("while") || key.startsWith("drag") && key !== "draggable" || key.startsWith("layout") || key.startsWith("onTap") || key.startsWith("onPan") || key.startsWith("onLayout") || validMotionProps.has(key); -} -let shouldForward = (key) => !isValidMotionProp(key); -function loadExternalIsValidProp(isValidProp) { - if (typeof isValidProp !== "function") - return; - shouldForward = (key) => key.startsWith("on") ? !isValidMotionProp(key) : isValidProp(key); -} -try { - const emotionPkg = "@emotion/is-prop-valid"; - loadExternalIsValidProp(require(emotionPkg).default); -} catch { -} -function filterProps(props, isDom, forwardMotionProps) { - const filteredProps = {}; - for (const key in props) { - if (key === "values" && typeof props.values === "object") - continue; - if (isMotionValue(props[key])) - continue; - if (shouldForward(key) || forwardMotionProps === true && isValidMotionProp(key) || !isDom && !isValidMotionProp(key) || // If trying to use native HTML drag events, forward drag listeners - props["draggable"] && key.startsWith("onDrag")) { - filteredProps[key] = props[key]; - } - } - return filteredProps; -} -const MotionContext = /* @__PURE__ */ reactExports.createContext({}); -function getCurrentTreeVariants(props, context) { - if (isControllingVariants(props)) { - const { initial, animate } = props; - return { - initial: initial === false || isVariantLabel(initial) ? initial : void 0, - animate: isVariantLabel(animate) ? animate : void 0 - }; - } - return props.inherit !== false ? context : {}; -} -function useCreateMotionContext(props) { - const { initial, animate } = getCurrentTreeVariants(props, reactExports.useContext(MotionContext)); - return reactExports.useMemo(() => ({ initial, animate }), [variantLabelsAsDependency(initial), variantLabelsAsDependency(animate)]); -} -function variantLabelsAsDependency(prop) { - return Array.isArray(prop) ? prop.join(" ") : prop; -} -const createHtmlRenderState = () => ({ - style: {}, - transform: {}, - transformOrigin: {}, - vars: {} -}); -function copyRawValuesOnly(target, source, props) { - for (const key in source) { - if (!isMotionValue(source[key]) && !isForcedMotionValue(key, props)) { - target[key] = source[key]; - } - } -} -function useInitialMotionValues({ transformTemplate }, visualState) { - return reactExports.useMemo(() => { - const state = createHtmlRenderState(); - buildHTMLStyles(state, visualState, transformTemplate); - return Object.assign({}, state.vars, state.style); - }, [visualState]); -} -function useStyle(props, visualState) { - const styleProp = props.style || {}; - const style = {}; - copyRawValuesOnly(style, styleProp, props); - Object.assign(style, useInitialMotionValues(props, visualState)); - return style; -} -function useHTMLProps(props, visualState) { - const htmlProps = {}; - const style = useStyle(props, visualState); - if (props.drag && props.dragListener !== false) { - htmlProps.draggable = false; - style.userSelect = style.WebkitUserSelect = style.WebkitTouchCallout = "none"; - style.touchAction = props.drag === true ? "none" : `pan-${props.drag === "x" ? "y" : "x"}`; - } - if (props.tabIndex === void 0 && (props.onTap || props.onTapStart || props.whileTap)) { - htmlProps.tabIndex = 0; - } - htmlProps.style = style; - return htmlProps; -} -const createSvgRenderState = () => ({ - ...createHtmlRenderState(), - attrs: {} -}); -function useSVGProps(props, visualState, _isStatic, Component) { - const visualProps = reactExports.useMemo(() => { - const state = createSvgRenderState(); - buildSVGAttrs(state, visualState, isSVGTag(Component), props.transformTemplate, props.style); - return { - ...state.attrs, - style: { ...state.style } - }; - }, [visualState]); - if (props.style) { - const rawStyles = {}; - copyRawValuesOnly(rawStyles, props.style, props); - visualProps.style = { ...rawStyles, ...visualProps.style }; - } - return visualProps; -} -const lowercaseSVGElements = [ - "animate", - "circle", - "defs", - "desc", - "ellipse", - "g", - "image", - "line", - "filter", - "marker", - "mask", - "metadata", - "path", - "pattern", - "polygon", - "polyline", - "rect", - "stop", - "switch", - "symbol", - "svg", - "text", - "tspan", - "use", - "view" -]; -function isSVGComponent(Component) { - if ( - /** - * If it's not a string, it's a custom React component. Currently we only support - * HTML custom React components. - */ - typeof Component !== "string" || /** - * If it contains a dash, the element is a custom HTML webcomponent. - */ - Component.includes("-") - ) { - return false; - } else if ( - /** - * If it's in our list of lowercase SVG tags, it's an SVG component - */ - lowercaseSVGElements.indexOf(Component) > -1 || /** - * If it contains a capital letter, it's an SVG component - */ - /[A-Z]/u.test(Component) - ) { - return true; - } - return false; -} -function useRender(Component, props, ref, { latestValues }, isStatic, forwardMotionProps = false, isSVG) { - const useVisualProps = isSVG ?? isSVGComponent(Component) ? useSVGProps : useHTMLProps; - const visualProps = useVisualProps(props, latestValues, isStatic, Component); - const filteredProps = filterProps(props, typeof Component === "string", forwardMotionProps); - const elementProps = Component !== reactExports.Fragment ? { ...filteredProps, ...visualProps, ref } : {}; - const { children } = props; - const renderedChildren = reactExports.useMemo(() => isMotionValue(children) ? children.get() : children, [children]); - return reactExports.createElement(Component, { - ...elementProps, - children: renderedChildren - }); -} -function makeState({ scrapeMotionValuesFromProps: scrapeMotionValuesFromProps2, createRenderState }, props, context, presenceContext) { - const state = { - latestValues: makeLatestValues(props, context, presenceContext, scrapeMotionValuesFromProps2), - renderState: createRenderState() - }; - return state; -} -function makeLatestValues(props, context, presenceContext, scrapeMotionValues) { - const values = {}; - const motionValues = scrapeMotionValues(props, {}); - for (const key in motionValues) { - values[key] = resolveMotionValue(motionValues[key]); - } - let { initial, animate } = props; - const isControllingVariants$1 = isControllingVariants(props); - const isVariantNode$1 = isVariantNode(props); - if (context && isVariantNode$1 && !isControllingVariants$1 && props.inherit !== false) { - if (initial === void 0) - initial = context.initial; - if (animate === void 0) - animate = context.animate; - } - let isInitialAnimationBlocked = presenceContext ? presenceContext.initial === false : false; - isInitialAnimationBlocked = isInitialAnimationBlocked || initial === false; - const variantToSet = isInitialAnimationBlocked ? animate : initial; - if (variantToSet && typeof variantToSet !== "boolean" && !isAnimationControls(variantToSet)) { - const list = Array.isArray(variantToSet) ? variantToSet : [variantToSet]; - for (let i = 0; i < list.length; i++) { - const resolved = resolveVariantFromProps(props, list[i]); - if (resolved) { - const { transitionEnd, transition, ...target } = resolved; - for (const key in target) { - let valueTarget = target[key]; - if (Array.isArray(valueTarget)) { - const index = isInitialAnimationBlocked ? valueTarget.length - 1 : 0; - valueTarget = valueTarget[index]; - } - if (valueTarget !== null) { - values[key] = valueTarget; - } - } - for (const key in transitionEnd) { - values[key] = transitionEnd[key]; - } - } - } - } - return values; -} -const makeUseVisualState = (config) => (props, isStatic) => { - const context = reactExports.useContext(MotionContext); - const presenceContext = reactExports.useContext(PresenceContext); - const make = () => makeState(config, props, context, presenceContext); - return isStatic ? make() : useConstant(make); -}; -const useHTMLVisualState = /* @__PURE__ */ makeUseVisualState({ - scrapeMotionValuesFromProps: scrapeMotionValuesFromProps$1, - createRenderState: createHtmlRenderState -}); -const useSVGVisualState = /* @__PURE__ */ makeUseVisualState({ - scrapeMotionValuesFromProps, - createRenderState: createSvgRenderState -}); -const motionComponentSymbol = /* @__PURE__ */ Symbol.for("motionComponentSymbol"); -function useMotionRef(visualState, visualElement, externalRef) { - const externalRefContainer = reactExports.useRef(externalRef); - reactExports.useInsertionEffect(() => { - externalRefContainer.current = externalRef; - }); - const refCleanup = reactExports.useRef(null); - return reactExports.useCallback((instance) => { - if (instance) { - visualState.onMount?.(instance); - } - const ref = externalRefContainer.current; - if (typeof ref === "function") { - if (instance) { - const cleanup = ref(instance); - if (typeof cleanup === "function") { - refCleanup.current = cleanup; - } - } else if (refCleanup.current) { - refCleanup.current(); - refCleanup.current = null; - } else { - ref(instance); - } - } else if (ref) { - ref.current = instance; - } - if (visualElement) { - instance ? visualElement.mount(instance) : visualElement.unmount(); - } - }, [visualElement]); -} -const SwitchLayoutGroupContext = reactExports.createContext({}); -function isRefObject(ref) { - return ref && typeof ref === "object" && Object.prototype.hasOwnProperty.call(ref, "current"); -} -function useVisualElement(Component, visualState, props, createVisualElement, ProjectionNodeConstructor, isSVG) { - const { visualElement: parent } = reactExports.useContext(MotionContext); - const lazyContext = reactExports.useContext(LazyContext); - const presenceContext = reactExports.useContext(PresenceContext); - const motionConfig = reactExports.useContext(MotionConfigContext); - const reducedMotionConfig = motionConfig.reducedMotion; - const skipAnimations = motionConfig.skipAnimations; - const visualElementRef = reactExports.useRef(null); - const hasMountedOnce = reactExports.useRef(false); - createVisualElement = createVisualElement || lazyContext.renderer; - if (!visualElementRef.current && createVisualElement) { - visualElementRef.current = createVisualElement(Component, { - visualState, - parent, - props, - presenceContext, - blockInitialAnimation: presenceContext ? presenceContext.initial === false : false, - reducedMotionConfig, - skipAnimations, - isSVG - }); - if (hasMountedOnce.current && visualElementRef.current) { - visualElementRef.current.manuallyAnimateOnMount = true; - } - } - const visualElement = visualElementRef.current; - const initialLayoutGroupConfig = reactExports.useContext(SwitchLayoutGroupContext); - if (visualElement && !visualElement.projection && ProjectionNodeConstructor && (visualElement.type === "html" || visualElement.type === "svg")) { - createProjectionNode(visualElementRef.current, props, ProjectionNodeConstructor, initialLayoutGroupConfig); - } - const isMounted = reactExports.useRef(false); - reactExports.useInsertionEffect(() => { - if (visualElement && isMounted.current) { - visualElement.update(props, presenceContext); - } - }); - const optimisedAppearId = props[optimizedAppearDataAttribute]; - const wantsHandoff = reactExports.useRef(Boolean(optimisedAppearId) && typeof window !== "undefined" && !window.MotionHandoffIsComplete?.(optimisedAppearId) && window.MotionHasOptimisedAnimation?.(optimisedAppearId)); - useIsomorphicLayoutEffect(() => { - hasMountedOnce.current = true; - if (!visualElement) - return; - isMounted.current = true; - window.MotionIsMounted = true; - visualElement.updateFeatures(); - visualElement.scheduleRenderMicrotask(); - if (wantsHandoff.current && visualElement.animationState) { - visualElement.animationState.animateChanges(); - } - }); - reactExports.useEffect(() => { - if (!visualElement) - return; - if (!wantsHandoff.current && visualElement.animationState) { - visualElement.animationState.animateChanges(); - } - if (wantsHandoff.current) { - queueMicrotask(() => { - window.MotionHandoffMarkAsComplete?.(optimisedAppearId); - }); - wantsHandoff.current = false; - } - visualElement.enteringChildren = void 0; - }); - return visualElement; -} -function createProjectionNode(visualElement, props, ProjectionNodeConstructor, initialPromotionConfig) { - const { layoutId, layout: layout2, drag: drag2, dragConstraints, layoutScroll, layoutRoot, layoutAnchor, layoutCrossfade } = props; - visualElement.projection = new ProjectionNodeConstructor(visualElement.latestValues, props["data-framer-portal-id"] ? void 0 : getClosestProjectingNode(visualElement.parent)); - visualElement.projection.setOptions({ - layoutId, - layout: layout2, - alwaysMeasureLayout: Boolean(drag2) || dragConstraints && isRefObject(dragConstraints), - visualElement, - /** - * TODO: Update options in an effect. This could be tricky as it'll be too late - * to update by the time layout animations run. - * We also need to fix this safeToRemove by linking it up to the one returned by usePresence, - * ensuring it gets called if there's no potential layout animations. - * - */ - animationType: typeof layout2 === "string" ? layout2 : "both", - initialPromotionConfig, - crossfade: layoutCrossfade, - layoutScroll, - layoutRoot, - layoutAnchor - }); -} -function getClosestProjectingNode(visualElement) { - if (!visualElement) - return void 0; - return visualElement.options.allowProjection !== false ? visualElement.projection : getClosestProjectingNode(visualElement.parent); -} -function createMotionComponent(Component, { forwardMotionProps = false, type } = {}, preloadedFeatures, createVisualElement) { - preloadedFeatures && loadFeatures(preloadedFeatures); - const isSVG = type ? type === "svg" : isSVGComponent(Component); - const useVisualState = isSVG ? useSVGVisualState : useHTMLVisualState; - function MotionDOMComponent(props, externalRef) { - let MeasureLayout2; - const configAndProps = { - ...reactExports.useContext(MotionConfigContext), - ...props, - layoutId: useLayoutId(props) - }; - const { isStatic } = configAndProps; - const context = useCreateMotionContext(props); - const visualState = useVisualState(props, isStatic); - if (!isStatic && typeof window !== "undefined") { - useStrictMode(configAndProps, preloadedFeatures); - const layoutProjection = getProjectionFunctionality(configAndProps); - MeasureLayout2 = layoutProjection.MeasureLayout; - context.visualElement = useVisualElement(Component, visualState, configAndProps, createVisualElement, layoutProjection.ProjectionNode, isSVG); - } - return jsxRuntimeExports.jsxs(MotionContext.Provider, { value: context, children: [MeasureLayout2 && context.visualElement ? jsxRuntimeExports.jsx(MeasureLayout2, { visualElement: context.visualElement, ...configAndProps }) : null, useRender(Component, props, useMotionRef(visualState, context.visualElement, externalRef), visualState, isStatic, forwardMotionProps, isSVG)] }); - } - MotionDOMComponent.displayName = `motion.${typeof Component === "string" ? Component : `create(${Component.displayName ?? Component.name ?? ""})`}`; - const ForwardRefMotionComponent = reactExports.forwardRef(MotionDOMComponent); - ForwardRefMotionComponent[motionComponentSymbol] = Component; - return ForwardRefMotionComponent; -} -function useLayoutId({ layoutId }) { - const layoutGroupId = reactExports.useContext(LayoutGroupContext).id; - return layoutGroupId && layoutId !== void 0 ? layoutGroupId + "-" + layoutId : layoutId; -} -function useStrictMode(configAndProps, preloadedFeatures) { - const isStrict = reactExports.useContext(LazyContext).strict; - if (process.env.NODE_ENV !== "production" && preloadedFeatures && isStrict) { - const strictMessage = "You have rendered a `motion` component within a `LazyMotion` component. This will break tree shaking. Import and render a `m` component instead."; - configAndProps.ignoreStrict ? warning(false, strictMessage, "lazy-strict-mode") : invariant(false, strictMessage, "lazy-strict-mode"); - } -} -function getProjectionFunctionality(props) { - const featureDefinitions2 = getInitializedFeatureDefinitions(); - const { drag: drag2, layout: layout2 } = featureDefinitions2; - if (!drag2 && !layout2) - return {}; - const combined = { ...drag2, ...layout2 }; - return { - MeasureLayout: drag2?.isEnabled(props) || layout2?.isEnabled(props) ? combined.MeasureLayout : void 0, - ProjectionNode: combined.ProjectionNode - }; -} -function createMotionProxy(preloadedFeatures, createVisualElement) { - if (typeof Proxy === "undefined") { - return createMotionComponent; - } - const componentCache = /* @__PURE__ */ new Map(); - const factory = (Component, options) => { - return createMotionComponent(Component, options, preloadedFeatures, createVisualElement); - }; - const deprecatedFactoryFunction = (Component, options) => { - if (process.env.NODE_ENV !== "production") { - warnOnce(false, "motion() is deprecated. Use motion.create() instead."); - } - return factory(Component, options); - }; - return new Proxy(deprecatedFactoryFunction, { - /** - * Called when `motion` is referenced with a prop: `motion.div`, `motion.input` etc. - * The prop name is passed through as `key` and we can use that to generate a `motion` - * DOM component with that name. - */ - get: (_target, key) => { - if (key === "create") - return factory; - if (!componentCache.has(key)) { - componentCache.set(key, createMotionComponent(key, void 0, preloadedFeatures, createVisualElement)); - } - return componentCache.get(key); - } - }); -} -const createDomVisualElement = (Component, options) => { - const isSVG = options.isSVG ?? isSVGComponent(Component); - return isSVG ? new SVGVisualElement(options) : new HTMLVisualElement(options, { - allowProjection: Component !== reactExports.Fragment - }); -}; -class AnimationFeature extends Feature { - /** - * We dynamically generate the AnimationState manager as it contains a reference - * to the underlying animation library. We only want to load that if we load this, - * so people can optionally code split it out using the `m` component. - */ - constructor(node) { - super(node); - node.animationState || (node.animationState = createAnimationState(node)); - } - updateAnimationControlsSubscription() { - const { animate } = this.node.getProps(); - if (isAnimationControls(animate)) { - this.unmountControls = animate.subscribe(this.node); - } - } - /** - * Subscribe any provided AnimationControls to the component's VisualElement - */ - mount() { - this.updateAnimationControlsSubscription(); - } - update() { - const { animate } = this.node.getProps(); - const { animate: prevAnimate } = this.node.prevProps || {}; - if (animate !== prevAnimate) { - this.updateAnimationControlsSubscription(); - } - } - unmount() { - this.node.animationState.reset(); - this.unmountControls?.(); - } -} -let id = 0; -class ExitAnimationFeature extends Feature { - constructor() { - super(...arguments); - this.id = id++; - this.isExitComplete = false; - } - update() { - if (!this.node.presenceContext) - return; - const { isPresent, onExitComplete } = this.node.presenceContext; - const { isPresent: prevIsPresent } = this.node.prevPresenceContext || {}; - if (!this.node.animationState || isPresent === prevIsPresent) { - return; - } - if (isPresent && prevIsPresent === false) { - if (this.isExitComplete) { - const { initial, custom } = this.node.getProps(); - if (typeof initial === "string") { - const resolved = resolveVariant(this.node, initial, custom); - if (resolved) { - const { transition, transitionEnd, ...target } = resolved; - for (const key in target) { - this.node.getValue(key)?.jump(target[key]); - } - } - } - this.node.animationState.reset(); - this.node.animationState.animateChanges(); - } else { - this.node.animationState.setActive("exit", false); - } - this.isExitComplete = false; - return; - } - const exitAnimation = this.node.animationState.setActive("exit", !isPresent); - if (onExitComplete && !isPresent) { - exitAnimation.then(() => { - this.isExitComplete = true; - onExitComplete(this.id); - }); - } - } - mount() { - const { register, onExitComplete } = this.node.presenceContext || {}; - if (onExitComplete) { - onExitComplete(this.id); - } - if (register) { - this.unmount = register(this.id); - } - } - unmount() { - } -} -const animations = { - animation: { - Feature: AnimationFeature - }, - exit: { - Feature: ExitAnimationFeature - } -}; -function extractEventInfo(event) { - return { - point: { - x: event.pageX, - y: event.pageY - } - }; -} -const addPointerInfo = (handler) => (event) => isPrimaryPointer(event) && handler(event, extractEventInfo(event)); -function addPointerEvent(target, eventName, handler, options) { - return addDomEvent(target, eventName, addPointerInfo(handler), options); -} -const getContextWindow = ({ current }) => { - return current ? current.ownerDocument.defaultView : null; -}; -const distance = (a, b) => Math.abs(a - b); -function distance2D(a, b) { - const xDelta = distance(a.x, b.x); - const yDelta = distance(a.y, b.y); - return Math.sqrt(xDelta ** 2 + yDelta ** 2); -} -const overflowStyles = /* @__PURE__ */ new Set(["auto", "scroll"]); -class PanSession { - constructor(event, handlers, { transformPagePoint, contextWindow = window, dragSnapToOrigin = false, distanceThreshold = 3, element } = {}) { - this.startEvent = null; - this.lastMoveEvent = null; - this.lastMoveEventInfo = null; - this.lastRawMoveEventInfo = null; - this.handlers = {}; - this.contextWindow = window; - this.scrollPositions = /* @__PURE__ */ new Map(); - this.removeScrollListeners = null; - this.onElementScroll = (event2) => { - this.handleScroll(event2.target); - }; - this.onWindowScroll = () => { - this.handleScroll(window); - }; - this.updatePoint = () => { - if (!(this.lastMoveEvent && this.lastMoveEventInfo)) - return; - if (this.lastRawMoveEventInfo) { - this.lastMoveEventInfo = transformPoint(this.lastRawMoveEventInfo, this.transformPagePoint); - } - const info2 = getPanInfo(this.lastMoveEventInfo, this.history); - const isPanStarted = this.startEvent !== null; - const isDistancePastThreshold = distance2D(info2.offset, { x: 0, y: 0 }) >= this.distanceThreshold; - if (!isPanStarted && !isDistancePastThreshold) - return; - const { point: point2 } = info2; - const { timestamp: timestamp2 } = frameData; - this.history.push({ ...point2, timestamp: timestamp2 }); - const { onStart, onMove } = this.handlers; - if (!isPanStarted) { - onStart && onStart(this.lastMoveEvent, info2); - this.startEvent = this.lastMoveEvent; - } - onMove && onMove(this.lastMoveEvent, info2); - }; - this.handlePointerMove = (event2, info2) => { - this.lastMoveEvent = event2; - this.lastRawMoveEventInfo = info2; - this.lastMoveEventInfo = transformPoint(info2, this.transformPagePoint); - frame.update(this.updatePoint, true); - }; - this.handlePointerUp = (event2, info2) => { - this.end(); - const { onEnd, onSessionEnd, resumeAnimation } = this.handlers; - if (this.dragSnapToOrigin || !this.startEvent) { - resumeAnimation && resumeAnimation(); - } - if (!(this.lastMoveEvent && this.lastMoveEventInfo)) - return; - const panInfo = getPanInfo(event2.type === "pointercancel" ? this.lastMoveEventInfo : transformPoint(info2, this.transformPagePoint), this.history); - if (this.startEvent && onEnd) { - onEnd(event2, panInfo); - } - onSessionEnd && onSessionEnd(event2, panInfo); - }; - if (!isPrimaryPointer(event)) - return; - this.dragSnapToOrigin = dragSnapToOrigin; - this.handlers = handlers; - this.transformPagePoint = transformPagePoint; - this.distanceThreshold = distanceThreshold; - this.contextWindow = contextWindow || window; - const info = extractEventInfo(event); - const initialInfo = transformPoint(info, this.transformPagePoint); - const { point } = initialInfo; - const { timestamp } = frameData; - this.history = [{ ...point, timestamp }]; - const { onSessionStart } = handlers; - onSessionStart && onSessionStart(event, getPanInfo(initialInfo, this.history)); - this.removeListeners = pipe(addPointerEvent(this.contextWindow, "pointermove", this.handlePointerMove), addPointerEvent(this.contextWindow, "pointerup", this.handlePointerUp), addPointerEvent(this.contextWindow, "pointercancel", this.handlePointerUp)); - if (element) { - this.startScrollTracking(element); - } - } - /** - * Start tracking scroll on ancestors and window. - */ - startScrollTracking(element) { - let current = element.parentElement; - while (current) { - const style = getComputedStyle(current); - if (overflowStyles.has(style.overflowX) || overflowStyles.has(style.overflowY)) { - this.scrollPositions.set(current, { - x: current.scrollLeft, - y: current.scrollTop - }); - } - current = current.parentElement; - } - this.scrollPositions.set(window, { - x: window.scrollX, - y: window.scrollY - }); - window.addEventListener("scroll", this.onElementScroll, { - capture: true - }); - window.addEventListener("scroll", this.onWindowScroll); - this.removeScrollListeners = () => { - window.removeEventListener("scroll", this.onElementScroll, { - capture: true - }); - window.removeEventListener("scroll", this.onWindowScroll); - }; - } - /** - * Handle scroll compensation during drag. - * - * For element scroll: adjusts history origin since pageX/pageY doesn't change. - * For window scroll: adjusts lastMoveEventInfo since pageX/pageY would change. - */ - handleScroll(target) { - const initial = this.scrollPositions.get(target); - if (!initial) - return; - const isWindow = target === window; - const current = isWindow ? { x: window.scrollX, y: window.scrollY } : { - x: target.scrollLeft, - y: target.scrollTop - }; - const delta = { x: current.x - initial.x, y: current.y - initial.y }; - if (delta.x === 0 && delta.y === 0) - return; - if (isWindow) { - if (this.lastMoveEventInfo) { - this.lastMoveEventInfo.point.x += delta.x; - this.lastMoveEventInfo.point.y += delta.y; - } - } else { - if (this.history.length > 0) { - this.history[0].x -= delta.x; - this.history[0].y -= delta.y; - } - } - this.scrollPositions.set(target, current); - frame.update(this.updatePoint, true); - } - updateHandlers(handlers) { - this.handlers = handlers; - } - end() { - this.removeListeners && this.removeListeners(); - this.removeScrollListeners && this.removeScrollListeners(); - this.scrollPositions.clear(); - cancelFrame(this.updatePoint); - } -} -function transformPoint(info, transformPagePoint) { - return transformPagePoint ? { point: transformPagePoint(info.point) } : info; -} -function subtractPoint(a, b) { - return { x: a.x - b.x, y: a.y - b.y }; -} -function getPanInfo({ point }, history) { - return { - point, - delta: subtractPoint(point, lastDevicePoint(history)), - offset: subtractPoint(point, startDevicePoint(history)), - velocity: getVelocity(history, 0.1) - }; -} -function startDevicePoint(history) { - return history[0]; -} -function lastDevicePoint(history) { - return history[history.length - 1]; -} -function getVelocity(history, timeDelta) { - if (history.length < 2) { - return { x: 0, y: 0 }; - } - let i = history.length - 1; - let timestampedPoint = null; - const lastPoint = lastDevicePoint(history); - while (i >= 0) { - timestampedPoint = history[i]; - if (lastPoint.timestamp - timestampedPoint.timestamp > /* @__PURE__ */ secondsToMilliseconds(timeDelta)) { - break; - } - i--; - } - if (!timestampedPoint) { - return { x: 0, y: 0 }; - } - if (timestampedPoint === history[0] && history.length > 2 && lastPoint.timestamp - timestampedPoint.timestamp > /* @__PURE__ */ secondsToMilliseconds(timeDelta) * 2) { - timestampedPoint = history[1]; - } - const time2 = /* @__PURE__ */ millisecondsToSeconds(lastPoint.timestamp - timestampedPoint.timestamp); - if (time2 === 0) { - return { x: 0, y: 0 }; - } - const currentVelocity = { - x: (lastPoint.x - timestampedPoint.x) / time2, - y: (lastPoint.y - timestampedPoint.y) / time2 - }; - if (currentVelocity.x === Infinity) { - currentVelocity.x = 0; - } - if (currentVelocity.y === Infinity) { - currentVelocity.y = 0; - } - return currentVelocity; -} -function applyConstraints(point, { min, max }, elastic) { - if (min !== void 0 && point < min) { - point = elastic ? mixNumber$1(min, point, elastic.min) : Math.max(point, min); - } else if (max !== void 0 && point > max) { - point = elastic ? mixNumber$1(max, point, elastic.max) : Math.min(point, max); - } - return point; -} -function calcRelativeAxisConstraints(axis, min, max) { - return { - min: min !== void 0 ? axis.min + min : void 0, - max: max !== void 0 ? axis.max + max - (axis.max - axis.min) : void 0 - }; -} -function calcRelativeConstraints(layoutBox, { top, left, bottom, right }) { - return { - x: calcRelativeAxisConstraints(layoutBox.x, left, right), - y: calcRelativeAxisConstraints(layoutBox.y, top, bottom) - }; -} -function calcViewportAxisConstraints(layoutAxis, constraintsAxis) { - let min = constraintsAxis.min - layoutAxis.min; - let max = constraintsAxis.max - layoutAxis.max; - if (constraintsAxis.max - constraintsAxis.min < layoutAxis.max - layoutAxis.min) { - [min, max] = [max, min]; - } - return { min, max }; -} -function calcViewportConstraints(layoutBox, constraintsBox) { - return { - x: calcViewportAxisConstraints(layoutBox.x, constraintsBox.x), - y: calcViewportAxisConstraints(layoutBox.y, constraintsBox.y) - }; -} -function calcOrigin(source, target) { - let origin = 0.5; - const sourceLength = calcLength(source); - const targetLength = calcLength(target); - if (targetLength > sourceLength) { - origin = /* @__PURE__ */ progress(target.min, target.max - sourceLength, source.min); - } else if (sourceLength > targetLength) { - origin = /* @__PURE__ */ progress(source.min, source.max - targetLength, target.min); - } - return clamp(0, 1, origin); -} -function rebaseAxisConstraints(layout2, constraints) { - const relativeConstraints = {}; - if (constraints.min !== void 0) { - relativeConstraints.min = constraints.min - layout2.min; - } - if (constraints.max !== void 0) { - relativeConstraints.max = constraints.max - layout2.min; - } - return relativeConstraints; -} -const defaultElastic = 0.35; -function resolveDragElastic(dragElastic = defaultElastic) { - if (dragElastic === false) { - dragElastic = 0; - } else if (dragElastic === true) { - dragElastic = defaultElastic; - } - return { - x: resolveAxisElastic(dragElastic, "left", "right"), - y: resolveAxisElastic(dragElastic, "top", "bottom") - }; -} -function resolveAxisElastic(dragElastic, minLabel, maxLabel) { - return { - min: resolvePointElastic(dragElastic, minLabel), - max: resolvePointElastic(dragElastic, maxLabel) - }; -} -function resolvePointElastic(dragElastic, label) { - return typeof dragElastic === "number" ? dragElastic : dragElastic[label] || 0; -} -const elementDragControls = /* @__PURE__ */ new WeakMap(); -class VisualElementDragControls { - constructor(visualElement) { - this.openDragLock = null; - this.isDragging = false; - this.currentDirection = null; - this.originPoint = { x: 0, y: 0 }; - this.constraints = false; - this.hasMutatedConstraints = false; - this.elastic = createBox(); - this.latestPointerEvent = null; - this.latestPanInfo = null; - this.visualElement = visualElement; - } - start(originEvent, { snapToCursor = false, distanceThreshold } = {}) { - const { presenceContext } = this.visualElement; - if (presenceContext && presenceContext.isPresent === false) - return; - const onSessionStart = (event) => { - if (snapToCursor) { - this.snapToCursor(extractEventInfo(event).point); - } - this.stopAnimation(); - }; - const onStart = (event, info) => { - const { drag: drag2, dragPropagation, onDragStart } = this.getProps(); - if (drag2 && !dragPropagation) { - if (this.openDragLock) - this.openDragLock(); - this.openDragLock = setDragLock(drag2); - if (!this.openDragLock) - return; - } - this.latestPointerEvent = event; - this.latestPanInfo = info; - this.isDragging = true; - this.currentDirection = null; - this.resolveConstraints(); - if (this.visualElement.projection) { - this.visualElement.projection.isAnimationBlocked = true; - this.visualElement.projection.target = void 0; - } - eachAxis((axis) => { - let current = this.getAxisMotionValue(axis).get() || 0; - if (percent.test(current)) { - const { projection } = this.visualElement; - if (projection && projection.layout) { - const measuredAxis = projection.layout.layoutBox[axis]; - if (measuredAxis) { - const length = calcLength(measuredAxis); - current = length * (parseFloat(current) / 100); - } - } - } - this.originPoint[axis] = current; - }); - if (onDragStart) { - frame.update(() => onDragStart(event, info), false, true); - } - addValueToWillChange(this.visualElement, "transform"); - const { animationState } = this.visualElement; - animationState && animationState.setActive("whileDrag", true); - }; - const onMove = (event, info) => { - this.latestPointerEvent = event; - this.latestPanInfo = info; - const { dragPropagation, dragDirectionLock, onDirectionLock, onDrag } = this.getProps(); - if (!dragPropagation && !this.openDragLock) - return; - const { offset } = info; - if (dragDirectionLock && this.currentDirection === null) { - this.currentDirection = getCurrentDirection(offset); - if (this.currentDirection !== null) { - onDirectionLock && onDirectionLock(this.currentDirection); - } - return; - } - this.updateAxis("x", info.point, offset); - this.updateAxis("y", info.point, offset); - this.visualElement.render(); - if (onDrag) { - frame.update(() => onDrag(event, info), false, true); - } - }; - const onSessionEnd = (event, info) => { - this.latestPointerEvent = event; - this.latestPanInfo = info; - this.stop(event, info); - this.latestPointerEvent = null; - this.latestPanInfo = null; - }; - const resumeAnimation = () => { - const { dragSnapToOrigin: snap } = this.getProps(); - if (snap || this.constraints) { - this.startAnimation({ x: 0, y: 0 }); - } - }; - const { dragSnapToOrigin } = this.getProps(); - this.panSession = new PanSession(originEvent, { - onSessionStart, - onStart, - onMove, - onSessionEnd, - resumeAnimation - }, { - transformPagePoint: this.visualElement.getTransformPagePoint(), - dragSnapToOrigin, - distanceThreshold, - contextWindow: getContextWindow(this.visualElement), - element: this.visualElement.current - }); - } - /** - * @internal - */ - stop(event, panInfo) { - const finalEvent = event || this.latestPointerEvent; - const finalPanInfo = panInfo || this.latestPanInfo; - const isDragging2 = this.isDragging; - this.cancel(); - if (!isDragging2 || !finalPanInfo || !finalEvent) - return; - const { velocity } = finalPanInfo; - this.startAnimation(velocity); - const { onDragEnd } = this.getProps(); - if (onDragEnd) { - frame.postRender(() => onDragEnd(finalEvent, finalPanInfo)); - } - } - /** - * @internal - */ - cancel() { - this.isDragging = false; - const { projection, animationState } = this.visualElement; - if (projection) { - projection.isAnimationBlocked = false; - } - this.endPanSession(); - const { dragPropagation } = this.getProps(); - if (!dragPropagation && this.openDragLock) { - this.openDragLock(); - this.openDragLock = null; - } - animationState && animationState.setActive("whileDrag", false); - } - /** - * Clean up the pan session without modifying other drag state. - * This is used during unmount to ensure event listeners are removed - * without affecting projection animations or drag locks. - * @internal - */ - endPanSession() { - this.panSession && this.panSession.end(); - this.panSession = void 0; - } - updateAxis(axis, _point, offset) { - const { drag: drag2 } = this.getProps(); - if (!offset || !shouldDrag(axis, drag2, this.currentDirection)) - return; - const axisValue = this.getAxisMotionValue(axis); - let next = this.originPoint[axis] + offset[axis]; - if (this.constraints && this.constraints[axis]) { - next = applyConstraints(next, this.constraints[axis], this.elastic[axis]); - } - axisValue.set(next); - } - resolveConstraints() { - const { dragConstraints, dragElastic } = this.getProps(); - const layout2 = this.visualElement.projection && !this.visualElement.projection.layout ? this.visualElement.projection.measure(false) : this.visualElement.projection?.layout; - const prevConstraints = this.constraints; - if (dragConstraints && isRefObject(dragConstraints)) { - if (!this.constraints) { - this.constraints = this.resolveRefConstraints(); - } - } else { - if (dragConstraints && layout2) { - this.constraints = calcRelativeConstraints(layout2.layoutBox, dragConstraints); - } else { - this.constraints = false; - } - } - this.elastic = resolveDragElastic(dragElastic); - if (prevConstraints !== this.constraints && !isRefObject(dragConstraints) && layout2 && this.constraints && !this.hasMutatedConstraints) { - eachAxis((axis) => { - if (this.constraints !== false && this.getAxisMotionValue(axis)) { - this.constraints[axis] = rebaseAxisConstraints(layout2.layoutBox[axis], this.constraints[axis]); - } - }); - } - } - resolveRefConstraints() { - const { dragConstraints: constraints, onMeasureDragConstraints } = this.getProps(); - if (!constraints || !isRefObject(constraints)) - return false; - const constraintsElement = constraints.current; - invariant(constraintsElement !== null, "If `dragConstraints` is set as a React ref, that ref must be passed to another component's `ref` prop.", "drag-constraints-ref"); - const { projection } = this.visualElement; - if (!projection || !projection.layout) - return false; - const constraintsBox = measurePageBox(constraintsElement, projection.root, this.visualElement.getTransformPagePoint()); - let measuredConstraints = calcViewportConstraints(projection.layout.layoutBox, constraintsBox); - if (onMeasureDragConstraints) { - const userConstraints = onMeasureDragConstraints(convertBoxToBoundingBox(measuredConstraints)); - this.hasMutatedConstraints = !!userConstraints; - if (userConstraints) { - measuredConstraints = convertBoundingBoxToBox(userConstraints); - } - } - return measuredConstraints; - } - startAnimation(velocity) { - const { drag: drag2, dragMomentum, dragElastic, dragTransition, dragSnapToOrigin, onDragTransitionEnd } = this.getProps(); - const constraints = this.constraints || {}; - const momentumAnimations = eachAxis((axis) => { - if (!shouldDrag(axis, drag2, this.currentDirection)) { - return; - } - let transition = constraints && constraints[axis] || {}; - if (dragSnapToOrigin === true || dragSnapToOrigin === axis) - transition = { min: 0, max: 0 }; - const bounceStiffness = dragElastic ? 200 : 1e6; - const bounceDamping = dragElastic ? 40 : 1e7; - const inertia2 = { - type: "inertia", - velocity: dragMomentum ? velocity[axis] : 0, - bounceStiffness, - bounceDamping, - timeConstant: 750, - restDelta: 1, - restSpeed: 10, - ...dragTransition, - ...transition - }; - return this.startAxisValueAnimation(axis, inertia2); - }); - return Promise.all(momentumAnimations).then(onDragTransitionEnd); - } - startAxisValueAnimation(axis, transition) { - const axisValue = this.getAxisMotionValue(axis); - addValueToWillChange(this.visualElement, axis); - return axisValue.start(animateMotionValue(axis, axisValue, 0, transition, this.visualElement, false)); - } - stopAnimation() { - eachAxis((axis) => this.getAxisMotionValue(axis).stop()); - } - /** - * Drag works differently depending on which props are provided. - * - * - If _dragX and _dragY are provided, we output the gesture delta directly to those motion values. - * - Otherwise, we apply the delta to the x/y motion values. - */ - getAxisMotionValue(axis) { - const dragKey = `_drag${axis.toUpperCase()}`; - const props = this.visualElement.getProps(); - const externalMotionValue = props[dragKey]; - return externalMotionValue ? externalMotionValue : this.visualElement.getValue(axis, (props.initial ? props.initial[axis] : void 0) || 0); - } - snapToCursor(point) { - eachAxis((axis) => { - const { drag: drag2 } = this.getProps(); - if (!shouldDrag(axis, drag2, this.currentDirection)) - return; - const { projection } = this.visualElement; - const axisValue = this.getAxisMotionValue(axis); - if (projection && projection.layout) { - const { min, max } = projection.layout.layoutBox[axis]; - const current = axisValue.get() || 0; - axisValue.set(point[axis] - mixNumber$1(min, max, 0.5) + current); - } - }); - } - /** - * When the viewport resizes we want to check if the measured constraints - * have changed and, if so, reposition the element within those new constraints - * relative to where it was before the resize. - */ - scalePositionWithinConstraints() { - if (!this.visualElement.current) - return; - const { drag: drag2, dragConstraints } = this.getProps(); - const { projection } = this.visualElement; - if (!isRefObject(dragConstraints) || !projection || !this.constraints) - return; - this.stopAnimation(); - const boxProgress = { x: 0, y: 0 }; - eachAxis((axis) => { - const axisValue = this.getAxisMotionValue(axis); - if (axisValue && this.constraints !== false) { - const latest = axisValue.get(); - boxProgress[axis] = calcOrigin({ min: latest, max: latest }, this.constraints[axis]); - } - }); - const { transformTemplate } = this.visualElement.getProps(); - this.visualElement.current.style.transform = transformTemplate ? transformTemplate({}, "") : "none"; - projection.root && projection.root.updateScroll(); - projection.updateLayout(); - this.constraints = false; - this.resolveConstraints(); - eachAxis((axis) => { - if (!shouldDrag(axis, drag2, null)) - return; - const axisValue = this.getAxisMotionValue(axis); - const { min, max } = this.constraints[axis]; - axisValue.set(mixNumber$1(min, max, boxProgress[axis])); - }); - this.visualElement.render(); - } - addListeners() { - if (!this.visualElement.current) - return; - elementDragControls.set(this.visualElement, this); - const element = this.visualElement.current; - const stopPointerListener = addPointerEvent(element, "pointerdown", (event) => { - const { drag: drag2, dragListener = true } = this.getProps(); - const target = event.target; - const isClickingTextInputChild = target !== element && isElementTextInput(target); - if (drag2 && dragListener && !isClickingTextInputChild) { - this.start(event); - } - }); - let stopResizeObservers; - const measureDragConstraints = () => { - const { dragConstraints } = this.getProps(); - if (isRefObject(dragConstraints) && dragConstraints.current) { - this.constraints = this.resolveRefConstraints(); - if (!stopResizeObservers) { - stopResizeObservers = startResizeObservers(element, dragConstraints.current, () => this.scalePositionWithinConstraints()); - } - } - }; - const { projection } = this.visualElement; - const stopMeasureLayoutListener = projection.addEventListener("measure", measureDragConstraints); - if (projection && !projection.layout) { - projection.root && projection.root.updateScroll(); - projection.updateLayout(); - } - frame.read(measureDragConstraints); - const stopResizeListener = addDomEvent(window, "resize", () => this.scalePositionWithinConstraints()); - const stopLayoutUpdateListener = projection.addEventListener("didUpdate", (({ delta, hasLayoutChanged }) => { - if (this.isDragging && hasLayoutChanged) { - eachAxis((axis) => { - const motionValue2 = this.getAxisMotionValue(axis); - if (!motionValue2) - return; - this.originPoint[axis] += delta[axis].translate; - motionValue2.set(motionValue2.get() + delta[axis].translate); - }); - this.visualElement.render(); - } - })); - return () => { - stopResizeListener(); - stopPointerListener(); - stopMeasureLayoutListener(); - stopLayoutUpdateListener && stopLayoutUpdateListener(); - stopResizeObservers && stopResizeObservers(); - }; - } - getProps() { - const props = this.visualElement.getProps(); - const { drag: drag2 = false, dragDirectionLock = false, dragPropagation = false, dragConstraints = false, dragElastic = defaultElastic, dragMomentum = true } = props; - return { - ...props, - drag: drag2, - dragDirectionLock, - dragPropagation, - dragConstraints, - dragElastic, - dragMomentum - }; - } -} -function skipFirstCall(callback) { - let isFirst = true; - return () => { - if (isFirst) { - isFirst = false; - return; - } - callback(); - }; -} -function startResizeObservers(element, constraintsElement, onResize) { - const stopElement = resize(element, skipFirstCall(onResize)); - const stopContainer = resize(constraintsElement, skipFirstCall(onResize)); - return () => { - stopElement(); - stopContainer(); - }; -} -function shouldDrag(direction, drag2, currentDirection) { - return (drag2 === true || drag2 === direction) && (currentDirection === null || currentDirection === direction); -} -function getCurrentDirection(offset, lockThreshold = 10) { - let direction = null; - if (Math.abs(offset.y) > lockThreshold) { - direction = "y"; - } else if (Math.abs(offset.x) > lockThreshold) { - direction = "x"; - } - return direction; -} -class DragGesture extends Feature { - constructor(node) { - super(node); - this.removeGroupControls = noop; - this.removeListeners = noop; - this.controls = new VisualElementDragControls(node); - } - mount() { - const { dragControls } = this.node.getProps(); - if (dragControls) { - this.removeGroupControls = dragControls.subscribe(this.controls); - } - this.removeListeners = this.controls.addListeners() || noop; - } - update() { - const { dragControls } = this.node.getProps(); - const { dragControls: prevDragControls } = this.node.prevProps || {}; - if (dragControls !== prevDragControls) { - this.removeGroupControls(); - if (dragControls) { - this.removeGroupControls = dragControls.subscribe(this.controls); - } - } - } - unmount() { - this.removeGroupControls(); - this.removeListeners(); - if (!this.controls.isDragging) { - this.controls.endPanSession(); - } - } -} -const asyncHandler = (handler) => (event, info) => { - if (handler) { - frame.update(() => handler(event, info), false, true); - } -}; -class PanGesture extends Feature { - constructor() { - super(...arguments); - this.removePointerDownListener = noop; - } - onPointerDown(pointerDownEvent) { - this.session = new PanSession(pointerDownEvent, this.createPanHandlers(), { - transformPagePoint: this.node.getTransformPagePoint(), - contextWindow: getContextWindow(this.node) - }); - } - createPanHandlers() { - const { onPanSessionStart, onPanStart, onPan, onPanEnd } = this.node.getProps(); - return { - onSessionStart: asyncHandler(onPanSessionStart), - onStart: asyncHandler(onPanStart), - onMove: asyncHandler(onPan), - onEnd: (event, info) => { - delete this.session; - if (onPanEnd) { - frame.postRender(() => onPanEnd(event, info)); - } - } - }; - } - mount() { - this.removePointerDownListener = addPointerEvent(this.node.current, "pointerdown", (event) => this.onPointerDown(event)); - } - update() { - this.session && this.session.updateHandlers(this.createPanHandlers()); - } - unmount() { - this.removePointerDownListener(); - this.session && this.session.end(); - } -} -let hasTakenAnySnapshot = false; -class MeasureLayoutWithContext extends reactExports.Component { - /** - * This only mounts projection nodes for components that - * need measuring, we might want to do it for all components - * in order to incorporate transforms - */ - componentDidMount() { - const { visualElement, layoutGroup, switchLayoutGroup, layoutId } = this.props; - const { projection } = visualElement; - if (projection) { - if (layoutGroup.group) - layoutGroup.group.add(projection); - if (switchLayoutGroup && switchLayoutGroup.register && layoutId) { - switchLayoutGroup.register(projection); - } - if (hasTakenAnySnapshot) { - projection.root.didUpdate(); - } - projection.addEventListener("animationComplete", () => { - this.safeToRemove(); - }); - projection.setOptions({ - ...projection.options, - layoutDependency: this.props.layoutDependency, - onExitComplete: () => this.safeToRemove() - }); - } - globalProjectionState.hasEverUpdated = true; - } - getSnapshotBeforeUpdate(prevProps) { - const { layoutDependency, visualElement, drag: drag2, isPresent } = this.props; - const { projection } = visualElement; - if (!projection) - return null; - projection.isPresent = isPresent; - if (prevProps.layoutDependency !== layoutDependency) { - projection.setOptions({ - ...projection.options, - layoutDependency - }); - } - hasTakenAnySnapshot = true; - if (drag2 || prevProps.layoutDependency !== layoutDependency || layoutDependency === void 0 || prevProps.isPresent !== isPresent) { - projection.willUpdate(); - } else { - this.safeToRemove(); - } - if (prevProps.isPresent !== isPresent) { - if (isPresent) { - projection.promote(); - } else if (!projection.relegate()) { - frame.postRender(() => { - const stack = projection.getStack(); - if (!stack || !stack.members.length) { - this.safeToRemove(); - } - }); - } - } - return null; - } - componentDidUpdate() { - const { visualElement, layoutAnchor } = this.props; - const { projection } = visualElement; - if (projection) { - projection.options.layoutAnchor = layoutAnchor; - projection.root.didUpdate(); - microtask.postRender(() => { - if (!projection.currentAnimation && projection.isLead()) { - this.safeToRemove(); - } - }); - } - } - componentWillUnmount() { - const { visualElement, layoutGroup, switchLayoutGroup: promoteContext } = this.props; - const { projection } = visualElement; - hasTakenAnySnapshot = true; - if (projection) { - projection.scheduleCheckAfterUnmount(); - if (layoutGroup && layoutGroup.group) - layoutGroup.group.remove(projection); - if (promoteContext && promoteContext.deregister) - promoteContext.deregister(projection); - } - } - safeToRemove() { - const { safeToRemove } = this.props; - safeToRemove && safeToRemove(); - } - render() { - return null; - } -} -function MeasureLayout(props) { - const [isPresent, safeToRemove] = usePresence(); - const layoutGroup = reactExports.useContext(LayoutGroupContext); - return jsxRuntimeExports.jsx(MeasureLayoutWithContext, { ...props, layoutGroup, switchLayoutGroup: reactExports.useContext(SwitchLayoutGroupContext), isPresent, safeToRemove }); -} -const drag = { - pan: { - Feature: PanGesture - }, - drag: { - Feature: DragGesture, - ProjectionNode: HTMLProjectionNode, - MeasureLayout - } -}; -function handleHoverEvent(node, event, lifecycle) { - const { props } = node; - if (node.animationState && props.whileHover) { - node.animationState.setActive("whileHover", lifecycle === "Start"); - } - const eventName = "onHover" + lifecycle; - const callback = props[eventName]; - if (callback) { - frame.postRender(() => callback(event, extractEventInfo(event))); - } -} -class HoverGesture extends Feature { - mount() { - const { current } = this.node; - if (!current) - return; - this.unmount = hover(current, (_element, startEvent) => { - handleHoverEvent(this.node, startEvent, "Start"); - return (endEvent) => handleHoverEvent(this.node, endEvent, "End"); - }); - } - unmount() { - } -} -class FocusGesture extends Feature { - constructor() { - super(...arguments); - this.isActive = false; - } - onFocus() { - let isFocusVisible = false; - try { - isFocusVisible = this.node.current.matches(":focus-visible"); - } catch (e) { - isFocusVisible = true; - } - if (!isFocusVisible || !this.node.animationState) - return; - this.node.animationState.setActive("whileFocus", true); - this.isActive = true; - } - onBlur() { - if (!this.isActive || !this.node.animationState) - return; - this.node.animationState.setActive("whileFocus", false); - this.isActive = false; - } - mount() { - this.unmount = pipe(addDomEvent(this.node.current, "focus", () => this.onFocus()), addDomEvent(this.node.current, "blur", () => this.onBlur())); - } - unmount() { - } -} -function handlePressEvent(node, event, lifecycle) { - const { props } = node; - if (node.current instanceof HTMLButtonElement && node.current.disabled) { - return; - } - if (node.animationState && props.whileTap) { - node.animationState.setActive("whileTap", lifecycle === "Start"); - } - const eventName = "onTap" + (lifecycle === "End" ? "" : lifecycle); - const callback = props[eventName]; - if (callback) { - frame.postRender(() => callback(event, extractEventInfo(event))); - } -} -class PressGesture extends Feature { - mount() { - const { current } = this.node; - if (!current) - return; - const { globalTapTarget, propagate } = this.node.props; - this.unmount = press(current, (_element, startEvent) => { - handlePressEvent(this.node, startEvent, "Start"); - return (endEvent, { success }) => handlePressEvent(this.node, endEvent, success ? "End" : "Cancel"); - }, { - useGlobalTarget: globalTapTarget, - stopPropagation: propagate?.tap === false - }); - } - unmount() { - } -} -const observerCallbacks = /* @__PURE__ */ new WeakMap(); -const observers = /* @__PURE__ */ new WeakMap(); -const fireObserverCallback = (entry) => { - const callback = observerCallbacks.get(entry.target); - callback && callback(entry); -}; -const fireAllObserverCallbacks = (entries) => { - entries.forEach(fireObserverCallback); -}; -function initIntersectionObserver({ root, ...options }) { - const lookupRoot = root || document; - if (!observers.has(lookupRoot)) { - observers.set(lookupRoot, {}); - } - const rootObservers = observers.get(lookupRoot); - const key = JSON.stringify(options); - if (!rootObservers[key]) { - rootObservers[key] = new IntersectionObserver(fireAllObserverCallbacks, { root, ...options }); - } - return rootObservers[key]; -} -function observeIntersection(element, options, callback) { - const rootInteresectionObserver = initIntersectionObserver(options); - observerCallbacks.set(element, callback); - rootInteresectionObserver.observe(element); - return () => { - observerCallbacks.delete(element); - rootInteresectionObserver.unobserve(element); - }; -} -const thresholdNames = { - some: 0, - all: 1 -}; -class InViewFeature extends Feature { - constructor() { - super(...arguments); - this.hasEnteredView = false; - this.isInView = false; - } - startObserver() { - this.stopObserver?.(); - const { viewport = {} } = this.node.getProps(); - const { root, margin: rootMargin, amount = "some", once } = viewport; - const options = { - root: root ? root.current : void 0, - rootMargin, - threshold: typeof amount === "number" ? amount : thresholdNames[amount] - }; - const onIntersectionUpdate = (entry) => { - const { isIntersecting } = entry; - if (this.isInView === isIntersecting) - return; - this.isInView = isIntersecting; - if (once && !isIntersecting && this.hasEnteredView) { - return; - } else if (isIntersecting) { - this.hasEnteredView = true; - } - if (this.node.animationState) { - this.node.animationState.setActive("whileInView", isIntersecting); - } - const { onViewportEnter, onViewportLeave } = this.node.getProps(); - const callback = isIntersecting ? onViewportEnter : onViewportLeave; - callback && callback(entry); - }; - this.stopObserver = observeIntersection(this.node.current, options, onIntersectionUpdate); - } - mount() { - this.startObserver(); - } - update() { - if (typeof IntersectionObserver === "undefined") - return; - const { props, prevProps } = this.node; - const hasOptionsChanged = ["amount", "margin", "root"].some(hasViewportOptionChanged(props, prevProps)); - if (hasOptionsChanged) { - this.startObserver(); - } - } - unmount() { - this.stopObserver?.(); - this.hasEnteredView = false; - this.isInView = false; - } -} -function hasViewportOptionChanged({ viewport = {} }, { viewport: prevViewport = {} } = {}) { - return (name) => viewport[name] !== prevViewport[name]; -} -const gestureAnimations = { - inView: { - Feature: InViewFeature - }, - tap: { - Feature: PressGesture - }, - focus: { - Feature: FocusGesture - }, - hover: { - Feature: HoverGesture - } -}; -const layout = { - layout: { - ProjectionNode: HTMLProjectionNode, - MeasureLayout - } -}; -const featureBundle = { - ...animations, - ...gestureAnimations, - ...drag, - ...layout -}; -const motion = /* @__PURE__ */ createMotionProxy(featureBundle, createDomVisualElement); -function useReducedMotion() { - !hasReducedMotionListener.current && initPrefersReducedMotion(); - const [shouldReduceMotion] = reactExports.useState(prefersReducedMotion.current); - if (process.env.NODE_ENV !== "production") { - warnOnce(shouldReduceMotion !== true, "You have Reduced Motion enabled on your device. Animations may not appear as expected.", "reduced-motion-disabled"); - } - return shouldReduceMotion; -} -export { - AnimatePresence as A, - motion as m, - useReducedMotion as u -}; diff --git a/bootstrap/ssr/assets/vendor-realtime-BGlcW0gB.js b/bootstrap/ssr/assets/vendor-realtime-BGlcW0gB.js deleted file mode 100644 index 3bcd0710..00000000 --- a/bootstrap/ssr/assets/vendor-realtime-BGlcW0gB.js +++ /dev/null @@ -1,9704 +0,0 @@ -import require$$0 from "util"; -import stream from "stream"; -import require$$5 from "url"; -import require$$6 from "fs"; -import require$$1 from "crypto"; -import require$$4$2 from "assert"; -import require$$1$1 from "buffer"; -import require$$2 from "child_process"; -import require$$8 from "net"; -import require$$10 from "tls"; -import { c as commonjsGlobal, g as getDefaultExportFromCjs } from "./vendor-tiptap-BUUKoc3C.js"; -import require$$4$1 from "events"; -import require$$3 from "http"; -import require$$4 from "https"; -class u { - constructor() { - this.notificationCreatedEvent = ".Illuminate\\Notifications\\Events\\BroadcastNotificationCreated"; - } - /** - * Listen for a whisper event on the channel instance. - */ - listenForWhisper(e, t) { - return this.listen(".client-" + e, t); - } - /** - * Listen for an event on the channel instance. - */ - notification(e) { - return this.listen(this.notificationCreatedEvent, e); - } - /** - * Stop listening for notification events on the channel instance. - */ - stopListeningForNotification(e) { - return this.stopListening(this.notificationCreatedEvent, e); - } - /** - * Stop listening for a whisper event on the channel instance. - */ - stopListeningForWhisper(e, t) { - return this.stopListening(".client-" + e, t); - } -} -class d { - /** - * Create a new class instance. - */ - constructor(e) { - this.namespace = e; - } - /** - * Format the given event name. - */ - format(e) { - return [".", "\\"].includes(e.charAt(0)) ? e.substring(1) : (this.namespace && (e = this.namespace + "." + e), e.replace(/\./g, "\\")); - } - /** - * Set the event namespace. - */ - setNamespace(e) { - this.namespace = e; - } -} -function g(s) { - try { - return Reflect.construct(String, [], s), true; - } catch { - return false; - } -} -class l extends u { - /** - * Create a new class instance. - */ - constructor(e, t, n) { - super(), this.name = t, this.pusher = e, this.options = n, this.eventFormatter = new d(this.options.namespace), this.subscribe(); - } - /** - * Subscribe to a Pusher channel. - */ - subscribe() { - this.subscription = this.pusher.subscribe(this.name); - } - /** - * Unsubscribe from a Pusher channel. - */ - unsubscribe() { - this.pusher.unsubscribe(this.name); - } - /** - * Listen for an event on the channel instance. - */ - listen(e, t) { - return this.on(this.eventFormatter.format(e), t), this; - } - /** - * Listen for all events on the channel instance. - */ - listenToAll(e) { - return this.subscription.bind_global((t, n) => { - if (t.startsWith("pusher:")) - return; - let i = String(this.options.namespace ?? "").replace( - /\./g, - "\\" - ), a = t.startsWith(i) ? t.substring(i.length + 1) : "." + t; - e(a, n); - }), this; - } - /** - * Stop listening for an event on the channel instance. - */ - stopListening(e, t) { - return t ? this.subscription.unbind( - this.eventFormatter.format(e), - t - ) : this.subscription.unbind(this.eventFormatter.format(e)), this; - } - /** - * Stop listening for all events on the channel instance. - */ - stopListeningToAll(e) { - return e ? this.subscription.unbind_global(e) : this.subscription.unbind_global(), this; - } - /** - * Register a callback to be called anytime a subscription succeeds. - */ - subscribed(e) { - return this.on("pusher:subscription_succeeded", () => { - e(); - }), this; - } - /** - * Register a callback to be called anytime a subscription error occurs. - */ - error(e) { - return this.on("pusher:subscription_error", (t) => { - e(t); - }), this; - } - /** - * Bind a channel to an event. - */ - on(e, t) { - return this.subscription.bind(e, t), this; - } -} -class f extends l { - /** - * Send a whisper event to other clients in the channel. - */ - whisper(e, t) { - return this.pusher.channels.channels[this.name].trigger( - `client-${e}`, - t - ), this; - } -} -class w extends l { - /** - * Send a whisper event to other clients in the channel. - */ - whisper(e, t) { - return this.pusher.channels.channels[this.name].trigger( - `client-${e}`, - t - ), this; - } -} -class _ extends f { - /** - * Register a callback to be called anytime the member list changes. - */ - here(e) { - return this.on("pusher:subscription_succeeded", (t) => { - e(Object.keys(t.members).map((n) => t.members[n])); - }), this; - } - /** - * Listen for someone joining the channel. - */ - joining(e) { - return this.on("pusher:member_added", (t) => { - e(t.info); - }), this; - } - /** - * Send a whisper event to other clients in the channel. - */ - whisper(e, t) { - return this.pusher.channels.channels[this.name].trigger( - `client-${e}`, - t - ), this; - } - /** - * Listen for someone leaving the channel. - */ - leaving(e) { - return this.on("pusher:member_removed", (t) => { - e(t.info); - }), this; - } -} -class b extends u { - /** - * Create a new class instance. - */ - constructor(e, t, n) { - super(), this.events = {}, this.listeners = {}, this.name = t, this.socket = e, this.options = n, this.eventFormatter = new d(this.options.namespace), this.subscribe(); - } - /** - * Subscribe to a Socket.io channel. - */ - subscribe() { - this.socket.emit("subscribe", { - channel: this.name, - auth: this.options.auth || {} - }); - } - /** - * Unsubscribe from channel and ubind event callbacks. - */ - unsubscribe() { - this.unbind(), this.socket.emit("unsubscribe", { - channel: this.name, - auth: this.options.auth || {} - }); - } - /** - * Listen for an event on the channel instance. - */ - listen(e, t) { - return this.on(this.eventFormatter.format(e), t), this; - } - /** - * Stop listening for an event on the channel instance. - */ - stopListening(e, t) { - return this.unbindEvent(this.eventFormatter.format(e), t), this; - } - /** - * Register a callback to be called anytime a subscription succeeds. - */ - subscribed(e) { - return this.on("connect", (t) => { - e(t); - }), this; - } - /** - * Register a callback to be called anytime an error occurs. - */ - error(e) { - return this; - } - /** - * Bind the channel's socket to an event and store the callback. - */ - on(e, t) { - return this.listeners[e] = this.listeners[e] || [], this.events[e] || (this.events[e] = (n, i) => { - this.name === n && this.listeners[e] && this.listeners[e].forEach((a) => a(i)); - }, this.socket.on(e, this.events[e])), this.listeners[e].push(t), this; - } - /** - * Unbind the channel's socket from all stored event callbacks. - */ - unbind() { - Object.keys(this.events).forEach((e) => { - this.unbindEvent(e); - }); - } - /** - * Unbind the listeners for the given event. - */ - unbindEvent(e, t) { - this.listeners[e] = this.listeners[e] || [], t && (this.listeners[e] = this.listeners[e].filter( - (n) => n !== t - )), (!t || this.listeners[e].length === 0) && (this.events[e] && (this.socket.removeListener(e, this.events[e]), delete this.events[e]), delete this.listeners[e]); - } -} -class v extends b { - /** - * Send a whisper event to other clients in the channel. - */ - whisper(e, t) { - return this.socket.emit("client event", { - channel: this.name, - event: `client-${e}`, - data: t - }), this; - } -} -class C extends v { - /** - * Register a callback to be called anytime the member list changes. - */ - here(e) { - return this.on("presence:subscribed", (t) => { - e(t.map((n) => n.user_info)); - }), this; - } - /** - * Listen for someone joining the channel. - */ - joining(e) { - return this.on( - "presence:joining", - (t) => e(t.user_info) - ), this; - } - /** - * Send a whisper event to other clients in the channel. - */ - whisper(e, t) { - return this.socket.emit("client event", { - channel: this.name, - event: `client-${e}`, - data: t - }), this; - } - /** - * Listen for someone leaving the channel. - */ - leaving(e) { - return this.on( - "presence:leaving", - (t) => e(t.user_info) - ), this; - } -} -class c extends u { - /** - * Subscribe to a channel. - */ - subscribe() { - } - /** - * Unsubscribe from a channel. - */ - unsubscribe() { - } - /** - * Listen for an event on the channel instance. - */ - listen(e, t) { - return this; - } - /** - * Listen for all events on the channel instance. - */ - listenToAll(e) { - return this; - } - /** - * Stop listening for an event on the channel instance. - */ - stopListening(e, t) { - return this; - } - /** - * Register a callback to be called anytime a subscription succeeds. - */ - subscribed(e) { - return this; - } - /** - * Register a callback to be called anytime an error occurs. - */ - error(e) { - return this; - } - /** - * Bind a channel to an event. - */ - on(e, t) { - return this; - } -} -class k extends c { - /** - * Send a whisper event to other clients in the channel. - */ - whisper(e, t) { - return this; - } -} -class y extends c { - /** - * Send a whisper event to other clients in the channel. - */ - whisper(e, t) { - return this; - } -} -class m extends k { - /** - * Register a callback to be called anytime the member list changes. - */ - here(e) { - return this; - } - /** - * Listen for someone joining the channel. - */ - joining(e) { - return this; - } - /** - * Send a whisper event to other clients in the channel. - */ - whisper(e, t) { - return this; - } - /** - * Listen for someone leaving the channel. - */ - leaving(e) { - return this; - } -} -const h = class h2 { - /** - * Create a new class instance. - */ - constructor(e) { - this.setOptions(e), this.connect(); - } - /** - * Merge the custom options with the defaults. - */ - setOptions(e) { - this.options = { - ...h2._defaultOptions, - ...e, - broadcaster: e.broadcaster - }; - let t = this.csrfToken(); - t && (this.options.auth.headers["X-CSRF-TOKEN"] = t, this.options.userAuthentication.headers["X-CSRF-TOKEN"] = t), t = this.options.bearerToken, t && (this.options.auth.headers.Authorization = "Bearer " + t, this.options.userAuthentication.headers.Authorization = "Bearer " + t); - } - /** - * Extract the CSRF token from the page. - */ - csrfToken() { - var e, t; - return typeof window < "u" && ((e = window.Laravel) != null && e.csrfToken) ? window.Laravel.csrfToken : this.options.csrfToken ? this.options.csrfToken : typeof document < "u" && typeof document.querySelector == "function" ? ((t = document.querySelector('meta[name="csrf-token"]')) == null ? void 0 : t.getAttribute("content")) ?? null : null; - } -}; -h._defaultOptions = { - auth: { - headers: {} - }, - authEndpoint: "/broadcasting/auth", - userAuthentication: { - endpoint: "/broadcasting/user-auth", - headers: {} - }, - csrfToken: null, - bearerToken: null, - host: null, - key: null, - namespace: "App.Events" -}; -let r = h; -class o extends r { - constructor() { - super(...arguments), this.channels = {}; - } - /** - * Create a fresh Pusher connection. - */ - connect() { - if (typeof this.options.client < "u") - this.pusher = this.options.client; - else if (this.options.Pusher) - this.pusher = new this.options.Pusher( - this.options.key, - this.options - ); - else if (typeof window < "u" && typeof window.Pusher < "u") - this.pusher = new window.Pusher(this.options.key, this.options); - else - throw new Error( - "Pusher client not found. Should be globally available or passed via options.client" - ); - } - /** - * Sign in the user via Pusher user authentication (https://pusher.com/docs/channels/using_channels/user-authentication/). - */ - signin() { - this.pusher.signin(); - } - /** - * Listen for an event on a channel instance. - */ - listen(e, t, n) { - return this.channel(e).listen(t, n); - } - /** - * Get a channel instance by name. - */ - channel(e) { - return this.channels[e] || (this.channels[e] = new l( - this.pusher, - e, - this.options - )), this.channels[e]; - } - /** - * Get a private channel instance by name. - */ - privateChannel(e) { - return this.channels["private-" + e] || (this.channels["private-" + e] = new f( - this.pusher, - "private-" + e, - this.options - )), this.channels["private-" + e]; - } - /** - * Get a private encrypted channel instance by name. - */ - encryptedPrivateChannel(e) { - return this.channels["private-encrypted-" + e] || (this.channels["private-encrypted-" + e] = new w( - this.pusher, - "private-encrypted-" + e, - this.options - )), this.channels["private-encrypted-" + e]; - } - /** - * Get a presence channel instance by name. - */ - presenceChannel(e) { - return this.channels["presence-" + e] || (this.channels["presence-" + e] = new _( - this.pusher, - "presence-" + e, - this.options - )), this.channels["presence-" + e]; - } - /** - * Leave the given channel, as well as its private and presence variants. - */ - leave(e) { - [ - e, - "private-" + e, - "private-encrypted-" + e, - "presence-" + e - ].forEach((n) => { - this.leaveChannel(n); - }); - } - /** - * Leave the given channel. - */ - leaveChannel(e) { - this.channels[e] && (this.channels[e].unsubscribe(), delete this.channels[e]); - } - /** - * Get the socket ID for the connection. - */ - socketId() { - return this.pusher.connection.socket_id; - } - /** - * Get the current connection status. - */ - connectionStatus() { - const e = this.pusher.connection.state; - switch (e) { - case "connected": - case "connecting": - return e; - case "failed": - case "unavailable": - return "failed"; - default: - return "disconnected"; - } - } - /** - * Subscribe to connection status changes. - */ - onConnectionChange(e) { - const t = () => { - e(this.connectionStatus()); - }, n = ["state_change", "connected", "disconnected"]; - return n.forEach((i) => { - this.pusher.connection.bind(i, t); - }), () => { - n.forEach((i) => { - this.pusher.connection.unbind(i, t); - }); - }; - } - /** - * Disconnect Pusher connection. - */ - disconnect() { - this.pusher.disconnect(); - } -} -class S extends r { - constructor() { - super(...arguments), this.channels = {}; - } - /** - * Create a fresh Socket.io connection. - */ - connect() { - let e = this.getSocketIO(); - this.socket = e( - this.options.host ?? void 0, - this.options - ), this.socket.io.on("reconnect", () => { - Object.values(this.channels).forEach((t) => { - t.subscribe(); - }); - }); - } - /** - * Get socket.io module from global scope or options. - */ - getSocketIO() { - if (typeof this.options.client < "u") - return this.options.client; - if (typeof window < "u" && typeof window.io < "u") - return window.io; - throw new Error( - "Socket.io client not found. Should be globally available or passed via options.client" - ); - } - /** - * Listen for an event on a channel instance. - */ - listen(e, t, n) { - return this.channel(e).listen(t, n); - } - /** - * Get a channel instance by name. - */ - channel(e) { - return this.channels[e] || (this.channels[e] = new b( - this.socket, - e, - this.options - )), this.channels[e]; - } - /** - * Get a private channel instance by name. - */ - privateChannel(e) { - return this.channels["private-" + e] || (this.channels["private-" + e] = new v( - this.socket, - "private-" + e, - this.options - )), this.channels["private-" + e]; - } - /** - * Get a presence channel instance by name. - */ - presenceChannel(e) { - return this.channels["presence-" + e] || (this.channels["presence-" + e] = new C( - this.socket, - "presence-" + e, - this.options - )), this.channels["presence-" + e]; - } - /** - * Leave the given channel, as well as its private and presence variants. - */ - leave(e) { - [e, "private-" + e, "presence-" + e].forEach((n) => { - this.leaveChannel(n); - }); - } - /** - * Leave the given channel. - */ - leaveChannel(e) { - this.channels[e] && (this.channels[e].unsubscribe(), delete this.channels[e]); - } - /** - * Get the socket ID for the connection. - */ - socketId() { - return this.socket.id; - } - /** - * Get the current connection status. - */ - connectionStatus() { - return this.socket.connected ? "connected" : this.socket.io._reconnecting ? "reconnecting" : this.socket.id !== void 0 ? "disconnected" : "connecting"; - } - /** - * Subscribe to connection status changes. - */ - onConnectionChange(e) { - const t = () => { - e(this.connectionStatus()); - }, n = [ - "connect", - "disconnect", - "connect_error", - "reconnect_attempt", - "reconnect", - "reconnect_error", - "reconnect_failed" - ]; - return n.forEach((i) => { - this.socket.on(i, t); - }), () => { - n.forEach((i) => { - this.socket.off(i, t); - }); - }; - } - /** - * Disconnect Socketio connection. - */ - disconnect() { - this.socket.disconnect(); - } -} -class p extends r { - constructor() { - super(...arguments), this.channels = {}; - } - /** - * Create a fresh connection. - */ - connect() { - } - /** - * Listen for an event on a channel instance. - */ - listen(e, t, n) { - return new c(); - } - /** - * Get a channel instance by name. - */ - channel(e) { - return new c(); - } - /** - * Get a private channel instance by name. - */ - privateChannel(e) { - return new k(); - } - /** - * Get a private encrypted channel instance by name. - */ - encryptedPrivateChannel(e) { - return new y(); - } - /** - * Get a presence channel instance by name. - */ - presenceChannel(e) { - return new m(); - } - /** - * Leave the given channel, as well as its private and presence variants. - */ - leave(e) { - } - /** - * Leave the given channel. - */ - leaveChannel(e) { - } - /** - * Get the socket ID for the connection. - */ - socketId() { - return "fake-socket-id"; - } - /** - * Get the current connection status. - */ - connectionStatus() { - return "connected"; - } - /** - * Subscribe to connection status changes. - */ - onConnectionChange(e) { - return () => { - }; - } - /** - * Disconnect the connection. - */ - disconnect() { - } -} -class E { - /** - * Create a new class instance. - */ - constructor(e) { - this.options = e, this.connect(), this.options.withoutInterceptors || this.registerInterceptors(); - } - /** - * Get a channel instance by name. - */ - channel(e) { - return this.connector.channel(e); - } - /** - * Create a new connection. - */ - connect() { - if (this.options.broadcaster === "reverb") - this.connector = new o({ - ...this.options, - cluster: "" - }); - else if (this.options.broadcaster === "pusher") - this.connector = new o(this.options); - else if (this.options.broadcaster === "ably") - this.connector = new o({ - ...this.options, - cluster: "", - broadcaster: "pusher" - }); - else if (this.options.broadcaster === "socket.io") - this.connector = new S(this.options); - else if (this.options.broadcaster === "null") - this.connector = new p(this.options); - else if (typeof this.options.broadcaster == "function" && g(this.options.broadcaster)) - this.connector = new this.options.broadcaster(this.options); - else - throw new Error( - `Broadcaster ${typeof this.options.broadcaster} ${String(this.options.broadcaster)} is not supported.` - ); - } - /** - * Disconnect from the Echo server. - */ - disconnect() { - this.connector.disconnect(); - } - /** - * Get a presence channel instance by name. - */ - join(e) { - return this.connector.presenceChannel(e); - } - /** - * Leave the given channel, as well as its private and presence variants. - */ - leave(e) { - this.connector.leave(e); - } - /** - * Leave the given channel. - */ - leaveChannel(e) { - this.connector.leaveChannel(e); - } - /** - * Leave all channels. - */ - leaveAllChannels() { - for (const e in this.connector.channels) - this.leaveChannel(e); - } - /** - * Listen for an event on a channel instance. - */ - listen(e, t, n) { - return this.connector.listen(e, t, n); - } - /** - * Get a private channel instance by name. - */ - private(e) { - return this.connector.privateChannel(e); - } - /** - * Get a private encrypted channel instance by name. - */ - encryptedPrivate(e) { - if (this.connectorSupportsEncryptedPrivateChannels(this.connector)) - return this.connector.encryptedPrivateChannel(e); - throw new Error( - `Broadcaster ${typeof this.options.broadcaster} ${String( - this.options.broadcaster - )} does not support encrypted private channels.` - ); - } - connectorSupportsEncryptedPrivateChannels(e) { - return e instanceof o || e instanceof p; - } - /** - * Get the Socket ID for the connection. - */ - socketId() { - return this.connector.socketId(); - } - /** - * Get the current connection status. - */ - connectionStatus() { - return this.connector.connectionStatus(); - } - /** - * Register 3rd party request interceptors. These are used to automatically - * send a connections socket id to a Laravel app with a X-Socket-Id header. - */ - registerInterceptors() { - typeof Vue < "u" && (Vue != null && Vue.http) && this.registerVueRequestInterceptor(), typeof axios == "function" && this.registerAxiosRequestInterceptor(), typeof jQuery == "function" && this.registerjQueryAjaxSetup(), typeof Turbo == "object" && this.registerTurboRequestInterceptor(); - } - /** - * Register a Vue HTTP interceptor to add the X-Socket-ID header. - */ - registerVueRequestInterceptor() { - Vue.http.interceptors.push( - (e, t) => { - this.socketId() && e.headers.set("X-Socket-ID", this.socketId()), t(); - } - ); - } - /** - * Register an Axios HTTP interceptor to add the X-Socket-ID header. - */ - registerAxiosRequestInterceptor() { - axios.interceptors.request.use( - (e) => (this.socketId() && (e.headers["X-Socket-Id"] = this.socketId()), e) - ); - } - /** - * Register jQuery AjaxPrefilter to add the X-Socket-ID header. - */ - registerjQueryAjaxSetup() { - typeof jQuery.ajax < "u" && jQuery.ajaxPrefilter( - (e, t, n) => { - this.socketId() && n.setRequestHeader("X-Socket-Id", this.socketId()); - } - ); - } - /** - * Register the Turbo Request interceptor to add the X-Socket-ID header. - */ - registerTurboRequestInterceptor() { - document.addEventListener( - "turbo:before-fetch-request", - (e) => { - e.detail.fetchOptions.headers["X-Socket-Id"] = this.socketId(); - } - ); - } -} -var pusher = { exports: {} }; -var hasRequiredPusher; -function requirePusher() { - if (hasRequiredPusher) return pusher.exports; - hasRequiredPusher = 1; - (function(module) { - (() => { - var __webpack_modules__ = { - /***/ - 594(__unused_webpack_module, exports$1) { - var __extends = this && this.__extends || /* @__PURE__ */ (function() { - var extendStatics = function(d2, b2) { - extendStatics = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(d3, b3) { - d3.__proto__ = b3; - } || function(d3, b3) { - for (var p2 in b3) if (b3.hasOwnProperty(p2)) d3[p2] = b3[p2]; - }; - return extendStatics(d2, b2); - }; - return function(d2, b2) { - extendStatics(d2, b2); - function __() { - this.constructor = d2; - } - d2.prototype = b2 === null ? Object.create(b2) : (__.prototype = b2.prototype, new __()); - }; - })(); - Object.defineProperty(exports$1, "__esModule", { value: true }); - var INVALID_BYTE = 256; - var Coder = ( - /** @class */ - (function() { - function Coder2(_paddingCharacter) { - if (_paddingCharacter === void 0) { - _paddingCharacter = "="; - } - this._paddingCharacter = _paddingCharacter; - } - Coder2.prototype.encodedLength = function(length) { - if (!this._paddingCharacter) { - return (length * 8 + 5) / 6 | 0; - } - return (length + 2) / 3 * 4 | 0; - }; - Coder2.prototype.encode = function(data) { - var out = ""; - var i = 0; - for (; i < data.length - 2; i += 3) { - var c2 = data[i] << 16 | data[i + 1] << 8 | data[i + 2]; - out += this._encodeByte(c2 >>> 3 * 6 & 63); - out += this._encodeByte(c2 >>> 2 * 6 & 63); - out += this._encodeByte(c2 >>> 1 * 6 & 63); - out += this._encodeByte(c2 >>> 0 * 6 & 63); - } - var left = data.length - i; - if (left > 0) { - var c2 = data[i] << 16 | (left === 2 ? data[i + 1] << 8 : 0); - out += this._encodeByte(c2 >>> 3 * 6 & 63); - out += this._encodeByte(c2 >>> 2 * 6 & 63); - if (left === 2) { - out += this._encodeByte(c2 >>> 1 * 6 & 63); - } else { - out += this._paddingCharacter || ""; - } - out += this._paddingCharacter || ""; - } - return out; - }; - Coder2.prototype.maxDecodedLength = function(length) { - if (!this._paddingCharacter) { - return (length * 6 + 7) / 8 | 0; - } - return length / 4 * 3 | 0; - }; - Coder2.prototype.decodedLength = function(s) { - return this.maxDecodedLength(s.length - this._getPaddingLength(s)); - }; - Coder2.prototype.decode = function(s) { - if (s.length === 0) { - return new Uint8Array(0); - } - var paddingLength = this._getPaddingLength(s); - var length = s.length - paddingLength; - var out = new Uint8Array(this.maxDecodedLength(length)); - var op = 0; - var i = 0; - var haveBad = 0; - var v0 = 0, v1 = 0, v2 = 0, v3 = 0; - for (; i < length - 4; i += 4) { - v0 = this._decodeChar(s.charCodeAt(i + 0)); - v1 = this._decodeChar(s.charCodeAt(i + 1)); - v2 = this._decodeChar(s.charCodeAt(i + 2)); - v3 = this._decodeChar(s.charCodeAt(i + 3)); - out[op++] = v0 << 2 | v1 >>> 4; - out[op++] = v1 << 4 | v2 >>> 2; - out[op++] = v2 << 6 | v3; - haveBad |= v0 & INVALID_BYTE; - haveBad |= v1 & INVALID_BYTE; - haveBad |= v2 & INVALID_BYTE; - haveBad |= v3 & INVALID_BYTE; - } - if (i < length - 1) { - v0 = this._decodeChar(s.charCodeAt(i)); - v1 = this._decodeChar(s.charCodeAt(i + 1)); - out[op++] = v0 << 2 | v1 >>> 4; - haveBad |= v0 & INVALID_BYTE; - haveBad |= v1 & INVALID_BYTE; - } - if (i < length - 2) { - v2 = this._decodeChar(s.charCodeAt(i + 2)); - out[op++] = v1 << 4 | v2 >>> 2; - haveBad |= v2 & INVALID_BYTE; - } - if (i < length - 3) { - v3 = this._decodeChar(s.charCodeAt(i + 3)); - out[op++] = v2 << 6 | v3; - haveBad |= v3 & INVALID_BYTE; - } - if (haveBad !== 0) { - throw new Error("Base64Coder: incorrect characters for decoding"); - } - return out; - }; - Coder2.prototype._encodeByte = function(b2) { - var result = b2; - result += 65; - result += 25 - b2 >>> 8 & 0 - 65 - 26 + 97; - result += 51 - b2 >>> 8 & 26 - 97 - 52 + 48; - result += 61 - b2 >>> 8 & 52 - 48 - 62 + 43; - result += 62 - b2 >>> 8 & 62 - 43 - 63 + 47; - return String.fromCharCode(result); - }; - Coder2.prototype._decodeChar = function(c2) { - var result = INVALID_BYTE; - result += (42 - c2 & c2 - 44) >>> 8 & -INVALID_BYTE + c2 - 43 + 62; - result += (46 - c2 & c2 - 48) >>> 8 & -INVALID_BYTE + c2 - 47 + 63; - result += (47 - c2 & c2 - 58) >>> 8 & -INVALID_BYTE + c2 - 48 + 52; - result += (64 - c2 & c2 - 91) >>> 8 & -INVALID_BYTE + c2 - 65 + 0; - result += (96 - c2 & c2 - 123) >>> 8 & -INVALID_BYTE + c2 - 97 + 26; - return result; - }; - Coder2.prototype._getPaddingLength = function(s) { - var paddingLength = 0; - if (this._paddingCharacter) { - for (var i = s.length - 1; i >= 0; i--) { - if (s[i] !== this._paddingCharacter) { - break; - } - paddingLength++; - } - if (s.length < 4 || paddingLength > 2) { - throw new Error("Base64Coder: incorrect padding"); - } - } - return paddingLength; - }; - return Coder2; - })() - ); - exports$1.Coder = Coder; - var stdCoder = new Coder(); - function encode(data) { - return stdCoder.encode(data); - } - exports$1.encode = encode; - function decode(s) { - return stdCoder.decode(s); - } - exports$1.decode = decode; - var URLSafeCoder = ( - /** @class */ - (function(_super) { - __extends(URLSafeCoder2, _super); - function URLSafeCoder2() { - return _super !== null && _super.apply(this, arguments) || this; - } - URLSafeCoder2.prototype._encodeByte = function(b2) { - var result = b2; - result += 65; - result += 25 - b2 >>> 8 & 0 - 65 - 26 + 97; - result += 51 - b2 >>> 8 & 26 - 97 - 52 + 48; - result += 61 - b2 >>> 8 & 52 - 48 - 62 + 45; - result += 62 - b2 >>> 8 & 62 - 45 - 63 + 95; - return String.fromCharCode(result); - }; - URLSafeCoder2.prototype._decodeChar = function(c2) { - var result = INVALID_BYTE; - result += (44 - c2 & c2 - 46) >>> 8 & -INVALID_BYTE + c2 - 45 + 62; - result += (94 - c2 & c2 - 96) >>> 8 & -INVALID_BYTE + c2 - 95 + 63; - result += (47 - c2 & c2 - 58) >>> 8 & -INVALID_BYTE + c2 - 48 + 52; - result += (64 - c2 & c2 - 91) >>> 8 & -INVALID_BYTE + c2 - 65 + 0; - result += (96 - c2 & c2 - 123) >>> 8 & -INVALID_BYTE + c2 - 97 + 26; - return result; - }; - return URLSafeCoder2; - })(Coder) - ); - exports$1.URLSafeCoder = URLSafeCoder; - var urlSafeCoder = new URLSafeCoder(); - function encodeURLSafe(data) { - return urlSafeCoder.encode(data); - } - exports$1.encodeURLSafe = encodeURLSafe; - function decodeURLSafe(s) { - return urlSafeCoder.decode(s); - } - exports$1.decodeURLSafe = decodeURLSafe; - exports$1.encodedLength = function(length) { - return stdCoder.encodedLength(length); - }; - exports$1.maxDecodedLength = function(length) { - return stdCoder.maxDecodedLength(length); - }; - exports$1.decodedLength = function(s) { - return stdCoder.decodedLength(s); - }; - }, - /***/ - 978(__unused_webpack_module, exports$1) { - var INVALID_UTF8 = "utf8: invalid source encoding"; - function decode(arr) { - var chars = []; - for (var i = 0; i < arr.length; i++) { - var b2 = arr[i]; - if (b2 & 128) { - var min = void 0; - if (b2 < 224) { - if (i >= arr.length) { - throw new Error(INVALID_UTF8); - } - var n1 = arr[++i]; - if ((n1 & 192) !== 128) { - throw new Error(INVALID_UTF8); - } - b2 = (b2 & 31) << 6 | n1 & 63; - min = 128; - } else if (b2 < 240) { - if (i >= arr.length - 1) { - throw new Error(INVALID_UTF8); - } - var n1 = arr[++i]; - var n2 = arr[++i]; - if ((n1 & 192) !== 128 || (n2 & 192) !== 128) { - throw new Error(INVALID_UTF8); - } - b2 = (b2 & 15) << 12 | (n1 & 63) << 6 | n2 & 63; - min = 2048; - } else if (b2 < 248) { - if (i >= arr.length - 2) { - throw new Error(INVALID_UTF8); - } - var n1 = arr[++i]; - var n2 = arr[++i]; - var n3 = arr[++i]; - if ((n1 & 192) !== 128 || (n2 & 192) !== 128 || (n3 & 192) !== 128) { - throw new Error(INVALID_UTF8); - } - b2 = (b2 & 15) << 18 | (n1 & 63) << 12 | (n2 & 63) << 6 | n3 & 63; - min = 65536; - } else { - throw new Error(INVALID_UTF8); - } - if (b2 < min || b2 >= 55296 && b2 <= 57343) { - throw new Error(INVALID_UTF8); - } - if (b2 >= 65536) { - if (b2 > 1114111) { - throw new Error(INVALID_UTF8); - } - b2 -= 65536; - chars.push(String.fromCharCode(55296 | b2 >> 10)); - b2 = 56320 | b2 & 1023; - } - } - chars.push(String.fromCharCode(b2)); - } - return chars.join(""); - } - exports$1.D4 = decode; - }, - /***/ - 945(module2, __unused_webpack_exports, __webpack_require__2) { - var Stream = __webpack_require__2(203).Stream, util = __webpack_require__2(23), driver = __webpack_require__2(41), Headers = __webpack_require__2(160), API = __webpack_require__2(720), EventTarget = __webpack_require__2(667), Event = __webpack_require__2(859); - var EventSource = function(request, response, options) { - this.writable = true; - options = options || {}; - this._stream = response.socket; - this._ping = options.ping || this.DEFAULT_PING; - this._retry = options.retry || this.DEFAULT_RETRY; - var scheme = driver.isSecureRequest(request) ? "https:" : "http:"; - this.url = scheme + "//" + request.headers.host + request.url; - this.lastEventId = request.headers["last-event-id"] || ""; - this.readyState = API.CONNECTING; - var headers = new Headers(), self2 = this; - if (options.headers) { - for (var key2 in options.headers) headers.set(key2, options.headers[key2]); - } - if (!this._stream || !this._stream.writable) return; - process.nextTick(function() { - self2._open(); - }); - this._stream.setTimeout(0); - this._stream.setNoDelay(true); - var handshake = "HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\nCache-Control: no-cache, no-store\r\nConnection: close\r\n" + headers.toString() + "\r\nretry: " + Math.floor(this._retry * 1e3) + "\r\n\r\n"; - this._write(handshake); - this._stream.on("drain", function() { - self2.emit("drain"); - }); - if (this._ping) - this._pingTimer = setInterval(function() { - self2.ping(); - }, this._ping * 1e3); - ["error", "end"].forEach(function(event) { - self2._stream.on(event, function() { - self2.close(); - }); - }); - }; - util.inherits(EventSource, Stream); - EventSource.isEventSource = function(request) { - if (request.method !== "GET") return false; - var accept = (request.headers.accept || "").split(/\s*,\s*/); - return accept.indexOf("text/event-stream") >= 0; - }; - var instance = { - DEFAULT_PING: 10, - DEFAULT_RETRY: 5, - _write: function(chunk) { - if (!this.writable) return false; - try { - return this._stream.write(chunk, "utf8"); - } catch (e) { - return false; - } - }, - _open: function() { - if (this.readyState !== API.CONNECTING) return; - this.readyState = API.OPEN; - var event = new Event("open"); - event.initEvent("open", false, false); - this.dispatchEvent(event); - }, - write: function(message) { - return this.send(message); - }, - end: function(message) { - if (message !== void 0) this.write(message); - this.close(); - }, - send: function(message, options) { - if (this.readyState > API.OPEN) return false; - message = String(message).replace(/(\r\n|\r|\n)/g, "$1data: "); - options = options || {}; - var frame = ""; - if (options.event) frame += "event: " + options.event + "\r\n"; - if (options.id) frame += "id: " + options.id + "\r\n"; - frame += "data: " + message + "\r\n\r\n"; - return this._write(frame); - }, - ping: function() { - return this._write(":\r\n\r\n"); - }, - close: function() { - if (this.readyState > API.OPEN) return false; - this.readyState = API.CLOSED; - this.writable = false; - if (this._pingTimer) clearInterval(this._pingTimer); - if (this._stream) this._stream.end(); - var event = new Event("close"); - event.initEvent("close", false, false); - this.dispatchEvent(event); - return true; - } - }; - for (var method in instance) EventSource.prototype[method] = instance[method]; - for (var key in EventTarget) EventSource.prototype[key] = EventTarget[key]; - module2.exports = EventSource; - }, - /***/ - 555(module2, __unused_webpack_exports, __webpack_require__2) { - var util = __webpack_require__2(23), driver = __webpack_require__2(41), API = __webpack_require__2(720); - var WebSocket = function(request, socket, body, protocols, options) { - options = options || {}; - this._stream = socket; - this._driver = driver.http(request, { maxLength: options.maxLength, protocols }); - var self2 = this; - if (!this._stream || !this._stream.writable) return; - if (!this._stream.readable) return this._stream.end(); - var catchup = function() { - self2._stream.removeListener("data", catchup); - }; - this._stream.on("data", catchup); - API.call(this, options); - process.nextTick(function() { - self2._driver.start(); - self2._driver.io.write(body); - }); - }; - util.inherits(WebSocket, API); - WebSocket.isWebSocket = function(request) { - return driver.isWebSocket(request); - }; - WebSocket.validateOptions = function(options, validKeys) { - driver.validateOptions(options, validKeys); - }; - WebSocket.WebSocket = WebSocket; - WebSocket.Client = __webpack_require__2(333); - WebSocket.EventSource = __webpack_require__2(945); - module2.exports = WebSocket; - }, - /***/ - 720(module2, __unused_webpack_exports, __webpack_require__2) { - var Stream = __webpack_require__2(203).Stream, util = __webpack_require__2(23), driver = __webpack_require__2(41), EventTarget = __webpack_require__2(667), Event = __webpack_require__2(859); - var API = function(options) { - options = options || {}; - driver.validateOptions(options, ["headers", "extensions", "maxLength", "ping", "proxy", "tls", "ca"]); - this.readable = this.writable = true; - var headers = options.headers; - if (headers) { - for (var name in headers) this._driver.setHeader(name, headers[name]); - } - var extensions = options.extensions; - if (extensions) { - [].concat(extensions).forEach(this._driver.addExtension, this._driver); - } - this._ping = options.ping; - this._pingId = 0; - this.readyState = API.CONNECTING; - this.bufferedAmount = 0; - this.protocol = ""; - this.url = this._driver.url; - this.version = this._driver.version; - var self2 = this; - this._driver.on("open", function(e) { - self2._open(); - }); - this._driver.on("message", function(e) { - self2._receiveMessage(e.data); - }); - this._driver.on("close", function(e) { - self2._beginClose(e.reason, e.code); - }); - this._driver.on("error", function(error) { - self2._emitError(error.message); - }); - this.on("error", function() { - }); - this._driver.messages.on("drain", function() { - self2.emit("drain"); - }); - if (this._ping) - this._pingTimer = setInterval(function() { - self2._pingId += 1; - self2.ping(self2._pingId.toString()); - }, this._ping * 1e3); - this._configureStream(); - if (!this._proxy) { - this._stream.pipe(this._driver.io); - this._driver.io.pipe(this._stream); - } - }; - util.inherits(API, Stream); - API.CONNECTING = 0; - API.OPEN = 1; - API.CLOSING = 2; - API.CLOSED = 3; - API.CLOSE_TIMEOUT = 3e4; - var instance = { - write: function(data) { - return this.send(data); - }, - end: function(data) { - if (data !== void 0) this.send(data); - this.close(); - }, - pause: function() { - return this._driver.messages.pause(); - }, - resume: function() { - return this._driver.messages.resume(); - }, - send: function(data) { - if (this.readyState > API.OPEN) return false; - if (!(data instanceof Buffer)) data = String(data); - return this._driver.messages.write(data); - }, - ping: function(message, callback) { - if (this.readyState > API.OPEN) return false; - return this._driver.ping(message, callback); - }, - close: function(code, reason) { - if (code === void 0) code = 1e3; - if (reason === void 0) reason = ""; - if (code !== 1e3 && (code < 3e3 || code > 4999)) - throw new Error("Failed to execute 'close' on WebSocket: The code must be either 1000, or between 3000 and 4999. " + code + " is neither."); - if (this.readyState !== API.CLOSED) this.readyState = API.CLOSING; - var self2 = this; - this._closeTimer = setTimeout(function() { - self2._beginClose("", 1006); - }, API.CLOSE_TIMEOUT); - this._driver.close(reason, code); - }, - _configureStream: function() { - var self2 = this; - this._stream.setTimeout(0); - this._stream.setNoDelay(true); - ["close", "end"].forEach(function(event) { - this._stream.on(event, function() { - self2._finalizeClose(); - }); - }, this); - this._stream.on("error", function(error) { - self2._emitError("Network error: " + self2.url + ": " + error.message); - self2._finalizeClose(); - }); - }, - _open: function() { - if (this.readyState !== API.CONNECTING) return; - this.readyState = API.OPEN; - this.protocol = this._driver.protocol || ""; - var event = new Event("open"); - event.initEvent("open", false, false); - this.dispatchEvent(event); - }, - _receiveMessage: function(data) { - if (this.readyState > API.OPEN) return false; - if (this.readable) this.emit("data", data); - var event = new Event("message", { data }); - event.initEvent("message", false, false); - this.dispatchEvent(event); - }, - _emitError: function(message) { - if (this.readyState >= API.CLOSING) return; - var event = new Event("error", { message }); - event.initEvent("error", false, false); - this.dispatchEvent(event); - }, - _beginClose: function(reason, code) { - if (this.readyState === API.CLOSED) return; - this.readyState = API.CLOSING; - this._closeParams = [reason, code]; - if (this._stream) { - this._stream.destroy(); - if (!this._stream.readable) this._finalizeClose(); - } - }, - _finalizeClose: function() { - if (this.readyState === API.CLOSED) return; - this.readyState = API.CLOSED; - if (this._closeTimer) clearTimeout(this._closeTimer); - if (this._pingTimer) clearInterval(this._pingTimer); - if (this._stream) this._stream.end(); - if (this.readable) this.emit("end"); - this.readable = this.writable = false; - var reason = this._closeParams ? this._closeParams[0] : "", code = this._closeParams ? this._closeParams[1] : 1006; - var event = new Event("close", { code, reason }); - event.initEvent("close", false, false); - this.dispatchEvent(event); - } - }; - for (var method in instance) API.prototype[method] = instance[method]; - for (var key in EventTarget) API.prototype[key] = EventTarget[key]; - module2.exports = API; - }, - /***/ - 859(module2) { - var Event = function(eventType, options) { - this.type = eventType; - for (var key in options) - this[key] = options[key]; - }; - Event.prototype.initEvent = function(eventType, canBubble, cancelable) { - this.type = eventType; - this.bubbles = canBubble; - this.cancelable = cancelable; - }; - Event.prototype.stopPropagation = function() { - }; - Event.prototype.preventDefault = function() { - }; - Event.CAPTURING_PHASE = 1; - Event.AT_TARGET = 2; - Event.BUBBLING_PHASE = 3; - module2.exports = Event; - }, - /***/ - 667(module2, __unused_webpack_exports, __webpack_require__2) { - var Event = __webpack_require__2(859); - var EventTarget = { - onopen: null, - onmessage: null, - onerror: null, - onclose: null, - addEventListener: function(eventType, listener, useCapture) { - this.on(eventType, listener); - }, - removeEventListener: function(eventType, listener, useCapture) { - this.removeListener(eventType, listener); - }, - dispatchEvent: function(event) { - event.target = event.currentTarget = this; - event.eventPhase = Event.AT_TARGET; - if (this["on" + event.type]) - this["on" + event.type](event); - this.emit(event.type, event); - } - }; - module2.exports = EventTarget; - }, - /***/ - 333(module2, __unused_webpack_exports, __webpack_require__2) { - var util = __webpack_require__2(23), net = __webpack_require__2(278), tls = __webpack_require__2(756), url = __webpack_require__2(16), driver = __webpack_require__2(41), API = __webpack_require__2(720); - __webpack_require__2(859); - var DEFAULT_PORTS = { "http:": 80, "https:": 443, "ws:": 80, "wss:": 443 }, SECURE_PROTOCOLS = ["https:", "wss:"]; - var Client = function(_url, protocols, options) { - options = options || {}; - this.url = _url; - this._driver = driver.client(this.url, { maxLength: options.maxLength, protocols }); - ["open", "error"].forEach(function(event) { - this._driver.on(event, function() { - self2.headers = self2._driver.headers; - self2.statusCode = self2._driver.statusCode; - }); - }, this); - var proxy = options.proxy || {}, endpoint = url.parse(proxy.origin || this.url), port = endpoint.port || DEFAULT_PORTS[endpoint.protocol], secure = SECURE_PROTOCOLS.indexOf(endpoint.protocol) >= 0, onConnect = function() { - self2._onConnect(); - }, netOptions = options.net || {}, originTLS = options.tls || {}, socketTLS = proxy.origin ? proxy.tls || {} : originTLS, self2 = this; - netOptions.host = socketTLS.host = endpoint.hostname; - netOptions.port = socketTLS.port = port; - originTLS.ca = originTLS.ca || options.ca; - socketTLS.servername = socketTLS.servername || endpoint.hostname; - this._stream = secure ? tls.connect(socketTLS, onConnect) : net.connect(netOptions, onConnect); - if (proxy.origin) this._configureProxy(proxy, originTLS); - API.call(this, options); - }; - util.inherits(Client, API); - Client.prototype._onConnect = function() { - var worker = this._proxy || this._driver; - worker.start(); - }; - Client.prototype._configureProxy = function(proxy, originTLS) { - var uri = url.parse(this.url), secure = SECURE_PROTOCOLS.indexOf(uri.protocol) >= 0, self2 = this, name; - this._proxy = this._driver.proxy(proxy.origin); - if (proxy.headers) { - for (name in proxy.headers) this._proxy.setHeader(name, proxy.headers[name]); - } - this._proxy.pipe(this._stream, { end: false }); - this._stream.pipe(this._proxy); - this._proxy.on("connect", function() { - if (secure) { - var options = { socket: self2._stream, servername: uri.hostname }; - for (name in originTLS) options[name] = originTLS[name]; - self2._stream = tls.connect(options); - self2._configureStream(); - } - self2._driver.io.pipe(self2._stream); - self2._stream.pipe(self2._driver.io); - self2._driver.start(); - }); - this._proxy.on("error", function(error) { - self2._driver.emit("error", error); - }); - }; - module2.exports = Client; - }, - /***/ - 895(__unused_webpack_module, exports$1, __webpack_require__2) { - var assert = __webpack_require__2(613); - exports$1.e = HTTPParser; - function HTTPParser(type) { - assert.ok(type === HTTPParser.REQUEST || type === HTTPParser.RESPONSE || type === void 0); - if (type === void 0) ; - else { - this.initialize(type); - } - this.maxHeaderSize = HTTPParser.maxHeaderSize; - } - HTTPParser.prototype.initialize = function(type, async_resource) { - assert.ok(type === HTTPParser.REQUEST || type === HTTPParser.RESPONSE); - this.type = type; - this.state = type + "_LINE"; - this.info = { - headers: [], - upgrade: false - }; - this.trailers = []; - this.line = ""; - this.isChunked = false; - this.connection = ""; - this.headerSize = 0; - this.body_bytes = null; - this.isUserCall = false; - this.hadError = false; - }; - HTTPParser.encoding = "ascii"; - HTTPParser.maxHeaderSize = 80 * 1024; - HTTPParser.REQUEST = "REQUEST"; - HTTPParser.RESPONSE = "RESPONSE"; - var kOnHeaders = HTTPParser.kOnHeaders = 1; - var kOnHeadersComplete = HTTPParser.kOnHeadersComplete = 2; - var kOnBody = HTTPParser.kOnBody = 3; - var kOnMessageComplete = HTTPParser.kOnMessageComplete = 4; - HTTPParser.prototype[kOnHeaders] = HTTPParser.prototype[kOnHeadersComplete] = HTTPParser.prototype[kOnBody] = HTTPParser.prototype[kOnMessageComplete] = function() { - }; - var compatMode0_12 = true; - Object.defineProperty(HTTPParser, "kOnExecute", { - get: function() { - compatMode0_12 = false; - return 99; - } - }); - var methods = HTTPParser.methods = [ - "DELETE", - "GET", - "HEAD", - "POST", - "PUT", - "CONNECT", - "OPTIONS", - "TRACE", - "COPY", - "LOCK", - "MKCOL", - "MOVE", - "PROPFIND", - "PROPPATCH", - "SEARCH", - "UNLOCK", - "BIND", - "REBIND", - "UNBIND", - "ACL", - "REPORT", - "MKACTIVITY", - "CHECKOUT", - "MERGE", - "M-SEARCH", - "NOTIFY", - "SUBSCRIBE", - "UNSUBSCRIBE", - "PATCH", - "PURGE", - "MKCALENDAR", - "LINK", - "UNLINK", - "SOURCE" - ]; - var method_connect = methods.indexOf("CONNECT"); - HTTPParser.prototype.reinitialize = HTTPParser; - HTTPParser.prototype.close = HTTPParser.prototype.pause = HTTPParser.prototype.resume = HTTPParser.prototype.free = function() { - }; - HTTPParser.prototype._compatMode0_11 = false; - HTTPParser.prototype.getAsyncId = function() { - return 0; - }; - var headerState = { - REQUEST_LINE: true, - RESPONSE_LINE: true, - HEADER: true - }; - HTTPParser.prototype.execute = function(chunk, start, length) { - if (!(this instanceof HTTPParser)) { - throw new TypeError("not a HTTPParser"); - } - start = start || 0; - length = typeof length === "number" ? length : chunk.length; - this.chunk = chunk; - this.offset = start; - var end = this.end = start + length; - try { - while (this.offset < end) { - if (this[this.state]()) { - break; - } - } - } catch (err) { - if (this.isUserCall) { - throw err; - } - this.hadError = true; - return err; - } - this.chunk = null; - length = this.offset - start; - if (headerState[this.state]) { - this.headerSize += length; - if (this.headerSize > (this.maxHeaderSize || HTTPParser.maxHeaderSize)) { - return new Error("max header size exceeded"); - } - } - return length; - }; - var stateFinishAllowed = { - REQUEST_LINE: true, - RESPONSE_LINE: true, - BODY_RAW: true - }; - HTTPParser.prototype.finish = function() { - if (this.hadError) { - return; - } - if (!stateFinishAllowed[this.state]) { - return new Error("invalid state for EOF"); - } - if (this.state === "BODY_RAW") { - this.userCall()(this[kOnMessageComplete]()); - } - }; - HTTPParser.prototype.consume = HTTPParser.prototype.unconsume = HTTPParser.prototype.getCurrentBuffer = function() { - }; - HTTPParser.prototype.userCall = function() { - this.isUserCall = true; - var self2 = this; - return function(ret) { - self2.isUserCall = false; - return ret; - }; - }; - HTTPParser.prototype.nextRequest = function() { - this.userCall()(this[kOnMessageComplete]()); - this.reinitialize(this.type); - }; - HTTPParser.prototype.consumeLine = function() { - var end = this.end, chunk = this.chunk; - for (var i = this.offset; i < end; i++) { - if (chunk[i] === 10) { - var line = this.line + chunk.toString(HTTPParser.encoding, this.offset, i); - if (line.charAt(line.length - 1) === "\r") { - line = line.substr(0, line.length - 1); - } - this.line = ""; - this.offset = i + 1; - return line; - } - } - this.line += chunk.toString(HTTPParser.encoding, this.offset, this.end); - this.offset = this.end; - }; - var headerExp = /^([^: \t]+):[ \t]*((?:.*[^ \t])|)/; - var headerContinueExp = /^[ \t]+(.*[^ \t])/; - HTTPParser.prototype.parseHeader = function(line, headers) { - if (line.indexOf("\r") !== -1) { - throw parseErrorCode("HPE_LF_EXPECTED"); - } - var match = headerExp.exec(line); - var k2 = match && match[1]; - if (k2) { - headers.push(k2); - headers.push(match[2]); - } else { - var matchContinue = headerContinueExp.exec(line); - if (matchContinue && headers.length) { - if (headers[headers.length - 1]) { - headers[headers.length - 1] += " "; - } - headers[headers.length - 1] += matchContinue[1]; - } - } - }; - var requestExp = /^([A-Z-]+) ([^ ]+) HTTP\/(\d)\.(\d)$/; - HTTPParser.prototype.REQUEST_LINE = function() { - var line = this.consumeLine(); - if (!line) { - return; - } - var match = requestExp.exec(line); - if (match === null) { - throw parseErrorCode("HPE_INVALID_CONSTANT"); - } - this.info.method = this._compatMode0_11 ? match[1] : methods.indexOf(match[1]); - if (this.info.method === -1) { - throw new Error("invalid request method"); - } - this.info.url = match[2]; - this.info.versionMajor = +match[3]; - this.info.versionMinor = +match[4]; - this.body_bytes = 0; - this.state = "HEADER"; - }; - var responseExp = /^HTTP\/(\d)\.(\d) (\d{3}) ?(.*)$/; - HTTPParser.prototype.RESPONSE_LINE = function() { - var line = this.consumeLine(); - if (!line) { - return; - } - var match = responseExp.exec(line); - if (match === null) { - throw parseErrorCode("HPE_INVALID_CONSTANT"); - } - this.info.versionMajor = +match[1]; - this.info.versionMinor = +match[2]; - var statusCode = this.info.statusCode = +match[3]; - this.info.statusMessage = match[4]; - if ((statusCode / 100 | 0) === 1 || statusCode === 204 || statusCode === 304) { - this.body_bytes = 0; - } - this.state = "HEADER"; - }; - HTTPParser.prototype.shouldKeepAlive = function() { - if (this.info.versionMajor > 0 && this.info.versionMinor > 0) { - if (this.connection.indexOf("close") !== -1) { - return false; - } - } else if (this.connection.indexOf("keep-alive") === -1) { - return false; - } - if (this.body_bytes !== null || this.isChunked) { - return true; - } - return false; - }; - HTTPParser.prototype.HEADER = function() { - var line = this.consumeLine(); - if (line === void 0) { - return; - } - var info = this.info; - if (line) { - this.parseHeader(line, info.headers); - } else { - var headers = info.headers; - var hasContentLength = false; - var currentContentLengthValue; - var hasUpgradeHeader = false; - for (var i = 0; i < headers.length; i += 2) { - switch (headers[i].toLowerCase()) { - case "transfer-encoding": - this.isChunked = headers[i + 1].toLowerCase() === "chunked"; - break; - case "content-length": - currentContentLengthValue = +headers[i + 1]; - if (hasContentLength) { - if (currentContentLengthValue !== this.body_bytes) { - throw parseErrorCode("HPE_UNEXPECTED_CONTENT_LENGTH"); - } - } else { - hasContentLength = true; - this.body_bytes = currentContentLengthValue; - } - break; - case "connection": - this.connection += headers[i + 1].toLowerCase(); - break; - case "upgrade": - hasUpgradeHeader = true; - break; - } - } - if (this.isChunked && hasContentLength) { - hasContentLength = false; - this.body_bytes = null; - } - if (hasUpgradeHeader && this.connection.indexOf("upgrade") != -1) { - info.upgrade = this.type === HTTPParser.REQUEST || info.statusCode === 101; - } else { - info.upgrade = info.method === method_connect; - } - if (this.isChunked && info.upgrade) { - this.isChunked = false; - } - info.shouldKeepAlive = this.shouldKeepAlive(); - var skipBody; - if (compatMode0_12) { - skipBody = this.userCall()(this[kOnHeadersComplete](info)); - } else { - skipBody = this.userCall()(this[kOnHeadersComplete]( - info.versionMajor, - info.versionMinor, - info.headers, - info.method, - info.url, - info.statusCode, - info.statusMessage, - info.upgrade, - info.shouldKeepAlive - )); - } - if (skipBody === 2) { - this.nextRequest(); - return true; - } else if (this.isChunked && !skipBody) { - this.state = "BODY_CHUNKHEAD"; - } else if (skipBody || this.body_bytes === 0) { - this.nextRequest(); - return info.upgrade; - } else if (this.body_bytes === null) { - this.state = "BODY_RAW"; - } else { - this.state = "BODY_SIZED"; - } - } - }; - HTTPParser.prototype.BODY_CHUNKHEAD = function() { - var line = this.consumeLine(); - if (line === void 0) { - return; - } - this.body_bytes = parseInt(line, 16); - if (!this.body_bytes) { - this.state = "BODY_CHUNKTRAILERS"; - } else { - this.state = "BODY_CHUNK"; - } - }; - HTTPParser.prototype.BODY_CHUNK = function() { - var length = Math.min(this.end - this.offset, this.body_bytes); - this.userCall()(this[kOnBody](this.chunk, this.offset, length)); - this.offset += length; - this.body_bytes -= length; - if (!this.body_bytes) { - this.state = "BODY_CHUNKEMPTYLINE"; - } - }; - HTTPParser.prototype.BODY_CHUNKEMPTYLINE = function() { - var line = this.consumeLine(); - if (line === void 0) { - return; - } - assert.equal(line, ""); - this.state = "BODY_CHUNKHEAD"; - }; - HTTPParser.prototype.BODY_CHUNKTRAILERS = function() { - var line = this.consumeLine(); - if (line === void 0) { - return; - } - if (line) { - this.parseHeader(line, this.trailers); - } else { - if (this.trailers.length) { - this.userCall()(this[kOnHeaders](this.trailers, "")); - } - this.nextRequest(); - } - }; - HTTPParser.prototype.BODY_RAW = function() { - var length = this.end - this.offset; - this.userCall()(this[kOnBody](this.chunk, this.offset, length)); - this.offset = this.end; - }; - HTTPParser.prototype.BODY_SIZED = function() { - var length = Math.min(this.end - this.offset, this.body_bytes); - this.userCall()(this[kOnBody](this.chunk, this.offset, length)); - this.offset += length; - this.body_bytes -= length; - if (!this.body_bytes) { - this.nextRequest(); - } - }; - ["Headers", "HeadersComplete", "Body", "MessageComplete"].forEach(function(name) { - var k2 = HTTPParser["kOn" + name]; - Object.defineProperty(HTTPParser.prototype, "on" + name, { - get: function() { - return this[k2]; - }, - set: function(to) { - this._compatMode0_11 = true; - method_connect = "CONNECT"; - return this[k2] = to; - } - }); - }); - function parseErrorCode(code) { - var err = new Error("Parse Error"); - err.code = code; - return err; - } - }, - /***/ - 891(module2, exports$1, __webpack_require__2) { - var buffer = __webpack_require__2(181); - var Buffer2 = buffer.Buffer; - function copyProps(src, dst) { - for (var key in src) { - dst[key] = src[key]; - } - } - if (Buffer2.from && Buffer2.alloc && Buffer2.allocUnsafe && Buffer2.allocUnsafeSlow) { - module2.exports = buffer; - } else { - copyProps(buffer, exports$1); - exports$1.Buffer = SafeBuffer; - } - function SafeBuffer(arg, encodingOrOffset, length) { - return Buffer2(arg, encodingOrOffset, length); - } - copyProps(Buffer2, SafeBuffer); - SafeBuffer.from = function(arg, encodingOrOffset, length) { - if (typeof arg === "number") { - throw new TypeError("Argument must not be a number"); - } - return Buffer2(arg, encodingOrOffset, length); - }; - SafeBuffer.alloc = function(size, fill, encoding) { - if (typeof size !== "number") { - throw new TypeError("Argument must be a number"); - } - var buf = Buffer2(size); - if (fill !== void 0) { - if (typeof encoding === "string") { - buf.fill(fill, encoding); - } else { - buf.fill(fill); - } - } else { - buf.fill(0); - } - return buf; - }; - SafeBuffer.allocUnsafe = function(size) { - if (typeof size !== "number") { - throw new TypeError("Argument must be a number"); - } - return Buffer2(size); - }; - SafeBuffer.allocUnsafeSlow = function(size) { - if (typeof size !== "number") { - throw new TypeError("Argument must be a number"); - } - return buffer.SlowBuffer(size); - }; - }, - /***/ - 601(module2, __unused_webpack_exports, __webpack_require__2) { - (function(nacl) { - var gf = function(init) { - var i, r2 = new Float64Array(16); - if (init) for (i = 0; i < init.length; i++) r2[i] = init[i]; - return r2; - }; - var randombytes = function() { - throw new Error("no PRNG"); - }; - var _0 = new Uint8Array(16); - var _9 = new Uint8Array(32); - _9[0] = 9; - var gf0 = gf(), gf1 = gf([1]), _121665 = gf([56129, 1]), D = gf([30883, 4953, 19914, 30187, 55467, 16705, 2637, 112, 59544, 30585, 16505, 36039, 65139, 11119, 27886, 20995]), D2 = gf([61785, 9906, 39828, 60374, 45398, 33411, 5274, 224, 53552, 61171, 33010, 6542, 64743, 22239, 55772, 9222]), X = gf([54554, 36645, 11616, 51542, 42930, 38181, 51040, 26924, 56412, 64982, 57905, 49316, 21502, 52590, 14035, 8553]), Y = gf([26200, 26214, 26214, 26214, 26214, 26214, 26214, 26214, 26214, 26214, 26214, 26214, 26214, 26214, 26214, 26214]), I = gf([41136, 18958, 6951, 50414, 58488, 44335, 6150, 12099, 55207, 15867, 153, 11085, 57099, 20417, 9344, 11139]); - function ts64(x, i, h3, l2) { - x[i] = h3 >> 24 & 255; - x[i + 1] = h3 >> 16 & 255; - x[i + 2] = h3 >> 8 & 255; - x[i + 3] = h3 & 255; - x[i + 4] = l2 >> 24 & 255; - x[i + 5] = l2 >> 16 & 255; - x[i + 6] = l2 >> 8 & 255; - x[i + 7] = l2 & 255; - } - function vn(x, xi, y2, yi, n) { - var i, d2 = 0; - for (i = 0; i < n; i++) d2 |= x[xi + i] ^ y2[yi + i]; - return (1 & d2 - 1 >>> 8) - 1; - } - function crypto_verify_16(x, xi, y2, yi) { - return vn(x, xi, y2, yi, 16); - } - function crypto_verify_32(x, xi, y2, yi) { - return vn(x, xi, y2, yi, 32); - } - function core_salsa20(o2, p2, k2, c2) { - var j0 = c2[0] & 255 | (c2[1] & 255) << 8 | (c2[2] & 255) << 16 | (c2[3] & 255) << 24, j1 = k2[0] & 255 | (k2[1] & 255) << 8 | (k2[2] & 255) << 16 | (k2[3] & 255) << 24, j2 = k2[4] & 255 | (k2[5] & 255) << 8 | (k2[6] & 255) << 16 | (k2[7] & 255) << 24, j3 = k2[8] & 255 | (k2[9] & 255) << 8 | (k2[10] & 255) << 16 | (k2[11] & 255) << 24, j4 = k2[12] & 255 | (k2[13] & 255) << 8 | (k2[14] & 255) << 16 | (k2[15] & 255) << 24, j5 = c2[4] & 255 | (c2[5] & 255) << 8 | (c2[6] & 255) << 16 | (c2[7] & 255) << 24, j6 = p2[0] & 255 | (p2[1] & 255) << 8 | (p2[2] & 255) << 16 | (p2[3] & 255) << 24, j7 = p2[4] & 255 | (p2[5] & 255) << 8 | (p2[6] & 255) << 16 | (p2[7] & 255) << 24, j8 = p2[8] & 255 | (p2[9] & 255) << 8 | (p2[10] & 255) << 16 | (p2[11] & 255) << 24, j9 = p2[12] & 255 | (p2[13] & 255) << 8 | (p2[14] & 255) << 16 | (p2[15] & 255) << 24, j10 = c2[8] & 255 | (c2[9] & 255) << 8 | (c2[10] & 255) << 16 | (c2[11] & 255) << 24, j11 = k2[16] & 255 | (k2[17] & 255) << 8 | (k2[18] & 255) << 16 | (k2[19] & 255) << 24, j12 = k2[20] & 255 | (k2[21] & 255) << 8 | (k2[22] & 255) << 16 | (k2[23] & 255) << 24, j13 = k2[24] & 255 | (k2[25] & 255) << 8 | (k2[26] & 255) << 16 | (k2[27] & 255) << 24, j14 = k2[28] & 255 | (k2[29] & 255) << 8 | (k2[30] & 255) << 16 | (k2[31] & 255) << 24, j15 = c2[12] & 255 | (c2[13] & 255) << 8 | (c2[14] & 255) << 16 | (c2[15] & 255) << 24; - var x0 = j0, x1 = j1, x2 = j2, x3 = j3, x4 = j4, x5 = j5, x6 = j6, x7 = j7, x8 = j8, x9 = j9, x10 = j10, x11 = j11, x12 = j12, x13 = j13, x14 = j14, x15 = j15, u2; - for (var i = 0; i < 20; i += 2) { - u2 = x0 + x12 | 0; - x4 ^= u2 << 7 | u2 >>> 32 - 7; - u2 = x4 + x0 | 0; - x8 ^= u2 << 9 | u2 >>> 32 - 9; - u2 = x8 + x4 | 0; - x12 ^= u2 << 13 | u2 >>> 32 - 13; - u2 = x12 + x8 | 0; - x0 ^= u2 << 18 | u2 >>> 32 - 18; - u2 = x5 + x1 | 0; - x9 ^= u2 << 7 | u2 >>> 32 - 7; - u2 = x9 + x5 | 0; - x13 ^= u2 << 9 | u2 >>> 32 - 9; - u2 = x13 + x9 | 0; - x1 ^= u2 << 13 | u2 >>> 32 - 13; - u2 = x1 + x13 | 0; - x5 ^= u2 << 18 | u2 >>> 32 - 18; - u2 = x10 + x6 | 0; - x14 ^= u2 << 7 | u2 >>> 32 - 7; - u2 = x14 + x10 | 0; - x2 ^= u2 << 9 | u2 >>> 32 - 9; - u2 = x2 + x14 | 0; - x6 ^= u2 << 13 | u2 >>> 32 - 13; - u2 = x6 + x2 | 0; - x10 ^= u2 << 18 | u2 >>> 32 - 18; - u2 = x15 + x11 | 0; - x3 ^= u2 << 7 | u2 >>> 32 - 7; - u2 = x3 + x15 | 0; - x7 ^= u2 << 9 | u2 >>> 32 - 9; - u2 = x7 + x3 | 0; - x11 ^= u2 << 13 | u2 >>> 32 - 13; - u2 = x11 + x7 | 0; - x15 ^= u2 << 18 | u2 >>> 32 - 18; - u2 = x0 + x3 | 0; - x1 ^= u2 << 7 | u2 >>> 32 - 7; - u2 = x1 + x0 | 0; - x2 ^= u2 << 9 | u2 >>> 32 - 9; - u2 = x2 + x1 | 0; - x3 ^= u2 << 13 | u2 >>> 32 - 13; - u2 = x3 + x2 | 0; - x0 ^= u2 << 18 | u2 >>> 32 - 18; - u2 = x5 + x4 | 0; - x6 ^= u2 << 7 | u2 >>> 32 - 7; - u2 = x6 + x5 | 0; - x7 ^= u2 << 9 | u2 >>> 32 - 9; - u2 = x7 + x6 | 0; - x4 ^= u2 << 13 | u2 >>> 32 - 13; - u2 = x4 + x7 | 0; - x5 ^= u2 << 18 | u2 >>> 32 - 18; - u2 = x10 + x9 | 0; - x11 ^= u2 << 7 | u2 >>> 32 - 7; - u2 = x11 + x10 | 0; - x8 ^= u2 << 9 | u2 >>> 32 - 9; - u2 = x8 + x11 | 0; - x9 ^= u2 << 13 | u2 >>> 32 - 13; - u2 = x9 + x8 | 0; - x10 ^= u2 << 18 | u2 >>> 32 - 18; - u2 = x15 + x14 | 0; - x12 ^= u2 << 7 | u2 >>> 32 - 7; - u2 = x12 + x15 | 0; - x13 ^= u2 << 9 | u2 >>> 32 - 9; - u2 = x13 + x12 | 0; - x14 ^= u2 << 13 | u2 >>> 32 - 13; - u2 = x14 + x13 | 0; - x15 ^= u2 << 18 | u2 >>> 32 - 18; - } - x0 = x0 + j0 | 0; - x1 = x1 + j1 | 0; - x2 = x2 + j2 | 0; - x3 = x3 + j3 | 0; - x4 = x4 + j4 | 0; - x5 = x5 + j5 | 0; - x6 = x6 + j6 | 0; - x7 = x7 + j7 | 0; - x8 = x8 + j8 | 0; - x9 = x9 + j9 | 0; - x10 = x10 + j10 | 0; - x11 = x11 + j11 | 0; - x12 = x12 + j12 | 0; - x13 = x13 + j13 | 0; - x14 = x14 + j14 | 0; - x15 = x15 + j15 | 0; - o2[0] = x0 >>> 0 & 255; - o2[1] = x0 >>> 8 & 255; - o2[2] = x0 >>> 16 & 255; - o2[3] = x0 >>> 24 & 255; - o2[4] = x1 >>> 0 & 255; - o2[5] = x1 >>> 8 & 255; - o2[6] = x1 >>> 16 & 255; - o2[7] = x1 >>> 24 & 255; - o2[8] = x2 >>> 0 & 255; - o2[9] = x2 >>> 8 & 255; - o2[10] = x2 >>> 16 & 255; - o2[11] = x2 >>> 24 & 255; - o2[12] = x3 >>> 0 & 255; - o2[13] = x3 >>> 8 & 255; - o2[14] = x3 >>> 16 & 255; - o2[15] = x3 >>> 24 & 255; - o2[16] = x4 >>> 0 & 255; - o2[17] = x4 >>> 8 & 255; - o2[18] = x4 >>> 16 & 255; - o2[19] = x4 >>> 24 & 255; - o2[20] = x5 >>> 0 & 255; - o2[21] = x5 >>> 8 & 255; - o2[22] = x5 >>> 16 & 255; - o2[23] = x5 >>> 24 & 255; - o2[24] = x6 >>> 0 & 255; - o2[25] = x6 >>> 8 & 255; - o2[26] = x6 >>> 16 & 255; - o2[27] = x6 >>> 24 & 255; - o2[28] = x7 >>> 0 & 255; - o2[29] = x7 >>> 8 & 255; - o2[30] = x7 >>> 16 & 255; - o2[31] = x7 >>> 24 & 255; - o2[32] = x8 >>> 0 & 255; - o2[33] = x8 >>> 8 & 255; - o2[34] = x8 >>> 16 & 255; - o2[35] = x8 >>> 24 & 255; - o2[36] = x9 >>> 0 & 255; - o2[37] = x9 >>> 8 & 255; - o2[38] = x9 >>> 16 & 255; - o2[39] = x9 >>> 24 & 255; - o2[40] = x10 >>> 0 & 255; - o2[41] = x10 >>> 8 & 255; - o2[42] = x10 >>> 16 & 255; - o2[43] = x10 >>> 24 & 255; - o2[44] = x11 >>> 0 & 255; - o2[45] = x11 >>> 8 & 255; - o2[46] = x11 >>> 16 & 255; - o2[47] = x11 >>> 24 & 255; - o2[48] = x12 >>> 0 & 255; - o2[49] = x12 >>> 8 & 255; - o2[50] = x12 >>> 16 & 255; - o2[51] = x12 >>> 24 & 255; - o2[52] = x13 >>> 0 & 255; - o2[53] = x13 >>> 8 & 255; - o2[54] = x13 >>> 16 & 255; - o2[55] = x13 >>> 24 & 255; - o2[56] = x14 >>> 0 & 255; - o2[57] = x14 >>> 8 & 255; - o2[58] = x14 >>> 16 & 255; - o2[59] = x14 >>> 24 & 255; - o2[60] = x15 >>> 0 & 255; - o2[61] = x15 >>> 8 & 255; - o2[62] = x15 >>> 16 & 255; - o2[63] = x15 >>> 24 & 255; - } - function core_hsalsa20(o2, p2, k2, c2) { - var j0 = c2[0] & 255 | (c2[1] & 255) << 8 | (c2[2] & 255) << 16 | (c2[3] & 255) << 24, j1 = k2[0] & 255 | (k2[1] & 255) << 8 | (k2[2] & 255) << 16 | (k2[3] & 255) << 24, j2 = k2[4] & 255 | (k2[5] & 255) << 8 | (k2[6] & 255) << 16 | (k2[7] & 255) << 24, j3 = k2[8] & 255 | (k2[9] & 255) << 8 | (k2[10] & 255) << 16 | (k2[11] & 255) << 24, j4 = k2[12] & 255 | (k2[13] & 255) << 8 | (k2[14] & 255) << 16 | (k2[15] & 255) << 24, j5 = c2[4] & 255 | (c2[5] & 255) << 8 | (c2[6] & 255) << 16 | (c2[7] & 255) << 24, j6 = p2[0] & 255 | (p2[1] & 255) << 8 | (p2[2] & 255) << 16 | (p2[3] & 255) << 24, j7 = p2[4] & 255 | (p2[5] & 255) << 8 | (p2[6] & 255) << 16 | (p2[7] & 255) << 24, j8 = p2[8] & 255 | (p2[9] & 255) << 8 | (p2[10] & 255) << 16 | (p2[11] & 255) << 24, j9 = p2[12] & 255 | (p2[13] & 255) << 8 | (p2[14] & 255) << 16 | (p2[15] & 255) << 24, j10 = c2[8] & 255 | (c2[9] & 255) << 8 | (c2[10] & 255) << 16 | (c2[11] & 255) << 24, j11 = k2[16] & 255 | (k2[17] & 255) << 8 | (k2[18] & 255) << 16 | (k2[19] & 255) << 24, j12 = k2[20] & 255 | (k2[21] & 255) << 8 | (k2[22] & 255) << 16 | (k2[23] & 255) << 24, j13 = k2[24] & 255 | (k2[25] & 255) << 8 | (k2[26] & 255) << 16 | (k2[27] & 255) << 24, j14 = k2[28] & 255 | (k2[29] & 255) << 8 | (k2[30] & 255) << 16 | (k2[31] & 255) << 24, j15 = c2[12] & 255 | (c2[13] & 255) << 8 | (c2[14] & 255) << 16 | (c2[15] & 255) << 24; - var x0 = j0, x1 = j1, x2 = j2, x3 = j3, x4 = j4, x5 = j5, x6 = j6, x7 = j7, x8 = j8, x9 = j9, x10 = j10, x11 = j11, x12 = j12, x13 = j13, x14 = j14, x15 = j15, u2; - for (var i = 0; i < 20; i += 2) { - u2 = x0 + x12 | 0; - x4 ^= u2 << 7 | u2 >>> 32 - 7; - u2 = x4 + x0 | 0; - x8 ^= u2 << 9 | u2 >>> 32 - 9; - u2 = x8 + x4 | 0; - x12 ^= u2 << 13 | u2 >>> 32 - 13; - u2 = x12 + x8 | 0; - x0 ^= u2 << 18 | u2 >>> 32 - 18; - u2 = x5 + x1 | 0; - x9 ^= u2 << 7 | u2 >>> 32 - 7; - u2 = x9 + x5 | 0; - x13 ^= u2 << 9 | u2 >>> 32 - 9; - u2 = x13 + x9 | 0; - x1 ^= u2 << 13 | u2 >>> 32 - 13; - u2 = x1 + x13 | 0; - x5 ^= u2 << 18 | u2 >>> 32 - 18; - u2 = x10 + x6 | 0; - x14 ^= u2 << 7 | u2 >>> 32 - 7; - u2 = x14 + x10 | 0; - x2 ^= u2 << 9 | u2 >>> 32 - 9; - u2 = x2 + x14 | 0; - x6 ^= u2 << 13 | u2 >>> 32 - 13; - u2 = x6 + x2 | 0; - x10 ^= u2 << 18 | u2 >>> 32 - 18; - u2 = x15 + x11 | 0; - x3 ^= u2 << 7 | u2 >>> 32 - 7; - u2 = x3 + x15 | 0; - x7 ^= u2 << 9 | u2 >>> 32 - 9; - u2 = x7 + x3 | 0; - x11 ^= u2 << 13 | u2 >>> 32 - 13; - u2 = x11 + x7 | 0; - x15 ^= u2 << 18 | u2 >>> 32 - 18; - u2 = x0 + x3 | 0; - x1 ^= u2 << 7 | u2 >>> 32 - 7; - u2 = x1 + x0 | 0; - x2 ^= u2 << 9 | u2 >>> 32 - 9; - u2 = x2 + x1 | 0; - x3 ^= u2 << 13 | u2 >>> 32 - 13; - u2 = x3 + x2 | 0; - x0 ^= u2 << 18 | u2 >>> 32 - 18; - u2 = x5 + x4 | 0; - x6 ^= u2 << 7 | u2 >>> 32 - 7; - u2 = x6 + x5 | 0; - x7 ^= u2 << 9 | u2 >>> 32 - 9; - u2 = x7 + x6 | 0; - x4 ^= u2 << 13 | u2 >>> 32 - 13; - u2 = x4 + x7 | 0; - x5 ^= u2 << 18 | u2 >>> 32 - 18; - u2 = x10 + x9 | 0; - x11 ^= u2 << 7 | u2 >>> 32 - 7; - u2 = x11 + x10 | 0; - x8 ^= u2 << 9 | u2 >>> 32 - 9; - u2 = x8 + x11 | 0; - x9 ^= u2 << 13 | u2 >>> 32 - 13; - u2 = x9 + x8 | 0; - x10 ^= u2 << 18 | u2 >>> 32 - 18; - u2 = x15 + x14 | 0; - x12 ^= u2 << 7 | u2 >>> 32 - 7; - u2 = x12 + x15 | 0; - x13 ^= u2 << 9 | u2 >>> 32 - 9; - u2 = x13 + x12 | 0; - x14 ^= u2 << 13 | u2 >>> 32 - 13; - u2 = x14 + x13 | 0; - x15 ^= u2 << 18 | u2 >>> 32 - 18; - } - o2[0] = x0 >>> 0 & 255; - o2[1] = x0 >>> 8 & 255; - o2[2] = x0 >>> 16 & 255; - o2[3] = x0 >>> 24 & 255; - o2[4] = x5 >>> 0 & 255; - o2[5] = x5 >>> 8 & 255; - o2[6] = x5 >>> 16 & 255; - o2[7] = x5 >>> 24 & 255; - o2[8] = x10 >>> 0 & 255; - o2[9] = x10 >>> 8 & 255; - o2[10] = x10 >>> 16 & 255; - o2[11] = x10 >>> 24 & 255; - o2[12] = x15 >>> 0 & 255; - o2[13] = x15 >>> 8 & 255; - o2[14] = x15 >>> 16 & 255; - o2[15] = x15 >>> 24 & 255; - o2[16] = x6 >>> 0 & 255; - o2[17] = x6 >>> 8 & 255; - o2[18] = x6 >>> 16 & 255; - o2[19] = x6 >>> 24 & 255; - o2[20] = x7 >>> 0 & 255; - o2[21] = x7 >>> 8 & 255; - o2[22] = x7 >>> 16 & 255; - o2[23] = x7 >>> 24 & 255; - o2[24] = x8 >>> 0 & 255; - o2[25] = x8 >>> 8 & 255; - o2[26] = x8 >>> 16 & 255; - o2[27] = x8 >>> 24 & 255; - o2[28] = x9 >>> 0 & 255; - o2[29] = x9 >>> 8 & 255; - o2[30] = x9 >>> 16 & 255; - o2[31] = x9 >>> 24 & 255; - } - function crypto_core_salsa20(out, inp, k2, c2) { - core_salsa20(out, inp, k2, c2); - } - function crypto_core_hsalsa20(out, inp, k2, c2) { - core_hsalsa20(out, inp, k2, c2); - } - var sigma = new Uint8Array([101, 120, 112, 97, 110, 100, 32, 51, 50, 45, 98, 121, 116, 101, 32, 107]); - function crypto_stream_salsa20_xor(c2, cpos, m2, mpos, b2, n, k2) { - var z = new Uint8Array(16), x = new Uint8Array(64); - var u2, i; - for (i = 0; i < 16; i++) z[i] = 0; - for (i = 0; i < 8; i++) z[i] = n[i]; - while (b2 >= 64) { - crypto_core_salsa20(x, z, k2, sigma); - for (i = 0; i < 64; i++) c2[cpos + i] = m2[mpos + i] ^ x[i]; - u2 = 1; - for (i = 8; i < 16; i++) { - u2 = u2 + (z[i] & 255) | 0; - z[i] = u2 & 255; - u2 >>>= 8; - } - b2 -= 64; - cpos += 64; - mpos += 64; - } - if (b2 > 0) { - crypto_core_salsa20(x, z, k2, sigma); - for (i = 0; i < b2; i++) c2[cpos + i] = m2[mpos + i] ^ x[i]; - } - return 0; - } - function crypto_stream_salsa20(c2, cpos, b2, n, k2) { - var z = new Uint8Array(16), x = new Uint8Array(64); - var u2, i; - for (i = 0; i < 16; i++) z[i] = 0; - for (i = 0; i < 8; i++) z[i] = n[i]; - while (b2 >= 64) { - crypto_core_salsa20(x, z, k2, sigma); - for (i = 0; i < 64; i++) c2[cpos + i] = x[i]; - u2 = 1; - for (i = 8; i < 16; i++) { - u2 = u2 + (z[i] & 255) | 0; - z[i] = u2 & 255; - u2 >>>= 8; - } - b2 -= 64; - cpos += 64; - } - if (b2 > 0) { - crypto_core_salsa20(x, z, k2, sigma); - for (i = 0; i < b2; i++) c2[cpos + i] = x[i]; - } - return 0; - } - function crypto_stream(c2, cpos, d2, n, k2) { - var s = new Uint8Array(32); - crypto_core_hsalsa20(s, n, k2, sigma); - var sn = new Uint8Array(8); - for (var i = 0; i < 8; i++) sn[i] = n[i + 16]; - return crypto_stream_salsa20(c2, cpos, d2, sn, s); - } - function crypto_stream_xor(c2, cpos, m2, mpos, d2, n, k2) { - var s = new Uint8Array(32); - crypto_core_hsalsa20(s, n, k2, sigma); - var sn = new Uint8Array(8); - for (var i = 0; i < 8; i++) sn[i] = n[i + 16]; - return crypto_stream_salsa20_xor(c2, cpos, m2, mpos, d2, sn, s); - } - var poly1305 = function(key) { - this.buffer = new Uint8Array(16); - this.r = new Uint16Array(10); - this.h = new Uint16Array(10); - this.pad = new Uint16Array(8); - this.leftover = 0; - this.fin = 0; - var t0, t1, t2, t3, t4, t5, t6, t7; - t0 = key[0] & 255 | (key[1] & 255) << 8; - this.r[0] = t0 & 8191; - t1 = key[2] & 255 | (key[3] & 255) << 8; - this.r[1] = (t0 >>> 13 | t1 << 3) & 8191; - t2 = key[4] & 255 | (key[5] & 255) << 8; - this.r[2] = (t1 >>> 10 | t2 << 6) & 7939; - t3 = key[6] & 255 | (key[7] & 255) << 8; - this.r[3] = (t2 >>> 7 | t3 << 9) & 8191; - t4 = key[8] & 255 | (key[9] & 255) << 8; - this.r[4] = (t3 >>> 4 | t4 << 12) & 255; - this.r[5] = t4 >>> 1 & 8190; - t5 = key[10] & 255 | (key[11] & 255) << 8; - this.r[6] = (t4 >>> 14 | t5 << 2) & 8191; - t6 = key[12] & 255 | (key[13] & 255) << 8; - this.r[7] = (t5 >>> 11 | t6 << 5) & 8065; - t7 = key[14] & 255 | (key[15] & 255) << 8; - this.r[8] = (t6 >>> 8 | t7 << 8) & 8191; - this.r[9] = t7 >>> 5 & 127; - this.pad[0] = key[16] & 255 | (key[17] & 255) << 8; - this.pad[1] = key[18] & 255 | (key[19] & 255) << 8; - this.pad[2] = key[20] & 255 | (key[21] & 255) << 8; - this.pad[3] = key[22] & 255 | (key[23] & 255) << 8; - this.pad[4] = key[24] & 255 | (key[25] & 255) << 8; - this.pad[5] = key[26] & 255 | (key[27] & 255) << 8; - this.pad[6] = key[28] & 255 | (key[29] & 255) << 8; - this.pad[7] = key[30] & 255 | (key[31] & 255) << 8; - }; - poly1305.prototype.blocks = function(m2, mpos, bytes) { - var hibit = this.fin ? 0 : 1 << 11; - var t0, t1, t2, t3, t4, t5, t6, t7, c2; - var d0, d1, d2, d3, d4, d5, d6, d7, d8, d9; - var h0 = this.h[0], h1 = this.h[1], h22 = this.h[2], h3 = this.h[3], h4 = this.h[4], h5 = this.h[5], h6 = this.h[6], h7 = this.h[7], h8 = this.h[8], h9 = this.h[9]; - var r0 = this.r[0], r1 = this.r[1], r2 = this.r[2], r3 = this.r[3], r4 = this.r[4], r5 = this.r[5], r6 = this.r[6], r7 = this.r[7], r8 = this.r[8], r9 = this.r[9]; - while (bytes >= 16) { - t0 = m2[mpos + 0] & 255 | (m2[mpos + 1] & 255) << 8; - h0 += t0 & 8191; - t1 = m2[mpos + 2] & 255 | (m2[mpos + 3] & 255) << 8; - h1 += (t0 >>> 13 | t1 << 3) & 8191; - t2 = m2[mpos + 4] & 255 | (m2[mpos + 5] & 255) << 8; - h22 += (t1 >>> 10 | t2 << 6) & 8191; - t3 = m2[mpos + 6] & 255 | (m2[mpos + 7] & 255) << 8; - h3 += (t2 >>> 7 | t3 << 9) & 8191; - t4 = m2[mpos + 8] & 255 | (m2[mpos + 9] & 255) << 8; - h4 += (t3 >>> 4 | t4 << 12) & 8191; - h5 += t4 >>> 1 & 8191; - t5 = m2[mpos + 10] & 255 | (m2[mpos + 11] & 255) << 8; - h6 += (t4 >>> 14 | t5 << 2) & 8191; - t6 = m2[mpos + 12] & 255 | (m2[mpos + 13] & 255) << 8; - h7 += (t5 >>> 11 | t6 << 5) & 8191; - t7 = m2[mpos + 14] & 255 | (m2[mpos + 15] & 255) << 8; - h8 += (t6 >>> 8 | t7 << 8) & 8191; - h9 += t7 >>> 5 | hibit; - c2 = 0; - d0 = c2; - d0 += h0 * r0; - d0 += h1 * (5 * r9); - d0 += h22 * (5 * r8); - d0 += h3 * (5 * r7); - d0 += h4 * (5 * r6); - c2 = d0 >>> 13; - d0 &= 8191; - d0 += h5 * (5 * r5); - d0 += h6 * (5 * r4); - d0 += h7 * (5 * r3); - d0 += h8 * (5 * r2); - d0 += h9 * (5 * r1); - c2 += d0 >>> 13; - d0 &= 8191; - d1 = c2; - d1 += h0 * r1; - d1 += h1 * r0; - d1 += h22 * (5 * r9); - d1 += h3 * (5 * r8); - d1 += h4 * (5 * r7); - c2 = d1 >>> 13; - d1 &= 8191; - d1 += h5 * (5 * r6); - d1 += h6 * (5 * r5); - d1 += h7 * (5 * r4); - d1 += h8 * (5 * r3); - d1 += h9 * (5 * r2); - c2 += d1 >>> 13; - d1 &= 8191; - d2 = c2; - d2 += h0 * r2; - d2 += h1 * r1; - d2 += h22 * r0; - d2 += h3 * (5 * r9); - d2 += h4 * (5 * r8); - c2 = d2 >>> 13; - d2 &= 8191; - d2 += h5 * (5 * r7); - d2 += h6 * (5 * r6); - d2 += h7 * (5 * r5); - d2 += h8 * (5 * r4); - d2 += h9 * (5 * r3); - c2 += d2 >>> 13; - d2 &= 8191; - d3 = c2; - d3 += h0 * r3; - d3 += h1 * r2; - d3 += h22 * r1; - d3 += h3 * r0; - d3 += h4 * (5 * r9); - c2 = d3 >>> 13; - d3 &= 8191; - d3 += h5 * (5 * r8); - d3 += h6 * (5 * r7); - d3 += h7 * (5 * r6); - d3 += h8 * (5 * r5); - d3 += h9 * (5 * r4); - c2 += d3 >>> 13; - d3 &= 8191; - d4 = c2; - d4 += h0 * r4; - d4 += h1 * r3; - d4 += h22 * r2; - d4 += h3 * r1; - d4 += h4 * r0; - c2 = d4 >>> 13; - d4 &= 8191; - d4 += h5 * (5 * r9); - d4 += h6 * (5 * r8); - d4 += h7 * (5 * r7); - d4 += h8 * (5 * r6); - d4 += h9 * (5 * r5); - c2 += d4 >>> 13; - d4 &= 8191; - d5 = c2; - d5 += h0 * r5; - d5 += h1 * r4; - d5 += h22 * r3; - d5 += h3 * r2; - d5 += h4 * r1; - c2 = d5 >>> 13; - d5 &= 8191; - d5 += h5 * r0; - d5 += h6 * (5 * r9); - d5 += h7 * (5 * r8); - d5 += h8 * (5 * r7); - d5 += h9 * (5 * r6); - c2 += d5 >>> 13; - d5 &= 8191; - d6 = c2; - d6 += h0 * r6; - d6 += h1 * r5; - d6 += h22 * r4; - d6 += h3 * r3; - d6 += h4 * r2; - c2 = d6 >>> 13; - d6 &= 8191; - d6 += h5 * r1; - d6 += h6 * r0; - d6 += h7 * (5 * r9); - d6 += h8 * (5 * r8); - d6 += h9 * (5 * r7); - c2 += d6 >>> 13; - d6 &= 8191; - d7 = c2; - d7 += h0 * r7; - d7 += h1 * r6; - d7 += h22 * r5; - d7 += h3 * r4; - d7 += h4 * r3; - c2 = d7 >>> 13; - d7 &= 8191; - d7 += h5 * r2; - d7 += h6 * r1; - d7 += h7 * r0; - d7 += h8 * (5 * r9); - d7 += h9 * (5 * r8); - c2 += d7 >>> 13; - d7 &= 8191; - d8 = c2; - d8 += h0 * r8; - d8 += h1 * r7; - d8 += h22 * r6; - d8 += h3 * r5; - d8 += h4 * r4; - c2 = d8 >>> 13; - d8 &= 8191; - d8 += h5 * r3; - d8 += h6 * r2; - d8 += h7 * r1; - d8 += h8 * r0; - d8 += h9 * (5 * r9); - c2 += d8 >>> 13; - d8 &= 8191; - d9 = c2; - d9 += h0 * r9; - d9 += h1 * r8; - d9 += h22 * r7; - d9 += h3 * r6; - d9 += h4 * r5; - c2 = d9 >>> 13; - d9 &= 8191; - d9 += h5 * r4; - d9 += h6 * r3; - d9 += h7 * r2; - d9 += h8 * r1; - d9 += h9 * r0; - c2 += d9 >>> 13; - d9 &= 8191; - c2 = (c2 << 2) + c2 | 0; - c2 = c2 + d0 | 0; - d0 = c2 & 8191; - c2 = c2 >>> 13; - d1 += c2; - h0 = d0; - h1 = d1; - h22 = d2; - h3 = d3; - h4 = d4; - h5 = d5; - h6 = d6; - h7 = d7; - h8 = d8; - h9 = d9; - mpos += 16; - bytes -= 16; - } - this.h[0] = h0; - this.h[1] = h1; - this.h[2] = h22; - this.h[3] = h3; - this.h[4] = h4; - this.h[5] = h5; - this.h[6] = h6; - this.h[7] = h7; - this.h[8] = h8; - this.h[9] = h9; - }; - poly1305.prototype.finish = function(mac, macpos) { - var g2 = new Uint16Array(10); - var c2, mask, f2, i; - if (this.leftover) { - i = this.leftover; - this.buffer[i++] = 1; - for (; i < 16; i++) this.buffer[i] = 0; - this.fin = 1; - this.blocks(this.buffer, 0, 16); - } - c2 = this.h[1] >>> 13; - this.h[1] &= 8191; - for (i = 2; i < 10; i++) { - this.h[i] += c2; - c2 = this.h[i] >>> 13; - this.h[i] &= 8191; - } - this.h[0] += c2 * 5; - c2 = this.h[0] >>> 13; - this.h[0] &= 8191; - this.h[1] += c2; - c2 = this.h[1] >>> 13; - this.h[1] &= 8191; - this.h[2] += c2; - g2[0] = this.h[0] + 5; - c2 = g2[0] >>> 13; - g2[0] &= 8191; - for (i = 1; i < 10; i++) { - g2[i] = this.h[i] + c2; - c2 = g2[i] >>> 13; - g2[i] &= 8191; - } - g2[9] -= 1 << 13; - mask = (c2 ^ 1) - 1; - for (i = 0; i < 10; i++) g2[i] &= mask; - mask = ~mask; - for (i = 0; i < 10; i++) this.h[i] = this.h[i] & mask | g2[i]; - this.h[0] = (this.h[0] | this.h[1] << 13) & 65535; - this.h[1] = (this.h[1] >>> 3 | this.h[2] << 10) & 65535; - this.h[2] = (this.h[2] >>> 6 | this.h[3] << 7) & 65535; - this.h[3] = (this.h[3] >>> 9 | this.h[4] << 4) & 65535; - this.h[4] = (this.h[4] >>> 12 | this.h[5] << 1 | this.h[6] << 14) & 65535; - this.h[5] = (this.h[6] >>> 2 | this.h[7] << 11) & 65535; - this.h[6] = (this.h[7] >>> 5 | this.h[8] << 8) & 65535; - this.h[7] = (this.h[8] >>> 8 | this.h[9] << 5) & 65535; - f2 = this.h[0] + this.pad[0]; - this.h[0] = f2 & 65535; - for (i = 1; i < 8; i++) { - f2 = (this.h[i] + this.pad[i] | 0) + (f2 >>> 16) | 0; - this.h[i] = f2 & 65535; - } - mac[macpos + 0] = this.h[0] >>> 0 & 255; - mac[macpos + 1] = this.h[0] >>> 8 & 255; - mac[macpos + 2] = this.h[1] >>> 0 & 255; - mac[macpos + 3] = this.h[1] >>> 8 & 255; - mac[macpos + 4] = this.h[2] >>> 0 & 255; - mac[macpos + 5] = this.h[2] >>> 8 & 255; - mac[macpos + 6] = this.h[3] >>> 0 & 255; - mac[macpos + 7] = this.h[3] >>> 8 & 255; - mac[macpos + 8] = this.h[4] >>> 0 & 255; - mac[macpos + 9] = this.h[4] >>> 8 & 255; - mac[macpos + 10] = this.h[5] >>> 0 & 255; - mac[macpos + 11] = this.h[5] >>> 8 & 255; - mac[macpos + 12] = this.h[6] >>> 0 & 255; - mac[macpos + 13] = this.h[6] >>> 8 & 255; - mac[macpos + 14] = this.h[7] >>> 0 & 255; - mac[macpos + 15] = this.h[7] >>> 8 & 255; - }; - poly1305.prototype.update = function(m2, mpos, bytes) { - var i, want; - if (this.leftover) { - want = 16 - this.leftover; - if (want > bytes) - want = bytes; - for (i = 0; i < want; i++) - this.buffer[this.leftover + i] = m2[mpos + i]; - bytes -= want; - mpos += want; - this.leftover += want; - if (this.leftover < 16) - return; - this.blocks(this.buffer, 0, 16); - this.leftover = 0; - } - if (bytes >= 16) { - want = bytes - bytes % 16; - this.blocks(m2, mpos, want); - mpos += want; - bytes -= want; - } - if (bytes) { - for (i = 0; i < bytes; i++) - this.buffer[this.leftover + i] = m2[mpos + i]; - this.leftover += bytes; - } - }; - function crypto_onetimeauth(out, outpos, m2, mpos, n, k2) { - var s = new poly1305(k2); - s.update(m2, mpos, n); - s.finish(out, outpos); - return 0; - } - function crypto_onetimeauth_verify(h3, hpos, m2, mpos, n, k2) { - var x = new Uint8Array(16); - crypto_onetimeauth(x, 0, m2, mpos, n, k2); - return crypto_verify_16(h3, hpos, x, 0); - } - function crypto_secretbox(c2, m2, d2, n, k2) { - var i; - if (d2 < 32) return -1; - crypto_stream_xor(c2, 0, m2, 0, d2, n, k2); - crypto_onetimeauth(c2, 16, c2, 32, d2 - 32, c2); - for (i = 0; i < 16; i++) c2[i] = 0; - return 0; - } - function crypto_secretbox_open(m2, c2, d2, n, k2) { - var i; - var x = new Uint8Array(32); - if (d2 < 32) return -1; - crypto_stream(x, 0, 32, n, k2); - if (crypto_onetimeauth_verify(c2, 16, c2, 32, d2 - 32, x) !== 0) return -1; - crypto_stream_xor(m2, 0, c2, 0, d2, n, k2); - for (i = 0; i < 32; i++) m2[i] = 0; - return 0; - } - function set25519(r2, a) { - var i; - for (i = 0; i < 16; i++) r2[i] = a[i] | 0; - } - function car25519(o2) { - var i, v2, c2 = 1; - for (i = 0; i < 16; i++) { - v2 = o2[i] + c2 + 65535; - c2 = Math.floor(v2 / 65536); - o2[i] = v2 - c2 * 65536; - } - o2[0] += c2 - 1 + 37 * (c2 - 1); - } - function sel25519(p2, q, b2) { - var t, c2 = ~(b2 - 1); - for (var i = 0; i < 16; i++) { - t = c2 & (p2[i] ^ q[i]); - p2[i] ^= t; - q[i] ^= t; - } - } - function pack25519(o2, n) { - var i, j, b2; - var m2 = gf(), t = gf(); - for (i = 0; i < 16; i++) t[i] = n[i]; - car25519(t); - car25519(t); - car25519(t); - for (j = 0; j < 2; j++) { - m2[0] = t[0] - 65517; - for (i = 1; i < 15; i++) { - m2[i] = t[i] - 65535 - (m2[i - 1] >> 16 & 1); - m2[i - 1] &= 65535; - } - m2[15] = t[15] - 32767 - (m2[14] >> 16 & 1); - b2 = m2[15] >> 16 & 1; - m2[14] &= 65535; - sel25519(t, m2, 1 - b2); - } - for (i = 0; i < 16; i++) { - o2[2 * i] = t[i] & 255; - o2[2 * i + 1] = t[i] >> 8; - } - } - function neq25519(a, b2) { - var c2 = new Uint8Array(32), d2 = new Uint8Array(32); - pack25519(c2, a); - pack25519(d2, b2); - return crypto_verify_32(c2, 0, d2, 0); - } - function par25519(a) { - var d2 = new Uint8Array(32); - pack25519(d2, a); - return d2[0] & 1; - } - function unpack25519(o2, n) { - var i; - for (i = 0; i < 16; i++) o2[i] = n[2 * i] + (n[2 * i + 1] << 8); - o2[15] &= 32767; - } - function A(o2, a, b2) { - for (var i = 0; i < 16; i++) o2[i] = a[i] + b2[i]; - } - function Z(o2, a, b2) { - for (var i = 0; i < 16; i++) o2[i] = a[i] - b2[i]; - } - function M(o2, a, b2) { - var v2, c2, t0 = 0, t1 = 0, t2 = 0, t3 = 0, t4 = 0, t5 = 0, t6 = 0, t7 = 0, t8 = 0, t9 = 0, t10 = 0, t11 = 0, t12 = 0, t13 = 0, t14 = 0, t15 = 0, t16 = 0, t17 = 0, t18 = 0, t19 = 0, t20 = 0, t21 = 0, t22 = 0, t23 = 0, t24 = 0, t25 = 0, t26 = 0, t27 = 0, t28 = 0, t29 = 0, t30 = 0, b0 = b2[0], b1 = b2[1], b22 = b2[2], b3 = b2[3], b4 = b2[4], b5 = b2[5], b6 = b2[6], b7 = b2[7], b8 = b2[8], b9 = b2[9], b10 = b2[10], b11 = b2[11], b12 = b2[12], b13 = b2[13], b14 = b2[14], b15 = b2[15]; - v2 = a[0]; - t0 += v2 * b0; - t1 += v2 * b1; - t2 += v2 * b22; - t3 += v2 * b3; - t4 += v2 * b4; - t5 += v2 * b5; - t6 += v2 * b6; - t7 += v2 * b7; - t8 += v2 * b8; - t9 += v2 * b9; - t10 += v2 * b10; - t11 += v2 * b11; - t12 += v2 * b12; - t13 += v2 * b13; - t14 += v2 * b14; - t15 += v2 * b15; - v2 = a[1]; - t1 += v2 * b0; - t2 += v2 * b1; - t3 += v2 * b22; - t4 += v2 * b3; - t5 += v2 * b4; - t6 += v2 * b5; - t7 += v2 * b6; - t8 += v2 * b7; - t9 += v2 * b8; - t10 += v2 * b9; - t11 += v2 * b10; - t12 += v2 * b11; - t13 += v2 * b12; - t14 += v2 * b13; - t15 += v2 * b14; - t16 += v2 * b15; - v2 = a[2]; - t2 += v2 * b0; - t3 += v2 * b1; - t4 += v2 * b22; - t5 += v2 * b3; - t6 += v2 * b4; - t7 += v2 * b5; - t8 += v2 * b6; - t9 += v2 * b7; - t10 += v2 * b8; - t11 += v2 * b9; - t12 += v2 * b10; - t13 += v2 * b11; - t14 += v2 * b12; - t15 += v2 * b13; - t16 += v2 * b14; - t17 += v2 * b15; - v2 = a[3]; - t3 += v2 * b0; - t4 += v2 * b1; - t5 += v2 * b22; - t6 += v2 * b3; - t7 += v2 * b4; - t8 += v2 * b5; - t9 += v2 * b6; - t10 += v2 * b7; - t11 += v2 * b8; - t12 += v2 * b9; - t13 += v2 * b10; - t14 += v2 * b11; - t15 += v2 * b12; - t16 += v2 * b13; - t17 += v2 * b14; - t18 += v2 * b15; - v2 = a[4]; - t4 += v2 * b0; - t5 += v2 * b1; - t6 += v2 * b22; - t7 += v2 * b3; - t8 += v2 * b4; - t9 += v2 * b5; - t10 += v2 * b6; - t11 += v2 * b7; - t12 += v2 * b8; - t13 += v2 * b9; - t14 += v2 * b10; - t15 += v2 * b11; - t16 += v2 * b12; - t17 += v2 * b13; - t18 += v2 * b14; - t19 += v2 * b15; - v2 = a[5]; - t5 += v2 * b0; - t6 += v2 * b1; - t7 += v2 * b22; - t8 += v2 * b3; - t9 += v2 * b4; - t10 += v2 * b5; - t11 += v2 * b6; - t12 += v2 * b7; - t13 += v2 * b8; - t14 += v2 * b9; - t15 += v2 * b10; - t16 += v2 * b11; - t17 += v2 * b12; - t18 += v2 * b13; - t19 += v2 * b14; - t20 += v2 * b15; - v2 = a[6]; - t6 += v2 * b0; - t7 += v2 * b1; - t8 += v2 * b22; - t9 += v2 * b3; - t10 += v2 * b4; - t11 += v2 * b5; - t12 += v2 * b6; - t13 += v2 * b7; - t14 += v2 * b8; - t15 += v2 * b9; - t16 += v2 * b10; - t17 += v2 * b11; - t18 += v2 * b12; - t19 += v2 * b13; - t20 += v2 * b14; - t21 += v2 * b15; - v2 = a[7]; - t7 += v2 * b0; - t8 += v2 * b1; - t9 += v2 * b22; - t10 += v2 * b3; - t11 += v2 * b4; - t12 += v2 * b5; - t13 += v2 * b6; - t14 += v2 * b7; - t15 += v2 * b8; - t16 += v2 * b9; - t17 += v2 * b10; - t18 += v2 * b11; - t19 += v2 * b12; - t20 += v2 * b13; - t21 += v2 * b14; - t22 += v2 * b15; - v2 = a[8]; - t8 += v2 * b0; - t9 += v2 * b1; - t10 += v2 * b22; - t11 += v2 * b3; - t12 += v2 * b4; - t13 += v2 * b5; - t14 += v2 * b6; - t15 += v2 * b7; - t16 += v2 * b8; - t17 += v2 * b9; - t18 += v2 * b10; - t19 += v2 * b11; - t20 += v2 * b12; - t21 += v2 * b13; - t22 += v2 * b14; - t23 += v2 * b15; - v2 = a[9]; - t9 += v2 * b0; - t10 += v2 * b1; - t11 += v2 * b22; - t12 += v2 * b3; - t13 += v2 * b4; - t14 += v2 * b5; - t15 += v2 * b6; - t16 += v2 * b7; - t17 += v2 * b8; - t18 += v2 * b9; - t19 += v2 * b10; - t20 += v2 * b11; - t21 += v2 * b12; - t22 += v2 * b13; - t23 += v2 * b14; - t24 += v2 * b15; - v2 = a[10]; - t10 += v2 * b0; - t11 += v2 * b1; - t12 += v2 * b22; - t13 += v2 * b3; - t14 += v2 * b4; - t15 += v2 * b5; - t16 += v2 * b6; - t17 += v2 * b7; - t18 += v2 * b8; - t19 += v2 * b9; - t20 += v2 * b10; - t21 += v2 * b11; - t22 += v2 * b12; - t23 += v2 * b13; - t24 += v2 * b14; - t25 += v2 * b15; - v2 = a[11]; - t11 += v2 * b0; - t12 += v2 * b1; - t13 += v2 * b22; - t14 += v2 * b3; - t15 += v2 * b4; - t16 += v2 * b5; - t17 += v2 * b6; - t18 += v2 * b7; - t19 += v2 * b8; - t20 += v2 * b9; - t21 += v2 * b10; - t22 += v2 * b11; - t23 += v2 * b12; - t24 += v2 * b13; - t25 += v2 * b14; - t26 += v2 * b15; - v2 = a[12]; - t12 += v2 * b0; - t13 += v2 * b1; - t14 += v2 * b22; - t15 += v2 * b3; - t16 += v2 * b4; - t17 += v2 * b5; - t18 += v2 * b6; - t19 += v2 * b7; - t20 += v2 * b8; - t21 += v2 * b9; - t22 += v2 * b10; - t23 += v2 * b11; - t24 += v2 * b12; - t25 += v2 * b13; - t26 += v2 * b14; - t27 += v2 * b15; - v2 = a[13]; - t13 += v2 * b0; - t14 += v2 * b1; - t15 += v2 * b22; - t16 += v2 * b3; - t17 += v2 * b4; - t18 += v2 * b5; - t19 += v2 * b6; - t20 += v2 * b7; - t21 += v2 * b8; - t22 += v2 * b9; - t23 += v2 * b10; - t24 += v2 * b11; - t25 += v2 * b12; - t26 += v2 * b13; - t27 += v2 * b14; - t28 += v2 * b15; - v2 = a[14]; - t14 += v2 * b0; - t15 += v2 * b1; - t16 += v2 * b22; - t17 += v2 * b3; - t18 += v2 * b4; - t19 += v2 * b5; - t20 += v2 * b6; - t21 += v2 * b7; - t22 += v2 * b8; - t23 += v2 * b9; - t24 += v2 * b10; - t25 += v2 * b11; - t26 += v2 * b12; - t27 += v2 * b13; - t28 += v2 * b14; - t29 += v2 * b15; - v2 = a[15]; - t15 += v2 * b0; - t16 += v2 * b1; - t17 += v2 * b22; - t18 += v2 * b3; - t19 += v2 * b4; - t20 += v2 * b5; - t21 += v2 * b6; - t22 += v2 * b7; - t23 += v2 * b8; - t24 += v2 * b9; - t25 += v2 * b10; - t26 += v2 * b11; - t27 += v2 * b12; - t28 += v2 * b13; - t29 += v2 * b14; - t30 += v2 * b15; - t0 += 38 * t16; - t1 += 38 * t17; - t2 += 38 * t18; - t3 += 38 * t19; - t4 += 38 * t20; - t5 += 38 * t21; - t6 += 38 * t22; - t7 += 38 * t23; - t8 += 38 * t24; - t9 += 38 * t25; - t10 += 38 * t26; - t11 += 38 * t27; - t12 += 38 * t28; - t13 += 38 * t29; - t14 += 38 * t30; - c2 = 1; - v2 = t0 + c2 + 65535; - c2 = Math.floor(v2 / 65536); - t0 = v2 - c2 * 65536; - v2 = t1 + c2 + 65535; - c2 = Math.floor(v2 / 65536); - t1 = v2 - c2 * 65536; - v2 = t2 + c2 + 65535; - c2 = Math.floor(v2 / 65536); - t2 = v2 - c2 * 65536; - v2 = t3 + c2 + 65535; - c2 = Math.floor(v2 / 65536); - t3 = v2 - c2 * 65536; - v2 = t4 + c2 + 65535; - c2 = Math.floor(v2 / 65536); - t4 = v2 - c2 * 65536; - v2 = t5 + c2 + 65535; - c2 = Math.floor(v2 / 65536); - t5 = v2 - c2 * 65536; - v2 = t6 + c2 + 65535; - c2 = Math.floor(v2 / 65536); - t6 = v2 - c2 * 65536; - v2 = t7 + c2 + 65535; - c2 = Math.floor(v2 / 65536); - t7 = v2 - c2 * 65536; - v2 = t8 + c2 + 65535; - c2 = Math.floor(v2 / 65536); - t8 = v2 - c2 * 65536; - v2 = t9 + c2 + 65535; - c2 = Math.floor(v2 / 65536); - t9 = v2 - c2 * 65536; - v2 = t10 + c2 + 65535; - c2 = Math.floor(v2 / 65536); - t10 = v2 - c2 * 65536; - v2 = t11 + c2 + 65535; - c2 = Math.floor(v2 / 65536); - t11 = v2 - c2 * 65536; - v2 = t12 + c2 + 65535; - c2 = Math.floor(v2 / 65536); - t12 = v2 - c2 * 65536; - v2 = t13 + c2 + 65535; - c2 = Math.floor(v2 / 65536); - t13 = v2 - c2 * 65536; - v2 = t14 + c2 + 65535; - c2 = Math.floor(v2 / 65536); - t14 = v2 - c2 * 65536; - v2 = t15 + c2 + 65535; - c2 = Math.floor(v2 / 65536); - t15 = v2 - c2 * 65536; - t0 += c2 - 1 + 37 * (c2 - 1); - c2 = 1; - v2 = t0 + c2 + 65535; - c2 = Math.floor(v2 / 65536); - t0 = v2 - c2 * 65536; - v2 = t1 + c2 + 65535; - c2 = Math.floor(v2 / 65536); - t1 = v2 - c2 * 65536; - v2 = t2 + c2 + 65535; - c2 = Math.floor(v2 / 65536); - t2 = v2 - c2 * 65536; - v2 = t3 + c2 + 65535; - c2 = Math.floor(v2 / 65536); - t3 = v2 - c2 * 65536; - v2 = t4 + c2 + 65535; - c2 = Math.floor(v2 / 65536); - t4 = v2 - c2 * 65536; - v2 = t5 + c2 + 65535; - c2 = Math.floor(v2 / 65536); - t5 = v2 - c2 * 65536; - v2 = t6 + c2 + 65535; - c2 = Math.floor(v2 / 65536); - t6 = v2 - c2 * 65536; - v2 = t7 + c2 + 65535; - c2 = Math.floor(v2 / 65536); - t7 = v2 - c2 * 65536; - v2 = t8 + c2 + 65535; - c2 = Math.floor(v2 / 65536); - t8 = v2 - c2 * 65536; - v2 = t9 + c2 + 65535; - c2 = Math.floor(v2 / 65536); - t9 = v2 - c2 * 65536; - v2 = t10 + c2 + 65535; - c2 = Math.floor(v2 / 65536); - t10 = v2 - c2 * 65536; - v2 = t11 + c2 + 65535; - c2 = Math.floor(v2 / 65536); - t11 = v2 - c2 * 65536; - v2 = t12 + c2 + 65535; - c2 = Math.floor(v2 / 65536); - t12 = v2 - c2 * 65536; - v2 = t13 + c2 + 65535; - c2 = Math.floor(v2 / 65536); - t13 = v2 - c2 * 65536; - v2 = t14 + c2 + 65535; - c2 = Math.floor(v2 / 65536); - t14 = v2 - c2 * 65536; - v2 = t15 + c2 + 65535; - c2 = Math.floor(v2 / 65536); - t15 = v2 - c2 * 65536; - t0 += c2 - 1 + 37 * (c2 - 1); - o2[0] = t0; - o2[1] = t1; - o2[2] = t2; - o2[3] = t3; - o2[4] = t4; - o2[5] = t5; - o2[6] = t6; - o2[7] = t7; - o2[8] = t8; - o2[9] = t9; - o2[10] = t10; - o2[11] = t11; - o2[12] = t12; - o2[13] = t13; - o2[14] = t14; - o2[15] = t15; - } - function S2(o2, a) { - M(o2, a, a); - } - function inv25519(o2, i) { - var c2 = gf(); - var a; - for (a = 0; a < 16; a++) c2[a] = i[a]; - for (a = 253; a >= 0; a--) { - S2(c2, c2); - if (a !== 2 && a !== 4) M(c2, c2, i); - } - for (a = 0; a < 16; a++) o2[a] = c2[a]; - } - function pow2523(o2, i) { - var c2 = gf(); - var a; - for (a = 0; a < 16; a++) c2[a] = i[a]; - for (a = 250; a >= 0; a--) { - S2(c2, c2); - if (a !== 1) M(c2, c2, i); - } - for (a = 0; a < 16; a++) o2[a] = c2[a]; - } - function crypto_scalarmult(q, n, p2) { - var z = new Uint8Array(32); - var x = new Float64Array(80), r2, i; - var a = gf(), b2 = gf(), c2 = gf(), d2 = gf(), e = gf(), f2 = gf(); - for (i = 0; i < 31; i++) z[i] = n[i]; - z[31] = n[31] & 127 | 64; - z[0] &= 248; - unpack25519(x, p2); - for (i = 0; i < 16; i++) { - b2[i] = x[i]; - d2[i] = a[i] = c2[i] = 0; - } - a[0] = d2[0] = 1; - for (i = 254; i >= 0; --i) { - r2 = z[i >>> 3] >>> (i & 7) & 1; - sel25519(a, b2, r2); - sel25519(c2, d2, r2); - A(e, a, c2); - Z(a, a, c2); - A(c2, b2, d2); - Z(b2, b2, d2); - S2(d2, e); - S2(f2, a); - M(a, c2, a); - M(c2, b2, e); - A(e, a, c2); - Z(a, a, c2); - S2(b2, a); - Z(c2, d2, f2); - M(a, c2, _121665); - A(a, a, d2); - M(c2, c2, a); - M(a, d2, f2); - M(d2, b2, x); - S2(b2, e); - sel25519(a, b2, r2); - sel25519(c2, d2, r2); - } - for (i = 0; i < 16; i++) { - x[i + 16] = a[i]; - x[i + 32] = c2[i]; - x[i + 48] = b2[i]; - x[i + 64] = d2[i]; - } - var x32 = x.subarray(32); - var x16 = x.subarray(16); - inv25519(x32, x32); - M(x16, x16, x32); - pack25519(q, x16); - return 0; - } - function crypto_scalarmult_base(q, n) { - return crypto_scalarmult(q, n, _9); - } - function crypto_box_keypair(y2, x) { - randombytes(x, 32); - return crypto_scalarmult_base(y2, x); - } - function crypto_box_beforenm(k2, y2, x) { - var s = new Uint8Array(32); - crypto_scalarmult(s, x, y2); - return crypto_core_hsalsa20(k2, _0, s, sigma); - } - var crypto_box_afternm = crypto_secretbox; - var crypto_box_open_afternm = crypto_secretbox_open; - function crypto_box(c2, m2, d2, n, y2, x) { - var k2 = new Uint8Array(32); - crypto_box_beforenm(k2, y2, x); - return crypto_box_afternm(c2, m2, d2, n, k2); - } - function crypto_box_open(m2, c2, d2, n, y2, x) { - var k2 = new Uint8Array(32); - crypto_box_beforenm(k2, y2, x); - return crypto_box_open_afternm(m2, c2, d2, n, k2); - } - var K = [ - 1116352408, - 3609767458, - 1899447441, - 602891725, - 3049323471, - 3964484399, - 3921009573, - 2173295548, - 961987163, - 4081628472, - 1508970993, - 3053834265, - 2453635748, - 2937671579, - 2870763221, - 3664609560, - 3624381080, - 2734883394, - 310598401, - 1164996542, - 607225278, - 1323610764, - 1426881987, - 3590304994, - 1925078388, - 4068182383, - 2162078206, - 991336113, - 2614888103, - 633803317, - 3248222580, - 3479774868, - 3835390401, - 2666613458, - 4022224774, - 944711139, - 264347078, - 2341262773, - 604807628, - 2007800933, - 770255983, - 1495990901, - 1249150122, - 1856431235, - 1555081692, - 3175218132, - 1996064986, - 2198950837, - 2554220882, - 3999719339, - 2821834349, - 766784016, - 2952996808, - 2566594879, - 3210313671, - 3203337956, - 3336571891, - 1034457026, - 3584528711, - 2466948901, - 113926993, - 3758326383, - 338241895, - 168717936, - 666307205, - 1188179964, - 773529912, - 1546045734, - 1294757372, - 1522805485, - 1396182291, - 2643833823, - 1695183700, - 2343527390, - 1986661051, - 1014477480, - 2177026350, - 1206759142, - 2456956037, - 344077627, - 2730485921, - 1290863460, - 2820302411, - 3158454273, - 3259730800, - 3505952657, - 3345764771, - 106217008, - 3516065817, - 3606008344, - 3600352804, - 1432725776, - 4094571909, - 1467031594, - 275423344, - 851169720, - 430227734, - 3100823752, - 506948616, - 1363258195, - 659060556, - 3750685593, - 883997877, - 3785050280, - 958139571, - 3318307427, - 1322822218, - 3812723403, - 1537002063, - 2003034995, - 1747873779, - 3602036899, - 1955562222, - 1575990012, - 2024104815, - 1125592928, - 2227730452, - 2716904306, - 2361852424, - 442776044, - 2428436474, - 593698344, - 2756734187, - 3733110249, - 3204031479, - 2999351573, - 3329325298, - 3815920427, - 3391569614, - 3928383900, - 3515267271, - 566280711, - 3940187606, - 3454069534, - 4118630271, - 4000239992, - 116418474, - 1914138554, - 174292421, - 2731055270, - 289380356, - 3203993006, - 460393269, - 320620315, - 685471733, - 587496836, - 852142971, - 1086792851, - 1017036298, - 365543100, - 1126000580, - 2618297676, - 1288033470, - 3409855158, - 1501505948, - 4234509866, - 1607167915, - 987167468, - 1816402316, - 1246189591 - ]; - function crypto_hashblocks_hl(hh, hl, m2, n) { - var wh = new Int32Array(16), wl = new Int32Array(16), bh0, bh1, bh2, bh3, bh4, bh5, bh6, bh7, bl0, bl1, bl2, bl3, bl4, bl5, bl6, bl7, th, tl, i, j, h3, l2, a, b2, c2, d2; - var ah0 = hh[0], ah1 = hh[1], ah2 = hh[2], ah3 = hh[3], ah4 = hh[4], ah5 = hh[5], ah6 = hh[6], ah7 = hh[7], al0 = hl[0], al1 = hl[1], al2 = hl[2], al3 = hl[3], al4 = hl[4], al5 = hl[5], al6 = hl[6], al7 = hl[7]; - var pos = 0; - while (n >= 128) { - for (i = 0; i < 16; i++) { - j = 8 * i + pos; - wh[i] = m2[j + 0] << 24 | m2[j + 1] << 16 | m2[j + 2] << 8 | m2[j + 3]; - wl[i] = m2[j + 4] << 24 | m2[j + 5] << 16 | m2[j + 6] << 8 | m2[j + 7]; - } - for (i = 0; i < 80; i++) { - bh0 = ah0; - bh1 = ah1; - bh2 = ah2; - bh3 = ah3; - bh4 = ah4; - bh5 = ah5; - bh6 = ah6; - bh7 = ah7; - bl0 = al0; - bl1 = al1; - bl2 = al2; - bl3 = al3; - bl4 = al4; - bl5 = al5; - bl6 = al6; - bl7 = al7; - h3 = ah7; - l2 = al7; - a = l2 & 65535; - b2 = l2 >>> 16; - c2 = h3 & 65535; - d2 = h3 >>> 16; - h3 = (ah4 >>> 14 | al4 << 32 - 14) ^ (ah4 >>> 18 | al4 << 32 - 18) ^ (al4 >>> 41 - 32 | ah4 << 32 - (41 - 32)); - l2 = (al4 >>> 14 | ah4 << 32 - 14) ^ (al4 >>> 18 | ah4 << 32 - 18) ^ (ah4 >>> 41 - 32 | al4 << 32 - (41 - 32)); - a += l2 & 65535; - b2 += l2 >>> 16; - c2 += h3 & 65535; - d2 += h3 >>> 16; - h3 = ah4 & ah5 ^ ~ah4 & ah6; - l2 = al4 & al5 ^ ~al4 & al6; - a += l2 & 65535; - b2 += l2 >>> 16; - c2 += h3 & 65535; - d2 += h3 >>> 16; - h3 = K[i * 2]; - l2 = K[i * 2 + 1]; - a += l2 & 65535; - b2 += l2 >>> 16; - c2 += h3 & 65535; - d2 += h3 >>> 16; - h3 = wh[i % 16]; - l2 = wl[i % 16]; - a += l2 & 65535; - b2 += l2 >>> 16; - c2 += h3 & 65535; - d2 += h3 >>> 16; - b2 += a >>> 16; - c2 += b2 >>> 16; - d2 += c2 >>> 16; - th = c2 & 65535 | d2 << 16; - tl = a & 65535 | b2 << 16; - h3 = th; - l2 = tl; - a = l2 & 65535; - b2 = l2 >>> 16; - c2 = h3 & 65535; - d2 = h3 >>> 16; - h3 = (ah0 >>> 28 | al0 << 32 - 28) ^ (al0 >>> 34 - 32 | ah0 << 32 - (34 - 32)) ^ (al0 >>> 39 - 32 | ah0 << 32 - (39 - 32)); - l2 = (al0 >>> 28 | ah0 << 32 - 28) ^ (ah0 >>> 34 - 32 | al0 << 32 - (34 - 32)) ^ (ah0 >>> 39 - 32 | al0 << 32 - (39 - 32)); - a += l2 & 65535; - b2 += l2 >>> 16; - c2 += h3 & 65535; - d2 += h3 >>> 16; - h3 = ah0 & ah1 ^ ah0 & ah2 ^ ah1 & ah2; - l2 = al0 & al1 ^ al0 & al2 ^ al1 & al2; - a += l2 & 65535; - b2 += l2 >>> 16; - c2 += h3 & 65535; - d2 += h3 >>> 16; - b2 += a >>> 16; - c2 += b2 >>> 16; - d2 += c2 >>> 16; - bh7 = c2 & 65535 | d2 << 16; - bl7 = a & 65535 | b2 << 16; - h3 = bh3; - l2 = bl3; - a = l2 & 65535; - b2 = l2 >>> 16; - c2 = h3 & 65535; - d2 = h3 >>> 16; - h3 = th; - l2 = tl; - a += l2 & 65535; - b2 += l2 >>> 16; - c2 += h3 & 65535; - d2 += h3 >>> 16; - b2 += a >>> 16; - c2 += b2 >>> 16; - d2 += c2 >>> 16; - bh3 = c2 & 65535 | d2 << 16; - bl3 = a & 65535 | b2 << 16; - ah1 = bh0; - ah2 = bh1; - ah3 = bh2; - ah4 = bh3; - ah5 = bh4; - ah6 = bh5; - ah7 = bh6; - ah0 = bh7; - al1 = bl0; - al2 = bl1; - al3 = bl2; - al4 = bl3; - al5 = bl4; - al6 = bl5; - al7 = bl6; - al0 = bl7; - if (i % 16 === 15) { - for (j = 0; j < 16; j++) { - h3 = wh[j]; - l2 = wl[j]; - a = l2 & 65535; - b2 = l2 >>> 16; - c2 = h3 & 65535; - d2 = h3 >>> 16; - h3 = wh[(j + 9) % 16]; - l2 = wl[(j + 9) % 16]; - a += l2 & 65535; - b2 += l2 >>> 16; - c2 += h3 & 65535; - d2 += h3 >>> 16; - th = wh[(j + 1) % 16]; - tl = wl[(j + 1) % 16]; - h3 = (th >>> 1 | tl << 32 - 1) ^ (th >>> 8 | tl << 32 - 8) ^ th >>> 7; - l2 = (tl >>> 1 | th << 32 - 1) ^ (tl >>> 8 | th << 32 - 8) ^ (tl >>> 7 | th << 32 - 7); - a += l2 & 65535; - b2 += l2 >>> 16; - c2 += h3 & 65535; - d2 += h3 >>> 16; - th = wh[(j + 14) % 16]; - tl = wl[(j + 14) % 16]; - h3 = (th >>> 19 | tl << 32 - 19) ^ (tl >>> 61 - 32 | th << 32 - (61 - 32)) ^ th >>> 6; - l2 = (tl >>> 19 | th << 32 - 19) ^ (th >>> 61 - 32 | tl << 32 - (61 - 32)) ^ (tl >>> 6 | th << 32 - 6); - a += l2 & 65535; - b2 += l2 >>> 16; - c2 += h3 & 65535; - d2 += h3 >>> 16; - b2 += a >>> 16; - c2 += b2 >>> 16; - d2 += c2 >>> 16; - wh[j] = c2 & 65535 | d2 << 16; - wl[j] = a & 65535 | b2 << 16; - } - } - } - h3 = ah0; - l2 = al0; - a = l2 & 65535; - b2 = l2 >>> 16; - c2 = h3 & 65535; - d2 = h3 >>> 16; - h3 = hh[0]; - l2 = hl[0]; - a += l2 & 65535; - b2 += l2 >>> 16; - c2 += h3 & 65535; - d2 += h3 >>> 16; - b2 += a >>> 16; - c2 += b2 >>> 16; - d2 += c2 >>> 16; - hh[0] = ah0 = c2 & 65535 | d2 << 16; - hl[0] = al0 = a & 65535 | b2 << 16; - h3 = ah1; - l2 = al1; - a = l2 & 65535; - b2 = l2 >>> 16; - c2 = h3 & 65535; - d2 = h3 >>> 16; - h3 = hh[1]; - l2 = hl[1]; - a += l2 & 65535; - b2 += l2 >>> 16; - c2 += h3 & 65535; - d2 += h3 >>> 16; - b2 += a >>> 16; - c2 += b2 >>> 16; - d2 += c2 >>> 16; - hh[1] = ah1 = c2 & 65535 | d2 << 16; - hl[1] = al1 = a & 65535 | b2 << 16; - h3 = ah2; - l2 = al2; - a = l2 & 65535; - b2 = l2 >>> 16; - c2 = h3 & 65535; - d2 = h3 >>> 16; - h3 = hh[2]; - l2 = hl[2]; - a += l2 & 65535; - b2 += l2 >>> 16; - c2 += h3 & 65535; - d2 += h3 >>> 16; - b2 += a >>> 16; - c2 += b2 >>> 16; - d2 += c2 >>> 16; - hh[2] = ah2 = c2 & 65535 | d2 << 16; - hl[2] = al2 = a & 65535 | b2 << 16; - h3 = ah3; - l2 = al3; - a = l2 & 65535; - b2 = l2 >>> 16; - c2 = h3 & 65535; - d2 = h3 >>> 16; - h3 = hh[3]; - l2 = hl[3]; - a += l2 & 65535; - b2 += l2 >>> 16; - c2 += h3 & 65535; - d2 += h3 >>> 16; - b2 += a >>> 16; - c2 += b2 >>> 16; - d2 += c2 >>> 16; - hh[3] = ah3 = c2 & 65535 | d2 << 16; - hl[3] = al3 = a & 65535 | b2 << 16; - h3 = ah4; - l2 = al4; - a = l2 & 65535; - b2 = l2 >>> 16; - c2 = h3 & 65535; - d2 = h3 >>> 16; - h3 = hh[4]; - l2 = hl[4]; - a += l2 & 65535; - b2 += l2 >>> 16; - c2 += h3 & 65535; - d2 += h3 >>> 16; - b2 += a >>> 16; - c2 += b2 >>> 16; - d2 += c2 >>> 16; - hh[4] = ah4 = c2 & 65535 | d2 << 16; - hl[4] = al4 = a & 65535 | b2 << 16; - h3 = ah5; - l2 = al5; - a = l2 & 65535; - b2 = l2 >>> 16; - c2 = h3 & 65535; - d2 = h3 >>> 16; - h3 = hh[5]; - l2 = hl[5]; - a += l2 & 65535; - b2 += l2 >>> 16; - c2 += h3 & 65535; - d2 += h3 >>> 16; - b2 += a >>> 16; - c2 += b2 >>> 16; - d2 += c2 >>> 16; - hh[5] = ah5 = c2 & 65535 | d2 << 16; - hl[5] = al5 = a & 65535 | b2 << 16; - h3 = ah6; - l2 = al6; - a = l2 & 65535; - b2 = l2 >>> 16; - c2 = h3 & 65535; - d2 = h3 >>> 16; - h3 = hh[6]; - l2 = hl[6]; - a += l2 & 65535; - b2 += l2 >>> 16; - c2 += h3 & 65535; - d2 += h3 >>> 16; - b2 += a >>> 16; - c2 += b2 >>> 16; - d2 += c2 >>> 16; - hh[6] = ah6 = c2 & 65535 | d2 << 16; - hl[6] = al6 = a & 65535 | b2 << 16; - h3 = ah7; - l2 = al7; - a = l2 & 65535; - b2 = l2 >>> 16; - c2 = h3 & 65535; - d2 = h3 >>> 16; - h3 = hh[7]; - l2 = hl[7]; - a += l2 & 65535; - b2 += l2 >>> 16; - c2 += h3 & 65535; - d2 += h3 >>> 16; - b2 += a >>> 16; - c2 += b2 >>> 16; - d2 += c2 >>> 16; - hh[7] = ah7 = c2 & 65535 | d2 << 16; - hl[7] = al7 = a & 65535 | b2 << 16; - pos += 128; - n -= 128; - } - return n; - } - function crypto_hash(out, m2, n) { - var hh = new Int32Array(8), hl = new Int32Array(8), x = new Uint8Array(256), i, b2 = n; - hh[0] = 1779033703; - hh[1] = 3144134277; - hh[2] = 1013904242; - hh[3] = 2773480762; - hh[4] = 1359893119; - hh[5] = 2600822924; - hh[6] = 528734635; - hh[7] = 1541459225; - hl[0] = 4089235720; - hl[1] = 2227873595; - hl[2] = 4271175723; - hl[3] = 1595750129; - hl[4] = 2917565137; - hl[5] = 725511199; - hl[6] = 4215389547; - hl[7] = 327033209; - crypto_hashblocks_hl(hh, hl, m2, n); - n %= 128; - for (i = 0; i < n; i++) x[i] = m2[b2 - n + i]; - x[n] = 128; - n = 256 - 128 * (n < 112 ? 1 : 0); - x[n - 9] = 0; - ts64(x, n - 8, b2 / 536870912 | 0, b2 << 3); - crypto_hashblocks_hl(hh, hl, x, n); - for (i = 0; i < 8; i++) ts64(out, 8 * i, hh[i], hl[i]); - return 0; - } - function add(p2, q) { - var a = gf(), b2 = gf(), c2 = gf(), d2 = gf(), e = gf(), f2 = gf(), g2 = gf(), h3 = gf(), t = gf(); - Z(a, p2[1], p2[0]); - Z(t, q[1], q[0]); - M(a, a, t); - A(b2, p2[0], p2[1]); - A(t, q[0], q[1]); - M(b2, b2, t); - M(c2, p2[3], q[3]); - M(c2, c2, D2); - M(d2, p2[2], q[2]); - A(d2, d2, d2); - Z(e, b2, a); - Z(f2, d2, c2); - A(g2, d2, c2); - A(h3, b2, a); - M(p2[0], e, f2); - M(p2[1], h3, g2); - M(p2[2], g2, f2); - M(p2[3], e, h3); - } - function cswap(p2, q, b2) { - var i; - for (i = 0; i < 4; i++) { - sel25519(p2[i], q[i], b2); - } - } - function pack(r2, p2) { - var tx = gf(), ty = gf(), zi = gf(); - inv25519(zi, p2[2]); - M(tx, p2[0], zi); - M(ty, p2[1], zi); - pack25519(r2, ty); - r2[31] ^= par25519(tx) << 7; - } - function scalarmult(p2, q, s) { - var b2, i; - set25519(p2[0], gf0); - set25519(p2[1], gf1); - set25519(p2[2], gf1); - set25519(p2[3], gf0); - for (i = 255; i >= 0; --i) { - b2 = s[i / 8 | 0] >> (i & 7) & 1; - cswap(p2, q, b2); - add(q, p2); - add(p2, p2); - cswap(p2, q, b2); - } - } - function scalarbase(p2, s) { - var q = [gf(), gf(), gf(), gf()]; - set25519(q[0], X); - set25519(q[1], Y); - set25519(q[2], gf1); - M(q[3], X, Y); - scalarmult(p2, q, s); - } - function crypto_sign_keypair(pk, sk, seeded) { - var d2 = new Uint8Array(64); - var p2 = [gf(), gf(), gf(), gf()]; - var i; - if (!seeded) randombytes(sk, 32); - crypto_hash(d2, sk, 32); - d2[0] &= 248; - d2[31] &= 127; - d2[31] |= 64; - scalarbase(p2, d2); - pack(pk, p2); - for (i = 0; i < 32; i++) sk[i + 32] = pk[i]; - return 0; - } - var L = new Float64Array([237, 211, 245, 92, 26, 99, 18, 88, 214, 156, 247, 162, 222, 249, 222, 20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 16]); - function modL(r2, x) { - var carry, i, j, k2; - for (i = 63; i >= 32; --i) { - carry = 0; - for (j = i - 32, k2 = i - 12; j < k2; ++j) { - x[j] += carry - 16 * x[i] * L[j - (i - 32)]; - carry = Math.floor((x[j] + 128) / 256); - x[j] -= carry * 256; - } - x[j] += carry; - x[i] = 0; - } - carry = 0; - for (j = 0; j < 32; j++) { - x[j] += carry - (x[31] >> 4) * L[j]; - carry = x[j] >> 8; - x[j] &= 255; - } - for (j = 0; j < 32; j++) x[j] -= carry * L[j]; - for (i = 0; i < 32; i++) { - x[i + 1] += x[i] >> 8; - r2[i] = x[i] & 255; - } - } - function reduce(r2) { - var x = new Float64Array(64), i; - for (i = 0; i < 64; i++) x[i] = r2[i]; - for (i = 0; i < 64; i++) r2[i] = 0; - modL(r2, x); - } - function crypto_sign(sm, m2, n, sk) { - var d2 = new Uint8Array(64), h3 = new Uint8Array(64), r2 = new Uint8Array(64); - var i, j, x = new Float64Array(64); - var p2 = [gf(), gf(), gf(), gf()]; - crypto_hash(d2, sk, 32); - d2[0] &= 248; - d2[31] &= 127; - d2[31] |= 64; - var smlen = n + 64; - for (i = 0; i < n; i++) sm[64 + i] = m2[i]; - for (i = 0; i < 32; i++) sm[32 + i] = d2[32 + i]; - crypto_hash(r2, sm.subarray(32), n + 32); - reduce(r2); - scalarbase(p2, r2); - pack(sm, p2); - for (i = 32; i < 64; i++) sm[i] = sk[i]; - crypto_hash(h3, sm, n + 64); - reduce(h3); - for (i = 0; i < 64; i++) x[i] = 0; - for (i = 0; i < 32; i++) x[i] = r2[i]; - for (i = 0; i < 32; i++) { - for (j = 0; j < 32; j++) { - x[i + j] += h3[i] * d2[j]; - } - } - modL(sm.subarray(32), x); - return smlen; - } - function unpackneg(r2, p2) { - var t = gf(), chk = gf(), num = gf(), den = gf(), den2 = gf(), den4 = gf(), den6 = gf(); - set25519(r2[2], gf1); - unpack25519(r2[1], p2); - S2(num, r2[1]); - M(den, num, D); - Z(num, num, r2[2]); - A(den, r2[2], den); - S2(den2, den); - S2(den4, den2); - M(den6, den4, den2); - M(t, den6, num); - M(t, t, den); - pow2523(t, t); - M(t, t, num); - M(t, t, den); - M(t, t, den); - M(r2[0], t, den); - S2(chk, r2[0]); - M(chk, chk, den); - if (neq25519(chk, num)) M(r2[0], r2[0], I); - S2(chk, r2[0]); - M(chk, chk, den); - if (neq25519(chk, num)) return -1; - if (par25519(r2[0]) === p2[31] >> 7) Z(r2[0], gf0, r2[0]); - M(r2[3], r2[0], r2[1]); - return 0; - } - function crypto_sign_open(m2, sm, n, pk) { - var i; - var t = new Uint8Array(32), h3 = new Uint8Array(64); - var p2 = [gf(), gf(), gf(), gf()], q = [gf(), gf(), gf(), gf()]; - if (n < 64) return -1; - if (unpackneg(q, pk)) return -1; - for (i = 0; i < n; i++) m2[i] = sm[i]; - for (i = 0; i < 32; i++) m2[i + 32] = pk[i]; - crypto_hash(h3, m2, n); - reduce(h3); - scalarmult(p2, q, h3); - scalarbase(q, sm.subarray(32)); - add(p2, q); - pack(t, p2); - n -= 64; - if (crypto_verify_32(sm, 0, t, 0)) { - for (i = 0; i < n; i++) m2[i] = 0; - return -1; - } - for (i = 0; i < n; i++) m2[i] = sm[i + 64]; - return n; - } - var crypto_secretbox_KEYBYTES = 32, crypto_secretbox_NONCEBYTES = 24, crypto_secretbox_ZEROBYTES = 32, crypto_secretbox_BOXZEROBYTES = 16, crypto_scalarmult_BYTES = 32, crypto_scalarmult_SCALARBYTES = 32, crypto_box_PUBLICKEYBYTES = 32, crypto_box_SECRETKEYBYTES = 32, crypto_box_BEFORENMBYTES = 32, crypto_box_NONCEBYTES = crypto_secretbox_NONCEBYTES, crypto_box_ZEROBYTES = crypto_secretbox_ZEROBYTES, crypto_box_BOXZEROBYTES = crypto_secretbox_BOXZEROBYTES, crypto_sign_BYTES = 64, crypto_sign_PUBLICKEYBYTES = 32, crypto_sign_SECRETKEYBYTES = 64, crypto_sign_SEEDBYTES = 32, crypto_hash_BYTES = 64; - nacl.lowlevel = { - crypto_core_hsalsa20, - crypto_stream_xor, - crypto_stream, - crypto_stream_salsa20_xor, - crypto_stream_salsa20, - crypto_onetimeauth, - crypto_onetimeauth_verify, - crypto_verify_16, - crypto_verify_32, - crypto_secretbox, - crypto_secretbox_open, - crypto_scalarmult, - crypto_scalarmult_base, - crypto_box_beforenm, - crypto_box_afternm, - crypto_box, - crypto_box_open, - crypto_box_keypair, - crypto_hash, - crypto_sign, - crypto_sign_keypair, - crypto_sign_open, - crypto_secretbox_KEYBYTES, - crypto_secretbox_NONCEBYTES, - crypto_secretbox_ZEROBYTES, - crypto_secretbox_BOXZEROBYTES, - crypto_scalarmult_BYTES, - crypto_scalarmult_SCALARBYTES, - crypto_box_PUBLICKEYBYTES, - crypto_box_SECRETKEYBYTES, - crypto_box_BEFORENMBYTES, - crypto_box_NONCEBYTES, - crypto_box_ZEROBYTES, - crypto_box_BOXZEROBYTES, - crypto_sign_BYTES, - crypto_sign_PUBLICKEYBYTES, - crypto_sign_SECRETKEYBYTES, - crypto_sign_SEEDBYTES, - crypto_hash_BYTES, - gf, - D, - L, - pack25519, - unpack25519, - M, - A, - S: S2, - Z, - pow2523, - add, - set25519, - modL, - scalarmult, - scalarbase - }; - function checkLengths(k2, n) { - if (k2.length !== crypto_secretbox_KEYBYTES) throw new Error("bad key size"); - if (n.length !== crypto_secretbox_NONCEBYTES) throw new Error("bad nonce size"); - } - function checkBoxLengths(pk, sk) { - if (pk.length !== crypto_box_PUBLICKEYBYTES) throw new Error("bad public key size"); - if (sk.length !== crypto_box_SECRETKEYBYTES) throw new Error("bad secret key size"); - } - function checkArrayTypes() { - for (var i = 0; i < arguments.length; i++) { - if (!(arguments[i] instanceof Uint8Array)) - throw new TypeError("unexpected type, use Uint8Array"); - } - } - function cleanup(arr) { - for (var i = 0; i < arr.length; i++) arr[i] = 0; - } - nacl.randomBytes = function(n) { - var b2 = new Uint8Array(n); - randombytes(b2, n); - return b2; - }; - nacl.secretbox = function(msg, nonce, key) { - checkArrayTypes(msg, nonce, key); - checkLengths(key, nonce); - var m2 = new Uint8Array(crypto_secretbox_ZEROBYTES + msg.length); - var c2 = new Uint8Array(m2.length); - for (var i = 0; i < msg.length; i++) m2[i + crypto_secretbox_ZEROBYTES] = msg[i]; - crypto_secretbox(c2, m2, m2.length, nonce, key); - return c2.subarray(crypto_secretbox_BOXZEROBYTES); - }; - nacl.secretbox.open = function(box, nonce, key) { - checkArrayTypes(box, nonce, key); - checkLengths(key, nonce); - var c2 = new Uint8Array(crypto_secretbox_BOXZEROBYTES + box.length); - var m2 = new Uint8Array(c2.length); - for (var i = 0; i < box.length; i++) c2[i + crypto_secretbox_BOXZEROBYTES] = box[i]; - if (c2.length < 32) return null; - if (crypto_secretbox_open(m2, c2, c2.length, nonce, key) !== 0) return null; - return m2.subarray(crypto_secretbox_ZEROBYTES); - }; - nacl.secretbox.keyLength = crypto_secretbox_KEYBYTES; - nacl.secretbox.nonceLength = crypto_secretbox_NONCEBYTES; - nacl.secretbox.overheadLength = crypto_secretbox_BOXZEROBYTES; - nacl.scalarMult = function(n, p2) { - checkArrayTypes(n, p2); - if (n.length !== crypto_scalarmult_SCALARBYTES) throw new Error("bad n size"); - if (p2.length !== crypto_scalarmult_BYTES) throw new Error("bad p size"); - var q = new Uint8Array(crypto_scalarmult_BYTES); - crypto_scalarmult(q, n, p2); - return q; - }; - nacl.scalarMult.base = function(n) { - checkArrayTypes(n); - if (n.length !== crypto_scalarmult_SCALARBYTES) throw new Error("bad n size"); - var q = new Uint8Array(crypto_scalarmult_BYTES); - crypto_scalarmult_base(q, n); - return q; - }; - nacl.scalarMult.scalarLength = crypto_scalarmult_SCALARBYTES; - nacl.scalarMult.groupElementLength = crypto_scalarmult_BYTES; - nacl.box = function(msg, nonce, publicKey, secretKey) { - var k2 = nacl.box.before(publicKey, secretKey); - return nacl.secretbox(msg, nonce, k2); - }; - nacl.box.before = function(publicKey, secretKey) { - checkArrayTypes(publicKey, secretKey); - checkBoxLengths(publicKey, secretKey); - var k2 = new Uint8Array(crypto_box_BEFORENMBYTES); - crypto_box_beforenm(k2, publicKey, secretKey); - return k2; - }; - nacl.box.after = nacl.secretbox; - nacl.box.open = function(msg, nonce, publicKey, secretKey) { - var k2 = nacl.box.before(publicKey, secretKey); - return nacl.secretbox.open(msg, nonce, k2); - }; - nacl.box.open.after = nacl.secretbox.open; - nacl.box.keyPair = function() { - var pk = new Uint8Array(crypto_box_PUBLICKEYBYTES); - var sk = new Uint8Array(crypto_box_SECRETKEYBYTES); - crypto_box_keypair(pk, sk); - return { publicKey: pk, secretKey: sk }; - }; - nacl.box.keyPair.fromSecretKey = function(secretKey) { - checkArrayTypes(secretKey); - if (secretKey.length !== crypto_box_SECRETKEYBYTES) - throw new Error("bad secret key size"); - var pk = new Uint8Array(crypto_box_PUBLICKEYBYTES); - crypto_scalarmult_base(pk, secretKey); - return { publicKey: pk, secretKey: new Uint8Array(secretKey) }; - }; - nacl.box.publicKeyLength = crypto_box_PUBLICKEYBYTES; - nacl.box.secretKeyLength = crypto_box_SECRETKEYBYTES; - nacl.box.sharedKeyLength = crypto_box_BEFORENMBYTES; - nacl.box.nonceLength = crypto_box_NONCEBYTES; - nacl.box.overheadLength = nacl.secretbox.overheadLength; - nacl.sign = function(msg, secretKey) { - checkArrayTypes(msg, secretKey); - if (secretKey.length !== crypto_sign_SECRETKEYBYTES) - throw new Error("bad secret key size"); - var signedMsg = new Uint8Array(crypto_sign_BYTES + msg.length); - crypto_sign(signedMsg, msg, msg.length, secretKey); - return signedMsg; - }; - nacl.sign.open = function(signedMsg, publicKey) { - checkArrayTypes(signedMsg, publicKey); - if (publicKey.length !== crypto_sign_PUBLICKEYBYTES) - throw new Error("bad public key size"); - var tmp = new Uint8Array(signedMsg.length); - var mlen = crypto_sign_open(tmp, signedMsg, signedMsg.length, publicKey); - if (mlen < 0) return null; - var m2 = new Uint8Array(mlen); - for (var i = 0; i < m2.length; i++) m2[i] = tmp[i]; - return m2; - }; - nacl.sign.detached = function(msg, secretKey) { - var signedMsg = nacl.sign(msg, secretKey); - var sig = new Uint8Array(crypto_sign_BYTES); - for (var i = 0; i < sig.length; i++) sig[i] = signedMsg[i]; - return sig; - }; - nacl.sign.detached.verify = function(msg, sig, publicKey) { - checkArrayTypes(msg, sig, publicKey); - if (sig.length !== crypto_sign_BYTES) - throw new Error("bad signature size"); - if (publicKey.length !== crypto_sign_PUBLICKEYBYTES) - throw new Error("bad public key size"); - var sm = new Uint8Array(crypto_sign_BYTES + msg.length); - var m2 = new Uint8Array(crypto_sign_BYTES + msg.length); - var i; - for (i = 0; i < crypto_sign_BYTES; i++) sm[i] = sig[i]; - for (i = 0; i < msg.length; i++) sm[i + crypto_sign_BYTES] = msg[i]; - return crypto_sign_open(m2, sm, sm.length, publicKey) >= 0; - }; - nacl.sign.keyPair = function() { - var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES); - var sk = new Uint8Array(crypto_sign_SECRETKEYBYTES); - crypto_sign_keypair(pk, sk); - return { publicKey: pk, secretKey: sk }; - }; - nacl.sign.keyPair.fromSecretKey = function(secretKey) { - checkArrayTypes(secretKey); - if (secretKey.length !== crypto_sign_SECRETKEYBYTES) - throw new Error("bad secret key size"); - var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES); - for (var i = 0; i < pk.length; i++) pk[i] = secretKey[32 + i]; - return { publicKey: pk, secretKey: new Uint8Array(secretKey) }; - }; - nacl.sign.keyPair.fromSeed = function(seed) { - checkArrayTypes(seed); - if (seed.length !== crypto_sign_SEEDBYTES) - throw new Error("bad seed size"); - var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES); - var sk = new Uint8Array(crypto_sign_SECRETKEYBYTES); - for (var i = 0; i < 32; i++) sk[i] = seed[i]; - crypto_sign_keypair(pk, sk, true); - return { publicKey: pk, secretKey: sk }; - }; - nacl.sign.publicKeyLength = crypto_sign_PUBLICKEYBYTES; - nacl.sign.secretKeyLength = crypto_sign_SECRETKEYBYTES; - nacl.sign.seedLength = crypto_sign_SEEDBYTES; - nacl.sign.signatureLength = crypto_sign_BYTES; - nacl.hash = function(msg) { - checkArrayTypes(msg); - var h3 = new Uint8Array(crypto_hash_BYTES); - crypto_hash(h3, msg, msg.length); - return h3; - }; - nacl.hash.hashLength = crypto_hash_BYTES; - nacl.verify = function(x, y2) { - checkArrayTypes(x, y2); - if (x.length === 0 || y2.length === 0) return false; - if (x.length !== y2.length) return false; - return vn(x, 0, y2, 0, x.length) === 0 ? true : false; - }; - nacl.setPRNG = function(fn) { - randombytes = fn; - }; - (function() { - var crypto = typeof self !== "undefined" ? self.crypto || self.msCrypto : null; - if (crypto && crypto.getRandomValues) { - var QUOTA = 65536; - nacl.setPRNG(function(x, n) { - var i, v2 = new Uint8Array(n); - for (i = 0; i < n; i += QUOTA) { - crypto.getRandomValues(v2.subarray(i, i + Math.min(n - i, QUOTA))); - } - for (i = 0; i < n; i++) x[i] = v2[i]; - cleanup(v2); - }); - } else { - crypto = __webpack_require__2(982); - if (crypto && crypto.randomBytes) { - nacl.setPRNG(function(x, n) { - var i, v2 = crypto.randomBytes(n); - for (i = 0; i < n; i++) x[i] = v2[i]; - cleanup(v2); - }); - } - } - })(); - })(module2.exports ? module2.exports : self.nacl = self.nacl || {}); - }, - /***/ - 41(module2, __unused_webpack_exports, __webpack_require__2) { - var Base = __webpack_require__2(369), Client = __webpack_require__2(483), Server = __webpack_require__2(983); - var Driver = { - client: function(url, options) { - options = options || {}; - if (options.masking === void 0) options.masking = true; - return new Client(url, options); - }, - server: function(options) { - options = options || {}; - if (options.requireMasking === void 0) options.requireMasking = true; - return new Server(options); - }, - http: function() { - return Server.http.apply(Server, arguments); - }, - isSecureRequest: function(request) { - return Server.isSecureRequest(request); - }, - isWebSocket: function(request) { - return Base.isWebSocket(request); - }, - validateOptions: function(options, validKeys) { - Base.validateOptions(options, validKeys); - } - }; - module2.exports = Driver; - }, - /***/ - 369(module2, __unused_webpack_exports, __webpack_require__2) { - var Buffer2 = __webpack_require__2(891).Buffer, Emitter = __webpack_require__2(434).EventEmitter, util = __webpack_require__2(23), streams = __webpack_require__2(578), Headers = __webpack_require__2(160), Reader = __webpack_require__2(212); - var Base = function(request, url, options) { - Emitter.call(this); - Base.validateOptions(options || {}, ["maxLength", "masking", "requireMasking", "protocols"]); - this._request = request; - this._reader = new Reader(); - this._options = options || {}; - this._maxLength = this._options.maxLength || this.MAX_LENGTH; - this._headers = new Headers(); - this.__queue = []; - this.readyState = 0; - this.url = url; - this.io = new streams.IO(this); - this.messages = new streams.Messages(this); - this._bindEventListeners(); - }; - util.inherits(Base, Emitter); - Base.isWebSocket = function(request) { - var connection = request.headers.connection || "", upgrade = request.headers.upgrade || ""; - return request.method === "GET" && connection.toLowerCase().split(/ *, */).indexOf("upgrade") >= 0 && upgrade.toLowerCase() === "websocket"; - }; - Base.validateOptions = function(options, validKeys) { - for (var key2 in options) { - if (validKeys.indexOf(key2) < 0) - throw new Error("Unrecognized option: " + key2); - } - }; - var instance = { - // This is 64MB, small enough for an average VPS to handle without - // crashing from process out of memory - MAX_LENGTH: 67108863, - STATES: ["connecting", "open", "closing", "closed"], - _bindEventListeners: function() { - var self2 = this; - this.messages.on("error", function() { - }); - this.on("message", function(event) { - var messages = self2.messages; - if (messages.readable) messages.emit("data", event.data); - }); - this.on("error", function(error) { - var messages = self2.messages; - if (messages.readable) messages.emit("error", error); - }); - this.on("close", function() { - var messages = self2.messages; - if (!messages.readable) return; - messages.readable = messages.writable = false; - messages.emit("end"); - }); - }, - getState: function() { - return this.STATES[this.readyState] || null; - }, - addExtension: function(extension) { - return false; - }, - setHeader: function(name, value) { - if (this.readyState > 0) return false; - this._headers.set(name, value); - return true; - }, - start: function() { - if (this.readyState !== 0) return false; - if (!Base.isWebSocket(this._request)) - return this._failHandshake(new Error("Not a WebSocket request")); - var response; - try { - response = this._handshakeResponse(); - } catch (error) { - return this._failHandshake(error); - } - this._write(response); - if (this._stage !== -1) this._open(); - return true; - }, - _failHandshake: function(error) { - var headers = new Headers(); - headers.set("Content-Type", "text/plain"); - headers.set("Content-Length", Buffer2.byteLength(error.message, "utf8")); - headers = ["HTTP/1.1 400 Bad Request", headers.toString(), error.message]; - this._write(Buffer2.from(headers.join("\r\n"), "utf8")); - this._fail("protocol_error", error.message); - return false; - }, - text: function(message) { - return this.frame(message); - }, - binary: function(message) { - return false; - }, - ping: function() { - return false; - }, - pong: function() { - return false; - }, - close: function(reason, code) { - if (this.readyState !== 1) return false; - this.readyState = 3; - this.emit("close", new Base.CloseEvent(null, null)); - return true; - }, - _open: function() { - this.readyState = 1; - this.__queue.forEach(function(args) { - this.frame.apply(this, args); - }, this); - this.__queue = []; - this.emit("open", new Base.OpenEvent()); - }, - _queue: function(message) { - this.__queue.push(message); - return true; - }, - _write: function(chunk) { - var io = this.io; - if (io.readable) io.emit("data", chunk); - }, - _fail: function(type, message) { - this.readyState = 2; - this.emit("error", new Error(message)); - this.close(); - } - }; - for (var key in instance) - Base.prototype[key] = instance[key]; - Base.ConnectEvent = function() { - }; - Base.OpenEvent = function() { - }; - Base.CloseEvent = function(code, reason) { - this.code = code; - this.reason = reason; - }; - Base.MessageEvent = function(data) { - this.data = data; - }; - Base.PingEvent = function(data) { - this.data = data; - }; - Base.PongEvent = function(data) { - this.data = data; - }; - module2.exports = Base; - }, - /***/ - 483(module2, __unused_webpack_exports, __webpack_require__2) { - var Buffer2 = __webpack_require__2(891).Buffer, crypto = __webpack_require__2(982), url = __webpack_require__2(16), util = __webpack_require__2(23), HttpParser = __webpack_require__2(565), Base = __webpack_require__2(369), Hybi = __webpack_require__2(518), Proxy = __webpack_require__2(662); - var Client = function(_url, options) { - this.version = "hybi-" + Hybi.VERSION; - Hybi.call(this, null, _url, options); - this.readyState = -1; - this._key = Client.generateKey(); - this._accept = Hybi.generateAccept(this._key); - this._http = new HttpParser("response"); - var uri = url.parse(this.url), auth = uri.auth && Buffer2.from(uri.auth, "utf8").toString("base64"); - if (this.VALID_PROTOCOLS.indexOf(uri.protocol) < 0) - throw new Error(this.url + " is not a valid WebSocket URL"); - this._pathname = (uri.pathname || "/") + (uri.search || ""); - this._headers.set("Host", uri.host); - this._headers.set("Upgrade", "websocket"); - this._headers.set("Connection", "Upgrade"); - this._headers.set("Sec-WebSocket-Key", this._key); - this._headers.set("Sec-WebSocket-Version", Hybi.VERSION); - if (this._protocols.length > 0) - this._headers.set("Sec-WebSocket-Protocol", this._protocols.join(", ")); - if (auth) - this._headers.set("Authorization", "Basic " + auth); - }; - util.inherits(Client, Hybi); - Client.generateKey = function() { - return crypto.randomBytes(16).toString("base64"); - }; - var instance = { - VALID_PROTOCOLS: ["ws:", "wss:"], - proxy: function(origin, options) { - return new Proxy(this, origin, options); - }, - start: function() { - if (this.readyState !== -1) return false; - this._write(this._handshakeRequest()); - this.readyState = 0; - return true; - }, - parse: function(chunk) { - if (this.readyState === 3) return; - if (this.readyState > 0) return Hybi.prototype.parse.call(this, chunk); - this._http.parse(chunk); - if (!this._http.isComplete()) return; - this._validateHandshake(); - if (this.readyState === 3) return; - this._open(); - this.parse(this._http.body); - }, - _handshakeRequest: function() { - var extensions = this._extensions.generateOffer(); - if (extensions) - this._headers.set("Sec-WebSocket-Extensions", extensions); - var start = "GET " + this._pathname + " HTTP/1.1", headers = [start, this._headers.toString(), ""]; - return Buffer2.from(headers.join("\r\n"), "utf8"); - }, - _failHandshake: function(message) { - message = "Error during WebSocket handshake: " + message; - this.readyState = 3; - this.emit("error", new Error(message)); - this.emit("close", new Base.CloseEvent(this.ERRORS.protocol_error, message)); - }, - _validateHandshake: function() { - this.statusCode = this._http.statusCode; - this.headers = this._http.headers; - if (this._http.error) - return this._failHandshake(this._http.error.message); - if (this._http.statusCode !== 101) - return this._failHandshake("Unexpected response code: " + this._http.statusCode); - var headers = this._http.headers, upgrade = headers["upgrade"] || "", connection = headers["connection"] || "", accept = headers["sec-websocket-accept"] || "", protocol = headers["sec-websocket-protocol"] || ""; - if (upgrade === "") - return this._failHandshake("'Upgrade' header is missing"); - if (upgrade.toLowerCase() !== "websocket") - return this._failHandshake("'Upgrade' header value is not 'WebSocket'"); - if (connection === "") - return this._failHandshake("'Connection' header is missing"); - if (connection.toLowerCase() !== "upgrade") - return this._failHandshake("'Connection' header value is not 'Upgrade'"); - if (accept !== this._accept) - return this._failHandshake("Sec-WebSocket-Accept mismatch"); - this.protocol = null; - if (protocol !== "") { - if (this._protocols.indexOf(protocol) < 0) - return this._failHandshake("Sec-WebSocket-Protocol mismatch"); - else - this.protocol = protocol; - } - try { - this._extensions.activate(this.headers["sec-websocket-extensions"]); - } catch (e) { - return this._failHandshake(e.message); - } - } - }; - for (var key in instance) - Client.prototype[key] = instance[key]; - module2.exports = Client; - }, - /***/ - 61(module2, __unused_webpack_exports, __webpack_require__2) { - var Buffer2 = __webpack_require__2(891).Buffer, Base = __webpack_require__2(369), util = __webpack_require__2(23); - var Draft75 = function(request, url, options) { - Base.apply(this, arguments); - this._stage = 0; - this.version = "hixie-75"; - this._headers.set("Upgrade", "WebSocket"); - this._headers.set("Connection", "Upgrade"); - this._headers.set("WebSocket-Origin", this._request.headers.origin); - this._headers.set("WebSocket-Location", this.url); - }; - util.inherits(Draft75, Base); - var instance = { - close: function() { - if (this.readyState === 3) return false; - this.readyState = 3; - this.emit("close", new Base.CloseEvent(null, null)); - return true; - }, - parse: function(chunk) { - if (this.readyState > 1) return; - this._reader.put(chunk); - this._reader.eachByte(function(octet) { - var message; - switch (this._stage) { - case -1: - this._body.push(octet); - this._sendHandshakeBody(); - break; - case 0: - this._parseLeadingByte(octet); - break; - case 1: - this._length = (octet & 127) + 128 * this._length; - if (this._closing && this._length === 0) { - return this.close(); - } else if ((octet & 128) !== 128) { - if (this._length === 0) { - this._stage = 0; - } else { - this._skipped = 0; - this._stage = 2; - } - } - break; - case 2: - if (octet === 255) { - this._stage = 0; - message = Buffer2.from(this._buffer).toString("utf8", 0, this._buffer.length); - this.emit("message", new Base.MessageEvent(message)); - } else { - if (this._length) { - this._skipped += 1; - if (this._skipped === this._length) - this._stage = 0; - } else { - this._buffer.push(octet); - if (this._buffer.length > this._maxLength) return this.close(); - } - } - break; - } - }, this); - }, - frame: function(buffer) { - if (this.readyState === 0) return this._queue([buffer]); - if (this.readyState > 1) return false; - if (typeof buffer !== "string") buffer = buffer.toString(); - var length = Buffer2.byteLength(buffer), frame = Buffer2.allocUnsafe(length + 2); - frame[0] = 0; - frame.write(buffer, 1); - frame[frame.length - 1] = 255; - this._write(frame); - return true; - }, - _handshakeResponse: function() { - var start = "HTTP/1.1 101 Web Socket Protocol Handshake", headers = [start, this._headers.toString(), ""]; - return Buffer2.from(headers.join("\r\n"), "utf8"); - }, - _parseLeadingByte: function(octet) { - if ((octet & 128) === 128) { - this._length = 0; - this._stage = 1; - } else { - delete this._length; - delete this._skipped; - this._buffer = []; - this._stage = 2; - } - } - }; - for (var key in instance) - Draft75.prototype[key] = instance[key]; - module2.exports = Draft75; - }, - /***/ - 476(module2, __unused_webpack_exports, __webpack_require__2) { - var Buffer2 = __webpack_require__2(891).Buffer, Base = __webpack_require__2(369), Draft75 = __webpack_require__2(61), crypto = __webpack_require__2(982), util = __webpack_require__2(23); - var numberFromKey = function(key2) { - return parseInt((key2.match(/[0-9]/g) || []).join(""), 10); - }; - var spacesInKey = function(key2) { - return (key2.match(/ /g) || []).length; - }; - var Draft76 = function(request, url, options) { - Draft75.apply(this, arguments); - this._stage = -1; - this._body = []; - this.version = "hixie-76"; - this._headers.clear(); - this._headers.set("Upgrade", "WebSocket"); - this._headers.set("Connection", "Upgrade"); - this._headers.set("Sec-WebSocket-Origin", this._request.headers.origin); - this._headers.set("Sec-WebSocket-Location", this.url); - }; - util.inherits(Draft76, Draft75); - var instance = { - BODY_SIZE: 8, - start: function() { - if (!Draft75.prototype.start.call(this)) return false; - this._started = true; - this._sendHandshakeBody(); - return true; - }, - close: function() { - if (this.readyState === 3) return false; - if (this.readyState === 1) this._write(Buffer2.from([255, 0])); - this.readyState = 3; - this.emit("close", new Base.CloseEvent(null, null)); - return true; - }, - _handshakeResponse: function() { - var headers = this._request.headers, key1 = headers["sec-websocket-key1"], key2 = headers["sec-websocket-key2"]; - if (!key1) throw new Error("Missing required header: Sec-WebSocket-Key1"); - if (!key2) throw new Error("Missing required header: Sec-WebSocket-Key2"); - var number1 = numberFromKey(key1), spaces1 = spacesInKey(key1), number2 = numberFromKey(key2), spaces2 = spacesInKey(key2); - if (number1 % spaces1 !== 0 || number2 % spaces2 !== 0) - throw new Error("Client sent invalid Sec-WebSocket-Key headers"); - this._keyValues = [number1 / spaces1, number2 / spaces2]; - var start = "HTTP/1.1 101 WebSocket Protocol Handshake", headers = [start, this._headers.toString(), ""]; - return Buffer2.from(headers.join("\r\n"), "binary"); - }, - _handshakeSignature: function() { - if (this._body.length < this.BODY_SIZE) return null; - var md5 = crypto.createHash("md5"), buffer = Buffer2.allocUnsafe(8 + this.BODY_SIZE); - buffer.writeUInt32BE(this._keyValues[0], 0); - buffer.writeUInt32BE(this._keyValues[1], 4); - Buffer2.from(this._body).copy(buffer, 8, 0, this.BODY_SIZE); - md5.update(buffer); - return Buffer2.from(md5.digest("binary"), "binary"); - }, - _sendHandshakeBody: function() { - if (!this._started) return; - var signature = this._handshakeSignature(); - if (!signature) return; - this._write(signature); - this._stage = 0; - this._open(); - if (this._body.length > this.BODY_SIZE) - this.parse(this._body.slice(this.BODY_SIZE)); - }, - _parseLeadingByte: function(octet) { - if (octet !== 255) - return Draft75.prototype._parseLeadingByte.call(this, octet); - this._closing = true; - this._length = 0; - this._stage = 1; - } - }; - for (var key in instance) - Draft76.prototype[key] = instance[key]; - module2.exports = Draft76; - }, - /***/ - 160(module2) { - var Headers = function() { - this.clear(); - }; - Headers.prototype.ALLOWED_DUPLICATES = ["set-cookie", "set-cookie2", "warning", "www-authenticate"]; - Headers.prototype.clear = function() { - this._sent = {}; - this._lines = []; - }; - Headers.prototype.set = function(name, value) { - if (value === void 0) return; - name = this._strip(name); - value = this._strip(value); - var key = name.toLowerCase(); - if (!this._sent.hasOwnProperty(key) || this.ALLOWED_DUPLICATES.indexOf(key) >= 0) { - this._sent[key] = true; - this._lines.push(name + ": " + value + "\r\n"); - } - }; - Headers.prototype.toString = function() { - return this._lines.join(""); - }; - Headers.prototype._strip = function(string) { - return string.toString().replace(/^ */, "").replace(/ *$/, ""); - }; - module2.exports = Headers; - }, - /***/ - 518(module2, __unused_webpack_exports, __webpack_require__2) { - var Buffer2 = __webpack_require__2(891).Buffer, crypto = __webpack_require__2(982), util = __webpack_require__2(23), Extensions = __webpack_require__2(769), Base = __webpack_require__2(369), Frame = __webpack_require__2(68), Message = __webpack_require__2(814); - var Hybi = function(request, url, options) { - Base.apply(this, arguments); - this._extensions = new Extensions(); - this._stage = 0; - this._masking = this._options.masking; - this._protocols = this._options.protocols || []; - this._requireMasking = this._options.requireMasking; - this._pingCallbacks = {}; - if (typeof this._protocols === "string") - this._protocols = this._protocols.split(/ *, */); - if (!this._request) return; - var protos = this._request.headers["sec-websocket-protocol"], supported = this._protocols; - if (protos !== void 0) { - if (typeof protos === "string") protos = protos.split(/ *, */); - this.protocol = protos.filter(function(p2) { - return supported.indexOf(p2) >= 0; - })[0]; - } - this.version = "hybi-" + Hybi.VERSION; - }; - util.inherits(Hybi, Base); - Hybi.VERSION = "13"; - Hybi.mask = function(payload, mask, offset) { - if (!mask || mask.length === 0) return payload; - offset = offset || 0; - for (var i = 0, n = payload.length - offset; i < n; i++) { - payload[offset + i] = payload[offset + i] ^ mask[i % 4]; - } - return payload; - }; - Hybi.generateAccept = function(key2) { - var sha1 = crypto.createHash("sha1"); - sha1.update(key2 + Hybi.GUID); - return sha1.digest("base64"); - }; - Hybi.GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"; - var instance = { - FIN: 128, - MASK: 128, - RSV1: 64, - RSV2: 32, - RSV3: 16, - OPCODE: 15, - LENGTH: 127, - OPCODES: { - continuation: 0, - text: 1, - binary: 2, - close: 8, - ping: 9, - pong: 10 - }, - OPCODE_CODES: [0, 1, 2, 8, 9, 10], - MESSAGE_OPCODES: [0, 1, 2], - OPENING_OPCODES: [1, 2], - ERRORS: { - normal_closure: 1e3, - going_away: 1001, - protocol_error: 1002, - unacceptable: 1003, - encoding_error: 1007, - policy_violation: 1008, - too_large: 1009, - extension_error: 1010, - unexpected_condition: 1011 - }, - ERROR_CODES: [1e3, 1001, 1002, 1003, 1007, 1008, 1009, 1010, 1011], - DEFAULT_ERROR_CODE: 1e3, - MIN_RESERVED_ERROR: 3e3, - MAX_RESERVED_ERROR: 4999, - // http://www.w3.org/International/questions/qa-forms-utf-8.en.php - UTF8_MATCH: /^([\x00-\x7F]|[\xC2-\xDF][\x80-\xBF]|\xE0[\xA0-\xBF][\x80-\xBF]|[\xE1-\xEC\xEE\xEF][\x80-\xBF]{2}|\xED[\x80-\x9F][\x80-\xBF]|\xF0[\x90-\xBF][\x80-\xBF]{2}|[\xF1-\xF3][\x80-\xBF]{3}|\xF4[\x80-\x8F][\x80-\xBF]{2})*$/, - addExtension: function(extension) { - this._extensions.add(extension); - return true; - }, - parse: function(chunk) { - this._reader.put(chunk); - var buffer = true; - while (buffer) { - switch (this._stage) { - case 0: - buffer = this._reader.read(1); - if (buffer) this._parseOpcode(buffer[0]); - break; - case 1: - buffer = this._reader.read(1); - if (buffer) this._parseLength(buffer[0]); - break; - case 2: - buffer = this._reader.read(this._frame.lengthBytes); - if (buffer) this._parseExtendedLength(buffer); - break; - case 3: - buffer = this._reader.read(4); - if (buffer) { - this._stage = 4; - this._frame.maskingKey = buffer; - } - break; - case 4: - buffer = this._reader.read(this._frame.length); - if (buffer) { - this._stage = 0; - this._emitFrame(buffer); - } - break; - default: - buffer = null; - } - } - }, - text: function(message) { - if (this.readyState > 1) return false; - return this.frame(message, "text"); - }, - binary: function(message) { - if (this.readyState > 1) return false; - return this.frame(message, "binary"); - }, - ping: function(message, callback) { - if (this.readyState > 1) return false; - message = message || ""; - if (callback) this._pingCallbacks[message] = callback; - return this.frame(message, "ping"); - }, - pong: function(message) { - if (this.readyState > 1) return false; - message = message || ""; - return this.frame(message, "pong"); - }, - close: function(reason, code) { - reason = reason || ""; - code = code || this.ERRORS.normal_closure; - if (this.readyState <= 0) { - this.readyState = 3; - this.emit("close", new Base.CloseEvent(code, reason)); - return true; - } else if (this.readyState === 1) { - this.readyState = 2; - this._extensions.close(function() { - this.frame(reason, "close", code); - }, this); - return true; - } else { - return false; - } - }, - frame: function(buffer, type, code) { - if (this.readyState <= 0) return this._queue([buffer, type, code]); - if (this.readyState > 2) return false; - if (buffer instanceof Array) buffer = Buffer2.from(buffer); - if (typeof buffer === "number") buffer = buffer.toString(); - var message = new Message(), isText = typeof buffer === "string", payload, copy; - message.rsv1 = message.rsv2 = message.rsv3 = false; - message.opcode = this.OPCODES[type || (isText ? "text" : "binary")]; - payload = isText ? Buffer2.from(buffer, "utf8") : buffer; - if (code) { - copy = payload; - payload = Buffer2.allocUnsafe(2 + copy.length); - payload.writeUInt16BE(code, 0); - copy.copy(payload, 2); - } - message.data = payload; - var onMessageReady = function(message2) { - var frame = new Frame(); - frame.final = true; - frame.rsv1 = message2.rsv1; - frame.rsv2 = message2.rsv2; - frame.rsv3 = message2.rsv3; - frame.opcode = message2.opcode; - frame.masked = !!this._masking; - frame.length = message2.data.length; - frame.payload = message2.data; - if (frame.masked) frame.maskingKey = crypto.randomBytes(4); - this._sendFrame(frame); - }; - if (this.MESSAGE_OPCODES.indexOf(message.opcode) >= 0) - this._extensions.processOutgoingMessage(message, function(error, message2) { - if (error) return this._fail("extension_error", error.message); - onMessageReady.call(this, message2); - }, this); - else - onMessageReady.call(this, message); - return true; - }, - _sendFrame: function(frame) { - var length = frame.length, header = length <= 125 ? 2 : length <= 65535 ? 4 : 10, offset = header + (frame.masked ? 4 : 0), buffer = Buffer2.allocUnsafe(offset + length), masked = frame.masked ? this.MASK : 0; - buffer[0] = (frame.final ? this.FIN : 0) | (frame.rsv1 ? this.RSV1 : 0) | (frame.rsv2 ? this.RSV2 : 0) | (frame.rsv3 ? this.RSV3 : 0) | frame.opcode; - if (length <= 125) { - buffer[1] = masked | length; - } else if (length <= 65535) { - buffer[1] = masked | 126; - buffer.writeUInt16BE(length, 2); - } else { - buffer[1] = masked | 127; - buffer.writeUInt32BE(Math.floor(length / 4294967296), 2); - buffer.writeUInt32BE(length % 4294967296, 6); - } - frame.payload.copy(buffer, offset); - if (frame.masked) { - frame.maskingKey.copy(buffer, header); - Hybi.mask(buffer, frame.maskingKey, offset); - } - this._write(buffer); - }, - _handshakeResponse: function() { - var secKey = this._request.headers["sec-websocket-key"], version = this._request.headers["sec-websocket-version"]; - if (version !== Hybi.VERSION) - throw new Error("Unsupported WebSocket version: " + version); - if (typeof secKey !== "string") - throw new Error("Missing handshake request header: Sec-WebSocket-Key"); - this._headers.set("Upgrade", "websocket"); - this._headers.set("Connection", "Upgrade"); - this._headers.set("Sec-WebSocket-Accept", Hybi.generateAccept(secKey)); - if (this.protocol) this._headers.set("Sec-WebSocket-Protocol", this.protocol); - var extensions = this._extensions.generateResponse(this._request.headers["sec-websocket-extensions"]); - if (extensions) this._headers.set("Sec-WebSocket-Extensions", extensions); - var start = "HTTP/1.1 101 Switching Protocols", headers = [start, this._headers.toString(), ""]; - return Buffer2.from(headers.join("\r\n"), "utf8"); - }, - _shutdown: function(code, reason, error) { - delete this._frame; - delete this._message; - this._stage = 5; - var sendCloseFrame = this.readyState === 1; - this.readyState = 2; - this._extensions.close(function() { - if (sendCloseFrame) this.frame(reason, "close", code); - this.readyState = 3; - if (error) this.emit("error", new Error(reason)); - this.emit("close", new Base.CloseEvent(code, reason)); - }, this); - }, - _fail: function(type, message) { - if (this.readyState > 1) return; - this._shutdown(this.ERRORS[type], message, true); - }, - _parseOpcode: function(octet) { - var rsvs = [this.RSV1, this.RSV2, this.RSV3].map(function(rsv) { - return (octet & rsv) === rsv; - }); - var frame = this._frame = new Frame(); - frame.final = (octet & this.FIN) === this.FIN; - frame.rsv1 = rsvs[0]; - frame.rsv2 = rsvs[1]; - frame.rsv3 = rsvs[2]; - frame.opcode = octet & this.OPCODE; - this._stage = 1; - if (!this._extensions.validFrameRsv(frame)) - return this._fail( - "protocol_error", - "One or more reserved bits are on: reserved1 = " + (frame.rsv1 ? 1 : 0) + ", reserved2 = " + (frame.rsv2 ? 1 : 0) + ", reserved3 = " + (frame.rsv3 ? 1 : 0) - ); - if (this.OPCODE_CODES.indexOf(frame.opcode) < 0) - return this._fail("protocol_error", "Unrecognized frame opcode: " + frame.opcode); - if (this.MESSAGE_OPCODES.indexOf(frame.opcode) < 0 && !frame.final) - return this._fail("protocol_error", "Received fragmented control frame: opcode = " + frame.opcode); - if (this._message && this.OPENING_OPCODES.indexOf(frame.opcode) >= 0) - return this._fail("protocol_error", "Received new data frame but previous continuous frame is unfinished"); - }, - _parseLength: function(octet) { - var frame = this._frame; - frame.masked = (octet & this.MASK) === this.MASK; - frame.length = octet & this.LENGTH; - if (frame.length >= 0 && frame.length <= 125) { - this._stage = frame.masked ? 3 : 4; - if (!this._checkFrameLength()) return; - } else { - this._stage = 2; - frame.lengthBytes = frame.length === 126 ? 2 : 8; - } - if (this._requireMasking && !frame.masked) - return this._fail("unacceptable", "Received unmasked frame but masking is required"); - }, - _parseExtendedLength: function(buffer) { - var frame = this._frame; - frame.length = this._readUInt(buffer); - this._stage = frame.masked ? 3 : 4; - if (this.MESSAGE_OPCODES.indexOf(frame.opcode) < 0 && frame.length > 125) - return this._fail("protocol_error", "Received control frame having too long payload: " + frame.length); - if (!this._checkFrameLength()) return; - }, - _checkFrameLength: function() { - var length = this._message ? this._message.length : 0; - if (length + this._frame.length > this._maxLength) { - this._fail("too_large", "WebSocket frame length too large"); - return false; - } else { - return true; - } - }, - _emitFrame: function(buffer) { - var frame = this._frame, payload = frame.payload = Hybi.mask(buffer, frame.maskingKey), opcode = frame.opcode, message, code, reason, callbacks, callback; - delete this._frame; - if (opcode === this.OPCODES.continuation) { - if (!this._message) return this._fail("protocol_error", "Received unexpected continuation frame"); - this._message.pushFrame(frame); - } - if (opcode === this.OPCODES.text || opcode === this.OPCODES.binary) { - this._message = new Message(); - this._message.pushFrame(frame); - } - if (frame.final && this.MESSAGE_OPCODES.indexOf(opcode) >= 0) - return this._emitMessage(this._message); - if (opcode === this.OPCODES.close) { - code = payload.length >= 2 ? payload.readUInt16BE(0) : null; - reason = payload.length > 2 ? this._encode(payload.slice(2)) : null; - if (!(payload.length === 0) && !(code !== null && code >= this.MIN_RESERVED_ERROR && code <= this.MAX_RESERVED_ERROR) && this.ERROR_CODES.indexOf(code) < 0) - code = this.ERRORS.protocol_error; - if (payload.length > 125 || payload.length > 2 && !reason) - code = this.ERRORS.protocol_error; - this._shutdown(code || this.DEFAULT_ERROR_CODE, reason || ""); - } - if (opcode === this.OPCODES.ping) { - this.frame(payload, "pong"); - this.emit("ping", new Base.PingEvent(payload.toString())); - } - if (opcode === this.OPCODES.pong) { - callbacks = this._pingCallbacks; - message = this._encode(payload); - callback = callbacks[message]; - delete callbacks[message]; - if (callback) callback(); - this.emit("pong", new Base.PongEvent(payload.toString())); - } - }, - _emitMessage: function(message) { - var message = this._message; - message.read(); - delete this._message; - this._extensions.processIncomingMessage(message, function(error, message2) { - if (error) return this._fail("extension_error", error.message); - var payload = message2.data; - if (message2.opcode === this.OPCODES.text) payload = this._encode(payload); - if (payload === null) - return this._fail("encoding_error", "Could not decode a text frame as UTF-8"); - else - this.emit("message", new Base.MessageEvent(payload)); - }, this); - }, - _encode: function(buffer) { - try { - var string = buffer.toString("binary", 0, buffer.length); - if (!this.UTF8_MATCH.test(string)) return null; - } catch (e) { - } - return buffer.toString("utf8", 0, buffer.length); - }, - _readUInt: function(buffer) { - if (buffer.length === 2) return buffer.readUInt16BE(0); - return buffer.readUInt32BE(0) * 4294967296 + buffer.readUInt32BE(4); - } - }; - for (var key in instance) - Hybi.prototype[key] = instance[key]; - module2.exports = Hybi; - }, - /***/ - 68(module2) { - var Frame = function() { - }; - var instance = { - final: false, - rsv1: false, - rsv2: false, - rsv3: false, - opcode: null, - masked: false, - maskingKey: null, - lengthBytes: 1, - length: 0, - payload: null - }; - for (var key in instance) - Frame.prototype[key] = instance[key]; - module2.exports = Frame; - }, - /***/ - 814(module2, __unused_webpack_exports, __webpack_require__2) { - var Buffer2 = __webpack_require__2(891).Buffer; - var Message = function() { - this.rsv1 = false; - this.rsv2 = false; - this.rsv3 = false; - this.opcode = null; - this.length = 0; - this._chunks = []; - }; - var instance = { - read: function() { - return this.data = this.data || Buffer2.concat(this._chunks, this.length); - }, - pushFrame: function(frame) { - this.rsv1 = this.rsv1 || frame.rsv1; - this.rsv2 = this.rsv2 || frame.rsv2; - this.rsv3 = this.rsv3 || frame.rsv3; - if (this.opcode === null) this.opcode = frame.opcode; - this._chunks.push(frame.payload); - this.length += frame.length; - } - }; - for (var key in instance) - Message.prototype[key] = instance[key]; - module2.exports = Message; - }, - /***/ - 662(module2, __unused_webpack_exports, __webpack_require__2) { - var Buffer2 = __webpack_require__2(891).Buffer, Stream = __webpack_require__2(203).Stream, url = __webpack_require__2(16), util = __webpack_require__2(23), Base = __webpack_require__2(369), Headers = __webpack_require__2(160), HttpParser = __webpack_require__2(565); - var PORTS = { "ws:": 80, "wss:": 443 }; - var Proxy = function(client, origin, options) { - this._client = client; - this._http = new HttpParser("response"); - this._origin = typeof client.url === "object" ? client.url : url.parse(client.url); - this._url = typeof origin === "object" ? origin : url.parse(origin); - this._options = options || {}; - this._state = 0; - this.readable = this.writable = true; - this._paused = false; - this._headers = new Headers(); - this._headers.set("Host", this._origin.host); - this._headers.set("Connection", "keep-alive"); - this._headers.set("Proxy-Connection", "keep-alive"); - var auth = this._url.auth && Buffer2.from(this._url.auth, "utf8").toString("base64"); - if (auth) this._headers.set("Proxy-Authorization", "Basic " + auth); - }; - util.inherits(Proxy, Stream); - var instance = { - setHeader: function(name, value) { - if (this._state !== 0) return false; - this._headers.set(name, value); - return true; - }, - start: function() { - if (this._state !== 0) return false; - this._state = 1; - var origin = this._origin, port = origin.port || PORTS[origin.protocol], start = "CONNECT " + origin.hostname + ":" + port + " HTTP/1.1"; - var headers = [start, this._headers.toString(), ""]; - this.emit("data", Buffer2.from(headers.join("\r\n"), "utf8")); - return true; - }, - pause: function() { - this._paused = true; - }, - resume: function() { - this._paused = false; - this.emit("drain"); - }, - write: function(chunk) { - if (!this.writable) return false; - this._http.parse(chunk); - if (!this._http.isComplete()) return !this._paused; - this.statusCode = this._http.statusCode; - this.headers = this._http.headers; - if (this.statusCode === 200) { - this.emit("connect", new Base.ConnectEvent()); - } else { - var message = "Can't establish a connection to the server at " + this._origin.href; - this.emit("error", new Error(message)); - } - this.end(); - return !this._paused; - }, - end: function(chunk) { - if (!this.writable) return; - if (chunk !== void 0) this.write(chunk); - this.readable = this.writable = false; - this.emit("close"); - this.emit("end"); - }, - destroy: function() { - this.end(); - } - }; - for (var key in instance) - Proxy.prototype[key] = instance[key]; - module2.exports = Proxy; - }, - /***/ - 983(module2, __unused_webpack_exports, __webpack_require__2) { - var util = __webpack_require__2(23), HttpParser = __webpack_require__2(565), Base = __webpack_require__2(369), Draft75 = __webpack_require__2(61), Draft76 = __webpack_require__2(476), Hybi = __webpack_require__2(518); - var Server = function(options) { - Base.call(this, null, null, options); - this._http = new HttpParser("request"); - }; - util.inherits(Server, Base); - var instance = { - EVENTS: ["open", "message", "error", "close", "ping", "pong"], - _bindEventListeners: function() { - this.messages.on("error", function() { - }); - this.on("error", function() { - }); - }, - parse: function(chunk) { - if (this._delegate) return this._delegate.parse(chunk); - this._http.parse(chunk); - if (!this._http.isComplete()) return; - this.method = this._http.method; - this.url = this._http.url; - this.headers = this._http.headers; - this.body = this._http.body; - var self2 = this; - this._delegate = Server.http(this, this._options); - this._delegate.messages = this.messages; - this._delegate.io = this.io; - this._open(); - this.EVENTS.forEach(function(event) { - this._delegate.on(event, function(e) { - self2.emit(event, e); - }); - }, this); - this.protocol = this._delegate.protocol; - this.version = this._delegate.version; - this.parse(this._http.body); - this.emit("connect", new Base.ConnectEvent()); - }, - _open: function() { - this.__queue.forEach(function(msg) { - this._delegate[msg[0]].apply(this._delegate, msg[1]); - }, this); - this.__queue = []; - } - }; - ["addExtension", "setHeader", "start", "frame", "text", "binary", "ping", "close"].forEach(function(method) { - instance[method] = function() { - if (this._delegate) { - return this._delegate[method].apply(this._delegate, arguments); - } else { - this.__queue.push([method, arguments]); - return true; - } - }; - }); - for (var key in instance) - Server.prototype[key] = instance[key]; - Server.isSecureRequest = function(request) { - if (request.connection && request.connection.authorized !== void 0) return true; - if (request.socket && request.socket.secure) return true; - var headers = request.headers; - if (!headers) return false; - if (headers["https"] === "on") return true; - if (headers["x-forwarded-ssl"] === "on") return true; - if (headers["x-forwarded-scheme"] === "https") return true; - if (headers["x-forwarded-proto"] === "https") return true; - return false; - }; - Server.determineUrl = function(request) { - var scheme = this.isSecureRequest(request) ? "wss:" : "ws:"; - return scheme + "//" + request.headers.host + request.url; - }; - Server.http = function(request, options) { - options = options || {}; - if (options.requireMasking === void 0) options.requireMasking = true; - var headers = request.headers, version = headers["sec-websocket-version"], key2 = headers["sec-websocket-key"], key1 = headers["sec-websocket-key1"], key22 = headers["sec-websocket-key2"], url = this.determineUrl(request); - if (version || key2) - return new Hybi(request, url, options); - else if (key1 || key22) - return new Draft76(request, url, options); - else - return new Draft75(request, url, options); - }; - module2.exports = Server; - }, - /***/ - 212(module2, __unused_webpack_exports, __webpack_require__2) { - var Buffer2 = __webpack_require__2(891).Buffer; - var StreamReader = function() { - this._queue = []; - this._queueSize = 0; - this._offset = 0; - }; - StreamReader.prototype.put = function(buffer) { - if (!buffer || buffer.length === 0) return; - if (!Buffer2.isBuffer(buffer)) buffer = Buffer2.from(buffer); - this._queue.push(buffer); - this._queueSize += buffer.length; - }; - StreamReader.prototype.read = function(length) { - if (length > this._queueSize) return null; - if (length === 0) return Buffer2.alloc(0); - this._queueSize -= length; - var queue = this._queue, remain = length, first = queue[0], buffers, buffer; - if (first.length >= length) { - if (first.length === length) { - return queue.shift(); - } else { - buffer = first.slice(0, length); - queue[0] = first.slice(length); - return buffer; - } - } - for (var i = 0, n = queue.length; i < n; i++) { - if (remain < queue[i].length) break; - remain -= queue[i].length; - } - buffers = queue.splice(0, i); - if (remain > 0 && queue.length > 0) { - buffers.push(queue[0].slice(0, remain)); - queue[0] = queue[0].slice(remain); - } - return Buffer2.concat(buffers, length); - }; - StreamReader.prototype.eachByte = function(callback, context) { - var buffer, n, index; - while (this._queue.length > 0) { - buffer = this._queue[0]; - n = buffer.length; - while (this._offset < n) { - index = this._offset; - this._offset += 1; - callback.call(context, buffer[index]); - } - this._offset = 0; - this._queue.shift(); - } - }; - module2.exports = StreamReader; - }, - /***/ - 565(module2, __unused_webpack_exports, __webpack_require__2) { - var NodeHTTPParser = __webpack_require__2(895).e, Buffer2 = __webpack_require__2(891).Buffer; - var TYPES = { - request: NodeHTTPParser.REQUEST || "request", - response: NodeHTTPParser.RESPONSE || "response" - }; - var HttpParser = function(type) { - this._type = type; - this._parser = new NodeHTTPParser(TYPES[type]); - this._complete = false; - this.headers = {}; - var current = null, self2 = this; - this._parser.onHeaderField = function(b2, start, length) { - current = b2.toString("utf8", start, start + length).toLowerCase(); - }; - this._parser.onHeaderValue = function(b2, start, length) { - var value = b2.toString("utf8", start, start + length); - if (self2.headers.hasOwnProperty(current)) - self2.headers[current] += ", " + value; - else - self2.headers[current] = value; - }; - this._parser.onHeadersComplete = this._parser[NodeHTTPParser.kOnHeadersComplete] = function(majorVersion, minorVersion, headers, method, pathname, statusCode) { - var info = arguments[0]; - if (typeof info === "object") { - method = info.method; - pathname = info.url; - statusCode = info.statusCode; - headers = info.headers; - } - self2.method = typeof method === "number" ? HttpParser.METHODS[method] : method; - self2.statusCode = statusCode; - self2.url = pathname; - if (!headers) return; - for (var i = 0, n = headers.length, key, value; i < n; i += 2) { - key = headers[i].toLowerCase(); - value = headers[i + 1]; - if (self2.headers.hasOwnProperty(key)) - self2.headers[key] += ", " + value; - else - self2.headers[key] = value; - } - self2._complete = true; - }; - }; - HttpParser.METHODS = { - 0: "DELETE", - 1: "GET", - 2: "HEAD", - 3: "POST", - 4: "PUT", - 5: "CONNECT", - 6: "OPTIONS", - 7: "TRACE", - 8: "COPY", - 9: "LOCK", - 10: "MKCOL", - 11: "MOVE", - 12: "PROPFIND", - 13: "PROPPATCH", - 14: "SEARCH", - 15: "UNLOCK", - 16: "BIND", - 17: "REBIND", - 18: "UNBIND", - 19: "ACL", - 20: "REPORT", - 21: "MKACTIVITY", - 22: "CHECKOUT", - 23: "MERGE", - 24: "M-SEARCH", - 25: "NOTIFY", - 26: "SUBSCRIBE", - 27: "UNSUBSCRIBE", - 28: "PATCH", - 29: "PURGE", - 30: "MKCALENDAR", - 31: "LINK", - 32: "UNLINK" - }; - var VERSION = process.version ? process.version.match(/[0-9]+/g).map(function(n) { - return parseInt(n, 10); - }) : []; - if (VERSION[0] === 0 && VERSION[1] === 12) { - HttpParser.METHODS[16] = "REPORT"; - HttpParser.METHODS[17] = "MKACTIVITY"; - HttpParser.METHODS[18] = "CHECKOUT"; - HttpParser.METHODS[19] = "MERGE"; - HttpParser.METHODS[20] = "M-SEARCH"; - HttpParser.METHODS[21] = "NOTIFY"; - HttpParser.METHODS[22] = "SUBSCRIBE"; - HttpParser.METHODS[23] = "UNSUBSCRIBE"; - HttpParser.METHODS[24] = "PATCH"; - HttpParser.METHODS[25] = "PURGE"; - } - HttpParser.prototype.isComplete = function() { - return this._complete; - }; - HttpParser.prototype.parse = function(chunk) { - var consumed = this._parser.execute(chunk, 0, chunk.length); - if (typeof consumed !== "number") { - this.error = consumed; - this._complete = true; - return; - } - if (this._complete) - this.body = consumed < chunk.length ? chunk.slice(consumed) : Buffer2.alloc(0); - }; - module2.exports = HttpParser; - }, - /***/ - 578(__unused_webpack_module, exports$1, __webpack_require__2) { - var Stream = __webpack_require__2(203).Stream, util = __webpack_require__2(23); - var IO = function(driver) { - this.readable = this.writable = true; - this._paused = false; - this._driver = driver; - }; - util.inherits(IO, Stream); - IO.prototype.pause = function() { - this._paused = true; - this._driver.messages._paused = true; - }; - IO.prototype.resume = function() { - this._paused = false; - this.emit("drain"); - var messages = this._driver.messages; - messages._paused = false; - messages.emit("drain"); - }; - IO.prototype.write = function(chunk) { - if (!this.writable) return false; - this._driver.parse(chunk); - return !this._paused; - }; - IO.prototype.end = function(chunk) { - if (!this.writable) return; - if (chunk !== void 0) this.write(chunk); - this.writable = false; - var messages = this._driver.messages; - if (messages.readable) { - messages.readable = messages.writable = false; - messages.emit("end"); - } - }; - IO.prototype.destroy = function() { - this.end(); - }; - var Messages = function(driver) { - this.readable = this.writable = true; - this._paused = false; - this._driver = driver; - }; - util.inherits(Messages, Stream); - Messages.prototype.pause = function() { - this._driver.io._paused = true; - }; - Messages.prototype.resume = function() { - this._driver.io._paused = false; - this._driver.io.emit("drain"); - }; - Messages.prototype.write = function(message) { - if (!this.writable) return false; - if (typeof message === "string") this._driver.text(message); - else this._driver.binary(message); - return !this._paused; - }; - Messages.prototype.end = function(message) { - if (message !== void 0) this.write(message); - }; - Messages.prototype.destroy = function() { - }; - exports$1.IO = IO; - exports$1.Messages = Messages; - }, - /***/ - 80(module2) { - var TOKEN = /([!#\$%&'\*\+\-\.\^_`\|~0-9A-Za-z]+)/, NOTOKEN = /([^!#\$%&'\*\+\-\.\^_`\|~0-9A-Za-z])/g, QUOTED = /"((?:\\[\x00-\x7f]|[^\x00-\x08\x0a-\x1f\x7f"\\])*)"/, PARAM = new RegExp(TOKEN.source + "(?:=(?:" + TOKEN.source + "|" + QUOTED.source + "))?"), EXT = new RegExp(TOKEN.source + "(?: *; *" + PARAM.source + ")*", "g"), EXT_LIST = new RegExp("^" + EXT.source + "(?: *, *" + EXT.source + ")*$"), NUMBER = /^-?(0|[1-9][0-9]*)(\.[0-9]+)?$/; - var hasOwnProperty = Object.prototype.hasOwnProperty; - var Parser = { - parseHeader: function(header) { - var offers = new Offers(); - if (header === "" || header === void 0) return offers; - if (!EXT_LIST.test(header)) - throw new SyntaxError("Invalid Sec-WebSocket-Extensions header: " + header); - var values = header.match(EXT); - values.forEach(function(value) { - var params = value.match(new RegExp(PARAM.source, "g")), name = params.shift(), offer = {}; - params.forEach(function(param) { - var args = param.match(PARAM), key = args[1], data; - if (args[2] !== void 0) { - data = args[2]; - } else if (args[3] !== void 0) { - data = args[3].replace(/\\/g, ""); - } else { - data = true; - } - if (NUMBER.test(data)) data = parseFloat(data); - if (hasOwnProperty.call(offer, key)) { - offer[key] = [].concat(offer[key]); - offer[key].push(data); - } else { - offer[key] = data; - } - }, this); - offers.push(name, offer); - }, this); - return offers; - }, - serializeParams: function(name, params) { - var values = []; - var print = function(key2, value) { - if (value instanceof Array) { - value.forEach(function(v2) { - print(key2, v2); - }); - } else if (value === true) { - values.push(key2); - } else if (typeof value === "number") { - values.push(key2 + "=" + value); - } else if (NOTOKEN.test(value)) { - values.push(key2 + '="' + value.replace(/"/g, '\\"') + '"'); - } else { - values.push(key2 + "=" + value); - } - }; - for (var key in params) print(key, params[key]); - return [name].concat(values).join("; "); - } - }; - var Offers = function() { - this._byName = {}; - this._inOrder = []; - }; - Offers.prototype.push = function(name, params) { - if (!hasOwnProperty.call(this._byName, name)) - this._byName[name] = []; - this._byName[name].push(params); - this._inOrder.push({ name, params }); - }; - Offers.prototype.eachOffer = function(callback, context) { - var list = this._inOrder; - for (var i = 0, n = list.length; i < n; i++) - callback.call(context, list[i].name, list[i].params); - }; - Offers.prototype.byName = function(name) { - return this._byName[name] || []; - }; - Offers.prototype.toArray = function() { - return this._inOrder.slice(); - }; - module2.exports = Parser; - }, - /***/ - 152(module2, __unused_webpack_exports, __webpack_require__2) { - var Functor = __webpack_require__2(277), Pledge = __webpack_require__2(521); - var Cell = function(tuple) { - this._ext = tuple[0]; - this._session = tuple[1]; - this._functors = { - incoming: new Functor(this._session, "processIncomingMessage"), - outgoing: new Functor(this._session, "processOutgoingMessage") - }; - }; - Cell.prototype.pending = function(direction) { - var functor = this._functors[direction]; - if (!functor._stopped) functor.pending += 1; - }; - Cell.prototype.incoming = function(error, message, callback, context) { - this._exec("incoming", error, message, callback, context); - }; - Cell.prototype.outgoing = function(error, message, callback, context) { - this._exec("outgoing", error, message, callback, context); - }; - Cell.prototype.close = function() { - this._closed = this._closed || new Pledge(); - this._doClose(); - return this._closed; - }; - Cell.prototype._exec = function(direction, error, message, callback, context) { - this._functors[direction].call(error, message, function(err, msg) { - if (err) err.message = this._ext.name + ": " + err.message; - callback.call(context, err, msg); - this._doClose(); - }, this); - }; - Cell.prototype._doClose = function() { - var fin = this._functors.incoming, fout = this._functors.outgoing; - if (!this._closed || fin.pending + fout.pending !== 0) return; - if (this._session) this._session.close(); - this._session = null; - this._closed.done(); - }; - module2.exports = Cell; - }, - /***/ - 277(module2, __unused_webpack_exports, __webpack_require__2) { - var RingBuffer = __webpack_require__2(411); - var Functor = function(session, method) { - this._session = session; - this._method = method; - this._queue = new RingBuffer(Functor.QUEUE_SIZE); - this._stopped = false; - this.pending = 0; - }; - Functor.QUEUE_SIZE = 8; - Functor.prototype.call = function(error, message, callback, context) { - if (this._stopped) return; - var record = { error, message, callback, context, done: false }, called = false, self2 = this; - this._queue.push(record); - if (record.error) { - record.done = true; - this._stop(); - return this._flushQueue(); - } - var handler = function(err, msg) { - if (!(called ^ (called = true))) return; - if (err) { - self2._stop(); - record.error = err; - record.message = null; - } else { - record.message = msg; - } - record.done = true; - self2._flushQueue(); - }; - try { - this._session[this._method](message, handler); - } catch (err) { - handler(err); - } - }; - Functor.prototype._stop = function() { - this.pending = this._queue.length; - this._stopped = true; - }; - Functor.prototype._flushQueue = function() { - var queue = this._queue, record; - while (queue.length > 0 && queue.peek().done) { - record = queue.shift(); - if (record.error) { - this.pending = 0; - queue.clear(); - } else { - this.pending -= 1; - } - record.callback.call(record.context, record.error, record.message); - } - }; - module2.exports = Functor; - }, - /***/ - 862(module2, __unused_webpack_exports, __webpack_require__2) { - var Cell = __webpack_require__2(152), Pledge = __webpack_require__2(521); - var Pipeline = function(sessions) { - this._cells = sessions.map(function(session) { - return new Cell(session); - }); - this._stopped = { incoming: false, outgoing: false }; - }; - Pipeline.prototype.processIncomingMessage = function(message, callback, context) { - if (this._stopped.incoming) return; - this._loop("incoming", this._cells.length - 1, -1, -1, message, callback, context); - }; - Pipeline.prototype.processOutgoingMessage = function(message, callback, context) { - if (this._stopped.outgoing) return; - this._loop("outgoing", 0, this._cells.length, 1, message, callback, context); - }; - Pipeline.prototype.close = function(callback, context) { - this._stopped = { incoming: true, outgoing: true }; - var closed = this._cells.map(function(a) { - return a.close(); - }); - if (callback) - Pledge.all(closed).then(function() { - callback.call(context); - }); - }; - Pipeline.prototype._loop = function(direction, start, end, step, message, callback, context) { - var cells = this._cells, n = cells.length, self2 = this; - while (n--) cells[n].pending(direction); - var pipe = function(index, error, msg) { - if (index === end) return callback.call(context, error, msg); - cells[index][direction](error, msg, function(err, m2) { - if (err) self2._stopped[direction] = true; - pipe(index + step, err, m2); - }); - }; - pipe(start, null, message); - }; - module2.exports = Pipeline; - }, - /***/ - 521(module2, __unused_webpack_exports, __webpack_require__2) { - var RingBuffer = __webpack_require__2(411); - var Pledge = function() { - this._complete = false; - this._callbacks = new RingBuffer(Pledge.QUEUE_SIZE); - }; - Pledge.QUEUE_SIZE = 4; - Pledge.all = function(list) { - var pledge = new Pledge(), pending = list.length, n = pending; - if (pending === 0) pledge.done(); - while (n--) list[n].then(function() { - pending -= 1; - if (pending === 0) pledge.done(); - }); - return pledge; - }; - Pledge.prototype.then = function(callback) { - if (this._complete) callback(); - else this._callbacks.push(callback); - }; - Pledge.prototype.done = function() { - this._complete = true; - var callbacks = this._callbacks, callback; - while (callback = callbacks.shift()) callback(); - }; - module2.exports = Pledge; - }, - /***/ - 411(module2) { - var RingBuffer = function(bufferSize) { - this._bufferSize = bufferSize; - this.clear(); - }; - RingBuffer.prototype.clear = function() { - this._buffer = new Array(this._bufferSize); - this._ringOffset = 0; - this._ringSize = this._bufferSize; - this._head = 0; - this._tail = 0; - this.length = 0; - }; - RingBuffer.prototype.push = function(value) { - var expandBuffer = false, expandRing = false; - if (this._ringSize < this._bufferSize) { - expandBuffer = this._tail === 0; - } else if (this._ringOffset === this._ringSize) { - expandBuffer = true; - expandRing = this._tail === 0; - } - if (expandBuffer) { - this._tail = this._bufferSize; - this._buffer = this._buffer.concat(new Array(this._bufferSize)); - this._bufferSize = this._buffer.length; - if (expandRing) - this._ringSize = this._bufferSize; - } - this._buffer[this._tail] = value; - this.length += 1; - if (this._tail < this._ringSize) this._ringOffset += 1; - this._tail = (this._tail + 1) % this._bufferSize; - }; - RingBuffer.prototype.peek = function() { - if (this.length === 0) return void 0; - return this._buffer[this._head]; - }; - RingBuffer.prototype.shift = function() { - if (this.length === 0) return void 0; - var value = this._buffer[this._head]; - this._buffer[this._head] = void 0; - this.length -= 1; - this._ringOffset -= 1; - if (this._ringOffset === 0 && this.length > 0) { - this._head = this._ringSize; - this._ringOffset = this.length; - this._ringSize = this._bufferSize; - } else { - this._head = (this._head + 1) % this._ringSize; - } - return value; - }; - module2.exports = RingBuffer; - }, - /***/ - 769(module2, __unused_webpack_exports, __webpack_require__2) { - var Parser = __webpack_require__2(80), Pipeline = __webpack_require__2(862); - var Extensions = function() { - this._rsv1 = this._rsv2 = this._rsv3 = null; - this._byName = {}; - this._inOrder = []; - this._sessions = []; - this._index = {}; - }; - Extensions.MESSAGE_OPCODES = [1, 2]; - var instance = { - add: function(ext) { - if (typeof ext.name !== "string") throw new TypeError("extension.name must be a string"); - if (ext.type !== "permessage") throw new TypeError('extension.type must be "permessage"'); - if (typeof ext.rsv1 !== "boolean") throw new TypeError("extension.rsv1 must be true or false"); - if (typeof ext.rsv2 !== "boolean") throw new TypeError("extension.rsv2 must be true or false"); - if (typeof ext.rsv3 !== "boolean") throw new TypeError("extension.rsv3 must be true or false"); - if (this._byName.hasOwnProperty(ext.name)) - throw new TypeError('An extension with name "' + ext.name + '" is already registered'); - this._byName[ext.name] = ext; - this._inOrder.push(ext); - }, - generateOffer: function() { - var sessions = [], offer = [], index = {}; - this._inOrder.forEach(function(ext) { - var session = ext.createClientSession(); - if (!session) return; - var record = [ext, session]; - sessions.push(record); - index[ext.name] = record; - var offers = session.generateOffer(); - offers = offers ? [].concat(offers) : []; - offers.forEach(function(off) { - offer.push(Parser.serializeParams(ext.name, off)); - }, this); - }, this); - this._sessions = sessions; - this._index = index; - return offer.length > 0 ? offer.join(", ") : null; - }, - activate: function(header) { - var responses = Parser.parseHeader(header), sessions = []; - responses.eachOffer(function(name, params) { - var record = this._index[name]; - if (!record) - throw new Error('Server sent an extension response for unknown extension "' + name + '"'); - var ext = record[0], session = record[1], reserved = this._reserved(ext); - if (reserved) - throw new Error("Server sent two extension responses that use the RSV" + reserved[0] + ' bit: "' + reserved[1] + '" and "' + ext.name + '"'); - if (session.activate(params) !== true) - throw new Error("Server sent unacceptable extension parameters: " + Parser.serializeParams(name, params)); - this._reserve(ext); - sessions.push(record); - }, this); - this._sessions = sessions; - this._pipeline = new Pipeline(sessions); - }, - generateResponse: function(header) { - var sessions = [], response = [], offers = Parser.parseHeader(header); - this._inOrder.forEach(function(ext) { - var offer = offers.byName(ext.name); - if (offer.length === 0 || this._reserved(ext)) return; - var session = ext.createServerSession(offer); - if (!session) return; - this._reserve(ext); - sessions.push([ext, session]); - response.push(Parser.serializeParams(ext.name, session.generateResponse())); - }, this); - this._sessions = sessions; - this._pipeline = new Pipeline(sessions); - return response.length > 0 ? response.join(", ") : null; - }, - validFrameRsv: function(frame) { - var allowed = { rsv1: false, rsv2: false, rsv3: false }, ext; - if (Extensions.MESSAGE_OPCODES.indexOf(frame.opcode) >= 0) { - for (var i = 0, n = this._sessions.length; i < n; i++) { - ext = this._sessions[i][0]; - allowed.rsv1 = allowed.rsv1 || ext.rsv1; - allowed.rsv2 = allowed.rsv2 || ext.rsv2; - allowed.rsv3 = allowed.rsv3 || ext.rsv3; - } - } - return (allowed.rsv1 || !frame.rsv1) && (allowed.rsv2 || !frame.rsv2) && (allowed.rsv3 || !frame.rsv3); - }, - processIncomingMessage: function(message, callback, context) { - this._pipeline.processIncomingMessage(message, callback, context); - }, - processOutgoingMessage: function(message, callback, context) { - this._pipeline.processOutgoingMessage(message, callback, context); - }, - close: function(callback, context) { - if (!this._pipeline) return callback.call(context); - this._pipeline.close(callback, context); - }, - _reserve: function(ext) { - this._rsv1 = this._rsv1 || ext.rsv1 && ext.name; - this._rsv2 = this._rsv2 || ext.rsv2 && ext.name; - this._rsv3 = this._rsv3 || ext.rsv3 && ext.name; - }, - _reserved: function(ext) { - if (this._rsv1 && ext.rsv1) return [1, this._rsv1]; - if (this._rsv2 && ext.rsv2) return [2, this._rsv2]; - if (this._rsv3 && ext.rsv3) return [3, this._rsv3]; - return false; - } - }; - for (var key in instance) - Extensions.prototype[key] = instance[key]; - module2.exports = Extensions; - }, - /***/ - 407(__unused_webpack_module, exports$1, __webpack_require__2) { - var Url = __webpack_require__2(16); - var spawn = __webpack_require__2(317).spawn; - var fs = __webpack_require__2(896); - exports$1.z = function() { - var self2 = this; - var http = __webpack_require__2(611); - var https = __webpack_require__2(692); - var request; - var response; - var settings = {}; - var disableHeaderCheck = false; - var defaultHeaders = { - "User-Agent": "node-XMLHttpRequest", - "Accept": "*/*" - }; - var headers = {}; - var headersCase = {}; - var forbiddenRequestHeaders = [ - "accept-charset", - "accept-encoding", - "access-control-request-headers", - "access-control-request-method", - "connection", - "content-length", - "content-transfer-encoding", - "cookie", - "cookie2", - "date", - "expect", - "host", - "keep-alive", - "origin", - "referer", - "te", - "trailer", - "transfer-encoding", - "upgrade", - "via" - ]; - var forbiddenRequestMethods = [ - "TRACE", - "TRACK", - "CONNECT" - ]; - var sendFlag = false; - var errorFlag = false; - var listeners = {}; - this.UNSENT = 0; - this.OPENED = 1; - this.HEADERS_RECEIVED = 2; - this.LOADING = 3; - this.DONE = 4; - this.readyState = this.UNSENT; - this.onreadystatechange = null; - this.responseText = ""; - this.responseXML = ""; - this.status = null; - this.statusText = null; - this.withCredentials = false; - var isAllowedHttpHeader = function(header) { - return disableHeaderCheck || header && forbiddenRequestHeaders.indexOf(header.toLowerCase()) === -1; - }; - var isAllowedHttpMethod = function(method) { - return method && forbiddenRequestMethods.indexOf(method) === -1; - }; - this.open = function(method, url, async, user, password) { - this.abort(); - errorFlag = false; - if (!isAllowedHttpMethod(method)) { - throw new Error("SecurityError: Request method not allowed"); - } - settings = { - "method": method, - "url": url.toString(), - "async": typeof async !== "boolean" ? true : async, - "user": user || null, - "password": password || null - }; - setState(this.OPENED); - }; - this.setDisableHeaderCheck = function(state) { - disableHeaderCheck = state; - }; - this.setRequestHeader = function(header, value) { - if (this.readyState !== this.OPENED) { - throw new Error("INVALID_STATE_ERR: setRequestHeader can only be called when state is OPEN"); - } - if (!isAllowedHttpHeader(header)) { - console.warn('Refused to set unsafe header "' + header + '"'); - return; - } - if (sendFlag) { - throw new Error("INVALID_STATE_ERR: send flag is true"); - } - header = headersCase[header.toLowerCase()] || header; - headersCase[header.toLowerCase()] = header; - headers[header] = headers[header] ? headers[header] + ", " + value : value; - }; - this.getResponseHeader = function(header) { - if (typeof header === "string" && this.readyState > this.OPENED && response && response.headers && response.headers[header.toLowerCase()] && !errorFlag) { - return response.headers[header.toLowerCase()]; - } - return null; - }; - this.getAllResponseHeaders = function() { - if (this.readyState < this.HEADERS_RECEIVED || errorFlag) { - return ""; - } - var result = ""; - for (var i in response.headers) { - if (i !== "set-cookie" && i !== "set-cookie2") { - result += i + ": " + response.headers[i] + "\r\n"; - } - } - return result.substr(0, result.length - 2); - }; - this.getRequestHeader = function(name) { - if (typeof name === "string" && headersCase[name.toLowerCase()]) { - return headers[headersCase[name.toLowerCase()]]; - } - return ""; - }; - this.send = function(data) { - if (this.readyState !== this.OPENED) { - throw new Error("INVALID_STATE_ERR: connection must be opened before send() is called"); - } - if (sendFlag) { - throw new Error("INVALID_STATE_ERR: send has already been called"); - } - var ssl = false, local = false; - var url = Url.parse(settings.url); - var host; - switch (url.protocol) { - case "https:": - ssl = true; - // SSL & non-SSL both need host, no break here. - case "http:": - host = url.hostname; - break; - case "file:": - local = true; - break; - case void 0: - case null: - case "": - host = "localhost"; - break; - default: - throw new Error("Protocol not supported."); - } - if (local) { - if (settings.method !== "GET") { - throw new Error("XMLHttpRequest: Only GET method is supported"); - } - if (settings.async) { - fs.readFile(url.pathname, "utf8", function(error, data2) { - if (error) { - self2.handleError(error); - } else { - self2.status = 200; - self2.responseText = data2; - setState(self2.DONE); - } - }); - } else { - try { - this.responseText = fs.readFileSync(url.pathname, "utf8"); - this.status = 200; - setState(self2.DONE); - } catch (e) { - this.handleError(e); - } - } - return; - } - var port = url.port || (ssl ? 443 : 80); - var uri = url.pathname + (url.search ? url.search : ""); - for (var name in defaultHeaders) { - if (!headersCase[name.toLowerCase()]) { - headers[name] = defaultHeaders[name]; - } - } - headers.Host = host; - if (!(ssl && port === 443 || port === 80)) { - headers.Host += ":" + url.port; - } - if (settings.user) { - if (typeof settings.password === "undefined") { - settings.password = ""; - } - var authBuf = new Buffer(settings.user + ":" + settings.password); - headers.Authorization = "Basic " + authBuf.toString("base64"); - } - if (settings.method === "GET" || settings.method === "HEAD") { - data = null; - } else if (data) { - headers["Content-Length"] = Buffer.isBuffer(data) ? data.length : Buffer.byteLength(data); - if (!headers["Content-Type"]) { - headers["Content-Type"] = "text/plain;charset=UTF-8"; - } - } else if (settings.method === "POST") { - headers["Content-Length"] = 0; - } - var options = { - host, - port, - path: uri, - method: settings.method, - headers, - agent: false, - withCredentials: self2.withCredentials - }; - errorFlag = false; - if (settings.async) { - var doRequest = ssl ? https.request : http.request; - sendFlag = true; - self2.dispatchEvent("readystatechange"); - var responseHandler = function responseHandler2(resp2) { - response = resp2; - if (response.statusCode === 301 || response.statusCode === 302 || response.statusCode === 303 || response.statusCode === 307) { - settings.url = response.headers.location; - var url2 = Url.parse(settings.url); - host = url2.hostname; - var newOptions = { - hostname: url2.hostname, - port: url2.port, - path: url2.path, - method: response.statusCode === 303 ? "GET" : settings.method, - headers, - withCredentials: self2.withCredentials - }; - request = doRequest(newOptions, responseHandler2).on("error", errorHandler); - request.end(); - return; - } - response.setEncoding("utf8"); - setState(self2.HEADERS_RECEIVED); - self2.status = response.statusCode; - response.on("data", function(chunk) { - if (chunk) { - self2.responseText += chunk; - } - if (sendFlag) { - setState(self2.LOADING); - } - }); - response.on("end", function() { - if (sendFlag) { - setState(self2.DONE); - sendFlag = false; - } - }); - response.on("error", function(error) { - self2.handleError(error); - }); - }; - var errorHandler = function errorHandler2(error) { - self2.handleError(error); - }; - request = doRequest(options, responseHandler).on("error", errorHandler); - if (data) { - request.write(data); - } - request.end(); - self2.dispatchEvent("loadstart"); - } else { - var contentFile = ".node-xmlhttprequest-content-" + process.pid; - var syncFile = ".node-xmlhttprequest-sync-" + process.pid; - fs.writeFileSync(syncFile, "", "utf8"); - var execString = "var http = require('http'), https = require('https'), fs = require('fs');var doRequest = http" + (ssl ? "s" : "") + ".request;var options = " + JSON.stringify(options) + ";var responseText = '';var req = doRequest(options, function(response) {response.setEncoding('utf8');response.on('data', function(chunk) { responseText += chunk;});response.on('end', function() {fs.writeFileSync('" + contentFile + "', JSON.stringify({err: null, data: {statusCode: response.statusCode, headers: response.headers, text: responseText}}), 'utf8');fs.unlinkSync('" + syncFile + "');});response.on('error', function(error) {fs.writeFileSync('" + contentFile + "', JSON.stringify({err: error}), 'utf8');fs.unlinkSync('" + syncFile + "');});}).on('error', function(error) {fs.writeFileSync('" + contentFile + "', JSON.stringify({err: error}), 'utf8');fs.unlinkSync('" + syncFile + "');});" + (data ? "req.write('" + JSON.stringify(data).slice(1, -1).replace(/'/g, "\\'") + "');" : "") + "req.end();"; - var syncProc = spawn(process.argv[0], ["-e", execString]); - while (fs.existsSync(syncFile)) { - } - var resp = JSON.parse(fs.readFileSync(contentFile, "utf8")); - syncProc.stdin.end(); - fs.unlinkSync(contentFile); - if (resp.err) { - self2.handleError(resp.err); - } else { - response = resp.data; - self2.status = resp.data.statusCode; - self2.responseText = resp.data.text; - setState(self2.DONE); - } - } - }; - this.handleError = function(error) { - this.status = 0; - this.statusText = error; - this.responseText = error.stack; - errorFlag = true; - setState(this.DONE); - this.dispatchEvent("error"); - }; - this.abort = function() { - if (request) { - request.abort(); - request = null; - } - headers = defaultHeaders; - this.status = 0; - this.responseText = ""; - this.responseXML = ""; - errorFlag = true; - if (this.readyState !== this.UNSENT && (this.readyState !== this.OPENED || sendFlag) && this.readyState !== this.DONE) { - sendFlag = false; - setState(this.DONE); - } - this.readyState = this.UNSENT; - this.dispatchEvent("abort"); - }; - this.addEventListener = function(event, callback) { - if (!(event in listeners)) { - listeners[event] = []; - } - listeners[event].push(callback); - }; - this.removeEventListener = function(event, callback) { - if (event in listeners) { - listeners[event] = listeners[event].filter(function(ev) { - return ev !== callback; - }); - } - }; - this.dispatchEvent = function(event) { - if (typeof self2["on" + event] === "function") { - self2["on" + event](); - } - if (event in listeners) { - for (var i = 0, len = listeners[event].length; i < len; i++) { - listeners[event][i].call(self2); - } - } - }; - var setState = function(state) { - if (state == self2.LOADING || self2.readyState !== state) { - self2.readyState = state; - if (settings.async || self2.readyState < self2.OPENED || self2.readyState === self2.DONE) { - self2.dispatchEvent("readystatechange"); - } - if (self2.readyState === self2.DONE && !errorFlag) { - self2.dispatchEvent("load"); - self2.dispatchEvent("loadend"); - } - } - }; - }; - }, - /***/ - 42(module2, __unused_webpack_exports, __webpack_require__2) { - module2.exports = __webpack_require__2(368)["default"]; - }, - /***/ - 368(__unused_webpack_module, __webpack_exports__2, __webpack_require__2) { - __webpack_require__2.d(__webpack_exports__2, { - "default": () => ( - /* binding */ - PusherWithEncryption - ) - }); - function encode(s) { - return btoa(utob(s)); - } - var fromCharCode = String.fromCharCode; - var b64chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; - var cb_utob = function(c2) { - var cc = c2.charCodeAt(0); - return cc < 128 ? c2 : cc < 2048 ? fromCharCode(192 | cc >>> 6) + fromCharCode(128 | cc & 63) : fromCharCode(224 | cc >>> 12 & 15) + fromCharCode(128 | cc >>> 6 & 63) + fromCharCode(128 | cc & 63); - }; - var utob = function(u2) { - return u2.replace(/[^\x00-\x7F]/g, cb_utob); - }; - var cb_encode = function(ccc) { - var padlen = [0, 2, 1][ccc.length % 3]; - var ord = ccc.charCodeAt(0) << 16 | (ccc.length > 1 ? ccc.charCodeAt(1) : 0) << 8 | (ccc.length > 2 ? ccc.charCodeAt(2) : 0); - var chars = [ - b64chars.charAt(ord >>> 18), - b64chars.charAt(ord >>> 12 & 63), - padlen >= 2 ? "=" : b64chars.charAt(ord >>> 6 & 63), - padlen >= 1 ? "=" : b64chars.charAt(ord & 63) - ]; - return chars.join(""); - }; - var btoa = commonjsGlobal.btoa || function(b2) { - return b2.replace(/[\s\S]{1,3}/g, cb_encode); - }; - class Timer { - constructor(set, clear, delay, callback) { - this.clear = clear; - this.timer = set(() => { - if (this.timer) { - this.timer = callback(this.timer); - } - }, delay); - } - isRunning() { - return this.timer !== null; - } - ensureAborted() { - if (this.timer) { - this.clear(this.timer); - this.timer = null; - } - } - } - const abstract_timer = Timer; - function timers_clearTimeout(timer) { - commonjsGlobal.clearTimeout(timer); - } - function timers_clearInterval(timer) { - commonjsGlobal.clearInterval(timer); - } - class OneOffTimer extends abstract_timer { - constructor(delay, callback) { - super(setTimeout, timers_clearTimeout, delay, function(timer) { - callback(); - return null; - }); - } - } - class PeriodicTimer extends abstract_timer { - constructor(delay, callback) { - super(setInterval, timers_clearInterval, delay, function(timer) { - callback(); - return timer; - }); - } - } - var Util = { - now() { - if (Date.now) { - return Date.now(); - } else { - return (/* @__PURE__ */ new Date()).valueOf(); - } - }, - defer(callback) { - return new OneOffTimer(0, callback); - }, - method(name, ...args) { - var boundArguments = Array.prototype.slice.call(arguments, 1); - return function(object) { - return object[name].apply(object, boundArguments.concat(arguments)); - }; - } - }; - const util = Util; - function extend(target, ...sources) { - for (var i = 0; i < sources.length; i++) { - var extensions = sources[i]; - for (var property in extensions) { - if (extensions[property] && extensions[property].constructor && extensions[property].constructor === Object) { - target[property] = extend(target[property] || {}, extensions[property]); - } else { - target[property] = extensions[property]; - } - } - } - return target; - } - function stringify() { - var m2 = ["Pusher"]; - for (var i = 0; i < arguments.length; i++) { - if (typeof arguments[i] === "string") { - m2.push(arguments[i]); - } else { - m2.push(safeJSONStringify(arguments[i])); - } - } - return m2.join(" : "); - } - function arrayIndexOf(array, item) { - var nativeIndexOf = Array.prototype.indexOf; - if (array === null) { - return -1; - } - if (nativeIndexOf && array.indexOf === nativeIndexOf) { - return array.indexOf(item); - } - for (var i = 0, l2 = array.length; i < l2; i++) { - if (array[i] === item) { - return i; - } - } - return -1; - } - function objectApply(object, f2) { - for (var key in object) { - if (Object.prototype.hasOwnProperty.call(object, key)) { - f2(object[key], key, object); - } - } - } - function keys(object) { - var keys2 = []; - objectApply(object, function(_2, key) { - keys2.push(key); - }); - return keys2; - } - function values(object) { - var values2 = []; - objectApply(object, function(value) { - values2.push(value); - }); - return values2; - } - function apply(array, f2, context) { - for (var i = 0; i < array.length; i++) { - f2.call(context || commonjsGlobal, array[i], i, array); - } - } - function map(array, f2) { - var result = []; - for (var i = 0; i < array.length; i++) { - result.push(f2(array[i], i, array, result)); - } - return result; - } - function mapObject(object, f2) { - var result = {}; - objectApply(object, function(value, key) { - result[key] = f2(value); - }); - return result; - } - function filter(array, test) { - test = test || function(value) { - return !!value; - }; - var result = []; - for (var i = 0; i < array.length; i++) { - if (test(array[i], i, array, result)) { - result.push(array[i]); - } - } - return result; - } - function filterObject(object, test) { - var result = {}; - objectApply(object, function(value, key) { - if (test && test(value, key, object, result) || Boolean(value)) { - result[key] = value; - } - }); - return result; - } - function flatten(object) { - var result = []; - objectApply(object, function(value, key) { - result.push([key, value]); - }); - return result; - } - function any(array, test) { - for (var i = 0; i < array.length; i++) { - if (test(array[i], i, array)) { - return true; - } - } - return false; - } - function collections_all(array, test) { - for (var i = 0; i < array.length; i++) { - if (!test(array[i], i, array)) { - return false; - } - } - return true; - } - function encodeParamsObject(data) { - return mapObject(data, function(value) { - if (typeof value === "object") { - value = safeJSONStringify(value); - } - return encodeURIComponent(encode(value.toString())); - }); - } - function buildQueryString(data) { - var params = filterObject(data, function(value) { - return value !== void 0; - }); - var query = map(flatten(encodeParamsObject(params)), util.method("join", "=")).join("&"); - return query; - } - function decycleObject(object) { - var objects = [], paths = []; - return (function derez(value, path) { - var i, name, nu; - switch (typeof value) { - case "object": - if (!value) { - return null; - } - for (i = 0; i < objects.length; i += 1) { - if (objects[i] === value) { - return { $ref: paths[i] }; - } - } - objects.push(value); - paths.push(path); - if (Object.prototype.toString.apply(value) === "[object Array]") { - nu = []; - for (i = 0; i < value.length; i += 1) { - nu[i] = derez(value[i], path + "[" + i + "]"); - } - } else { - nu = {}; - for (name in value) { - if (Object.prototype.hasOwnProperty.call(value, name)) { - nu[name] = derez(value[name], path + "[" + JSON.stringify(name) + "]"); - } - } - } - return nu; - case "number": - case "string": - case "boolean": - return value; - } - })(object, "$"); - } - function safeJSONStringify(source) { - try { - return JSON.stringify(source); - } catch (e) { - return JSON.stringify(decycleObject(source)); - } - } - var Defaults = { - VERSION: "8.5.0", - PROTOCOL: 7, - wsPort: 80, - wssPort: 443, - wsPath: "", - httpHost: "sockjs.pusher.com", - httpPort: 80, - httpsPort: 443, - httpPath: "/pusher", - stats_host: "stats.pusher.com", - authEndpoint: "/pusher/auth", - authTransport: "ajax", - activityTimeout: 12e4, - pongTimeout: 3e4, - unavailableTimeout: 1e4, - userAuthentication: { - endpoint: "/pusher/user-auth", - transport: "ajax" - }, - channelAuthorization: { - endpoint: "/pusher/auth", - transport: "ajax" - } - }; - const defaults = Defaults; - function getGenericURL(baseScheme, params, path) { - var scheme = baseScheme + (params.useTLS ? "s" : ""); - var host = params.useTLS ? params.hostTLS : params.hostNonTLS; - return scheme + "://" + host + path; - } - function getGenericPath(key, queryString) { - var path = "/app/" + key; - var query = "?protocol=" + defaults.PROTOCOL + "&client=js&version=" + defaults.VERSION + (queryString ? "&" + queryString : ""); - return path + query; - } - var ws = { - getInitial: function(key, params) { - var path = (params.httpPath || "") + getGenericPath(key, "flash=false"); - return getGenericURL("ws", params, path); - } - }; - var http = { - getInitial: function(key, params) { - var path = (params.httpPath || "/pusher") + getGenericPath(key); - return getGenericURL("http", params, path); - } - }; - class CallbackRegistry { - constructor() { - this._callbacks = {}; - } - get(name) { - return this._callbacks[prefix(name)]; - } - add(name, callback, context) { - var prefixedEventName = prefix(name); - this._callbacks[prefixedEventName] = this._callbacks[prefixedEventName] || []; - this._callbacks[prefixedEventName].push({ - fn: callback, - context - }); - } - remove(name, callback, context) { - if (!name && !callback && !context) { - this._callbacks = {}; - return; - } - var names = name ? [prefix(name)] : keys(this._callbacks); - if (callback || context) { - this.removeCallback(names, callback, context); - } else { - this.removeAllCallbacks(names); - } - } - removeCallback(names, callback, context) { - apply(names, function(name) { - this._callbacks[name] = filter(this._callbacks[name] || [], function(binding) { - return callback && callback !== binding.fn || context && context !== binding.context; - }); - if (this._callbacks[name].length === 0) { - delete this._callbacks[name]; - } - }, this); - } - removeAllCallbacks(names) { - apply(names, function(name) { - delete this._callbacks[name]; - }, this); - } - } - function prefix(name) { - return "_" + name; - } - class Dispatcher { - constructor(failThrough) { - this.callbacks = new CallbackRegistry(); - this.global_callbacks = []; - this.failThrough = failThrough; - } - bind(eventName, callback, context) { - this.callbacks.add(eventName, callback, context); - return this; - } - bind_global(callback) { - this.global_callbacks.push(callback); - return this; - } - unbind(eventName, callback, context) { - this.callbacks.remove(eventName, callback, context); - return this; - } - unbind_global(callback) { - if (!callback) { - this.global_callbacks = []; - return this; - } - this.global_callbacks = filter(this.global_callbacks || [], (c2) => c2 !== callback); - return this; - } - unbind_all() { - this.unbind(); - this.unbind_global(); - return this; - } - emit(eventName, data, metadata) { - for (var i = 0; i < this.global_callbacks.length; i++) { - this.global_callbacks[i](eventName, data); - } - var callbacks = this.callbacks.get(eventName); - var args = []; - if (metadata) { - args.push(data, metadata); - } else if (data) { - args.push(data); - } - if (callbacks && callbacks.length > 0) { - for (var i = 0; i < callbacks.length; i++) { - callbacks[i].fn.apply(callbacks[i].context || commonjsGlobal, args); - } - } else if (this.failThrough) { - this.failThrough(eventName, data); - } - return this; - } - } - class Logger { - constructor() { - this.globalLog = (message) => { - if (commonjsGlobal.console && commonjsGlobal.console.log) { - commonjsGlobal.console.log(message); - } - }; - } - debug(...args) { - this.log(this.globalLog, args); - } - warn(...args) { - this.log(this.globalLogWarn, args); - } - error(...args) { - this.log(this.globalLogError, args); - } - globalLogWarn(message) { - if (commonjsGlobal.console && commonjsGlobal.console.warn) { - commonjsGlobal.console.warn(message); - } else { - this.globalLog(message); - } - } - globalLogError(message) { - if (commonjsGlobal.console && commonjsGlobal.console.error) { - commonjsGlobal.console.error(message); - } else { - this.globalLogWarn(message); - } - } - log(defaultLoggingFunction, ...args) { - var message = stringify.apply(this, arguments); - if (pusher2.log) { - pusher2.log(message); - } else if (pusher2.logToConsole) { - const log = defaultLoggingFunction.bind(this); - log(message); - } - } - } - const logger = new Logger(); - class TransportConnection extends Dispatcher { - constructor(hooks2, name, priority, key, options) { - super(); - this.initialize = node_runtime.transportConnectionInitializer; - this.hooks = hooks2; - this.name = name; - this.priority = priority; - this.key = key; - this.options = options; - this.state = "new"; - this.timeline = options.timeline; - this.activityTimeout = options.activityTimeout; - this.id = this.timeline.generateUniqueID(); - } - handlesActivityChecks() { - return Boolean(this.hooks.handlesActivityChecks); - } - supportsPing() { - return Boolean(this.hooks.supportsPing); - } - connect() { - if (this.socket || this.state !== "initialized") { - return false; - } - var url = this.hooks.urls.getInitial(this.key, this.options); - try { - this.socket = this.hooks.getSocket(url, this.options); - } catch (e) { - util.defer(() => { - this.onError(e); - this.changeState("closed"); - }); - return false; - } - this.bindListeners(); - logger.debug("Connecting", { transport: this.name, url }); - this.changeState("connecting"); - return true; - } - close() { - if (this.socket) { - this.socket.close(); - return true; - } else { - return false; - } - } - send(data) { - if (this.state === "open") { - util.defer(() => { - if (this.socket) { - this.socket.send(data); - } - }); - return true; - } else { - return false; - } - } - ping() { - if (this.state === "open" && this.supportsPing()) { - this.socket.ping(); - } - } - onOpen() { - if (this.hooks.beforeOpen) { - this.hooks.beforeOpen(this.socket, this.hooks.urls.getPath(this.key, this.options)); - } - this.changeState("open"); - this.socket.onopen = void 0; - } - onError(error) { - this.emit("error", { type: "WebSocketError", error }); - this.timeline.error(this.buildTimelineMessage({ error: error.toString() })); - } - onClose(closeEvent) { - if (closeEvent) { - this.changeState("closed", { - code: closeEvent.code, - reason: closeEvent.reason, - wasClean: closeEvent.wasClean - }); - } else { - this.changeState("closed"); - } - this.unbindListeners(); - this.socket = void 0; - } - onMessage(message) { - this.emit("message", message); - } - onActivity() { - this.emit("activity"); - } - bindListeners() { - this.socket.onopen = () => { - this.onOpen(); - }; - this.socket.onerror = (error) => { - this.onError(error); - }; - this.socket.onclose = (closeEvent) => { - this.onClose(closeEvent); - }; - this.socket.onmessage = (message) => { - this.onMessage(message); - }; - if (this.supportsPing()) { - this.socket.onactivity = () => { - this.onActivity(); - }; - } - } - unbindListeners() { - if (this.socket) { - this.socket.onopen = void 0; - this.socket.onerror = void 0; - this.socket.onclose = void 0; - this.socket.onmessage = void 0; - if (this.supportsPing()) { - this.socket.onactivity = void 0; - } - } - } - changeState(state2, params) { - this.state = state2; - this.timeline.info(this.buildTimelineMessage({ - state: state2, - params - })); - this.emit(state2, params); - } - buildTimelineMessage(message) { - return extend({ cid: this.id }, message); - } - } - class Transport { - constructor(hooks2) { - this.hooks = hooks2; - } - isSupported(environment) { - return this.hooks.isSupported(environment); - } - createConnection(name, priority, key, options) { - return new TransportConnection(this.hooks, name, priority, key, options); - } - } - var WSTransport = new Transport({ - urls: ws, - handlesActivityChecks: false, - supportsPing: false, - isInitialized: function() { - return Boolean(node_runtime.getWebSocketAPI()); - }, - isSupported: function() { - return Boolean(node_runtime.getWebSocketAPI()); - }, - getSocket: function(url) { - return node_runtime.createWebSocket(url); - } - }); - var httpConfiguration = { - urls: http, - handlesActivityChecks: false, - supportsPing: true, - isInitialized: function() { - return true; - } - }; - var streamingConfiguration = extend({ - getSocket: function(url) { - return node_runtime.HTTPFactory.createStreamingSocket(url); - } - }, httpConfiguration); - var pollingConfiguration = extend({ - getSocket: function(url) { - return node_runtime.HTTPFactory.createPollingSocket(url); - } - }, httpConfiguration); - var xhrConfiguration = { - isSupported: function() { - return node_runtime.isXHRSupported(); - } - }; - var XHRStreamingTransport = new Transport(extend({}, streamingConfiguration, xhrConfiguration)); - var XHRPollingTransport = new Transport(extend({}, pollingConfiguration, xhrConfiguration)); - var Transports = { - ws: WSTransport, - xhr_streaming: XHRStreamingTransport, - xhr_polling: XHRPollingTransport - }; - const transports = Transports; - class AssistantToTheTransportManager { - constructor(manager, transport, options) { - this.manager = manager; - this.transport = transport; - this.minPingDelay = options.minPingDelay; - this.maxPingDelay = options.maxPingDelay; - this.pingDelay = void 0; - } - createConnection(name, priority, key, options) { - options = extend({}, options, { - activityTimeout: this.pingDelay - }); - var connection = this.transport.createConnection(name, priority, key, options); - var openTimestamp = null; - var onOpen = function() { - connection.unbind("open", onOpen); - connection.bind("closed", onClosed); - openTimestamp = util.now(); - }; - var onClosed = (closeEvent) => { - connection.unbind("closed", onClosed); - if (closeEvent.code === 1002 || closeEvent.code === 1003) { - this.manager.reportDeath(); - } else if (!closeEvent.wasClean && openTimestamp) { - var lifespan = util.now() - openTimestamp; - if (lifespan < 2 * this.maxPingDelay) { - this.manager.reportDeath(); - this.pingDelay = Math.max(lifespan / 2, this.minPingDelay); - } - } - }; - connection.bind("open", onOpen); - return connection; - } - isSupported(environment) { - return this.manager.isAlive() && this.transport.isSupported(environment); - } - } - const Protocol = { - decodeMessage: function(messageEvent) { - try { - var messageData = JSON.parse(messageEvent.data); - var pusherEventData = messageData.data; - if (typeof pusherEventData === "string") { - try { - pusherEventData = JSON.parse(messageData.data); - } catch (e) { - } - } - var pusherEvent = { - event: messageData.event, - channel: messageData.channel, - data: pusherEventData - }; - if (messageData.user_id) { - pusherEvent.user_id = messageData.user_id; - } - return pusherEvent; - } catch (e) { - throw { type: "MessageParseError", error: e, data: messageEvent.data }; - } - }, - encodeMessage: function(event) { - return JSON.stringify(event); - }, - processHandshake: function(messageEvent) { - var message = Protocol.decodeMessage(messageEvent); - if (message.event === "pusher:connection_established") { - if (!message.data.activity_timeout) { - throw "No activity timeout specified in handshake"; - } - return { - action: "connected", - id: message.data.socket_id, - activityTimeout: message.data.activity_timeout * 1e3 - }; - } else if (message.event === "pusher:error") { - return { - action: this.getCloseAction(message.data), - error: this.getCloseError(message.data) - }; - } else { - throw "Invalid handshake"; - } - }, - getCloseAction: function(closeEvent) { - if (closeEvent.code < 4e3) { - if (closeEvent.code >= 1002 && closeEvent.code <= 1004) { - return "backoff"; - } else { - return null; - } - } else if (closeEvent.code === 4e3) { - return "tls_only"; - } else if (closeEvent.code < 4100) { - return "refused"; - } else if (closeEvent.code < 4200) { - return "backoff"; - } else if (closeEvent.code < 4300) { - return "retry"; - } else { - return "refused"; - } - }, - getCloseError: function(closeEvent) { - if (closeEvent.code !== 1e3 && closeEvent.code !== 1001) { - return { - type: "PusherError", - data: { - code: closeEvent.code, - message: closeEvent.reason || closeEvent.message - } - }; - } else { - return null; - } - } - }; - const protocol = Protocol; - class Connection extends Dispatcher { - constructor(id, transport) { - super(); - this.id = id; - this.transport = transport; - this.activityTimeout = transport.activityTimeout; - this.bindListeners(); - } - handlesActivityChecks() { - return this.transport.handlesActivityChecks(); - } - send(data) { - return this.transport.send(data); - } - send_event(name, data, channel) { - var event = { event: name, data }; - if (channel) { - event.channel = channel; - } - logger.debug("Event sent", event); - return this.send(protocol.encodeMessage(event)); - } - ping() { - if (this.transport.supportsPing()) { - this.transport.ping(); - } else { - this.send_event("pusher:ping", {}); - } - } - close() { - this.transport.close(); - } - bindListeners() { - var listeners = { - message: (messageEvent) => { - var pusherEvent; - try { - pusherEvent = protocol.decodeMessage(messageEvent); - } catch (e) { - this.emit("error", { - type: "MessageParseError", - error: e, - data: messageEvent.data - }); - } - if (pusherEvent !== void 0) { - logger.debug("Event recd", pusherEvent); - switch (pusherEvent.event) { - case "pusher:error": - this.emit("error", { - type: "PusherError", - data: pusherEvent.data - }); - break; - case "pusher:ping": - this.emit("ping"); - break; - case "pusher:pong": - this.emit("pong"); - break; - } - this.emit("message", pusherEvent); - } - }, - activity: () => { - this.emit("activity"); - }, - error: (error) => { - this.emit("error", error); - }, - closed: (closeEvent) => { - unbindListeners(); - if (closeEvent && closeEvent.code) { - this.handleCloseEvent(closeEvent); - } - this.transport = null; - this.emit("closed"); - } - }; - var unbindListeners = () => { - objectApply(listeners, (listener, event) => { - this.transport.unbind(event, listener); - }); - }; - objectApply(listeners, (listener, event) => { - this.transport.bind(event, listener); - }); - } - handleCloseEvent(closeEvent) { - var action = protocol.getCloseAction(closeEvent); - var error = protocol.getCloseError(closeEvent); - if (error) { - this.emit("error", error); - } - if (action) { - this.emit(action, { action, error }); - } - } - } - class Handshake { - constructor(transport, callback) { - this.transport = transport; - this.callback = callback; - this.bindListeners(); - } - close() { - this.unbindListeners(); - this.transport.close(); - } - bindListeners() { - this.onMessage = (m2) => { - this.unbindListeners(); - var result; - try { - result = protocol.processHandshake(m2); - } catch (e) { - this.finish("error", { error: e }); - this.transport.close(); - return; - } - if (result.action === "connected") { - this.finish("connected", { - connection: new Connection(result.id, this.transport), - activityTimeout: result.activityTimeout - }); - } else { - this.finish(result.action, { error: result.error }); - this.transport.close(); - } - }; - this.onClosed = (closeEvent) => { - this.unbindListeners(); - var action = protocol.getCloseAction(closeEvent) || "backoff"; - var error = protocol.getCloseError(closeEvent); - this.finish(action, { error }); - }; - this.transport.bind("message", this.onMessage); - this.transport.bind("closed", this.onClosed); - } - unbindListeners() { - this.transport.unbind("message", this.onMessage); - this.transport.unbind("closed", this.onClosed); - } - finish(action, params) { - this.callback(extend({ transport: this.transport, action }, params)); - } - } - class TimelineSender { - constructor(timeline, options) { - this.timeline = timeline; - this.options = options || {}; - } - send(useTLS, callback) { - if (this.timeline.isEmpty()) { - return; - } - this.timeline.send(node_runtime.TimelineTransport.getAgent(this, useTLS), callback); - } - } - class BadEventName extends Error { - constructor(msg) { - super(msg); - Object.setPrototypeOf(this, new.target.prototype); - } - } - class BadChannelName extends Error { - constructor(msg) { - super(msg); - Object.setPrototypeOf(this, new.target.prototype); - } - } - class TransportPriorityTooLow extends Error { - constructor(msg) { - super(msg); - Object.setPrototypeOf(this, new.target.prototype); - } - } - class TransportClosed extends Error { - constructor(msg) { - super(msg); - Object.setPrototypeOf(this, new.target.prototype); - } - } - class UnsupportedFeature extends Error { - constructor(msg) { - super(msg); - Object.setPrototypeOf(this, new.target.prototype); - } - } - class UnsupportedTransport extends Error { - constructor(msg) { - super(msg); - Object.setPrototypeOf(this, new.target.prototype); - } - } - class UnsupportedStrategy extends Error { - constructor(msg) { - super(msg); - Object.setPrototypeOf(this, new.target.prototype); - } - } - class HTTPAuthError extends Error { - constructor(status, msg) { - super(msg); - this.status = status; - Object.setPrototypeOf(this, new.target.prototype); - } - } - const urlStore = { - baseUrl: "https://pusher.com", - urls: { - authenticationEndpoint: { - path: "/docs/channels/server_api/authenticating_users" - }, - authorizationEndpoint: { - path: "/docs/channels/server_api/authorizing-users/" - }, - javascriptQuickStart: { - path: "/docs/javascript_quick_start" - }, - triggeringClientEvents: { - path: "/docs/client_api_guide/client_events#trigger-events" - }, - encryptedChannelSupport: { - fullUrl: "https://github.com/pusher/pusher-js/tree/cc491015371a4bde5743d1c87a0fbac0feb53195#encrypted-channel-support" - } - } - }; - const buildLogSuffix = function(key) { - const urlPrefix = "See:"; - const urlObj = urlStore.urls[key]; - if (!urlObj) - return ""; - let url; - if (urlObj.fullUrl) { - url = urlObj.fullUrl; - } else if (urlObj.path) { - url = urlStore.baseUrl + urlObj.path; - } - if (!url) - return ""; - return `${urlPrefix} ${url}`; - }; - const url_store = { buildLogSuffix }; - class Channel extends Dispatcher { - constructor(name, pusher3) { - super(function(event, data) { - logger.debug("No callbacks on " + name + " for " + event); - }); - this.name = name; - this.pusher = pusher3; - this.subscribed = false; - this.subscriptionPending = false; - this.subscriptionCancelled = false; - } - authorize(socketId, callback) { - return callback(null, { auth: "" }); - } - trigger(event, data) { - if (event.indexOf("client-") !== 0) { - throw new BadEventName("Event '" + event + "' does not start with 'client-'"); - } - if (!this.subscribed) { - var suffix = url_store.buildLogSuffix("triggeringClientEvents"); - logger.warn(`Client event triggered before channel 'subscription_succeeded' event . ${suffix}`); - } - return this.pusher.send_event(event, data, this.name); - } - disconnect() { - this.subscribed = false; - this.subscriptionPending = false; - } - handleEvent(event) { - var eventName = event.event; - var data = event.data; - if (eventName === "pusher_internal:subscription_succeeded") { - this.handleSubscriptionSucceededEvent(event); - } else if (eventName === "pusher_internal:subscription_count") { - this.handleSubscriptionCountEvent(event); - } else if (eventName.indexOf("pusher_internal:") !== 0) { - var metadata = {}; - this.emit(eventName, data, metadata); - } - } - handleSubscriptionSucceededEvent(event) { - this.subscriptionPending = false; - this.subscribed = true; - if (this.subscriptionCancelled) { - this.pusher.unsubscribe(this.name); - } else { - this.emit("pusher:subscription_succeeded", event.data); - } - } - handleSubscriptionCountEvent(event) { - if (event.data.subscription_count) { - this.subscriptionCount = event.data.subscription_count; - } - this.emit("pusher:subscription_count", event.data); - } - subscribe() { - if (this.subscribed) { - return; - } - this.subscriptionPending = true; - this.subscriptionCancelled = false; - this.authorize(this.pusher.connection.socket_id, (error, data) => { - if (error) { - this.subscriptionPending = false; - logger.error(error.toString()); - this.emit("pusher:subscription_error", Object.assign({}, { - type: "AuthError", - error: error.message - }, error instanceof HTTPAuthError ? { status: error.status } : {})); - } else { - this.pusher.send_event("pusher:subscribe", { - auth: data.auth, - channel_data: data.channel_data, - channel: this.name - }); - } - }); - } - unsubscribe() { - this.subscribed = false; - this.pusher.send_event("pusher:unsubscribe", { - channel: this.name - }); - } - cancelSubscription() { - this.subscriptionCancelled = true; - } - reinstateSubscription() { - this.subscriptionCancelled = false; - } - } - class PrivateChannel extends Channel { - authorize(socketId, callback) { - return this.pusher.config.channelAuthorizer({ - channelName: this.name, - socketId - }, callback); - } - } - class Members { - constructor() { - this.reset(); - } - get(id) { - if (Object.prototype.hasOwnProperty.call(this.members, id)) { - return { - id, - info: this.members[id] - }; - } else { - return null; - } - } - each(callback) { - objectApply(this.members, (member, id) => { - callback(this.get(id)); - }); - } - setMyID(id) { - this.myID = id; - } - onSubscription(subscriptionData) { - this.members = subscriptionData.presence.hash; - this.count = subscriptionData.presence.count; - this.me = this.get(this.myID); - } - addMember(memberData) { - if (this.get(memberData.user_id) === null) { - this.count++; - } - this.members[memberData.user_id] = memberData.user_info; - return this.get(memberData.user_id); - } - removeMember(memberData) { - var member = this.get(memberData.user_id); - if (member) { - delete this.members[memberData.user_id]; - this.count--; - } - return member; - } - reset() { - this.members = {}; - this.count = 0; - this.myID = null; - this.me = null; - } - } - var __awaiter = function(thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P ? value : new P(function(resolve) { - resolve(value); - }); - } - return new (P || (P = Promise))(function(resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; - class PresenceChannel extends PrivateChannel { - constructor(name, pusher3) { - super(name, pusher3); - this.members = new Members(); - } - authorize(socketId, callback) { - super.authorize(socketId, (error, authData) => __awaiter(this, void 0, void 0, function* () { - if (!error) { - authData = authData; - if (authData.channel_data != null) { - var channelData = JSON.parse(authData.channel_data); - this.members.setMyID(channelData.user_id); - } else { - yield this.pusher.user.signinDonePromise; - if (this.pusher.user.user_data != null) { - this.members.setMyID(this.pusher.user.user_data.id); - } else { - let suffix = url_store.buildLogSuffix("authorizationEndpoint"); - logger.error(`Invalid auth response for channel '${this.name}', expected 'channel_data' field. ${suffix}, or the user should be signed in.`); - callback("Invalid auth response"); - return; - } - } - } - callback(error, authData); - })); - } - handleEvent(event) { - var eventName = event.event; - if (eventName.indexOf("pusher_internal:") === 0) { - this.handleInternalEvent(event); - } else { - var data = event.data; - var metadata = {}; - if (event.user_id) { - metadata.user_id = event.user_id; - } - this.emit(eventName, data, metadata); - } - } - handleInternalEvent(event) { - var eventName = event.event; - var data = event.data; - switch (eventName) { - case "pusher_internal:subscription_succeeded": - this.handleSubscriptionSucceededEvent(event); - break; - case "pusher_internal:subscription_count": - this.handleSubscriptionCountEvent(event); - break; - case "pusher_internal:member_added": - var addedMember = this.members.addMember(data); - this.emit("pusher:member_added", addedMember); - break; - case "pusher_internal:member_removed": - var removedMember = this.members.removeMember(data); - if (removedMember) { - this.emit("pusher:member_removed", removedMember); - } - break; - } - } - handleSubscriptionSucceededEvent(event) { - this.subscriptionPending = false; - this.subscribed = true; - if (this.subscriptionCancelled) { - this.pusher.unsubscribe(this.name); - } else { - this.members.onSubscription(event.data); - this.emit("pusher:subscription_succeeded", this.members); - } - } - disconnect() { - this.members.reset(); - super.disconnect(); - } - } - var utf8 = __webpack_require__2(978); - var base64 = __webpack_require__2(594); - class EncryptedChannel extends PrivateChannel { - constructor(name, pusher3, nacl) { - super(name, pusher3); - this.key = null; - this.nacl = nacl; - } - authorize(socketId, callback) { - super.authorize(socketId, (error, authData) => { - if (error) { - callback(error, authData); - return; - } - let sharedSecret = authData["shared_secret"]; - if (!sharedSecret) { - callback(new Error(`No shared_secret key in auth payload for encrypted channel: ${this.name}`), null); - return; - } - this.key = (0, base64.decode)(sharedSecret); - delete authData["shared_secret"]; - callback(null, authData); - }); - } - trigger(event, data) { - throw new UnsupportedFeature("Client events are not currently supported for encrypted channels"); - } - handleEvent(event) { - var eventName = event.event; - var data = event.data; - if (eventName.indexOf("pusher_internal:") === 0 || eventName.indexOf("pusher:") === 0) { - super.handleEvent(event); - return; - } - this.handleEncryptedEvent(eventName, data); - } - handleEncryptedEvent(event, data) { - if (!this.key) { - logger.debug("Received encrypted event before key has been retrieved from the authEndpoint"); - return; - } - if (!data.ciphertext || !data.nonce) { - logger.error("Unexpected format for encrypted event, expected object with `ciphertext` and `nonce` fields, got: " + data); - return; - } - let cipherText = (0, base64.decode)(data.ciphertext); - if (cipherText.length < this.nacl.secretbox.overheadLength) { - logger.error(`Expected encrypted event ciphertext length to be ${this.nacl.secretbox.overheadLength}, got: ${cipherText.length}`); - return; - } - let nonce = (0, base64.decode)(data.nonce); - if (nonce.length < this.nacl.secretbox.nonceLength) { - logger.error(`Expected encrypted event nonce length to be ${this.nacl.secretbox.nonceLength}, got: ${nonce.length}`); - return; - } - let bytes = this.nacl.secretbox.open(cipherText, nonce, this.key); - if (bytes === null) { - logger.debug("Failed to decrypt an event, probably because it was encrypted with a different key. Fetching a new key from the authEndpoint..."); - this.authorize(this.pusher.connection.socket_id, (error, authData) => { - if (error) { - logger.error(`Failed to make a request to the authEndpoint: ${authData}. Unable to fetch new key, so dropping encrypted event`); - return; - } - bytes = this.nacl.secretbox.open(cipherText, nonce, this.key); - if (bytes === null) { - logger.error(`Failed to decrypt event with new key. Dropping encrypted event`); - return; - } - this.emit(event, this.getDataToEmit(bytes)); - return; - }); - return; - } - this.emit(event, this.getDataToEmit(bytes)); - } - getDataToEmit(bytes) { - let raw = (0, utf8.D4)(bytes); - try { - return JSON.parse(raw); - } catch (_a) { - return raw; - } - } - } - class ConnectionManager extends Dispatcher { - constructor(key, options) { - super(); - this.state = "initialized"; - this.connection = null; - this.key = key; - this.options = options; - this.timeline = this.options.timeline; - this.usingTLS = this.options.useTLS; - this.errorCallbacks = this.buildErrorCallbacks(); - this.connectionCallbacks = this.buildConnectionCallbacks(this.errorCallbacks); - this.handshakeCallbacks = this.buildHandshakeCallbacks(this.errorCallbacks); - var Network2 = node_runtime.getNetwork(); - Network2.bind("online", () => { - this.timeline.info({ netinfo: "online" }); - if (this.state === "connecting" || this.state === "unavailable") { - this.retryIn(0); - } - }); - Network2.bind("offline", () => { - this.timeline.info({ netinfo: "offline" }); - if (this.connection) { - this.sendActivityCheck(); - } - }); - this.updateStrategy(); - } - switchCluster(key) { - this.key = key; - this.updateStrategy(); - this.retryIn(0); - } - connect() { - if (this.connection || this.runner) { - return; - } - if (!this.strategy.isSupported()) { - this.updateState("failed"); - return; - } - this.updateState("connecting"); - this.startConnecting(); - this.setUnavailableTimer(); - } - send(data) { - if (this.connection) { - return this.connection.send(data); - } else { - return false; - } - } - send_event(name, data, channel) { - if (this.connection) { - return this.connection.send_event(name, data, channel); - } else { - return false; - } - } - disconnect() { - this.disconnectInternally(); - this.updateState("disconnected"); - } - isUsingTLS() { - return this.usingTLS; - } - startConnecting() { - var callback = (error, handshake) => { - if (error) { - this.runner = this.strategy.connect(0, callback); - } else { - if (handshake.action === "error") { - this.emit("error", { - type: "HandshakeError", - error: handshake.error - }); - this.timeline.error({ handshakeError: handshake.error }); - } else { - this.abortConnecting(); - this.handshakeCallbacks[handshake.action](handshake); - } - } - }; - this.runner = this.strategy.connect(0, callback); - } - abortConnecting() { - if (this.runner) { - this.runner.abort(); - this.runner = null; - } - } - disconnectInternally() { - this.abortConnecting(); - this.clearRetryTimer(); - this.clearUnavailableTimer(); - if (this.connection) { - var connection = this.abandonConnection(); - connection.close(); - } - } - updateStrategy() { - this.strategy = this.options.getStrategy({ - key: this.key, - timeline: this.timeline, - useTLS: this.usingTLS - }); - } - retryIn(delay) { - this.timeline.info({ action: "retry", delay }); - if (delay > 0) { - this.emit("connecting_in", Math.round(delay / 1e3)); - } - this.retryTimer = new OneOffTimer(delay || 0, () => { - this.disconnectInternally(); - this.connect(); - }); - } - clearRetryTimer() { - if (this.retryTimer) { - this.retryTimer.ensureAborted(); - this.retryTimer = null; - } - } - setUnavailableTimer() { - this.unavailableTimer = new OneOffTimer(this.options.unavailableTimeout, () => { - this.updateState("unavailable"); - }); - } - clearUnavailableTimer() { - if (this.unavailableTimer) { - this.unavailableTimer.ensureAborted(); - } - } - sendActivityCheck() { - this.stopActivityCheck(); - this.connection.ping(); - this.activityTimer = new OneOffTimer(this.options.pongTimeout, () => { - this.timeline.error({ pong_timed_out: this.options.pongTimeout }); - this.retryIn(0); - }); - } - resetActivityCheck() { - this.stopActivityCheck(); - if (this.connection && !this.connection.handlesActivityChecks()) { - this.activityTimer = new OneOffTimer(this.activityTimeout, () => { - this.sendActivityCheck(); - }); - } - } - stopActivityCheck() { - if (this.activityTimer) { - this.activityTimer.ensureAborted(); - } - } - buildConnectionCallbacks(errorCallbacks) { - return extend({}, errorCallbacks, { - message: (message) => { - this.resetActivityCheck(); - this.emit("message", message); - }, - ping: () => { - this.send_event("pusher:pong", {}); - }, - activity: () => { - this.resetActivityCheck(); - }, - error: (error) => { - this.emit("error", error); - }, - closed: () => { - this.abandonConnection(); - if (this.shouldRetry()) { - this.retryIn(1e3); - } - } - }); - } - buildHandshakeCallbacks(errorCallbacks) { - return extend({}, errorCallbacks, { - connected: (handshake) => { - this.activityTimeout = Math.min(this.options.activityTimeout, handshake.activityTimeout, handshake.connection.activityTimeout || Infinity); - this.clearUnavailableTimer(); - this.setConnection(handshake.connection); - this.socket_id = this.connection.id; - this.updateState("connected", { socket_id: this.socket_id }); - } - }); - } - buildErrorCallbacks() { - let withErrorEmitted = (callback) => { - return (result) => { - if (result.error) { - this.emit("error", { type: "WebSocketError", error: result.error }); - } - callback(result); - }; - }; - return { - tls_only: withErrorEmitted(() => { - this.usingTLS = true; - this.updateStrategy(); - this.retryIn(0); - }), - refused: withErrorEmitted(() => { - this.disconnect(); - }), - backoff: withErrorEmitted(() => { - this.retryIn(1e3); - }), - retry: withErrorEmitted(() => { - this.retryIn(0); - }) - }; - } - setConnection(connection) { - this.connection = connection; - for (var event in this.connectionCallbacks) { - this.connection.bind(event, this.connectionCallbacks[event]); - } - this.resetActivityCheck(); - } - abandonConnection() { - if (!this.connection) { - return; - } - this.stopActivityCheck(); - for (var event in this.connectionCallbacks) { - this.connection.unbind(event, this.connectionCallbacks[event]); - } - var connection = this.connection; - this.connection = null; - return connection; - } - updateState(newState, data) { - var previousState = this.state; - this.state = newState; - if (previousState !== newState) { - var newStateDescription = newState; - if (newStateDescription === "connected") { - newStateDescription += " with new socket ID " + data.socket_id; - } - logger.debug("State changed", previousState + " -> " + newStateDescription); - this.timeline.info({ state: newState, params: data }); - this.emit("state_change", { previous: previousState, current: newState }); - this.emit(newState, data); - } - } - shouldRetry() { - return this.state === "connecting" || this.state === "connected"; - } - } - class Channels { - constructor() { - this.channels = {}; - } - add(name, pusher3) { - if (!this.channels[name]) { - this.channels[name] = createChannel(name, pusher3); - } - return this.channels[name]; - } - all() { - return values(this.channels); - } - find(name) { - return this.channels[name]; - } - remove(name) { - var channel = this.channels[name]; - delete this.channels[name]; - return channel; - } - disconnect() { - objectApply(this.channels, function(channel) { - channel.disconnect(); - }); - } - } - function createChannel(name, pusher3) { - if (name.indexOf("private-encrypted-") === 0) { - if (pusher3.config.nacl) { - return factory.createEncryptedChannel(name, pusher3, pusher3.config.nacl); - } - let errMsg = "Tried to subscribe to a private-encrypted- channel but no nacl implementation available"; - let suffix = url_store.buildLogSuffix("encryptedChannelSupport"); - throw new UnsupportedFeature(`${errMsg}. ${suffix}`); - } else if (name.indexOf("private-") === 0) { - return factory.createPrivateChannel(name, pusher3); - } else if (name.indexOf("presence-") === 0) { - return factory.createPresenceChannel(name, pusher3); - } else if (name.indexOf("#") === 0) { - throw new BadChannelName('Cannot create a channel with name "' + name + '".'); - } else { - return factory.createChannel(name, pusher3); - } - } - var Factory = { - createChannels() { - return new Channels(); - }, - createConnectionManager(key, options) { - return new ConnectionManager(key, options); - }, - createChannel(name, pusher3) { - return new Channel(name, pusher3); - }, - createPrivateChannel(name, pusher3) { - return new PrivateChannel(name, pusher3); - }, - createPresenceChannel(name, pusher3) { - return new PresenceChannel(name, pusher3); - }, - createEncryptedChannel(name, pusher3, nacl) { - return new EncryptedChannel(name, pusher3, nacl); - }, - createTimelineSender(timeline, options) { - return new TimelineSender(timeline, options); - }, - createHandshake(transport, callback) { - return new Handshake(transport, callback); - }, - createAssistantToTheTransportManager(manager, transport, options) { - return new AssistantToTheTransportManager(manager, transport, options); - } - }; - const factory = Factory; - class TransportManager { - constructor(options) { - this.options = options || {}; - this.livesLeft = this.options.lives || Infinity; - } - getAssistant(transport) { - return factory.createAssistantToTheTransportManager(this, transport, { - minPingDelay: this.options.minPingDelay, - maxPingDelay: this.options.maxPingDelay - }); - } - isAlive() { - return this.livesLeft > 0; - } - reportDeath() { - this.livesLeft -= 1; - } - } - class SequentialStrategy { - constructor(strategies, options) { - this.strategies = strategies; - this.loop = Boolean(options.loop); - this.failFast = Boolean(options.failFast); - this.timeout = options.timeout; - this.timeoutLimit = options.timeoutLimit; - } - isSupported() { - return any(this.strategies, util.method("isSupported")); - } - connect(minPriority, callback) { - var strategies = this.strategies; - var current = 0; - var timeout = this.timeout; - var runner = null; - var tryNextStrategy = (error, handshake) => { - if (handshake) { - callback(null, handshake); - } else { - current = current + 1; - if (this.loop) { - current = current % strategies.length; - } - if (current < strategies.length) { - if (timeout) { - timeout = timeout * 2; - if (this.timeoutLimit) { - timeout = Math.min(timeout, this.timeoutLimit); - } - } - runner = this.tryStrategy(strategies[current], minPriority, { timeout, failFast: this.failFast }, tryNextStrategy); - } else { - callback(true); - } - } - }; - runner = this.tryStrategy(strategies[current], minPriority, { timeout, failFast: this.failFast }, tryNextStrategy); - return { - abort: function() { - runner.abort(); - }, - forceMinPriority: function(p2) { - minPriority = p2; - if (runner) { - runner.forceMinPriority(p2); - } - } - }; - } - tryStrategy(strategy, minPriority, options, callback) { - var timer = null; - var runner = null; - if (options.timeout > 0) { - timer = new OneOffTimer(options.timeout, function() { - runner.abort(); - callback(true); - }); - } - runner = strategy.connect(minPriority, function(error, handshake) { - if (error && timer && timer.isRunning() && !options.failFast) { - return; - } - if (timer) { - timer.ensureAborted(); - } - callback(error, handshake); - }); - return { - abort: function() { - if (timer) { - timer.ensureAborted(); - } - runner.abort(); - }, - forceMinPriority: function(p2) { - runner.forceMinPriority(p2); - } - }; - } - } - class BestConnectedEverStrategy { - constructor(strategies) { - this.strategies = strategies; - } - isSupported() { - return any(this.strategies, util.method("isSupported")); - } - connect(minPriority, callback) { - return connect(this.strategies, minPriority, function(i, runners) { - return function(error, handshake) { - runners[i].error = error; - if (error) { - if (allRunnersFailed(runners)) { - callback(true); - } - return; - } - apply(runners, function(runner) { - runner.forceMinPriority(handshake.transport.priority); - }); - callback(null, handshake); - }; - }); - } - } - function connect(strategies, minPriority, callbackBuilder) { - var runners = map(strategies, function(strategy, i, _2, rs) { - return strategy.connect(minPriority, callbackBuilder(i, rs)); - }); - return { - abort: function() { - apply(runners, abortRunner); - }, - forceMinPriority: function(p2) { - apply(runners, function(runner) { - runner.forceMinPriority(p2); - }); - } - }; - } - function allRunnersFailed(runners) { - return collections_all(runners, function(runner) { - return Boolean(runner.error); - }); - } - function abortRunner(runner) { - if (!runner.error && !runner.aborted) { - runner.abort(); - runner.aborted = true; - } - } - class WebSocketPrioritizedCachedStrategy { - constructor(strategy, transports2, options) { - this.strategy = strategy; - this.transports = transports2; - this.ttl = options.ttl || 1800 * 1e3; - this.usingTLS = options.useTLS; - this.timeline = options.timeline; - } - isSupported() { - return this.strategy.isSupported(); - } - connect(minPriority, callback) { - var usingTLS = this.usingTLS; - var info = fetchTransportCache(usingTLS); - var cacheSkipCount = info && info.cacheSkipCount ? info.cacheSkipCount : 0; - var strategies = [this.strategy]; - if (info && info.timestamp + this.ttl >= util.now()) { - var transport = this.transports[info.transport]; - if (transport) { - if (["ws", "wss"].includes(info.transport) || cacheSkipCount > 3) { - this.timeline.info({ - cached: true, - transport: info.transport, - latency: info.latency - }); - strategies.push(new SequentialStrategy([transport], { - timeout: info.latency * 2 + 1e3, - failFast: true - })); - } else { - cacheSkipCount++; - } - } - } - var startTimestamp = util.now(); - var runner = strategies.pop().connect(minPriority, function cb(error, handshake) { - if (error) { - flushTransportCache(usingTLS); - if (strategies.length > 0) { - startTimestamp = util.now(); - runner = strategies.pop().connect(minPriority, cb); - } else { - callback(error); - } - } else { - storeTransportCache(usingTLS, handshake.transport.name, util.now() - startTimestamp, cacheSkipCount); - callback(null, handshake); - } - }); - return { - abort: function() { - runner.abort(); - }, - forceMinPriority: function(p2) { - minPriority = p2; - if (runner) { - runner.forceMinPriority(p2); - } - } - }; - } - } - function getTransportCacheKey(usingTLS) { - return "pusherTransport" + (usingTLS ? "TLS" : "NonTLS"); - } - function fetchTransportCache(usingTLS) { - var storage = node_runtime.getLocalStorage(); - if (storage) { - try { - var serializedCache = storage[getTransportCacheKey(usingTLS)]; - if (serializedCache) { - return JSON.parse(serializedCache); - } - } catch (e) { - flushTransportCache(usingTLS); - } - } - return null; - } - function storeTransportCache(usingTLS, transport, latency, cacheSkipCount) { - var storage = node_runtime.getLocalStorage(); - if (storage) { - try { - storage[getTransportCacheKey(usingTLS)] = safeJSONStringify({ - timestamp: util.now(), - transport, - latency, - cacheSkipCount - }); - } catch (e) { - } - } - } - function flushTransportCache(usingTLS) { - var storage = node_runtime.getLocalStorage(); - if (storage) { - try { - delete storage[getTransportCacheKey(usingTLS)]; - } catch (e) { - } - } - } - class DelayedStrategy { - constructor(strategy, { delay: number }) { - this.strategy = strategy; - this.options = { delay: number }; - } - isSupported() { - return this.strategy.isSupported(); - } - connect(minPriority, callback) { - var strategy = this.strategy; - var runner; - var timer = new OneOffTimer(this.options.delay, function() { - runner = strategy.connect(minPriority, callback); - }); - return { - abort: function() { - timer.ensureAborted(); - if (runner) { - runner.abort(); - } - }, - forceMinPriority: function(p2) { - minPriority = p2; - if (runner) { - runner.forceMinPriority(p2); - } - } - }; - } - } - class IfStrategy { - constructor(test, trueBranch, falseBranch) { - this.test = test; - this.trueBranch = trueBranch; - this.falseBranch = falseBranch; - } - isSupported() { - var branch = this.test() ? this.trueBranch : this.falseBranch; - return branch.isSupported(); - } - connect(minPriority, callback) { - var branch = this.test() ? this.trueBranch : this.falseBranch; - return branch.connect(minPriority, callback); - } - } - class FirstConnectedStrategy { - constructor(strategy) { - this.strategy = strategy; - } - isSupported() { - return this.strategy.isSupported(); - } - connect(minPriority, callback) { - var runner = this.strategy.connect(minPriority, function(error, handshake) { - if (handshake) { - runner.abort(); - } - callback(error, handshake); - }); - return runner; - } - } - function testSupportsStrategy(strategy) { - return function() { - return strategy.isSupported(); - }; - } - var getDefaultStrategy = function(config, baseOptions, defineTransport2) { - var definedTransports = {}; - function defineTransportStrategy(name, type, priority, options, manager) { - var transport = defineTransport2(config, name, type, priority, options, manager); - definedTransports[name] = transport; - return transport; - } - var ws_options = Object.assign({}, baseOptions, { - hostNonTLS: config.wsHost + ":" + config.wsPort, - hostTLS: config.wsHost + ":" + config.wssPort, - httpPath: config.wsPath - }); - var wss_options = extend({}, ws_options, { - useTLS: true - }); - var http_options = Object.assign({}, baseOptions, { - hostNonTLS: config.httpHost + ":" + config.httpPort, - hostTLS: config.httpHost + ":" + config.httpsPort, - httpPath: config.httpPath - }); - var timeouts = { - loop: true, - timeout: 15e3, - timeoutLimit: 6e4 - }; - var ws_manager = new TransportManager({ - minPingDelay: 1e4, - maxPingDelay: config.activityTimeout - }); - var streaming_manager = new TransportManager({ - lives: 2, - minPingDelay: 1e4, - maxPingDelay: config.activityTimeout - }); - var ws_transport = defineTransportStrategy("ws", "ws", 3, ws_options, ws_manager); - var wss_transport = defineTransportStrategy("wss", "ws", 3, wss_options, ws_manager); - var xhr_streaming_transport = defineTransportStrategy("xhr_streaming", "xhr_streaming", 1, http_options, streaming_manager); - var xhr_polling_transport = defineTransportStrategy("xhr_polling", "xhr_polling", 1, http_options); - var ws_loop = new SequentialStrategy([ws_transport], timeouts); - var wss_loop = new SequentialStrategy([wss_transport], timeouts); - var streaming_loop = new SequentialStrategy([xhr_streaming_transport], timeouts); - var polling_loop = new SequentialStrategy([xhr_polling_transport], timeouts); - var http_loop = new SequentialStrategy([ - new IfStrategy(testSupportsStrategy(streaming_loop), new BestConnectedEverStrategy([ - streaming_loop, - new DelayedStrategy(polling_loop, { delay: 4e3 }) - ]), polling_loop) - ], timeouts); - var wsStrategy; - if (baseOptions.useTLS) { - wsStrategy = new BestConnectedEverStrategy([ - ws_loop, - new DelayedStrategy(http_loop, { delay: 2e3 }) - ]); - } else { - wsStrategy = new BestConnectedEverStrategy([ - ws_loop, - new DelayedStrategy(wss_loop, { delay: 2e3 }), - new DelayedStrategy(http_loop, { delay: 5e3 }) - ]); - } - return new WebSocketPrioritizedCachedStrategy(new FirstConnectedStrategy(new IfStrategy(testSupportsStrategy(ws_transport), wsStrategy, http_loop)), definedTransports, { - ttl: 18e5, - timeline: baseOptions.timeline, - useTLS: baseOptions.useTLS - }); - }; - const default_strategy = getDefaultStrategy; - function transport_connection_initializer() { - var self2 = this; - self2.timeline.info(self2.buildTimelineMessage({ - transport: self2.name + (self2.options.useTLS ? "s" : "") - })); - if (self2.hooks.isInitialized()) { - self2.changeState("initialized"); - } else { - self2.onClose(); - } - } - const MAX_BUFFER_LENGTH = 256 * 1024; - class HTTPRequest extends Dispatcher { - constructor(hooks2, method, url) { - super(); - this.hooks = hooks2; - this.method = method; - this.url = url; - } - start(payload) { - this.position = 0; - this.xhr = this.hooks.getRequest(this); - this.unloader = () => { - this.close(); - }; - node_runtime.addUnloadListener(this.unloader); - this.xhr.open(this.method, this.url, true); - if (this.xhr.setRequestHeader) { - this.xhr.setRequestHeader("Content-Type", "application/json"); - } - this.xhr.send(payload); - } - close() { - if (this.unloader) { - node_runtime.removeUnloadListener(this.unloader); - this.unloader = null; - } - if (this.xhr) { - this.hooks.abortRequest(this.xhr); - this.xhr = null; - } - } - onChunk(status, data) { - while (true) { - var chunk = this.advanceBuffer(data); - if (chunk) { - this.emit("chunk", { status, data: chunk }); - } else { - break; - } - } - if (this.isBufferTooLong(data)) { - this.emit("buffer_too_long"); - } - } - advanceBuffer(buffer) { - var unreadData = buffer.slice(this.position); - var endOfLinePosition = unreadData.indexOf("\n"); - if (endOfLinePosition !== -1) { - this.position += endOfLinePosition + 1; - return unreadData.slice(0, endOfLinePosition); - } else { - return null; - } - } - isBufferTooLong(buffer) { - return this.position === buffer.length && buffer.length > MAX_BUFFER_LENGTH; - } - } - var State; - (function(State2) { - State2[State2["CONNECTING"] = 0] = "CONNECTING"; - State2[State2["OPEN"] = 1] = "OPEN"; - State2[State2["CLOSED"] = 3] = "CLOSED"; - })(State || (State = {})); - const state = State; - var autoIncrement = 1; - class HTTPSocket { - constructor(hooks2, url) { - this.hooks = hooks2; - this.session = randomNumber(1e3) + "/" + randomString(8); - this.location = getLocation(url); - this.readyState = state.CONNECTING; - this.openStream(); - } - send(payload) { - return this.sendRaw(JSON.stringify([payload])); - } - ping() { - this.hooks.sendHeartbeat(this); - } - close(code, reason) { - this.onClose(code, reason, true); - } - sendRaw(payload) { - if (this.readyState === state.OPEN) { - try { - node_runtime.createSocketRequest("POST", getUniqueURL(getSendURL(this.location, this.session))).start(payload); - return true; - } catch (e) { - return false; - } - } else { - return false; - } - } - reconnect() { - this.closeStream(); - this.openStream(); - } - onClose(code, reason, wasClean) { - this.closeStream(); - this.readyState = state.CLOSED; - if (this.onclose) { - this.onclose({ - code, - reason, - wasClean - }); - } - } - onChunk(chunk) { - if (chunk.status !== 200) { - return; - } - if (this.readyState === state.OPEN) { - this.onActivity(); - } - var payload; - var type = chunk.data.slice(0, 1); - switch (type) { - case "o": - payload = JSON.parse(chunk.data.slice(1) || "{}"); - this.onOpen(payload); - break; - case "a": - payload = JSON.parse(chunk.data.slice(1) || "[]"); - for (var i = 0; i < payload.length; i++) { - this.onEvent(payload[i]); - } - break; - case "m": - payload = JSON.parse(chunk.data.slice(1) || "null"); - this.onEvent(payload); - break; - case "h": - this.hooks.onHeartbeat(this); - break; - case "c": - payload = JSON.parse(chunk.data.slice(1) || "[]"); - this.onClose(payload[0], payload[1], true); - break; - } - } - onOpen(options) { - if (this.readyState === state.CONNECTING) { - if (options && options.hostname) { - this.location.base = replaceHost(this.location.base, options.hostname); - } - this.readyState = state.OPEN; - if (this.onopen) { - this.onopen(); - } - } else { - this.onClose(1006, "Server lost session", true); - } - } - onEvent(event) { - if (this.readyState === state.OPEN && this.onmessage) { - this.onmessage({ data: event }); - } - } - onActivity() { - if (this.onactivity) { - this.onactivity(); - } - } - onError(error) { - if (this.onerror) { - this.onerror(error); - } - } - openStream() { - this.stream = node_runtime.createSocketRequest("POST", getUniqueURL(this.hooks.getReceiveURL(this.location, this.session))); - this.stream.bind("chunk", (chunk) => { - this.onChunk(chunk); - }); - this.stream.bind("finished", (status) => { - this.hooks.onFinished(this, status); - }); - this.stream.bind("buffer_too_long", () => { - this.reconnect(); - }); - try { - this.stream.start(); - } catch (error) { - util.defer(() => { - this.onError(error); - this.onClose(1006, "Could not start streaming", false); - }); - } - } - closeStream() { - if (this.stream) { - this.stream.unbind_all(); - this.stream.close(); - this.stream = null; - } - } - } - function getLocation(url) { - var parts = /([^\?]*)\/*(\??.*)/.exec(url); - return { - base: parts[1], - queryString: parts[2] - }; - } - function getSendURL(url, session) { - return url.base + "/" + session + "/xhr_send"; - } - function getUniqueURL(url) { - var separator = url.indexOf("?") === -1 ? "?" : "&"; - return url + separator + "t=" + +/* @__PURE__ */ new Date() + "&n=" + autoIncrement++; - } - function replaceHost(url, hostname) { - var urlParts = /(https?:\/\/)([^\/:]+)((\/|:)?.*)/.exec(url); - return urlParts[1] + hostname + urlParts[3]; - } - function randomNumber(max) { - return node_runtime.randomInt(max); - } - function randomString(length) { - var result = []; - for (var i = 0; i < length; i++) { - result.push(randomNumber(32).toString(32)); - } - return result.join(""); - } - const http_socket = HTTPSocket; - var hooks = { - getReceiveURL: function(url, session) { - return url.base + "/" + session + "/xhr_streaming" + url.queryString; - }, - onHeartbeat: function(socket) { - socket.sendRaw("[]"); - }, - sendHeartbeat: function(socket) { - socket.sendRaw("[]"); - }, - onFinished: function(socket, status) { - socket.onClose(1006, "Connection interrupted (" + status + ")", false); - } - }; - const http_streaming_socket = hooks; - var http_polling_socket_hooks = { - getReceiveURL: function(url, session) { - return url.base + "/" + session + "/xhr" + url.queryString; - }, - onHeartbeat: function() { - }, - sendHeartbeat: function(socket) { - socket.sendRaw("[]"); - }, - onFinished: function(socket, status) { - if (status === 200) { - socket.reconnect(); - } else { - socket.onClose(1006, "Connection interrupted (" + status + ")", false); - } - } - }; - const http_polling_socket = http_polling_socket_hooks; - var http_xhr_request_hooks = { - getRequest: function(socket) { - var Constructor = node_runtime.getXHRAPI(); - var xhr2 = new Constructor(); - xhr2.onreadystatechange = xhr2.onprogress = function() { - switch (xhr2.readyState) { - case 3: - if (xhr2.responseText && xhr2.responseText.length > 0) { - socket.onChunk(xhr2.status, xhr2.responseText); - } - break; - case 4: - if (xhr2.responseText && xhr2.responseText.length > 0) { - socket.onChunk(xhr2.status, xhr2.responseText); - } - socket.emit("finished", xhr2.status); - socket.close(); - break; - } - }; - return xhr2; - }, - abortRequest: function(xhr2) { - xhr2.onreadystatechange = null; - xhr2.abort(); - } - }; - const http_xhr_request = http_xhr_request_hooks; - var HTTP = { - createStreamingSocket(url) { - return this.createSocket(http_streaming_socket, url); - }, - createPollingSocket(url) { - return this.createSocket(http_polling_socket, url); - }, - createSocket(hooks2, url) { - return new http_socket(hooks2, url); - }, - createXHR(method, url) { - return this.createRequest(http_xhr_request, method, url); - }, - createRequest(hooks2, method, url) { - return new HTTPRequest(hooks2, method, url); - } - }; - const http_http = HTTP; - var Isomorphic = { - getDefaultStrategy: default_strategy, - Transports: transports, - transportConnectionInitializer: transport_connection_initializer, - HTTPFactory: http_http, - setup(PusherClass) { - PusherClass.ready(); - }, - getLocalStorage() { - return void 0; - }, - getClientFeatures() { - return keys(filterObject({ ws: transports.ws }, function(t) { - return t.isSupported({}); - })); - }, - getProtocol() { - return "http:"; - }, - isXHRSupported() { - return true; - }, - createSocketRequest(method, url) { - if (this.isXHRSupported()) { - return this.HTTPFactory.createXHR(method, url); - } else { - throw "Cross-origin HTTP requests are not supported"; - } - }, - createXHR() { - var Constructor = this.getXHRAPI(); - return new Constructor(); - }, - createWebSocket(url) { - var Constructor = this.getWebSocketAPI(); - return new Constructor(url); - }, - addUnloadListener(listener) { - }, - removeUnloadListener(listener) { - } - }; - const runtime = Isomorphic; - var websocket = __webpack_require__2(555); - var XMLHttpRequest = __webpack_require__2(407); - class NetInfo extends Dispatcher { - isOnline() { - return true; - } - } - var Network = new NetInfo(); - var AuthRequestType; - (function(AuthRequestType2) { - AuthRequestType2["UserAuthentication"] = "user-authentication"; - AuthRequestType2["ChannelAuthorization"] = "channel-authorization"; - })(AuthRequestType || (AuthRequestType = {})); - const ajax = function(context, query, authOptions, authRequestType, callback) { - const xhr2 = node_runtime.createXHR(); - xhr2.open("POST", authOptions.endpoint, true); - xhr2.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); - for (var headerName in authOptions.headers) { - xhr2.setRequestHeader(headerName, authOptions.headers[headerName]); - } - if (authOptions.headersProvider != null) { - let dynamicHeaders = authOptions.headersProvider(); - for (var headerName in dynamicHeaders) { - xhr2.setRequestHeader(headerName, dynamicHeaders[headerName]); - } - } - xhr2.onreadystatechange = function() { - if (xhr2.readyState === 4) { - if (xhr2.status === 200) { - let data; - let parsed = false; - try { - data = JSON.parse(xhr2.responseText); - parsed = true; - } catch (e) { - callback(new HTTPAuthError(200, `JSON returned from ${authRequestType.toString()} endpoint was invalid, yet status code was 200. Data was: ${xhr2.responseText}`), null); - } - if (parsed) { - callback(null, data); - } - } else { - let suffix = ""; - switch (authRequestType) { - case AuthRequestType.UserAuthentication: - suffix = url_store.buildLogSuffix("authenticationEndpoint"); - break; - case AuthRequestType.ChannelAuthorization: - suffix = `Clients must be authorized to join private or presence channels. ${url_store.buildLogSuffix("authorizationEndpoint")}`; - break; - } - callback(new HTTPAuthError(xhr2.status, `Unable to retrieve auth string from ${authRequestType.toString()} endpoint - received status: ${xhr2.status} from ${authOptions.endpoint}. ${suffix}`), null); - } - } - }; - xhr2.send(query); - return xhr2; - }; - const xhr_auth = ajax; - var getAgent = function(sender, useTLS) { - return function(data, callback) { - var scheme = "http" + (useTLS ? "s" : "") + "://"; - var url = scheme + (sender.host || sender.options.host) + sender.options.path; - var query = buildQueryString(data); - url += "/2?" + query; - var xhr2 = node_runtime.createXHR(); - xhr2.open("GET", url, true); - xhr2.onreadystatechange = function() { - if (xhr2.readyState === 4) { - let { status, responseText } = xhr2; - if (status !== 200) { - logger.debug(`TimelineSender Error: received ${status} from stats.pusher.com`); - return; - } - try { - var { host } = JSON.parse(responseText); - } catch (e) { - logger.debug(`TimelineSenderError: invalid response ${responseText}`); - } - if (host) { - sender.host = host; - } - } - }; - xhr2.send(); - }; - }; - var xhr = { - name: "xhr", - getAgent - }; - const xhr_timeline = xhr; - var external_crypto_ = __webpack_require__2(982); - const { getDefaultStrategy: runtime_getDefaultStrategy, Transports: runtime_Transports, setup, getProtocol, isXHRSupported, getLocalStorage, createXHR, createWebSocket, addUnloadListener, removeUnloadListener, transportConnectionInitializer, createSocketRequest, HTTPFactory } = runtime; - const NodeJS = { - getDefaultStrategy: runtime_getDefaultStrategy, - Transports: runtime_Transports, - setup, - getProtocol, - isXHRSupported, - createSocketRequest, - getLocalStorage, - createXHR, - createWebSocket, - addUnloadListener, - removeUnloadListener, - transportConnectionInitializer, - HTTPFactory, - TimelineTransport: xhr_timeline, - getAuthorizers() { - return { ajax: xhr_auth }; - }, - getWebSocketAPI() { - return websocket.Client; - }, - getXHRAPI() { - return XMLHttpRequest.z; - }, - getNetwork() { - return Network; - }, - randomInt(max) { - return (0, external_crypto_.randomInt)(max); - } - }; - const node_runtime = NodeJS; - var TimelineLevel; - (function(TimelineLevel2) { - TimelineLevel2[TimelineLevel2["ERROR"] = 3] = "ERROR"; - TimelineLevel2[TimelineLevel2["INFO"] = 6] = "INFO"; - TimelineLevel2[TimelineLevel2["DEBUG"] = 7] = "DEBUG"; - })(TimelineLevel || (TimelineLevel = {})); - const level = TimelineLevel; - class Timeline { - constructor(key, session, options) { - this.key = key; - this.session = session; - this.events = []; - this.options = options || {}; - this.sent = 0; - this.uniqueID = 0; - } - log(level2, event) { - if (level2 <= this.options.level) { - this.events.push(extend({}, event, { timestamp: util.now() })); - if (this.options.limit && this.events.length > this.options.limit) { - this.events.shift(); - } - } - } - error(event) { - this.log(level.ERROR, event); - } - info(event) { - this.log(level.INFO, event); - } - debug(event) { - this.log(level.DEBUG, event); - } - isEmpty() { - return this.events.length === 0; - } - send(sendfn, callback) { - var data = extend({ - session: this.session, - bundle: this.sent + 1, - key: this.key, - lib: "js", - version: this.options.version, - cluster: this.options.cluster, - features: this.options.features, - timeline: this.events - }, this.options.params); - this.events = []; - sendfn(data, (error, result) => { - if (!error) { - this.sent++; - } - if (callback) { - callback(error, result); - } - }); - return true; - } - generateUniqueID() { - this.uniqueID++; - return this.uniqueID; - } - } - class TransportStrategy { - constructor(name, priority, transport, options) { - this.name = name; - this.priority = priority; - this.transport = transport; - this.options = options || {}; - } - isSupported() { - return this.transport.isSupported({ - useTLS: this.options.useTLS - }); - } - connect(minPriority, callback) { - if (!this.isSupported()) { - return failAttempt(new UnsupportedStrategy(), callback); - } else if (this.priority < minPriority) { - return failAttempt(new TransportPriorityTooLow(), callback); - } - var connected = false; - var transport = this.transport.createConnection(this.name, this.priority, this.options.key, this.options); - var handshake = null; - var onInitialized = function() { - transport.unbind("initialized", onInitialized); - transport.connect(); - }; - var onOpen = function() { - handshake = factory.createHandshake(transport, function(result) { - connected = true; - unbindListeners(); - callback(null, result); - }); - }; - var onError = function(error) { - unbindListeners(); - callback(error); - }; - var onClosed = function() { - unbindListeners(); - var serializedTransport; - serializedTransport = safeJSONStringify(transport); - callback(new TransportClosed(serializedTransport)); - }; - var unbindListeners = function() { - transport.unbind("initialized", onInitialized); - transport.unbind("open", onOpen); - transport.unbind("error", onError); - transport.unbind("closed", onClosed); - }; - transport.bind("initialized", onInitialized); - transport.bind("open", onOpen); - transport.bind("error", onError); - transport.bind("closed", onClosed); - transport.initialize(); - return { - abort: () => { - if (connected) { - return; - } - unbindListeners(); - if (handshake) { - handshake.close(); - } else { - transport.close(); - } - }, - forceMinPriority: (p2) => { - if (connected) { - return; - } - if (this.priority < p2) { - if (handshake) { - handshake.close(); - } else { - transport.close(); - } - } - } - }; - } - } - function failAttempt(error, callback) { - util.defer(function() { - callback(error); - }); - return { - abort: function() { - }, - forceMinPriority: function() { - } - }; - } - const { Transports: strategy_builder_Transports } = node_runtime; - var defineTransport = function(config, name, type, priority, options, manager) { - var transportClass = strategy_builder_Transports[type]; - if (!transportClass) { - throw new UnsupportedTransport(type); - } - var enabled = (!config.enabledTransports || arrayIndexOf(config.enabledTransports, name) !== -1) && (!config.disabledTransports || arrayIndexOf(config.disabledTransports, name) === -1); - var transport; - if (enabled) { - options = Object.assign({ ignoreNullOrigin: config.ignoreNullOrigin }, options); - transport = new TransportStrategy(name, priority, manager ? manager.getAssistant(transportClass) : transportClass, options); - } else { - transport = strategy_builder_UnsupportedStrategy; - } - return transport; - }; - var strategy_builder_UnsupportedStrategy = { - isSupported: function() { - return false; - }, - connect: function(_2, callback) { - var deferred = util.defer(function() { - callback(new UnsupportedStrategy()); - }); - return { - abort: function() { - deferred.ensureAborted(); - }, - forceMinPriority: function() { - } - }; - } - }; - function validateOptions(options) { - if (options == null) { - throw "You must pass an options object"; - } - if (options.cluster == null) { - throw "Options object must provide a cluster"; - } - if ("disableStats" in options) { - logger.warn("The disableStats option is deprecated in favor of enableStats"); - } - } - const composeChannelQuery = (params, authOptions) => { - var query = "socket_id=" + encodeURIComponent(params.socketId); - for (var key in authOptions.params) { - query += "&" + encodeURIComponent(key) + "=" + encodeURIComponent(authOptions.params[key]); - } - if (authOptions.paramsProvider != null) { - let dynamicParams = authOptions.paramsProvider(); - for (var key in dynamicParams) { - query += "&" + encodeURIComponent(key) + "=" + encodeURIComponent(dynamicParams[key]); - } - } - return query; - }; - const UserAuthenticator = (authOptions) => { - if (typeof node_runtime.getAuthorizers()[authOptions.transport] === "undefined") { - throw `'${authOptions.transport}' is not a recognized auth transport`; - } - return (params, callback) => { - const query = composeChannelQuery(params, authOptions); - node_runtime.getAuthorizers()[authOptions.transport](node_runtime, query, authOptions, AuthRequestType.UserAuthentication, callback); - }; - }; - const user_authenticator = UserAuthenticator; - const channel_authorizer_composeChannelQuery = (params, authOptions) => { - var query = "socket_id=" + encodeURIComponent(params.socketId); - query += "&channel_name=" + encodeURIComponent(params.channelName); - for (var key in authOptions.params) { - query += "&" + encodeURIComponent(key) + "=" + encodeURIComponent(authOptions.params[key]); - } - if (authOptions.paramsProvider != null) { - let dynamicParams = authOptions.paramsProvider(); - for (var key in dynamicParams) { - query += "&" + encodeURIComponent(key) + "=" + encodeURIComponent(dynamicParams[key]); - } - } - return query; - }; - const ChannelAuthorizer = (authOptions) => { - if (typeof node_runtime.getAuthorizers()[authOptions.transport] === "undefined") { - throw `'${authOptions.transport}' is not a recognized auth transport`; - } - return (params, callback) => { - const query = channel_authorizer_composeChannelQuery(params, authOptions); - node_runtime.getAuthorizers()[authOptions.transport](node_runtime, query, authOptions, AuthRequestType.ChannelAuthorization, callback); - }; - }; - const channel_authorizer = ChannelAuthorizer; - const ChannelAuthorizerProxy = (pusher3, authOptions, channelAuthorizerGenerator) => { - const deprecatedAuthorizerOptions = { - authTransport: authOptions.transport, - authEndpoint: authOptions.endpoint, - auth: { - params: authOptions.params, - headers: authOptions.headers - } - }; - return (params, callback) => { - const channel = pusher3.channel(params.channelName); - const channelAuthorizer = channelAuthorizerGenerator(channel, deprecatedAuthorizerOptions); - channelAuthorizer.authorize(params.socketId, callback); - }; - }; - function getConfig(opts, pusher3) { - let config = { - activityTimeout: opts.activityTimeout || defaults.activityTimeout, - cluster: opts.cluster, - httpPath: opts.httpPath || defaults.httpPath, - httpPort: opts.httpPort || defaults.httpPort, - httpsPort: opts.httpsPort || defaults.httpsPort, - pongTimeout: opts.pongTimeout || defaults.pongTimeout, - statsHost: opts.statsHost || defaults.stats_host, - unavailableTimeout: opts.unavailableTimeout || defaults.unavailableTimeout, - wsPath: opts.wsPath || defaults.wsPath, - wsPort: opts.wsPort || defaults.wsPort, - wssPort: opts.wssPort || defaults.wssPort, - enableStats: getEnableStatsConfig(opts), - httpHost: getHttpHost(opts), - useTLS: shouldUseTLS(opts), - wsHost: getWebsocketHost(opts), - userAuthenticator: buildUserAuthenticator(opts), - channelAuthorizer: buildChannelAuthorizer(opts, pusher3) - }; - if ("disabledTransports" in opts) - config.disabledTransports = opts.disabledTransports; - if ("enabledTransports" in opts) - config.enabledTransports = opts.enabledTransports; - if ("ignoreNullOrigin" in opts) - config.ignoreNullOrigin = opts.ignoreNullOrigin; - if ("timelineParams" in opts) - config.timelineParams = opts.timelineParams; - if ("nacl" in opts) { - config.nacl = opts.nacl; - } - return config; - } - function getHttpHost(opts) { - if (opts.httpHost) { - return opts.httpHost; - } - if (opts.cluster) { - return `sockjs-${opts.cluster}.pusher.com`; - } - return defaults.httpHost; - } - function getWebsocketHost(opts) { - if (opts.wsHost) { - return opts.wsHost; - } - return getWebsocketHostFromCluster(opts.cluster); - } - function getWebsocketHostFromCluster(cluster) { - return `ws-${cluster}.pusher.com`; - } - function shouldUseTLS(opts) { - if (node_runtime.getProtocol() === "https:") { - return true; - } else if (opts.forceTLS === false) { - return false; - } - return true; - } - function getEnableStatsConfig(opts) { - if ("enableStats" in opts) { - return opts.enableStats; - } - if ("disableStats" in opts) { - return !opts.disableStats; - } - return false; - } - const hasCustomHandler = (auth) => { - return "customHandler" in auth && auth["customHandler"] != null; - }; - function buildUserAuthenticator(opts) { - const userAuthentication = Object.assign(Object.assign({}, defaults.userAuthentication), opts.userAuthentication); - if (hasCustomHandler(userAuthentication)) { - return userAuthentication["customHandler"]; - } - return user_authenticator(userAuthentication); - } - function buildChannelAuth(opts, pusher3) { - let channelAuthorization; - if ("channelAuthorization" in opts) { - channelAuthorization = Object.assign(Object.assign({}, defaults.channelAuthorization), opts.channelAuthorization); - } else { - channelAuthorization = { - transport: opts.authTransport || defaults.authTransport, - endpoint: opts.authEndpoint || defaults.authEndpoint - }; - if ("auth" in opts) { - if ("params" in opts.auth) - channelAuthorization.params = opts.auth.params; - if ("headers" in opts.auth) - channelAuthorization.headers = opts.auth.headers; - } - if ("authorizer" in opts) { - return { - customHandler: ChannelAuthorizerProxy(pusher3, channelAuthorization, opts.authorizer) - }; - } - } - return channelAuthorization; - } - function buildChannelAuthorizer(opts, pusher3) { - const channelAuthorization = buildChannelAuth(opts, pusher3); - if (hasCustomHandler(channelAuthorization)) { - return channelAuthorization["customHandler"]; - } - return channel_authorizer(channelAuthorization); - } - class WatchlistFacade extends Dispatcher { - constructor(pusher3) { - super(function(eventName, data) { - logger.debug(`No callbacks on watchlist events for ${eventName}`); - }); - this.pusher = pusher3; - this.bindWatchlistInternalEvent(); - } - handleEvent(pusherEvent) { - pusherEvent.data.events.forEach((watchlistEvent) => { - this.emit(watchlistEvent.name, watchlistEvent); - }); - } - bindWatchlistInternalEvent() { - this.pusher.connection.bind("message", (pusherEvent) => { - var eventName = pusherEvent.event; - if (eventName === "pusher_internal:watchlist_events") { - this.handleEvent(pusherEvent); - } - }); - } - } - function flatPromise() { - let resolve, reject; - const promise = new Promise((res, rej) => { - resolve = res; - reject = rej; - }); - return { promise, resolve, reject }; - } - const flat_promise = flatPromise; - class UserFacade extends Dispatcher { - constructor(pusher3) { - super(function(eventName, data) { - logger.debug("No callbacks on user for " + eventName); - }); - this.signin_requested = false; - this.user_data = null; - this.serverToUserChannel = null; - this.signinDonePromise = null; - this._signinDoneResolve = null; - this._onAuthorize = (err, authData) => { - if (err) { - logger.warn(`Error during signin: ${err}`); - this._cleanup(); - return; - } - this.pusher.send_event("pusher:signin", { - auth: authData.auth, - user_data: authData.user_data - }); - }; - this.pusher = pusher3; - this.pusher.connection.bind("state_change", ({ previous, current }) => { - if (previous !== "connected" && current === "connected") { - this._signin(); - } - if (previous === "connected" && current !== "connected") { - this._cleanup(); - this._newSigninPromiseIfNeeded(); - } - }); - this.watchlist = new WatchlistFacade(pusher3); - this.pusher.connection.bind("message", (event) => { - var eventName = event.event; - if (eventName === "pusher:signin_success") { - this._onSigninSuccess(event.data); - } - if (this.serverToUserChannel && this.serverToUserChannel.name === event.channel) { - this.serverToUserChannel.handleEvent(event); - } - }); - } - signin() { - if (this.signin_requested) { - return; - } - this.signin_requested = true; - this._signin(); - } - _signin() { - if (!this.signin_requested) { - return; - } - this._newSigninPromiseIfNeeded(); - if (this.pusher.connection.state !== "connected") { - return; - } - this.pusher.config.userAuthenticator({ - socketId: this.pusher.connection.socket_id - }, this._onAuthorize); - } - _onSigninSuccess(data) { - try { - this.user_data = JSON.parse(data.user_data); - } catch (e) { - logger.error(`Failed parsing user data after signin: ${data.user_data}`); - this._cleanup(); - return; - } - if (typeof this.user_data.id !== "string" || this.user_data.id === "") { - logger.error(`user_data doesn't contain an id. user_data: ${this.user_data}`); - this._cleanup(); - return; - } - this._signinDoneResolve(); - this._subscribeChannels(); - } - _subscribeChannels() { - const ensure_subscribed = (channel) => { - if (channel.subscriptionPending && channel.subscriptionCancelled) { - channel.reinstateSubscription(); - } else if (!channel.subscriptionPending && this.pusher.connection.state === "connected") { - channel.subscribe(); - } - }; - this.serverToUserChannel = new Channel(`#server-to-user-${this.user_data.id}`, this.pusher); - this.serverToUserChannel.bind_global((eventName, data) => { - if (eventName.indexOf("pusher_internal:") === 0 || eventName.indexOf("pusher:") === 0) { - return; - } - this.emit(eventName, data); - }); - ensure_subscribed(this.serverToUserChannel); - } - _cleanup() { - this.user_data = null; - if (this.serverToUserChannel) { - this.serverToUserChannel.unbind_all(); - this.serverToUserChannel.disconnect(); - this.serverToUserChannel = null; - } - if (this.signin_requested) { - this._signinDoneResolve(); - } - } - _newSigninPromiseIfNeeded() { - if (!this.signin_requested) { - return; - } - if (this.signinDonePromise && !this.signinDonePromise.done) { - return; - } - const { promise, resolve } = flat_promise(); - promise.done = false; - const setDone = () => { - promise.done = true; - }; - promise.then(setDone).catch(setDone); - this.signinDonePromise = promise; - this._signinDoneResolve = resolve; - } - } - class Pusher2 { - static ready() { - Pusher2.isReady = true; - for (var i = 0, l2 = Pusher2.instances.length; i < l2; i++) { - Pusher2.instances[i].connect(); - } - } - static getClientFeatures() { - return keys(filterObject({ ws: node_runtime.Transports.ws }, function(t) { - return t.isSupported({}); - })); - } - constructor(app_key, options) { - checkAppKey(app_key); - validateOptions(options); - this.key = app_key; - this.options = options; - this.config = getConfig(this.options, this); - this.channels = factory.createChannels(); - this.global_emitter = new Dispatcher(); - this.sessionID = node_runtime.randomInt(1e9); - this.timeline = new Timeline(this.key, this.sessionID, { - cluster: this.config.cluster, - features: Pusher2.getClientFeatures(), - params: this.config.timelineParams || {}, - limit: 50, - level: level.INFO, - version: defaults.VERSION - }); - if (this.config.enableStats) { - this.timelineSender = factory.createTimelineSender(this.timeline, { - host: this.config.statsHost, - path: "/timeline/v2/" + node_runtime.TimelineTransport.name - }); - } - var getStrategy = (options2) => { - return node_runtime.getDefaultStrategy(this.config, options2, defineTransport); - }; - this.connection = factory.createConnectionManager(this.key, { - getStrategy, - timeline: this.timeline, - activityTimeout: this.config.activityTimeout, - pongTimeout: this.config.pongTimeout, - unavailableTimeout: this.config.unavailableTimeout, - useTLS: Boolean(this.config.useTLS) - }); - this.connection.bind("connected", () => { - this.subscribeAll(); - if (this.timelineSender) { - this.timelineSender.send(this.connection.isUsingTLS()); - } - }); - this.connection.bind("message", (event) => { - var eventName = event.event; - var internal = eventName.indexOf("pusher_internal:") === 0; - if (event.channel) { - var channel = this.channel(event.channel); - if (channel) { - channel.handleEvent(event); - } - } - if (!internal) { - this.global_emitter.emit(event.event, event.data); - } - }); - this.connection.bind("connecting", () => { - this.channels.disconnect(); - }); - this.connection.bind("disconnected", () => { - this.channels.disconnect(); - }); - this.connection.bind("error", (err) => { - logger.warn(err); - }); - Pusher2.instances.push(this); - this.timeline.info({ instances: Pusher2.instances.length }); - this.user = new UserFacade(this); - if (Pusher2.isReady) { - this.connect(); - } - } - switchCluster(options) { - const { appKey, cluster } = options; - this.key = appKey; - this.options = Object.assign(Object.assign({}, this.options), { cluster }); - this.config = getConfig(this.options, this); - this.connection.switchCluster(this.key); - } - channel(name) { - return this.channels.find(name); - } - allChannels() { - return this.channels.all(); - } - connect() { - this.connection.connect(); - if (this.timelineSender) { - if (!this.timelineSenderTimer) { - var usingTLS = this.connection.isUsingTLS(); - var timelineSender = this.timelineSender; - this.timelineSenderTimer = new PeriodicTimer(6e4, function() { - timelineSender.send(usingTLS); - }); - } - } - } - disconnect() { - this.connection.disconnect(); - if (this.timelineSenderTimer) { - this.timelineSenderTimer.ensureAborted(); - this.timelineSenderTimer = null; - } - } - bind(event_name, callback, context) { - this.global_emitter.bind(event_name, callback, context); - return this; - } - unbind(event_name, callback, context) { - this.global_emitter.unbind(event_name, callback, context); - return this; - } - bind_global(callback) { - this.global_emitter.bind_global(callback); - return this; - } - unbind_global(callback) { - this.global_emitter.unbind_global(callback); - return this; - } - unbind_all(callback) { - this.global_emitter.unbind_all(); - return this; - } - subscribeAll() { - var channelName; - for (channelName in this.channels.channels) { - if (this.channels.channels.hasOwnProperty(channelName)) { - this.subscribe(channelName); - } - } - } - subscribe(channel_name) { - var channel = this.channels.add(channel_name, this); - if (channel.subscriptionPending && channel.subscriptionCancelled) { - channel.reinstateSubscription(); - } else if (!channel.subscriptionPending && this.connection.state === "connected") { - channel.subscribe(); - } - return channel; - } - unsubscribe(channel_name) { - var channel = this.channels.find(channel_name); - if (channel && channel.subscriptionPending) { - channel.cancelSubscription(); - } else { - channel = this.channels.remove(channel_name); - if (channel && channel.subscribed) { - channel.unsubscribe(); - } - } - } - send_event(event_name, data, channel) { - return this.connection.send_event(event_name, data, channel); - } - shouldUseTLS() { - return this.config.useTLS; - } - signin() { - this.user.signin(); - } - } - Pusher2.instances = []; - Pusher2.isReady = false; - Pusher2.logToConsole = false; - Pusher2.Runtime = node_runtime; - Pusher2.ScriptReceivers = node_runtime.ScriptReceivers; - Pusher2.DependenciesReceivers = node_runtime.DependenciesReceivers; - Pusher2.auth_callbacks = node_runtime.auth_callbacks; - const pusher2 = Pusher2; - function checkAppKey(key) { - if (key === null || key === void 0) { - throw "You must pass your app key when you instantiate Pusher."; - } - } - node_runtime.setup(Pusher2); - var nacl_fast = __webpack_require__2(601); - class PusherWithEncryption extends pusher2 { - constructor(app_key, options) { - pusher2.logToConsole = PusherWithEncryption.logToConsole; - pusher2.log = PusherWithEncryption.log; - validateOptions(options); - options.nacl = nacl_fast; - super(app_key, options); - } - } - }, - /***/ - 613(module2) { - module2.exports = require$$4$2; - }, - /***/ - 181(module2) { - module2.exports = require$$1$1; - }, - /***/ - 317(module2) { - module2.exports = require$$2; - }, - /***/ - 982(module2) { - module2.exports = require$$1; - }, - /***/ - 434(module2) { - module2.exports = require$$4$1; - }, - /***/ - 896(module2) { - module2.exports = require$$6; - }, - /***/ - 611(module2) { - module2.exports = require$$3; - }, - /***/ - 692(module2) { - module2.exports = require$$4; - }, - /***/ - 278(module2) { - module2.exports = require$$8; - }, - /***/ - 203(module2) { - module2.exports = stream; - }, - /***/ - 756(module2) { - module2.exports = require$$10; - }, - /***/ - 16(module2) { - module2.exports = require$$5; - }, - /***/ - 23(module2) { - module2.exports = require$$0; - } - /******/ - }; - var __webpack_module_cache__ = {}; - function __webpack_require__(moduleId) { - var cachedModule = __webpack_module_cache__[moduleId]; - if (cachedModule !== void 0) { - return cachedModule.exports; - } - var module2 = __webpack_module_cache__[moduleId] = { - /******/ - // no module.id needed - /******/ - // no module.loaded needed - /******/ - exports: {} - /******/ - }; - __webpack_modules__[moduleId].call(module2.exports, module2, module2.exports, __webpack_require__); - return module2.exports; - } - (() => { - __webpack_require__.d = (exports$1, definition) => { - for (var key in definition) { - if (__webpack_require__.o(definition, key) && !__webpack_require__.o(exports$1, key)) { - Object.defineProperty(exports$1, key, { enumerable: true, get: definition[key] }); - } - } - }; - })(); - (() => { - __webpack_require__.o = (obj, prop) => Object.prototype.hasOwnProperty.call(obj, prop); - })(); - var __webpack_exports__ = __webpack_require__(42); - module.exports.Pusher = __webpack_exports__; - })(); - })(pusher); - return pusher.exports; -} -var pusherExports = requirePusher(); -const Pusher = /* @__PURE__ */ getDefaultExportFromCjs(pusherExports); -export { - E, - Pusher as P -}; diff --git a/bootstrap/ssr/assets/vendor-tiptap-BUUKoc3C.js b/bootstrap/ssr/assets/vendor-tiptap-BUUKoc3C.js deleted file mode 100644 index 11cc75d9..00000000 --- a/bootstrap/ssr/assets/vendor-tiptap-BUUKoc3C.js +++ /dev/null @@ -1,27179 +0,0 @@ -var commonjsGlobal = typeof globalThis !== "undefined" ? globalThis : typeof window !== "undefined" ? window : typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : {}; -function getDefaultExportFromCjs(x) { - return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, "default") ? x["default"] : x; -} -var react = { exports: {} }; -var react_production = {}; -var hasRequiredReact_production; -function requireReact_production() { - if (hasRequiredReact_production) return react_production; - hasRequiredReact_production = 1; - var REACT_ELEMENT_TYPE = /* @__PURE__ */ Symbol.for("react.transitional.element"), REACT_PORTAL_TYPE = /* @__PURE__ */ Symbol.for("react.portal"), REACT_FRAGMENT_TYPE = /* @__PURE__ */ Symbol.for("react.fragment"), REACT_STRICT_MODE_TYPE = /* @__PURE__ */ Symbol.for("react.strict_mode"), REACT_PROFILER_TYPE = /* @__PURE__ */ Symbol.for("react.profiler"), REACT_CONSUMER_TYPE = /* @__PURE__ */ Symbol.for("react.consumer"), REACT_CONTEXT_TYPE = /* @__PURE__ */ Symbol.for("react.context"), REACT_FORWARD_REF_TYPE = /* @__PURE__ */ Symbol.for("react.forward_ref"), REACT_SUSPENSE_TYPE = /* @__PURE__ */ Symbol.for("react.suspense"), REACT_MEMO_TYPE = /* @__PURE__ */ Symbol.for("react.memo"), REACT_LAZY_TYPE = /* @__PURE__ */ Symbol.for("react.lazy"), REACT_ACTIVITY_TYPE = /* @__PURE__ */ Symbol.for("react.activity"), MAYBE_ITERATOR_SYMBOL = Symbol.iterator; - function getIteratorFn(maybeIterable) { - if (null === maybeIterable || "object" !== typeof maybeIterable) return null; - maybeIterable = MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL] || maybeIterable["@@iterator"]; - return "function" === typeof maybeIterable ? maybeIterable : null; - } - var ReactNoopUpdateQueue = { - isMounted: function() { - return false; - }, - enqueueForceUpdate: function() { - }, - enqueueReplaceState: function() { - }, - enqueueSetState: function() { - } - }, assign = Object.assign, emptyObject = {}; - function Component(props, context, updater) { - this.props = props; - this.context = context; - this.refs = emptyObject; - this.updater = updater || ReactNoopUpdateQueue; - } - Component.prototype.isReactComponent = {}; - Component.prototype.setState = function(partialState, callback) { - if ("object" !== typeof partialState && "function" !== typeof partialState && null != partialState) - throw Error( - "takes an object of state variables to update or a function which returns an object of state variables." - ); - this.updater.enqueueSetState(this, partialState, callback, "setState"); - }; - Component.prototype.forceUpdate = function(callback) { - this.updater.enqueueForceUpdate(this, callback, "forceUpdate"); - }; - function ComponentDummy() { - } - ComponentDummy.prototype = Component.prototype; - function PureComponent(props, context, updater) { - this.props = props; - this.context = context; - this.refs = emptyObject; - this.updater = updater || ReactNoopUpdateQueue; - } - var pureComponentPrototype = PureComponent.prototype = new ComponentDummy(); - pureComponentPrototype.constructor = PureComponent; - assign(pureComponentPrototype, Component.prototype); - pureComponentPrototype.isPureReactComponent = true; - var isArrayImpl = Array.isArray; - function noop2() { - } - var ReactSharedInternals = { H: null, A: null, T: null, S: null }, hasOwnProperty2 = Object.prototype.hasOwnProperty; - function ReactElement(type, key, props) { - var refProp = props.ref; - return { - $$typeof: REACT_ELEMENT_TYPE, - type, - key, - ref: void 0 !== refProp ? refProp : null, - props - }; - } - function cloneAndReplaceKey(oldElement, newKey) { - return ReactElement(oldElement.type, newKey, oldElement.props); - } - function isValidElement(object) { - return "object" === typeof object && null !== object && object.$$typeof === REACT_ELEMENT_TYPE; - } - function escape(key) { - var escaperLookup = { "=": "=0", ":": "=2" }; - return "$" + key.replace(/[=:]/g, function(match) { - return escaperLookup[match]; - }); - } - var userProvidedKeyEscapeRegex = /\/+/g; - function getElementKey(element, index) { - return "object" === typeof element && null !== element && null != element.key ? escape("" + element.key) : index.toString(36); - } - function resolveThenable(thenable) { - switch (thenable.status) { - case "fulfilled": - return thenable.value; - case "rejected": - throw thenable.reason; - default: - switch ("string" === typeof thenable.status ? thenable.then(noop2, noop2) : (thenable.status = "pending", thenable.then( - function(fulfilledValue) { - "pending" === thenable.status && (thenable.status = "fulfilled", thenable.value = fulfilledValue); - }, - function(error) { - "pending" === thenable.status && (thenable.status = "rejected", thenable.reason = error); - } - )), thenable.status) { - case "fulfilled": - return thenable.value; - case "rejected": - throw thenable.reason; - } - } - throw thenable; - } - function mapIntoArray(children, array, escapedPrefix, nameSoFar, callback) { - var type = typeof children; - if ("undefined" === type || "boolean" === type) children = null; - var invokeCallback = false; - if (null === children) invokeCallback = true; - else - switch (type) { - case "bigint": - case "string": - case "number": - invokeCallback = true; - break; - case "object": - switch (children.$$typeof) { - case REACT_ELEMENT_TYPE: - case REACT_PORTAL_TYPE: - invokeCallback = true; - break; - case REACT_LAZY_TYPE: - return invokeCallback = children._init, mapIntoArray( - invokeCallback(children._payload), - array, - escapedPrefix, - nameSoFar, - callback - ); - } - } - if (invokeCallback) - return callback = callback(children), invokeCallback = "" === nameSoFar ? "." + getElementKey(children, 0) : nameSoFar, isArrayImpl(callback) ? (escapedPrefix = "", null != invokeCallback && (escapedPrefix = invokeCallback.replace(userProvidedKeyEscapeRegex, "$&/") + "/"), mapIntoArray(callback, array, escapedPrefix, "", function(c) { - return c; - })) : null != callback && (isValidElement(callback) && (callback = cloneAndReplaceKey( - callback, - escapedPrefix + (null == callback.key || children && children.key === callback.key ? "" : ("" + callback.key).replace( - userProvidedKeyEscapeRegex, - "$&/" - ) + "/") + invokeCallback - )), array.push(callback)), 1; - invokeCallback = 0; - var nextNamePrefix = "" === nameSoFar ? "." : nameSoFar + ":"; - if (isArrayImpl(children)) - for (var i = 0; i < children.length; i++) - nameSoFar = children[i], type = nextNamePrefix + getElementKey(nameSoFar, i), invokeCallback += mapIntoArray( - nameSoFar, - array, - escapedPrefix, - type, - callback - ); - else if (i = getIteratorFn(children), "function" === typeof i) - for (children = i.call(children), i = 0; !(nameSoFar = children.next()).done; ) - nameSoFar = nameSoFar.value, type = nextNamePrefix + getElementKey(nameSoFar, i++), invokeCallback += mapIntoArray( - nameSoFar, - array, - escapedPrefix, - type, - callback - ); - else if ("object" === type) { - if ("function" === typeof children.then) - return mapIntoArray( - resolveThenable(children), - array, - escapedPrefix, - nameSoFar, - callback - ); - array = String(children); - throw Error( - "Objects are not valid as a React child (found: " + ("[object Object]" === array ? "object with keys {" + Object.keys(children).join(", ") + "}" : array) + "). If you meant to render a collection of children, use an array instead." - ); - } - return invokeCallback; - } - function mapChildren2(children, func, context) { - if (null == children) return children; - var result = [], count = 0; - mapIntoArray(children, result, "", "", function(child) { - return func.call(context, child, count++); - }); - return result; - } - function lazyInitializer(payload) { - if (-1 === payload._status) { - var ctor = payload._result; - ctor = ctor(); - ctor.then( - function(moduleObject) { - if (0 === payload._status || -1 === payload._status) - payload._status = 1, payload._result = moduleObject; - }, - function(error) { - if (0 === payload._status || -1 === payload._status) - payload._status = 2, payload._result = error; - } - ); - -1 === payload._status && (payload._status = 0, payload._result = ctor); - } - if (1 === payload._status) return payload._result.default; - throw payload._result; - } - var reportGlobalError = "function" === typeof reportError ? reportError : function(error) { - if ("object" === typeof window && "function" === typeof window.ErrorEvent) { - var event = new window.ErrorEvent("error", { - bubbles: true, - cancelable: true, - message: "object" === typeof error && null !== error && "string" === typeof error.message ? String(error.message) : String(error), - error - }); - if (!window.dispatchEvent(event)) return; - } else if ("object" === typeof process && "function" === typeof process.emit) { - process.emit("uncaughtException", error); - return; - } - console.error(error); - }, Children = { - map: mapChildren2, - forEach: function(children, forEachFunc, forEachContext) { - mapChildren2( - children, - function() { - forEachFunc.apply(this, arguments); - }, - forEachContext - ); - }, - count: function(children) { - var n = 0; - mapChildren2(children, function() { - n++; - }); - return n; - }, - toArray: function(children) { - return mapChildren2(children, function(child) { - return child; - }) || []; - }, - only: function(children) { - if (!isValidElement(children)) - throw Error( - "React.Children.only expected to receive a single React element child." - ); - return children; - } - }; - react_production.Activity = REACT_ACTIVITY_TYPE; - react_production.Children = Children; - react_production.Component = Component; - react_production.Fragment = REACT_FRAGMENT_TYPE; - react_production.Profiler = REACT_PROFILER_TYPE; - react_production.PureComponent = PureComponent; - react_production.StrictMode = REACT_STRICT_MODE_TYPE; - react_production.Suspense = REACT_SUSPENSE_TYPE; - react_production.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE = ReactSharedInternals; - react_production.__COMPILER_RUNTIME = { - __proto__: null, - c: function(size) { - return ReactSharedInternals.H.useMemoCache(size); - } - }; - react_production.cache = function(fn) { - return function() { - return fn.apply(null, arguments); - }; - }; - react_production.cacheSignal = function() { - return null; - }; - react_production.cloneElement = function(element, config, children) { - if (null === element || void 0 === element) - throw Error( - "The argument must be a React element, but you passed " + element + "." - ); - var props = assign({}, element.props), key = element.key; - if (null != config) - for (propName in void 0 !== config.key && (key = "" + config.key), config) - !hasOwnProperty2.call(config, propName) || "key" === propName || "__self" === propName || "__source" === propName || "ref" === propName && void 0 === config.ref || (props[propName] = config[propName]); - var propName = arguments.length - 2; - if (1 === propName) props.children = children; - else if (1 < propName) { - for (var childArray = Array(propName), i = 0; i < propName; i++) - childArray[i] = arguments[i + 2]; - props.children = childArray; - } - return ReactElement(element.type, key, props); - }; - react_production.createContext = function(defaultValue) { - defaultValue = { - $$typeof: REACT_CONTEXT_TYPE, - _currentValue: defaultValue, - _currentValue2: defaultValue, - _threadCount: 0, - Provider: null, - Consumer: null - }; - defaultValue.Provider = defaultValue; - defaultValue.Consumer = { - $$typeof: REACT_CONSUMER_TYPE, - _context: defaultValue - }; - return defaultValue; - }; - react_production.createElement = function(type, config, children) { - var propName, props = {}, key = null; - if (null != config) - for (propName in void 0 !== config.key && (key = "" + config.key), config) - hasOwnProperty2.call(config, propName) && "key" !== propName && "__self" !== propName && "__source" !== propName && (props[propName] = config[propName]); - var childrenLength = arguments.length - 2; - if (1 === childrenLength) props.children = children; - else if (1 < childrenLength) { - for (var childArray = Array(childrenLength), i = 0; i < childrenLength; i++) - childArray[i] = arguments[i + 2]; - props.children = childArray; - } - if (type && type.defaultProps) - for (propName in childrenLength = type.defaultProps, childrenLength) - void 0 === props[propName] && (props[propName] = childrenLength[propName]); - return ReactElement(type, key, props); - }; - react_production.createRef = function() { - return { current: null }; - }; - react_production.forwardRef = function(render) { - return { $$typeof: REACT_FORWARD_REF_TYPE, render }; - }; - react_production.isValidElement = isValidElement; - react_production.lazy = function(ctor) { - return { - $$typeof: REACT_LAZY_TYPE, - _payload: { _status: -1, _result: ctor }, - _init: lazyInitializer - }; - }; - react_production.memo = function(type, compare) { - return { - $$typeof: REACT_MEMO_TYPE, - type, - compare: void 0 === compare ? null : compare - }; - }; - react_production.startTransition = function(scope) { - var prevTransition = ReactSharedInternals.T, currentTransition = {}; - ReactSharedInternals.T = currentTransition; - try { - var returnValue = scope(), onStartTransitionFinish = ReactSharedInternals.S; - null !== onStartTransitionFinish && onStartTransitionFinish(currentTransition, returnValue); - "object" === typeof returnValue && null !== returnValue && "function" === typeof returnValue.then && returnValue.then(noop2, reportGlobalError); - } catch (error) { - reportGlobalError(error); - } finally { - null !== prevTransition && null !== currentTransition.types && (prevTransition.types = currentTransition.types), ReactSharedInternals.T = prevTransition; - } - }; - react_production.unstable_useCacheRefresh = function() { - return ReactSharedInternals.H.useCacheRefresh(); - }; - react_production.use = function(usable) { - return ReactSharedInternals.H.use(usable); - }; - react_production.useActionState = function(action, initialState, permalink) { - return ReactSharedInternals.H.useActionState(action, initialState, permalink); - }; - react_production.useCallback = function(callback, deps) { - return ReactSharedInternals.H.useCallback(callback, deps); - }; - react_production.useContext = function(Context) { - return ReactSharedInternals.H.useContext(Context); - }; - react_production.useDebugValue = function() { - }; - react_production.useDeferredValue = function(value, initialValue) { - return ReactSharedInternals.H.useDeferredValue(value, initialValue); - }; - react_production.useEffect = function(create, deps) { - return ReactSharedInternals.H.useEffect(create, deps); - }; - react_production.useEffectEvent = function(callback) { - return ReactSharedInternals.H.useEffectEvent(callback); - }; - react_production.useId = function() { - return ReactSharedInternals.H.useId(); - }; - react_production.useImperativeHandle = function(ref, create, deps) { - return ReactSharedInternals.H.useImperativeHandle(ref, create, deps); - }; - react_production.useInsertionEffect = function(create, deps) { - return ReactSharedInternals.H.useInsertionEffect(create, deps); - }; - react_production.useLayoutEffect = function(create, deps) { - return ReactSharedInternals.H.useLayoutEffect(create, deps); - }; - react_production.useMemo = function(create, deps) { - return ReactSharedInternals.H.useMemo(create, deps); - }; - react_production.useOptimistic = function(passthrough, reducer) { - return ReactSharedInternals.H.useOptimistic(passthrough, reducer); - }; - react_production.useReducer = function(reducer, initialArg, init2) { - return ReactSharedInternals.H.useReducer(reducer, initialArg, init2); - }; - react_production.useRef = function(initialValue) { - return ReactSharedInternals.H.useRef(initialValue); - }; - react_production.useState = function(initialState) { - return ReactSharedInternals.H.useState(initialState); - }; - react_production.useSyncExternalStore = function(subscribe, getSnapshot, getServerSnapshot) { - return ReactSharedInternals.H.useSyncExternalStore( - subscribe, - getSnapshot, - getServerSnapshot - ); - }; - react_production.useTransition = function() { - return ReactSharedInternals.H.useTransition(); - }; - react_production.version = "19.2.4"; - return react_production; -} -var react_development = { exports: {} }; -react_development.exports; -var hasRequiredReact_development; -function requireReact_development() { - if (hasRequiredReact_development) return react_development.exports; - hasRequiredReact_development = 1; - (function(module, exports$1) { - "production" !== process.env.NODE_ENV && (function() { - function defineDeprecationWarning(methodName, info) { - Object.defineProperty(Component.prototype, methodName, { - get: function() { - console.warn( - "%s(...) is deprecated in plain JavaScript React classes. %s", - info[0], - info[1] - ); - } - }); - } - function getIteratorFn(maybeIterable) { - if (null === maybeIterable || "object" !== typeof maybeIterable) - return null; - maybeIterable = MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL] || maybeIterable["@@iterator"]; - return "function" === typeof maybeIterable ? maybeIterable : null; - } - function warnNoop(publicInstance, callerName) { - publicInstance = (publicInstance = publicInstance.constructor) && (publicInstance.displayName || publicInstance.name) || "ReactClass"; - var warningKey = publicInstance + "." + callerName; - didWarnStateUpdateForUnmountedComponent[warningKey] || (console.error( - "Can't call %s on a component that is not yet mounted. This is a no-op, but it might indicate a bug in your application. Instead, assign to `this.state` directly or define a `state = {};` class property with the desired state in the %s component.", - callerName, - publicInstance - ), didWarnStateUpdateForUnmountedComponent[warningKey] = true); - } - function Component(props, context, updater) { - this.props = props; - this.context = context; - this.refs = emptyObject; - this.updater = updater || ReactNoopUpdateQueue; - } - function ComponentDummy() { - } - function PureComponent(props, context, updater) { - this.props = props; - this.context = context; - this.refs = emptyObject; - this.updater = updater || ReactNoopUpdateQueue; - } - function noop2() { - } - function testStringCoercion(value) { - return "" + value; - } - function checkKeyStringCoercion(value) { - try { - testStringCoercion(value); - var JSCompiler_inline_result = false; - } catch (e) { - JSCompiler_inline_result = true; - } - if (JSCompiler_inline_result) { - JSCompiler_inline_result = console; - var JSCompiler_temp_const = JSCompiler_inline_result.error; - var JSCompiler_inline_result$jscomp$0 = "function" === typeof Symbol && Symbol.toStringTag && value[Symbol.toStringTag] || value.constructor.name || "Object"; - JSCompiler_temp_const.call( - JSCompiler_inline_result, - "The provided key is an unsupported type %s. This value must be coerced to a string before using it here.", - JSCompiler_inline_result$jscomp$0 - ); - return testStringCoercion(value); - } - } - function getComponentNameFromType(type) { - if (null == type) return null; - if ("function" === typeof type) - return type.$$typeof === REACT_CLIENT_REFERENCE ? null : type.displayName || type.name || null; - if ("string" === typeof type) return type; - switch (type) { - case REACT_FRAGMENT_TYPE: - return "Fragment"; - case REACT_PROFILER_TYPE: - return "Profiler"; - case REACT_STRICT_MODE_TYPE: - return "StrictMode"; - case REACT_SUSPENSE_TYPE: - return "Suspense"; - case REACT_SUSPENSE_LIST_TYPE: - return "SuspenseList"; - case REACT_ACTIVITY_TYPE: - return "Activity"; - } - if ("object" === typeof type) - switch ("number" === typeof type.tag && console.error( - "Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue." - ), type.$$typeof) { - case REACT_PORTAL_TYPE: - return "Portal"; - case REACT_CONTEXT_TYPE: - return type.displayName || "Context"; - case REACT_CONSUMER_TYPE: - return (type._context.displayName || "Context") + ".Consumer"; - case REACT_FORWARD_REF_TYPE: - var innerType = type.render; - type = type.displayName; - type || (type = innerType.displayName || innerType.name || "", type = "" !== type ? "ForwardRef(" + type + ")" : "ForwardRef"); - return type; - case REACT_MEMO_TYPE: - return innerType = type.displayName || null, null !== innerType ? innerType : getComponentNameFromType(type.type) || "Memo"; - case REACT_LAZY_TYPE: - innerType = type._payload; - type = type._init; - try { - return getComponentNameFromType(type(innerType)); - } catch (x) { - } - } - return null; - } - function getTaskName(type) { - if (type === REACT_FRAGMENT_TYPE) return "<>"; - if ("object" === typeof type && null !== type && type.$$typeof === REACT_LAZY_TYPE) - return "<...>"; - try { - var name = getComponentNameFromType(type); - return name ? "<" + name + ">" : "<...>"; - } catch (x) { - return "<...>"; - } - } - function getOwner() { - var dispatcher = ReactSharedInternals.A; - return null === dispatcher ? null : dispatcher.getOwner(); - } - function UnknownOwner() { - return Error("react-stack-top-frame"); - } - function hasValidKey(config) { - if (hasOwnProperty2.call(config, "key")) { - var getter = Object.getOwnPropertyDescriptor(config, "key").get; - if (getter && getter.isReactWarning) return false; - } - return void 0 !== config.key; - } - function defineKeyPropWarningGetter(props, displayName) { - function warnAboutAccessingKey() { - specialPropKeyWarningShown || (specialPropKeyWarningShown = true, console.error( - "%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://react.dev/link/special-props)", - displayName - )); - } - warnAboutAccessingKey.isReactWarning = true; - Object.defineProperty(props, "key", { - get: warnAboutAccessingKey, - configurable: true - }); - } - function elementRefGetterWithDeprecationWarning() { - var componentName = getComponentNameFromType(this.type); - didWarnAboutElementRef[componentName] || (didWarnAboutElementRef[componentName] = true, console.error( - "Accessing element.ref was removed in React 19. ref is now a regular prop. It will be removed from the JSX Element type in a future release." - )); - componentName = this.props.ref; - return void 0 !== componentName ? componentName : null; - } - function ReactElement(type, key, props, owner, debugStack, debugTask) { - var refProp = props.ref; - type = { - $$typeof: REACT_ELEMENT_TYPE, - type, - key, - props, - _owner: owner - }; - null !== (void 0 !== refProp ? refProp : null) ? Object.defineProperty(type, "ref", { - enumerable: false, - get: elementRefGetterWithDeprecationWarning - }) : Object.defineProperty(type, "ref", { enumerable: false, value: null }); - type._store = {}; - Object.defineProperty(type._store, "validated", { - configurable: false, - enumerable: false, - writable: true, - value: 0 - }); - Object.defineProperty(type, "_debugInfo", { - configurable: false, - enumerable: false, - writable: true, - value: null - }); - Object.defineProperty(type, "_debugStack", { - configurable: false, - enumerable: false, - writable: true, - value: debugStack - }); - Object.defineProperty(type, "_debugTask", { - configurable: false, - enumerable: false, - writable: true, - value: debugTask - }); - Object.freeze && (Object.freeze(type.props), Object.freeze(type)); - return type; - } - function cloneAndReplaceKey(oldElement, newKey) { - newKey = ReactElement( - oldElement.type, - newKey, - oldElement.props, - oldElement._owner, - oldElement._debugStack, - oldElement._debugTask - ); - oldElement._store && (newKey._store.validated = oldElement._store.validated); - return newKey; - } - function validateChildKeys(node) { - isValidElement(node) ? node._store && (node._store.validated = 1) : "object" === typeof node && null !== node && node.$$typeof === REACT_LAZY_TYPE && ("fulfilled" === node._payload.status ? isValidElement(node._payload.value) && node._payload.value._store && (node._payload.value._store.validated = 1) : node._store && (node._store.validated = 1)); - } - function isValidElement(object) { - return "object" === typeof object && null !== object && object.$$typeof === REACT_ELEMENT_TYPE; - } - function escape(key) { - var escaperLookup = { "=": "=0", ":": "=2" }; - return "$" + key.replace(/[=:]/g, function(match) { - return escaperLookup[match]; - }); - } - function getElementKey(element, index) { - return "object" === typeof element && null !== element && null != element.key ? (checkKeyStringCoercion(element.key), escape("" + element.key)) : index.toString(36); - } - function resolveThenable(thenable) { - switch (thenable.status) { - case "fulfilled": - return thenable.value; - case "rejected": - throw thenable.reason; - default: - switch ("string" === typeof thenable.status ? thenable.then(noop2, noop2) : (thenable.status = "pending", thenable.then( - function(fulfilledValue) { - "pending" === thenable.status && (thenable.status = "fulfilled", thenable.value = fulfilledValue); - }, - function(error) { - "pending" === thenable.status && (thenable.status = "rejected", thenable.reason = error); - } - )), thenable.status) { - case "fulfilled": - return thenable.value; - case "rejected": - throw thenable.reason; - } - } - throw thenable; - } - function mapIntoArray(children, array, escapedPrefix, nameSoFar, callback) { - var type = typeof children; - if ("undefined" === type || "boolean" === type) children = null; - var invokeCallback = false; - if (null === children) invokeCallback = true; - else - switch (type) { - case "bigint": - case "string": - case "number": - invokeCallback = true; - break; - case "object": - switch (children.$$typeof) { - case REACT_ELEMENT_TYPE: - case REACT_PORTAL_TYPE: - invokeCallback = true; - break; - case REACT_LAZY_TYPE: - return invokeCallback = children._init, mapIntoArray( - invokeCallback(children._payload), - array, - escapedPrefix, - nameSoFar, - callback - ); - } - } - if (invokeCallback) { - invokeCallback = children; - callback = callback(invokeCallback); - var childKey = "" === nameSoFar ? "." + getElementKey(invokeCallback, 0) : nameSoFar; - isArrayImpl(callback) ? (escapedPrefix = "", null != childKey && (escapedPrefix = childKey.replace(userProvidedKeyEscapeRegex, "$&/") + "/"), mapIntoArray(callback, array, escapedPrefix, "", function(c) { - return c; - })) : null != callback && (isValidElement(callback) && (null != callback.key && (invokeCallback && invokeCallback.key === callback.key || checkKeyStringCoercion(callback.key)), escapedPrefix = cloneAndReplaceKey( - callback, - escapedPrefix + (null == callback.key || invokeCallback && invokeCallback.key === callback.key ? "" : ("" + callback.key).replace( - userProvidedKeyEscapeRegex, - "$&/" - ) + "/") + childKey - ), "" !== nameSoFar && null != invokeCallback && isValidElement(invokeCallback) && null == invokeCallback.key && invokeCallback._store && !invokeCallback._store.validated && (escapedPrefix._store.validated = 2), callback = escapedPrefix), array.push(callback)); - return 1; - } - invokeCallback = 0; - childKey = "" === nameSoFar ? "." : nameSoFar + ":"; - if (isArrayImpl(children)) - for (var i = 0; i < children.length; i++) - nameSoFar = children[i], type = childKey + getElementKey(nameSoFar, i), invokeCallback += mapIntoArray( - nameSoFar, - array, - escapedPrefix, - type, - callback - ); - else if (i = getIteratorFn(children), "function" === typeof i) - for (i === children.entries && (didWarnAboutMaps || console.warn( - "Using Maps as children is not supported. Use an array of keyed ReactElements instead." - ), didWarnAboutMaps = true), children = i.call(children), i = 0; !(nameSoFar = children.next()).done; ) - nameSoFar = nameSoFar.value, type = childKey + getElementKey(nameSoFar, i++), invokeCallback += mapIntoArray( - nameSoFar, - array, - escapedPrefix, - type, - callback - ); - else if ("object" === type) { - if ("function" === typeof children.then) - return mapIntoArray( - resolveThenable(children), - array, - escapedPrefix, - nameSoFar, - callback - ); - array = String(children); - throw Error( - "Objects are not valid as a React child (found: " + ("[object Object]" === array ? "object with keys {" + Object.keys(children).join(", ") + "}" : array) + "). If you meant to render a collection of children, use an array instead." - ); - } - return invokeCallback; - } - function mapChildren2(children, func, context) { - if (null == children) return children; - var result = [], count = 0; - mapIntoArray(children, result, "", "", function(child) { - return func.call(context, child, count++); - }); - return result; - } - function lazyInitializer(payload) { - if (-1 === payload._status) { - var ioInfo = payload._ioInfo; - null != ioInfo && (ioInfo.start = ioInfo.end = performance.now()); - ioInfo = payload._result; - var thenable = ioInfo(); - thenable.then( - function(moduleObject) { - if (0 === payload._status || -1 === payload._status) { - payload._status = 1; - payload._result = moduleObject; - var _ioInfo = payload._ioInfo; - null != _ioInfo && (_ioInfo.end = performance.now()); - void 0 === thenable.status && (thenable.status = "fulfilled", thenable.value = moduleObject); - } - }, - function(error) { - if (0 === payload._status || -1 === payload._status) { - payload._status = 2; - payload._result = error; - var _ioInfo2 = payload._ioInfo; - null != _ioInfo2 && (_ioInfo2.end = performance.now()); - void 0 === thenable.status && (thenable.status = "rejected", thenable.reason = error); - } - } - ); - ioInfo = payload._ioInfo; - if (null != ioInfo) { - ioInfo.value = thenable; - var displayName = thenable.displayName; - "string" === typeof displayName && (ioInfo.name = displayName); - } - -1 === payload._status && (payload._status = 0, payload._result = thenable); - } - if (1 === payload._status) - return ioInfo = payload._result, void 0 === ioInfo && console.error( - "lazy: Expected the result of a dynamic import() call. Instead received: %s\n\nYour code should look like: \n const MyComponent = lazy(() => import('./MyComponent'))\n\nDid you accidentally put curly braces around the import?", - ioInfo - ), "default" in ioInfo || console.error( - "lazy: Expected the result of a dynamic import() call. Instead received: %s\n\nYour code should look like: \n const MyComponent = lazy(() => import('./MyComponent'))", - ioInfo - ), ioInfo.default; - throw payload._result; - } - function resolveDispatcher() { - var dispatcher = ReactSharedInternals.H; - null === dispatcher && console.error( - "Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:\n1. You might have mismatching versions of React and the renderer (such as React DOM)\n2. You might be breaking the Rules of Hooks\n3. You might have more than one copy of React in the same app\nSee https://react.dev/link/invalid-hook-call for tips about how to debug and fix this problem." - ); - return dispatcher; - } - function releaseAsyncTransition() { - ReactSharedInternals.asyncTransitions--; - } - function enqueueTask(task) { - if (null === enqueueTaskImpl) - try { - var requireString = ("require" + Math.random()).slice(0, 7); - enqueueTaskImpl = (module && module[requireString]).call( - module, - "timers" - ).setImmediate; - } catch (_err) { - enqueueTaskImpl = function(callback) { - false === didWarnAboutMessageChannel && (didWarnAboutMessageChannel = true, "undefined" === typeof MessageChannel && console.error( - "This browser does not have a MessageChannel implementation, so enqueuing tasks via await act(async () => ...) will fail. Please file an issue at https://github.com/facebook/react/issues if you encounter this warning." - )); - var channel = new MessageChannel(); - channel.port1.onmessage = callback; - channel.port2.postMessage(void 0); - }; - } - return enqueueTaskImpl(task); - } - function aggregateErrors(errors) { - return 1 < errors.length && "function" === typeof AggregateError ? new AggregateError(errors) : errors[0]; - } - function popActScope(prevActQueue, prevActScopeDepth) { - prevActScopeDepth !== actScopeDepth - 1 && console.error( - "You seem to have overlapping act() calls, this is not supported. Be sure to await previous act() calls before making a new one. " - ); - actScopeDepth = prevActScopeDepth; - } - function recursivelyFlushAsyncActWork(returnValue, resolve, reject) { - var queue = ReactSharedInternals.actQueue; - if (null !== queue) - if (0 !== queue.length) - try { - flushActQueue(queue); - enqueueTask(function() { - return recursivelyFlushAsyncActWork(returnValue, resolve, reject); - }); - return; - } catch (error) { - ReactSharedInternals.thrownErrors.push(error); - } - else ReactSharedInternals.actQueue = null; - 0 < ReactSharedInternals.thrownErrors.length ? (queue = aggregateErrors(ReactSharedInternals.thrownErrors), ReactSharedInternals.thrownErrors.length = 0, reject(queue)) : resolve(returnValue); - } - function flushActQueue(queue) { - if (!isFlushing) { - isFlushing = true; - var i = 0; - try { - for (; i < queue.length; i++) { - var callback = queue[i]; - do { - ReactSharedInternals.didUsePromise = false; - var continuation = callback(false); - if (null !== continuation) { - if (ReactSharedInternals.didUsePromise) { - queue[i] = callback; - queue.splice(0, i); - return; - } - callback = continuation; - } else break; - } while (1); - } - queue.length = 0; - } catch (error) { - queue.splice(0, i + 1), ReactSharedInternals.thrownErrors.push(error); - } finally { - isFlushing = false; - } - } - } - "undefined" !== typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ && "function" === typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart && __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(Error()); - var REACT_ELEMENT_TYPE = /* @__PURE__ */ Symbol.for("react.transitional.element"), REACT_PORTAL_TYPE = /* @__PURE__ */ Symbol.for("react.portal"), REACT_FRAGMENT_TYPE = /* @__PURE__ */ Symbol.for("react.fragment"), REACT_STRICT_MODE_TYPE = /* @__PURE__ */ Symbol.for("react.strict_mode"), REACT_PROFILER_TYPE = /* @__PURE__ */ Symbol.for("react.profiler"), REACT_CONSUMER_TYPE = /* @__PURE__ */ Symbol.for("react.consumer"), REACT_CONTEXT_TYPE = /* @__PURE__ */ Symbol.for("react.context"), REACT_FORWARD_REF_TYPE = /* @__PURE__ */ Symbol.for("react.forward_ref"), REACT_SUSPENSE_TYPE = /* @__PURE__ */ Symbol.for("react.suspense"), REACT_SUSPENSE_LIST_TYPE = /* @__PURE__ */ Symbol.for("react.suspense_list"), REACT_MEMO_TYPE = /* @__PURE__ */ Symbol.for("react.memo"), REACT_LAZY_TYPE = /* @__PURE__ */ Symbol.for("react.lazy"), REACT_ACTIVITY_TYPE = /* @__PURE__ */ Symbol.for("react.activity"), MAYBE_ITERATOR_SYMBOL = Symbol.iterator, didWarnStateUpdateForUnmountedComponent = {}, ReactNoopUpdateQueue = { - isMounted: function() { - return false; - }, - enqueueForceUpdate: function(publicInstance) { - warnNoop(publicInstance, "forceUpdate"); - }, - enqueueReplaceState: function(publicInstance) { - warnNoop(publicInstance, "replaceState"); - }, - enqueueSetState: function(publicInstance) { - warnNoop(publicInstance, "setState"); - } - }, assign = Object.assign, emptyObject = {}; - Object.freeze(emptyObject); - Component.prototype.isReactComponent = {}; - Component.prototype.setState = function(partialState, callback) { - if ("object" !== typeof partialState && "function" !== typeof partialState && null != partialState) - throw Error( - "takes an object of state variables to update or a function which returns an object of state variables." - ); - this.updater.enqueueSetState(this, partialState, callback, "setState"); - }; - Component.prototype.forceUpdate = function(callback) { - this.updater.enqueueForceUpdate(this, callback, "forceUpdate"); - }; - var deprecatedAPIs = { - isMounted: [ - "isMounted", - "Instead, make sure to clean up subscriptions and pending requests in componentWillUnmount to prevent memory leaks." - ], - replaceState: [ - "replaceState", - "Refactor your code to use setState instead (see https://github.com/facebook/react/issues/3236)." - ] - }; - for (fnName in deprecatedAPIs) - deprecatedAPIs.hasOwnProperty(fnName) && defineDeprecationWarning(fnName, deprecatedAPIs[fnName]); - ComponentDummy.prototype = Component.prototype; - deprecatedAPIs = PureComponent.prototype = new ComponentDummy(); - deprecatedAPIs.constructor = PureComponent; - assign(deprecatedAPIs, Component.prototype); - deprecatedAPIs.isPureReactComponent = true; - var isArrayImpl = Array.isArray, REACT_CLIENT_REFERENCE = /* @__PURE__ */ Symbol.for("react.client.reference"), ReactSharedInternals = { - H: null, - A: null, - T: null, - S: null, - actQueue: null, - asyncTransitions: 0, - isBatchingLegacy: false, - didScheduleLegacyUpdate: false, - didUsePromise: false, - thrownErrors: [], - getCurrentStack: null, - recentlyCreatedOwnerStacks: 0 - }, hasOwnProperty2 = Object.prototype.hasOwnProperty, createTask = console.createTask ? console.createTask : function() { - return null; - }; - deprecatedAPIs = { - react_stack_bottom_frame: function(callStackForError) { - return callStackForError(); - } - }; - var specialPropKeyWarningShown, didWarnAboutOldJSXRuntime; - var didWarnAboutElementRef = {}; - var unknownOwnerDebugStack = deprecatedAPIs.react_stack_bottom_frame.bind( - deprecatedAPIs, - UnknownOwner - )(); - var unknownOwnerDebugTask = createTask(getTaskName(UnknownOwner)); - var didWarnAboutMaps = false, userProvidedKeyEscapeRegex = /\/+/g, reportGlobalError = "function" === typeof reportError ? reportError : function(error) { - if ("object" === typeof window && "function" === typeof window.ErrorEvent) { - var event = new window.ErrorEvent("error", { - bubbles: true, - cancelable: true, - message: "object" === typeof error && null !== error && "string" === typeof error.message ? String(error.message) : String(error), - error - }); - if (!window.dispatchEvent(event)) return; - } else if ("object" === typeof process && "function" === typeof process.emit) { - process.emit("uncaughtException", error); - return; - } - console.error(error); - }, didWarnAboutMessageChannel = false, enqueueTaskImpl = null, actScopeDepth = 0, didWarnNoAwaitAct = false, isFlushing = false, queueSeveralMicrotasks = "function" === typeof queueMicrotask ? function(callback) { - queueMicrotask(function() { - return queueMicrotask(callback); - }); - } : enqueueTask; - deprecatedAPIs = Object.freeze({ - __proto__: null, - c: function(size) { - return resolveDispatcher().useMemoCache(size); - } - }); - var fnName = { - map: mapChildren2, - forEach: function(children, forEachFunc, forEachContext) { - mapChildren2( - children, - function() { - forEachFunc.apply(this, arguments); - }, - forEachContext - ); - }, - count: function(children) { - var n = 0; - mapChildren2(children, function() { - n++; - }); - return n; - }, - toArray: function(children) { - return mapChildren2(children, function(child) { - return child; - }) || []; - }, - only: function(children) { - if (!isValidElement(children)) - throw Error( - "React.Children.only expected to receive a single React element child." - ); - return children; - } - }; - exports$1.Activity = REACT_ACTIVITY_TYPE; - exports$1.Children = fnName; - exports$1.Component = Component; - exports$1.Fragment = REACT_FRAGMENT_TYPE; - exports$1.Profiler = REACT_PROFILER_TYPE; - exports$1.PureComponent = PureComponent; - exports$1.StrictMode = REACT_STRICT_MODE_TYPE; - exports$1.Suspense = REACT_SUSPENSE_TYPE; - exports$1.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE = ReactSharedInternals; - exports$1.__COMPILER_RUNTIME = deprecatedAPIs; - exports$1.act = function(callback) { - var prevActQueue = ReactSharedInternals.actQueue, prevActScopeDepth = actScopeDepth; - actScopeDepth++; - var queue = ReactSharedInternals.actQueue = null !== prevActQueue ? prevActQueue : [], didAwaitActCall = false; - try { - var result = callback(); - } catch (error) { - ReactSharedInternals.thrownErrors.push(error); - } - if (0 < ReactSharedInternals.thrownErrors.length) - throw popActScope(prevActQueue, prevActScopeDepth), callback = aggregateErrors(ReactSharedInternals.thrownErrors), ReactSharedInternals.thrownErrors.length = 0, callback; - if (null !== result && "object" === typeof result && "function" === typeof result.then) { - var thenable = result; - queueSeveralMicrotasks(function() { - didAwaitActCall || didWarnNoAwaitAct || (didWarnNoAwaitAct = true, console.error( - "You called act(async () => ...) without await. This could lead to unexpected testing behaviour, interleaving multiple act calls and mixing their scopes. You should - await act(async () => ...);" - )); - }); - return { - then: function(resolve, reject) { - didAwaitActCall = true; - thenable.then( - function(returnValue) { - popActScope(prevActQueue, prevActScopeDepth); - if (0 === prevActScopeDepth) { - try { - flushActQueue(queue), enqueueTask(function() { - return recursivelyFlushAsyncActWork( - returnValue, - resolve, - reject - ); - }); - } catch (error$0) { - ReactSharedInternals.thrownErrors.push(error$0); - } - if (0 < ReactSharedInternals.thrownErrors.length) { - var _thrownError = aggregateErrors( - ReactSharedInternals.thrownErrors - ); - ReactSharedInternals.thrownErrors.length = 0; - reject(_thrownError); - } - } else resolve(returnValue); - }, - function(error) { - popActScope(prevActQueue, prevActScopeDepth); - 0 < ReactSharedInternals.thrownErrors.length ? (error = aggregateErrors( - ReactSharedInternals.thrownErrors - ), ReactSharedInternals.thrownErrors.length = 0, reject(error)) : reject(error); - } - ); - } - }; - } - var returnValue$jscomp$0 = result; - popActScope(prevActQueue, prevActScopeDepth); - 0 === prevActScopeDepth && (flushActQueue(queue), 0 !== queue.length && queueSeveralMicrotasks(function() { - didAwaitActCall || didWarnNoAwaitAct || (didWarnNoAwaitAct = true, console.error( - "A component suspended inside an `act` scope, but the `act` call was not awaited. When testing React components that depend on asynchronous data, you must await the result:\n\nawait act(() => ...)" - )); - }), ReactSharedInternals.actQueue = null); - if (0 < ReactSharedInternals.thrownErrors.length) - throw callback = aggregateErrors(ReactSharedInternals.thrownErrors), ReactSharedInternals.thrownErrors.length = 0, callback; - return { - then: function(resolve, reject) { - didAwaitActCall = true; - 0 === prevActScopeDepth ? (ReactSharedInternals.actQueue = queue, enqueueTask(function() { - return recursivelyFlushAsyncActWork( - returnValue$jscomp$0, - resolve, - reject - ); - })) : resolve(returnValue$jscomp$0); - } - }; - }; - exports$1.cache = function(fn) { - return function() { - return fn.apply(null, arguments); - }; - }; - exports$1.cacheSignal = function() { - return null; - }; - exports$1.captureOwnerStack = function() { - var getCurrentStack = ReactSharedInternals.getCurrentStack; - return null === getCurrentStack ? null : getCurrentStack(); - }; - exports$1.cloneElement = function(element, config, children) { - if (null === element || void 0 === element) - throw Error( - "The argument must be a React element, but you passed " + element + "." - ); - var props = assign({}, element.props), key = element.key, owner = element._owner; - if (null != config) { - var JSCompiler_inline_result; - a: { - if (hasOwnProperty2.call(config, "ref") && (JSCompiler_inline_result = Object.getOwnPropertyDescriptor( - config, - "ref" - ).get) && JSCompiler_inline_result.isReactWarning) { - JSCompiler_inline_result = false; - break a; - } - JSCompiler_inline_result = void 0 !== config.ref; - } - JSCompiler_inline_result && (owner = getOwner()); - hasValidKey(config) && (checkKeyStringCoercion(config.key), key = "" + config.key); - for (propName in config) - !hasOwnProperty2.call(config, propName) || "key" === propName || "__self" === propName || "__source" === propName || "ref" === propName && void 0 === config.ref || (props[propName] = config[propName]); - } - var propName = arguments.length - 2; - if (1 === propName) props.children = children; - else if (1 < propName) { - JSCompiler_inline_result = Array(propName); - for (var i = 0; i < propName; i++) - JSCompiler_inline_result[i] = arguments[i + 2]; - props.children = JSCompiler_inline_result; - } - props = ReactElement( - element.type, - key, - props, - owner, - element._debugStack, - element._debugTask - ); - for (key = 2; key < arguments.length; key++) - validateChildKeys(arguments[key]); - return props; - }; - exports$1.createContext = function(defaultValue) { - defaultValue = { - $$typeof: REACT_CONTEXT_TYPE, - _currentValue: defaultValue, - _currentValue2: defaultValue, - _threadCount: 0, - Provider: null, - Consumer: null - }; - defaultValue.Provider = defaultValue; - defaultValue.Consumer = { - $$typeof: REACT_CONSUMER_TYPE, - _context: defaultValue - }; - defaultValue._currentRenderer = null; - defaultValue._currentRenderer2 = null; - return defaultValue; - }; - exports$1.createElement = function(type, config, children) { - for (var i = 2; i < arguments.length; i++) - validateChildKeys(arguments[i]); - i = {}; - var key = null; - if (null != config) - for (propName in didWarnAboutOldJSXRuntime || !("__self" in config) || "key" in config || (didWarnAboutOldJSXRuntime = true, console.warn( - "Your app (or one of its dependencies) is using an outdated JSX transform. Update to the modern JSX transform for faster performance: https://react.dev/link/new-jsx-transform" - )), hasValidKey(config) && (checkKeyStringCoercion(config.key), key = "" + config.key), config) - hasOwnProperty2.call(config, propName) && "key" !== propName && "__self" !== propName && "__source" !== propName && (i[propName] = config[propName]); - var childrenLength = arguments.length - 2; - if (1 === childrenLength) i.children = children; - else if (1 < childrenLength) { - for (var childArray = Array(childrenLength), _i = 0; _i < childrenLength; _i++) - childArray[_i] = arguments[_i + 2]; - Object.freeze && Object.freeze(childArray); - i.children = childArray; - } - if (type && type.defaultProps) - for (propName in childrenLength = type.defaultProps, childrenLength) - void 0 === i[propName] && (i[propName] = childrenLength[propName]); - key && defineKeyPropWarningGetter( - i, - "function" === typeof type ? type.displayName || type.name || "Unknown" : type - ); - var propName = 1e4 > ReactSharedInternals.recentlyCreatedOwnerStacks++; - return ReactElement( - type, - key, - i, - getOwner(), - propName ? Error("react-stack-top-frame") : unknownOwnerDebugStack, - propName ? createTask(getTaskName(type)) : unknownOwnerDebugTask - ); - }; - exports$1.createRef = function() { - var refObject = { current: null }; - Object.seal(refObject); - return refObject; - }; - exports$1.forwardRef = function(render) { - null != render && render.$$typeof === REACT_MEMO_TYPE ? console.error( - "forwardRef requires a render function but received a `memo` component. Instead of forwardRef(memo(...)), use memo(forwardRef(...))." - ) : "function" !== typeof render ? console.error( - "forwardRef requires a render function but was given %s.", - null === render ? "null" : typeof render - ) : 0 !== render.length && 2 !== render.length && console.error( - "forwardRef render functions accept exactly two parameters: props and ref. %s", - 1 === render.length ? "Did you forget to use the ref parameter?" : "Any additional parameter will be undefined." - ); - null != render && null != render.defaultProps && console.error( - "forwardRef render functions do not support defaultProps. Did you accidentally pass a React component?" - ); - var elementType = { $$typeof: REACT_FORWARD_REF_TYPE, render }, ownName; - Object.defineProperty(elementType, "displayName", { - enumerable: false, - configurable: true, - get: function() { - return ownName; - }, - set: function(name) { - ownName = name; - render.name || render.displayName || (Object.defineProperty(render, "name", { value: name }), render.displayName = name); - } - }); - return elementType; - }; - exports$1.isValidElement = isValidElement; - exports$1.lazy = function(ctor) { - ctor = { _status: -1, _result: ctor }; - var lazyType = { - $$typeof: REACT_LAZY_TYPE, - _payload: ctor, - _init: lazyInitializer - }, ioInfo = { - name: "lazy", - start: -1, - end: -1, - value: null, - owner: null, - debugStack: Error("react-stack-top-frame"), - debugTask: console.createTask ? console.createTask("lazy()") : null - }; - ctor._ioInfo = ioInfo; - lazyType._debugInfo = [{ awaited: ioInfo }]; - return lazyType; - }; - exports$1.memo = function(type, compare) { - null == type && console.error( - "memo: The first argument must be a component. Instead received: %s", - null === type ? "null" : typeof type - ); - compare = { - $$typeof: REACT_MEMO_TYPE, - type, - compare: void 0 === compare ? null : compare - }; - var ownName; - Object.defineProperty(compare, "displayName", { - enumerable: false, - configurable: true, - get: function() { - return ownName; - }, - set: function(name) { - ownName = name; - type.name || type.displayName || (Object.defineProperty(type, "name", { value: name }), type.displayName = name); - } - }); - return compare; - }; - exports$1.startTransition = function(scope) { - var prevTransition = ReactSharedInternals.T, currentTransition = {}; - currentTransition._updatedFibers = /* @__PURE__ */ new Set(); - ReactSharedInternals.T = currentTransition; - try { - var returnValue = scope(), onStartTransitionFinish = ReactSharedInternals.S; - null !== onStartTransitionFinish && onStartTransitionFinish(currentTransition, returnValue); - "object" === typeof returnValue && null !== returnValue && "function" === typeof returnValue.then && (ReactSharedInternals.asyncTransitions++, returnValue.then(releaseAsyncTransition, releaseAsyncTransition), returnValue.then(noop2, reportGlobalError)); - } catch (error) { - reportGlobalError(error); - } finally { - null === prevTransition && currentTransition._updatedFibers && (scope = currentTransition._updatedFibers.size, currentTransition._updatedFibers.clear(), 10 < scope && console.warn( - "Detected a large number of updates inside startTransition. If this is due to a subscription please re-write it to use React provided hooks. Otherwise concurrent mode guarantees are off the table." - )), null !== prevTransition && null !== currentTransition.types && (null !== prevTransition.types && prevTransition.types !== currentTransition.types && console.error( - "We expected inner Transitions to have transferred the outer types set and that you cannot add to the outer Transition while inside the inner.This is a bug in React." - ), prevTransition.types = currentTransition.types), ReactSharedInternals.T = prevTransition; - } - }; - exports$1.unstable_useCacheRefresh = function() { - return resolveDispatcher().useCacheRefresh(); - }; - exports$1.use = function(usable) { - return resolveDispatcher().use(usable); - }; - exports$1.useActionState = function(action, initialState, permalink) { - return resolveDispatcher().useActionState( - action, - initialState, - permalink - ); - }; - exports$1.useCallback = function(callback, deps) { - return resolveDispatcher().useCallback(callback, deps); - }; - exports$1.useContext = function(Context) { - var dispatcher = resolveDispatcher(); - Context.$$typeof === REACT_CONSUMER_TYPE && console.error( - "Calling useContext(Context.Consumer) is not supported and will cause bugs. Did you mean to call useContext(Context) instead?" - ); - return dispatcher.useContext(Context); - }; - exports$1.useDebugValue = function(value, formatterFn) { - return resolveDispatcher().useDebugValue(value, formatterFn); - }; - exports$1.useDeferredValue = function(value, initialValue) { - return resolveDispatcher().useDeferredValue(value, initialValue); - }; - exports$1.useEffect = function(create, deps) { - null == create && console.warn( - "React Hook useEffect requires an effect callback. Did you forget to pass a callback to the hook?" - ); - return resolveDispatcher().useEffect(create, deps); - }; - exports$1.useEffectEvent = function(callback) { - return resolveDispatcher().useEffectEvent(callback); - }; - exports$1.useId = function() { - return resolveDispatcher().useId(); - }; - exports$1.useImperativeHandle = function(ref, create, deps) { - return resolveDispatcher().useImperativeHandle(ref, create, deps); - }; - exports$1.useInsertionEffect = function(create, deps) { - null == create && console.warn( - "React Hook useInsertionEffect requires an effect callback. Did you forget to pass a callback to the hook?" - ); - return resolveDispatcher().useInsertionEffect(create, deps); - }; - exports$1.useLayoutEffect = function(create, deps) { - null == create && console.warn( - "React Hook useLayoutEffect requires an effect callback. Did you forget to pass a callback to the hook?" - ); - return resolveDispatcher().useLayoutEffect(create, deps); - }; - exports$1.useMemo = function(create, deps) { - return resolveDispatcher().useMemo(create, deps); - }; - exports$1.useOptimistic = function(passthrough, reducer) { - return resolveDispatcher().useOptimistic(passthrough, reducer); - }; - exports$1.useReducer = function(reducer, initialArg, init2) { - return resolveDispatcher().useReducer(reducer, initialArg, init2); - }; - exports$1.useRef = function(initialValue) { - return resolveDispatcher().useRef(initialValue); - }; - exports$1.useState = function(initialState) { - return resolveDispatcher().useState(initialState); - }; - exports$1.useSyncExternalStore = function(subscribe, getSnapshot, getServerSnapshot) { - return resolveDispatcher().useSyncExternalStore( - subscribe, - getSnapshot, - getServerSnapshot - ); - }; - exports$1.useTransition = function() { - return resolveDispatcher().useTransition(); - }; - exports$1.version = "19.2.4"; - "undefined" !== typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ && "function" === typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop && __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(Error()); - })(); - })(react_development, react_development.exports); - return react_development.exports; -} -var hasRequiredReact; -function requireReact() { - if (hasRequiredReact) return react.exports; - hasRequiredReact = 1; - if (process.env.NODE_ENV === "production") { - react.exports = requireReact_production(); - } else { - react.exports = requireReact_development(); - } - return react.exports; -} -var reactExports = requireReact(); -const React = /* @__PURE__ */ getDefaultExportFromCjs(reactExports); -var reactDom = { exports: {} }; -var reactDom_production = {}; -var hasRequiredReactDom_production; -function requireReactDom_production() { - if (hasRequiredReactDom_production) return reactDom_production; - hasRequiredReactDom_production = 1; - var React2 = requireReact(); - function formatProdErrorMessage(code) { - var url = "https://react.dev/errors/" + code; - if (1 < arguments.length) { - url += "?args[]=" + encodeURIComponent(arguments[1]); - for (var i = 2; i < arguments.length; i++) - url += "&args[]=" + encodeURIComponent(arguments[i]); - } - return "Minified React error #" + code + "; visit " + url + " for the full message or use the non-minified dev environment for full errors and additional helpful warnings."; - } - function noop2() { - } - var Internals = { - d: { - f: noop2, - r: function() { - throw Error(formatProdErrorMessage(522)); - }, - D: noop2, - C: noop2, - L: noop2, - m: noop2, - X: noop2, - S: noop2, - M: noop2 - }, - p: 0, - findDOMNode: null - }, REACT_PORTAL_TYPE = /* @__PURE__ */ Symbol.for("react.portal"); - function createPortal$1(children, containerInfo, implementation) { - var key = 3 < arguments.length && void 0 !== arguments[3] ? arguments[3] : null; - return { - $$typeof: REACT_PORTAL_TYPE, - key: null == key ? null : "" + key, - children, - containerInfo, - implementation - }; - } - var ReactSharedInternals = React2.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE; - function getCrossOriginStringAs(as, input) { - if ("font" === as) return ""; - if ("string" === typeof input) - return "use-credentials" === input ? input : ""; - } - reactDom_production.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE = Internals; - reactDom_production.createPortal = function(children, container) { - var key = 2 < arguments.length && void 0 !== arguments[2] ? arguments[2] : null; - if (!container || 1 !== container.nodeType && 9 !== container.nodeType && 11 !== container.nodeType) - throw Error(formatProdErrorMessage(299)); - return createPortal$1(children, container, null, key); - }; - reactDom_production.flushSync = function(fn) { - var previousTransition = ReactSharedInternals.T, previousUpdatePriority = Internals.p; - try { - if (ReactSharedInternals.T = null, Internals.p = 2, fn) return fn(); - } finally { - ReactSharedInternals.T = previousTransition, Internals.p = previousUpdatePriority, Internals.d.f(); - } - }; - reactDom_production.preconnect = function(href, options) { - "string" === typeof href && (options ? (options = options.crossOrigin, options = "string" === typeof options ? "use-credentials" === options ? options : "" : void 0) : options = null, Internals.d.C(href, options)); - }; - reactDom_production.prefetchDNS = function(href) { - "string" === typeof href && Internals.d.D(href); - }; - reactDom_production.preinit = function(href, options) { - if ("string" === typeof href && options && "string" === typeof options.as) { - var as = options.as, crossOrigin = getCrossOriginStringAs(as, options.crossOrigin), integrity = "string" === typeof options.integrity ? options.integrity : void 0, fetchPriority = "string" === typeof options.fetchPriority ? options.fetchPriority : void 0; - "style" === as ? Internals.d.S( - href, - "string" === typeof options.precedence ? options.precedence : void 0, - { - crossOrigin, - integrity, - fetchPriority - } - ) : "script" === as && Internals.d.X(href, { - crossOrigin, - integrity, - fetchPriority, - nonce: "string" === typeof options.nonce ? options.nonce : void 0 - }); - } - }; - reactDom_production.preinitModule = function(href, options) { - if ("string" === typeof href) - if ("object" === typeof options && null !== options) { - if (null == options.as || "script" === options.as) { - var crossOrigin = getCrossOriginStringAs( - options.as, - options.crossOrigin - ); - Internals.d.M(href, { - crossOrigin, - integrity: "string" === typeof options.integrity ? options.integrity : void 0, - nonce: "string" === typeof options.nonce ? options.nonce : void 0 - }); - } - } else null == options && Internals.d.M(href); - }; - reactDom_production.preload = function(href, options) { - if ("string" === typeof href && "object" === typeof options && null !== options && "string" === typeof options.as) { - var as = options.as, crossOrigin = getCrossOriginStringAs(as, options.crossOrigin); - Internals.d.L(href, as, { - crossOrigin, - integrity: "string" === typeof options.integrity ? options.integrity : void 0, - nonce: "string" === typeof options.nonce ? options.nonce : void 0, - type: "string" === typeof options.type ? options.type : void 0, - fetchPriority: "string" === typeof options.fetchPriority ? options.fetchPriority : void 0, - referrerPolicy: "string" === typeof options.referrerPolicy ? options.referrerPolicy : void 0, - imageSrcSet: "string" === typeof options.imageSrcSet ? options.imageSrcSet : void 0, - imageSizes: "string" === typeof options.imageSizes ? options.imageSizes : void 0, - media: "string" === typeof options.media ? options.media : void 0 - }); - } - }; - reactDom_production.preloadModule = function(href, options) { - if ("string" === typeof href) - if (options) { - var crossOrigin = getCrossOriginStringAs(options.as, options.crossOrigin); - Internals.d.m(href, { - as: "string" === typeof options.as && "script" !== options.as ? options.as : void 0, - crossOrigin, - integrity: "string" === typeof options.integrity ? options.integrity : void 0 - }); - } else Internals.d.m(href); - }; - reactDom_production.requestFormReset = function(form) { - Internals.d.r(form); - }; - reactDom_production.unstable_batchedUpdates = function(fn, a) { - return fn(a); - }; - reactDom_production.useFormState = function(action, initialState, permalink) { - return ReactSharedInternals.H.useFormState(action, initialState, permalink); - }; - reactDom_production.useFormStatus = function() { - return ReactSharedInternals.H.useHostTransitionStatus(); - }; - reactDom_production.version = "19.2.4"; - return reactDom_production; -} -var reactDom_development = {}; -var hasRequiredReactDom_development; -function requireReactDom_development() { - if (hasRequiredReactDom_development) return reactDom_development; - hasRequiredReactDom_development = 1; - "production" !== process.env.NODE_ENV && (function() { - function noop2() { - } - function testStringCoercion(value) { - return "" + value; - } - function createPortal$1(children, containerInfo, implementation) { - var key = 3 < arguments.length && void 0 !== arguments[3] ? arguments[3] : null; - try { - testStringCoercion(key); - var JSCompiler_inline_result = false; - } catch (e) { - JSCompiler_inline_result = true; - } - JSCompiler_inline_result && (console.error( - "The provided key is an unsupported type %s. This value must be coerced to a string before using it here.", - "function" === typeof Symbol && Symbol.toStringTag && key[Symbol.toStringTag] || key.constructor.name || "Object" - ), testStringCoercion(key)); - return { - $$typeof: REACT_PORTAL_TYPE, - key: null == key ? null : "" + key, - children, - containerInfo, - implementation - }; - } - function getCrossOriginStringAs(as, input) { - if ("font" === as) return ""; - if ("string" === typeof input) - return "use-credentials" === input ? input : ""; - } - function getValueDescriptorExpectingObjectForWarning(thing) { - return null === thing ? "`null`" : void 0 === thing ? "`undefined`" : "" === thing ? "an empty string" : 'something with type "' + typeof thing + '"'; - } - function getValueDescriptorExpectingEnumForWarning(thing) { - return null === thing ? "`null`" : void 0 === thing ? "`undefined`" : "" === thing ? "an empty string" : "string" === typeof thing ? JSON.stringify(thing) : "number" === typeof thing ? "`" + thing + "`" : 'something with type "' + typeof thing + '"'; - } - function resolveDispatcher() { - var dispatcher = ReactSharedInternals.H; - null === dispatcher && console.error( - "Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:\n1. You might have mismatching versions of React and the renderer (such as React DOM)\n2. You might be breaking the Rules of Hooks\n3. You might have more than one copy of React in the same app\nSee https://react.dev/link/invalid-hook-call for tips about how to debug and fix this problem." - ); - return dispatcher; - } - "undefined" !== typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ && "function" === typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart && __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(Error()); - var React2 = requireReact(), Internals = { - d: { - f: noop2, - r: function() { - throw Error( - "Invalid form element. requestFormReset must be passed a form that was rendered by React." - ); - }, - D: noop2, - C: noop2, - L: noop2, - m: noop2, - X: noop2, - S: noop2, - M: noop2 - }, - p: 0, - findDOMNode: null - }, REACT_PORTAL_TYPE = /* @__PURE__ */ Symbol.for("react.portal"), ReactSharedInternals = React2.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE; - "function" === typeof Map && null != Map.prototype && "function" === typeof Map.prototype.forEach && "function" === typeof Set && null != Set.prototype && "function" === typeof Set.prototype.clear && "function" === typeof Set.prototype.forEach || console.error( - "React depends on Map and Set built-in types. Make sure that you load a polyfill in older browsers. https://reactjs.org/link/react-polyfills" - ); - reactDom_development.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE = Internals; - reactDom_development.createPortal = function(children, container) { - var key = 2 < arguments.length && void 0 !== arguments[2] ? arguments[2] : null; - if (!container || 1 !== container.nodeType && 9 !== container.nodeType && 11 !== container.nodeType) - throw Error("Target container is not a DOM element."); - return createPortal$1(children, container, null, key); - }; - reactDom_development.flushSync = function(fn) { - var previousTransition = ReactSharedInternals.T, previousUpdatePriority = Internals.p; - try { - if (ReactSharedInternals.T = null, Internals.p = 2, fn) - return fn(); - } finally { - ReactSharedInternals.T = previousTransition, Internals.p = previousUpdatePriority, Internals.d.f() && console.error( - "flushSync was called from inside a lifecycle method. React cannot flush when React is already rendering. Consider moving this call to a scheduler task or micro task." - ); - } - }; - reactDom_development.preconnect = function(href, options) { - "string" === typeof href && href ? null != options && "object" !== typeof options ? console.error( - "ReactDOM.preconnect(): Expected the `options` argument (second) to be an object but encountered %s instead. The only supported option at this time is `crossOrigin` which accepts a string.", - getValueDescriptorExpectingEnumForWarning(options) - ) : null != options && "string" !== typeof options.crossOrigin && console.error( - "ReactDOM.preconnect(): Expected the `crossOrigin` option (second argument) to be a string but encountered %s instead. Try removing this option or passing a string value instead.", - getValueDescriptorExpectingObjectForWarning(options.crossOrigin) - ) : console.error( - "ReactDOM.preconnect(): Expected the `href` argument (first) to be a non-empty string but encountered %s instead.", - getValueDescriptorExpectingObjectForWarning(href) - ); - "string" === typeof href && (options ? (options = options.crossOrigin, options = "string" === typeof options ? "use-credentials" === options ? options : "" : void 0) : options = null, Internals.d.C(href, options)); - }; - reactDom_development.prefetchDNS = function(href) { - if ("string" !== typeof href || !href) - console.error( - "ReactDOM.prefetchDNS(): Expected the `href` argument (first) to be a non-empty string but encountered %s instead.", - getValueDescriptorExpectingObjectForWarning(href) - ); - else if (1 < arguments.length) { - var options = arguments[1]; - "object" === typeof options && options.hasOwnProperty("crossOrigin") ? console.error( - "ReactDOM.prefetchDNS(): Expected only one argument, `href`, but encountered %s as a second argument instead. This argument is reserved for future options and is currently disallowed. It looks like the you are attempting to set a crossOrigin property for this DNS lookup hint. Browsers do not perform DNS queries using CORS and setting this attribute on the resource hint has no effect. Try calling ReactDOM.prefetchDNS() with just a single string argument, `href`.", - getValueDescriptorExpectingEnumForWarning(options) - ) : console.error( - "ReactDOM.prefetchDNS(): Expected only one argument, `href`, but encountered %s as a second argument instead. This argument is reserved for future options and is currently disallowed. Try calling ReactDOM.prefetchDNS() with just a single string argument, `href`.", - getValueDescriptorExpectingEnumForWarning(options) - ); - } - "string" === typeof href && Internals.d.D(href); - }; - reactDom_development.preinit = function(href, options) { - "string" === typeof href && href ? null == options || "object" !== typeof options ? console.error( - "ReactDOM.preinit(): Expected the `options` argument (second) to be an object with an `as` property describing the type of resource to be preinitialized but encountered %s instead.", - getValueDescriptorExpectingEnumForWarning(options) - ) : "style" !== options.as && "script" !== options.as && console.error( - 'ReactDOM.preinit(): Expected the `as` property in the `options` argument (second) to contain a valid value describing the type of resource to be preinitialized but encountered %s instead. Valid values for `as` are "style" and "script".', - getValueDescriptorExpectingEnumForWarning(options.as) - ) : console.error( - "ReactDOM.preinit(): Expected the `href` argument (first) to be a non-empty string but encountered %s instead.", - getValueDescriptorExpectingObjectForWarning(href) - ); - if ("string" === typeof href && options && "string" === typeof options.as) { - var as = options.as, crossOrigin = getCrossOriginStringAs(as, options.crossOrigin), integrity = "string" === typeof options.integrity ? options.integrity : void 0, fetchPriority = "string" === typeof options.fetchPriority ? options.fetchPriority : void 0; - "style" === as ? Internals.d.S( - href, - "string" === typeof options.precedence ? options.precedence : void 0, - { - crossOrigin, - integrity, - fetchPriority - } - ) : "script" === as && Internals.d.X(href, { - crossOrigin, - integrity, - fetchPriority, - nonce: "string" === typeof options.nonce ? options.nonce : void 0 - }); - } - }; - reactDom_development.preinitModule = function(href, options) { - var encountered = ""; - "string" === typeof href && href || (encountered += " The `href` argument encountered was " + getValueDescriptorExpectingObjectForWarning(href) + "."); - void 0 !== options && "object" !== typeof options ? encountered += " The `options` argument encountered was " + getValueDescriptorExpectingObjectForWarning(options) + "." : options && "as" in options && "script" !== options.as && (encountered += " The `as` option encountered was " + getValueDescriptorExpectingEnumForWarning(options.as) + "."); - if (encountered) - console.error( - "ReactDOM.preinitModule(): Expected up to two arguments, a non-empty `href` string and, optionally, an `options` object with a valid `as` property.%s", - encountered - ); - else - switch (encountered = options && "string" === typeof options.as ? options.as : "script", encountered) { - case "script": - break; - default: - encountered = getValueDescriptorExpectingEnumForWarning(encountered), console.error( - 'ReactDOM.preinitModule(): Currently the only supported "as" type for this function is "script" but received "%s" instead. This warning was generated for `href` "%s". In the future other module types will be supported, aligning with the import-attributes proposal. Learn more here: (https://github.com/tc39/proposal-import-attributes)', - encountered, - href - ); - } - if ("string" === typeof href) - if ("object" === typeof options && null !== options) { - if (null == options.as || "script" === options.as) - encountered = getCrossOriginStringAs( - options.as, - options.crossOrigin - ), Internals.d.M(href, { - crossOrigin: encountered, - integrity: "string" === typeof options.integrity ? options.integrity : void 0, - nonce: "string" === typeof options.nonce ? options.nonce : void 0 - }); - } else null == options && Internals.d.M(href); - }; - reactDom_development.preload = function(href, options) { - var encountered = ""; - "string" === typeof href && href || (encountered += " The `href` argument encountered was " + getValueDescriptorExpectingObjectForWarning(href) + "."); - null == options || "object" !== typeof options ? encountered += " The `options` argument encountered was " + getValueDescriptorExpectingObjectForWarning(options) + "." : "string" === typeof options.as && options.as || (encountered += " The `as` option encountered was " + getValueDescriptorExpectingObjectForWarning(options.as) + "."); - encountered && console.error( - 'ReactDOM.preload(): Expected two arguments, a non-empty `href` string and an `options` object with an `as` property valid for a `` tag.%s', - encountered - ); - if ("string" === typeof href && "object" === typeof options && null !== options && "string" === typeof options.as) { - encountered = options.as; - var crossOrigin = getCrossOriginStringAs( - encountered, - options.crossOrigin - ); - Internals.d.L(href, encountered, { - crossOrigin, - integrity: "string" === typeof options.integrity ? options.integrity : void 0, - nonce: "string" === typeof options.nonce ? options.nonce : void 0, - type: "string" === typeof options.type ? options.type : void 0, - fetchPriority: "string" === typeof options.fetchPriority ? options.fetchPriority : void 0, - referrerPolicy: "string" === typeof options.referrerPolicy ? options.referrerPolicy : void 0, - imageSrcSet: "string" === typeof options.imageSrcSet ? options.imageSrcSet : void 0, - imageSizes: "string" === typeof options.imageSizes ? options.imageSizes : void 0, - media: "string" === typeof options.media ? options.media : void 0 - }); - } - }; - reactDom_development.preloadModule = function(href, options) { - var encountered = ""; - "string" === typeof href && href || (encountered += " The `href` argument encountered was " + getValueDescriptorExpectingObjectForWarning(href) + "."); - void 0 !== options && "object" !== typeof options ? encountered += " The `options` argument encountered was " + getValueDescriptorExpectingObjectForWarning(options) + "." : options && "as" in options && "string" !== typeof options.as && (encountered += " The `as` option encountered was " + getValueDescriptorExpectingObjectForWarning(options.as) + "."); - encountered && console.error( - 'ReactDOM.preloadModule(): Expected two arguments, a non-empty `href` string and, optionally, an `options` object with an `as` property valid for a `` tag.%s', - encountered - ); - "string" === typeof href && (options ? (encountered = getCrossOriginStringAs( - options.as, - options.crossOrigin - ), Internals.d.m(href, { - as: "string" === typeof options.as && "script" !== options.as ? options.as : void 0, - crossOrigin: encountered, - integrity: "string" === typeof options.integrity ? options.integrity : void 0 - })) : Internals.d.m(href)); - }; - reactDom_development.requestFormReset = function(form) { - Internals.d.r(form); - }; - reactDom_development.unstable_batchedUpdates = function(fn, a) { - return fn(a); - }; - reactDom_development.useFormState = function(action, initialState, permalink) { - return resolveDispatcher().useFormState(action, initialState, permalink); - }; - reactDom_development.useFormStatus = function() { - return resolveDispatcher().useHostTransitionStatus(); - }; - reactDom_development.version = "19.2.4"; - "undefined" !== typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ && "function" === typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop && __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(Error()); - })(); - return reactDom_development; -} -var hasRequiredReactDom; -function requireReactDom() { - if (hasRequiredReactDom) return reactDom.exports; - hasRequiredReactDom = 1; - function checkDCE() { - if (typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ === "undefined" || typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE !== "function") { - return; - } - if (process.env.NODE_ENV !== "production") { - throw new Error("^_^"); - } - try { - __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(checkDCE); - } catch (err) { - console.error(err); - } - } - if (process.env.NODE_ENV === "production") { - checkDCE(); - reactDom.exports = requireReactDom_production(); - } else { - reactDom.exports = requireReactDom_development(); - } - return reactDom.exports; -} -var reactDomExports = requireReactDom(); -const ReactDOM = /* @__PURE__ */ getDefaultExportFromCjs(reactDomExports); -var shim = { exports: {} }; -var useSyncExternalStoreShim_production = {}; -var hasRequiredUseSyncExternalStoreShim_production; -function requireUseSyncExternalStoreShim_production() { - if (hasRequiredUseSyncExternalStoreShim_production) return useSyncExternalStoreShim_production; - hasRequiredUseSyncExternalStoreShim_production = 1; - var React2 = requireReact(); - function is(x, y) { - return x === y && (0 !== x || 1 / x === 1 / y) || x !== x && y !== y; - } - var objectIs = "function" === typeof Object.is ? Object.is : is, useState = React2.useState, useEffect = React2.useEffect, useLayoutEffect = React2.useLayoutEffect, useDebugValue = React2.useDebugValue; - function useSyncExternalStore$2(subscribe, getSnapshot) { - var value = getSnapshot(), _useState = useState({ inst: { value, getSnapshot } }), inst = _useState[0].inst, forceUpdate = _useState[1]; - useLayoutEffect( - function() { - inst.value = value; - inst.getSnapshot = getSnapshot; - checkIfSnapshotChanged(inst) && forceUpdate({ inst }); - }, - [subscribe, value, getSnapshot] - ); - useEffect( - function() { - checkIfSnapshotChanged(inst) && forceUpdate({ inst }); - return subscribe(function() { - checkIfSnapshotChanged(inst) && forceUpdate({ inst }); - }); - }, - [subscribe] - ); - useDebugValue(value); - return value; - } - function checkIfSnapshotChanged(inst) { - var latestGetSnapshot = inst.getSnapshot; - inst = inst.value; - try { - var nextValue = latestGetSnapshot(); - return !objectIs(inst, nextValue); - } catch (error) { - return true; - } - } - function useSyncExternalStore$1(subscribe, getSnapshot) { - return getSnapshot(); - } - var shim2 = "undefined" === typeof window || "undefined" === typeof window.document || "undefined" === typeof window.document.createElement ? useSyncExternalStore$1 : useSyncExternalStore$2; - useSyncExternalStoreShim_production.useSyncExternalStore = void 0 !== React2.useSyncExternalStore ? React2.useSyncExternalStore : shim2; - return useSyncExternalStoreShim_production; -} -var useSyncExternalStoreShim_development = {}; -var hasRequiredUseSyncExternalStoreShim_development; -function requireUseSyncExternalStoreShim_development() { - if (hasRequiredUseSyncExternalStoreShim_development) return useSyncExternalStoreShim_development; - hasRequiredUseSyncExternalStoreShim_development = 1; - "production" !== process.env.NODE_ENV && (function() { - function is(x, y) { - return x === y && (0 !== x || 1 / x === 1 / y) || x !== x && y !== y; - } - function useSyncExternalStore$2(subscribe, getSnapshot) { - didWarnOld18Alpha || void 0 === React2.startTransition || (didWarnOld18Alpha = true, console.error( - "You are using an outdated, pre-release alpha of React 18 that does not support useSyncExternalStore. The use-sync-external-store shim will not work correctly. Upgrade to a newer pre-release." - )); - var value = getSnapshot(); - if (!didWarnUncachedGetSnapshot) { - var cachedValue = getSnapshot(); - objectIs(value, cachedValue) || (console.error( - "The result of getSnapshot should be cached to avoid an infinite loop" - ), didWarnUncachedGetSnapshot = true); - } - cachedValue = useState({ - inst: { value, getSnapshot } - }); - var inst = cachedValue[0].inst, forceUpdate = cachedValue[1]; - useLayoutEffect( - function() { - inst.value = value; - inst.getSnapshot = getSnapshot; - checkIfSnapshotChanged(inst) && forceUpdate({ inst }); - }, - [subscribe, value, getSnapshot] - ); - useEffect( - function() { - checkIfSnapshotChanged(inst) && forceUpdate({ inst }); - return subscribe(function() { - checkIfSnapshotChanged(inst) && forceUpdate({ inst }); - }); - }, - [subscribe] - ); - useDebugValue(value); - return value; - } - function checkIfSnapshotChanged(inst) { - var latestGetSnapshot = inst.getSnapshot; - inst = inst.value; - try { - var nextValue = latestGetSnapshot(); - return !objectIs(inst, nextValue); - } catch (error) { - return true; - } - } - function useSyncExternalStore$1(subscribe, getSnapshot) { - return getSnapshot(); - } - "undefined" !== typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ && "function" === typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart && __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(Error()); - var React2 = requireReact(), objectIs = "function" === typeof Object.is ? Object.is : is, useState = React2.useState, useEffect = React2.useEffect, useLayoutEffect = React2.useLayoutEffect, useDebugValue = React2.useDebugValue, didWarnOld18Alpha = false, didWarnUncachedGetSnapshot = false, shim2 = "undefined" === typeof window || "undefined" === typeof window.document || "undefined" === typeof window.document.createElement ? useSyncExternalStore$1 : useSyncExternalStore$2; - useSyncExternalStoreShim_development.useSyncExternalStore = void 0 !== React2.useSyncExternalStore ? React2.useSyncExternalStore : shim2; - "undefined" !== typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ && "function" === typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop && __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(Error()); - })(); - return useSyncExternalStoreShim_development; -} -var hasRequiredShim; -function requireShim() { - if (hasRequiredShim) return shim.exports; - hasRequiredShim = 1; - if (process.env.NODE_ENV === "production") { - shim.exports = requireUseSyncExternalStoreShim_production(); - } else { - shim.exports = requireUseSyncExternalStoreShim_development(); - } - return shim.exports; -} -var shimExports = requireShim(); -var jsxRuntime = { exports: {} }; -var reactJsxRuntime_production = {}; -var hasRequiredReactJsxRuntime_production; -function requireReactJsxRuntime_production() { - if (hasRequiredReactJsxRuntime_production) return reactJsxRuntime_production; - hasRequiredReactJsxRuntime_production = 1; - var REACT_ELEMENT_TYPE = /* @__PURE__ */ Symbol.for("react.transitional.element"), REACT_FRAGMENT_TYPE = /* @__PURE__ */ Symbol.for("react.fragment"); - function jsxProd(type, config, maybeKey) { - var key = null; - void 0 !== maybeKey && (key = "" + maybeKey); - void 0 !== config.key && (key = "" + config.key); - if ("key" in config) { - maybeKey = {}; - for (var propName in config) - "key" !== propName && (maybeKey[propName] = config[propName]); - } else maybeKey = config; - config = maybeKey.ref; - return { - $$typeof: REACT_ELEMENT_TYPE, - type, - key, - ref: void 0 !== config ? config : null, - props: maybeKey - }; - } - reactJsxRuntime_production.Fragment = REACT_FRAGMENT_TYPE; - reactJsxRuntime_production.jsx = jsxProd; - reactJsxRuntime_production.jsxs = jsxProd; - return reactJsxRuntime_production; -} -var reactJsxRuntime_development = {}; -var hasRequiredReactJsxRuntime_development; -function requireReactJsxRuntime_development() { - if (hasRequiredReactJsxRuntime_development) return reactJsxRuntime_development; - hasRequiredReactJsxRuntime_development = 1; - "production" !== process.env.NODE_ENV && (function() { - function getComponentNameFromType(type) { - if (null == type) return null; - if ("function" === typeof type) - return type.$$typeof === REACT_CLIENT_REFERENCE ? null : type.displayName || type.name || null; - if ("string" === typeof type) return type; - switch (type) { - case REACT_FRAGMENT_TYPE: - return "Fragment"; - case REACT_PROFILER_TYPE: - return "Profiler"; - case REACT_STRICT_MODE_TYPE: - return "StrictMode"; - case REACT_SUSPENSE_TYPE: - return "Suspense"; - case REACT_SUSPENSE_LIST_TYPE: - return "SuspenseList"; - case REACT_ACTIVITY_TYPE: - return "Activity"; - } - if ("object" === typeof type) - switch ("number" === typeof type.tag && console.error( - "Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue." - ), type.$$typeof) { - case REACT_PORTAL_TYPE: - return "Portal"; - case REACT_CONTEXT_TYPE: - return type.displayName || "Context"; - case REACT_CONSUMER_TYPE: - return (type._context.displayName || "Context") + ".Consumer"; - case REACT_FORWARD_REF_TYPE: - var innerType = type.render; - type = type.displayName; - type || (type = innerType.displayName || innerType.name || "", type = "" !== type ? "ForwardRef(" + type + ")" : "ForwardRef"); - return type; - case REACT_MEMO_TYPE: - return innerType = type.displayName || null, null !== innerType ? innerType : getComponentNameFromType(type.type) || "Memo"; - case REACT_LAZY_TYPE: - innerType = type._payload; - type = type._init; - try { - return getComponentNameFromType(type(innerType)); - } catch (x) { - } - } - return null; - } - function testStringCoercion(value) { - return "" + value; - } - function checkKeyStringCoercion(value) { - try { - testStringCoercion(value); - var JSCompiler_inline_result = false; - } catch (e) { - JSCompiler_inline_result = true; - } - if (JSCompiler_inline_result) { - JSCompiler_inline_result = console; - var JSCompiler_temp_const = JSCompiler_inline_result.error; - var JSCompiler_inline_result$jscomp$0 = "function" === typeof Symbol && Symbol.toStringTag && value[Symbol.toStringTag] || value.constructor.name || "Object"; - JSCompiler_temp_const.call( - JSCompiler_inline_result, - "The provided key is an unsupported type %s. This value must be coerced to a string before using it here.", - JSCompiler_inline_result$jscomp$0 - ); - return testStringCoercion(value); - } - } - function getTaskName(type) { - if (type === REACT_FRAGMENT_TYPE) return "<>"; - if ("object" === typeof type && null !== type && type.$$typeof === REACT_LAZY_TYPE) - return "<...>"; - try { - var name = getComponentNameFromType(type); - return name ? "<" + name + ">" : "<...>"; - } catch (x) { - return "<...>"; - } - } - function getOwner() { - var dispatcher = ReactSharedInternals.A; - return null === dispatcher ? null : dispatcher.getOwner(); - } - function UnknownOwner() { - return Error("react-stack-top-frame"); - } - function hasValidKey(config) { - if (hasOwnProperty2.call(config, "key")) { - var getter = Object.getOwnPropertyDescriptor(config, "key").get; - if (getter && getter.isReactWarning) return false; - } - return void 0 !== config.key; - } - function defineKeyPropWarningGetter(props, displayName) { - function warnAboutAccessingKey() { - specialPropKeyWarningShown || (specialPropKeyWarningShown = true, console.error( - "%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://react.dev/link/special-props)", - displayName - )); - } - warnAboutAccessingKey.isReactWarning = true; - Object.defineProperty(props, "key", { - get: warnAboutAccessingKey, - configurable: true - }); - } - function elementRefGetterWithDeprecationWarning() { - var componentName = getComponentNameFromType(this.type); - didWarnAboutElementRef[componentName] || (didWarnAboutElementRef[componentName] = true, console.error( - "Accessing element.ref was removed in React 19. ref is now a regular prop. It will be removed from the JSX Element type in a future release." - )); - componentName = this.props.ref; - return void 0 !== componentName ? componentName : null; - } - function ReactElement(type, key, props, owner, debugStack, debugTask) { - var refProp = props.ref; - type = { - $$typeof: REACT_ELEMENT_TYPE, - type, - key, - props, - _owner: owner - }; - null !== (void 0 !== refProp ? refProp : null) ? Object.defineProperty(type, "ref", { - enumerable: false, - get: elementRefGetterWithDeprecationWarning - }) : Object.defineProperty(type, "ref", { enumerable: false, value: null }); - type._store = {}; - Object.defineProperty(type._store, "validated", { - configurable: false, - enumerable: false, - writable: true, - value: 0 - }); - Object.defineProperty(type, "_debugInfo", { - configurable: false, - enumerable: false, - writable: true, - value: null - }); - Object.defineProperty(type, "_debugStack", { - configurable: false, - enumerable: false, - writable: true, - value: debugStack - }); - Object.defineProperty(type, "_debugTask", { - configurable: false, - enumerable: false, - writable: true, - value: debugTask - }); - Object.freeze && (Object.freeze(type.props), Object.freeze(type)); - return type; - } - function jsxDEVImpl(type, config, maybeKey, isStaticChildren, debugStack, debugTask) { - var children = config.children; - if (void 0 !== children) - if (isStaticChildren) - if (isArrayImpl(children)) { - for (isStaticChildren = 0; isStaticChildren < children.length; isStaticChildren++) - validateChildKeys(children[isStaticChildren]); - Object.freeze && Object.freeze(children); - } else - console.error( - "React.jsx: Static children should always be an array. You are likely explicitly calling React.jsxs or React.jsxDEV. Use the Babel transform instead." - ); - else validateChildKeys(children); - if (hasOwnProperty2.call(config, "key")) { - children = getComponentNameFromType(type); - var keys2 = Object.keys(config).filter(function(k) { - return "key" !== k; - }); - isStaticChildren = 0 < keys2.length ? "{key: someKey, " + keys2.join(": ..., ") + ": ...}" : "{key: someKey}"; - didWarnAboutKeySpread[children + isStaticChildren] || (keys2 = 0 < keys2.length ? "{" + keys2.join(": ..., ") + ": ...}" : "{}", console.error( - 'A props object containing a "key" prop is being spread into JSX:\n let props = %s;\n <%s {...props} />\nReact keys must be passed directly to JSX without using spread:\n let props = %s;\n <%s key={someKey} {...props} />', - isStaticChildren, - children, - keys2, - children - ), didWarnAboutKeySpread[children + isStaticChildren] = true); - } - children = null; - void 0 !== maybeKey && (checkKeyStringCoercion(maybeKey), children = "" + maybeKey); - hasValidKey(config) && (checkKeyStringCoercion(config.key), children = "" + config.key); - if ("key" in config) { - maybeKey = {}; - for (var propName in config) - "key" !== propName && (maybeKey[propName] = config[propName]); - } else maybeKey = config; - children && defineKeyPropWarningGetter( - maybeKey, - "function" === typeof type ? type.displayName || type.name || "Unknown" : type - ); - return ReactElement( - type, - children, - maybeKey, - getOwner(), - debugStack, - debugTask - ); - } - function validateChildKeys(node) { - isValidElement(node) ? node._store && (node._store.validated = 1) : "object" === typeof node && null !== node && node.$$typeof === REACT_LAZY_TYPE && ("fulfilled" === node._payload.status ? isValidElement(node._payload.value) && node._payload.value._store && (node._payload.value._store.validated = 1) : node._store && (node._store.validated = 1)); - } - function isValidElement(object) { - return "object" === typeof object && null !== object && object.$$typeof === REACT_ELEMENT_TYPE; - } - var React2 = requireReact(), REACT_ELEMENT_TYPE = /* @__PURE__ */ Symbol.for("react.transitional.element"), REACT_PORTAL_TYPE = /* @__PURE__ */ Symbol.for("react.portal"), REACT_FRAGMENT_TYPE = /* @__PURE__ */ Symbol.for("react.fragment"), REACT_STRICT_MODE_TYPE = /* @__PURE__ */ Symbol.for("react.strict_mode"), REACT_PROFILER_TYPE = /* @__PURE__ */ Symbol.for("react.profiler"), REACT_CONSUMER_TYPE = /* @__PURE__ */ Symbol.for("react.consumer"), REACT_CONTEXT_TYPE = /* @__PURE__ */ Symbol.for("react.context"), REACT_FORWARD_REF_TYPE = /* @__PURE__ */ Symbol.for("react.forward_ref"), REACT_SUSPENSE_TYPE = /* @__PURE__ */ Symbol.for("react.suspense"), REACT_SUSPENSE_LIST_TYPE = /* @__PURE__ */ Symbol.for("react.suspense_list"), REACT_MEMO_TYPE = /* @__PURE__ */ Symbol.for("react.memo"), REACT_LAZY_TYPE = /* @__PURE__ */ Symbol.for("react.lazy"), REACT_ACTIVITY_TYPE = /* @__PURE__ */ Symbol.for("react.activity"), REACT_CLIENT_REFERENCE = /* @__PURE__ */ Symbol.for("react.client.reference"), ReactSharedInternals = React2.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE, hasOwnProperty2 = Object.prototype.hasOwnProperty, isArrayImpl = Array.isArray, createTask = console.createTask ? console.createTask : function() { - return null; - }; - React2 = { - react_stack_bottom_frame: function(callStackForError) { - return callStackForError(); - } - }; - var specialPropKeyWarningShown; - var didWarnAboutElementRef = {}; - var unknownOwnerDebugStack = React2.react_stack_bottom_frame.bind( - React2, - UnknownOwner - )(); - var unknownOwnerDebugTask = createTask(getTaskName(UnknownOwner)); - var didWarnAboutKeySpread = {}; - reactJsxRuntime_development.Fragment = REACT_FRAGMENT_TYPE; - reactJsxRuntime_development.jsx = function(type, config, maybeKey) { - var trackActualOwner = 1e4 > ReactSharedInternals.recentlyCreatedOwnerStacks++; - return jsxDEVImpl( - type, - config, - maybeKey, - false, - trackActualOwner ? Error("react-stack-top-frame") : unknownOwnerDebugStack, - trackActualOwner ? createTask(getTaskName(type)) : unknownOwnerDebugTask - ); - }; - reactJsxRuntime_development.jsxs = function(type, config, maybeKey) { - var trackActualOwner = 1e4 > ReactSharedInternals.recentlyCreatedOwnerStacks++; - return jsxDEVImpl( - type, - config, - maybeKey, - true, - trackActualOwner ? Error("react-stack-top-frame") : unknownOwnerDebugStack, - trackActualOwner ? createTask(getTaskName(type)) : unknownOwnerDebugTask - ); - }; - })(); - return reactJsxRuntime_development; -} -var hasRequiredJsxRuntime; -function requireJsxRuntime() { - if (hasRequiredJsxRuntime) return jsxRuntime.exports; - hasRequiredJsxRuntime = 1; - if (process.env.NODE_ENV === "production") { - jsxRuntime.exports = requireReactJsxRuntime_production(); - } else { - jsxRuntime.exports = requireReactJsxRuntime_development(); - } - return jsxRuntime.exports; -} -var jsxRuntimeExports = requireJsxRuntime(); -function OrderedMap(content) { - this.content = content; -} -OrderedMap.prototype = { - constructor: OrderedMap, - find: function(key) { - for (var i = 0; i < this.content.length; i += 2) - if (this.content[i] === key) return i; - return -1; - }, - // :: (string) → ?any - // Retrieve the value stored under `key`, or return undefined when - // no such key exists. - get: function(key) { - var found2 = this.find(key); - return found2 == -1 ? void 0 : this.content[found2 + 1]; - }, - // :: (string, any, ?string) → OrderedMap - // Create a new map by replacing the value of `key` with a new - // value, or adding a binding to the end of the map. If `newKey` is - // given, the key of the binding will be replaced with that key. - update: function(key, value, newKey) { - var self2 = newKey && newKey != key ? this.remove(newKey) : this; - var found2 = self2.find(key), content = self2.content.slice(); - if (found2 == -1) { - content.push(newKey || key, value); - } else { - content[found2 + 1] = value; - if (newKey) content[found2] = newKey; - } - return new OrderedMap(content); - }, - // :: (string) → OrderedMap - // Return a map with the given key removed, if it existed. - remove: function(key) { - var found2 = this.find(key); - if (found2 == -1) return this; - var content = this.content.slice(); - content.splice(found2, 2); - return new OrderedMap(content); - }, - // :: (string, any) → OrderedMap - // Add a new key to the start of the map. - addToStart: function(key, value) { - return new OrderedMap([key, value].concat(this.remove(key).content)); - }, - // :: (string, any) → OrderedMap - // Add a new key to the end of the map. - addToEnd: function(key, value) { - var content = this.remove(key).content.slice(); - content.push(key, value); - return new OrderedMap(content); - }, - // :: (string, string, any) → OrderedMap - // Add a key after the given key. If `place` is not found, the new - // key is added to the end. - addBefore: function(place, key, value) { - var without = this.remove(key), content = without.content.slice(); - var found2 = without.find(place); - content.splice(found2 == -1 ? content.length : found2, 0, key, value); - return new OrderedMap(content); - }, - // :: ((key: string, value: any)) - // Call the given function for each key/value pair in the map, in - // order. - forEach: function(f) { - for (var i = 0; i < this.content.length; i += 2) - f(this.content[i], this.content[i + 1]); - }, - // :: (union) → OrderedMap - // Create a new map by prepending the keys in this map that don't - // appear in `map` before the keys in `map`. - prepend: function(map2) { - map2 = OrderedMap.from(map2); - if (!map2.size) return this; - return new OrderedMap(map2.content.concat(this.subtract(map2).content)); - }, - // :: (union) → OrderedMap - // Create a new map by appending the keys in this map that don't - // appear in `map` after the keys in `map`. - append: function(map2) { - map2 = OrderedMap.from(map2); - if (!map2.size) return this; - return new OrderedMap(this.subtract(map2).content.concat(map2.content)); - }, - // :: (union) → OrderedMap - // Create a map containing all the keys in this map that don't - // appear in `map`. - subtract: function(map2) { - var result = this; - map2 = OrderedMap.from(map2); - for (var i = 0; i < map2.content.length; i += 2) - result = result.remove(map2.content[i]); - return result; - }, - // :: () → Object - // Turn ordered map into a plain object. - toObject: function() { - var result = {}; - this.forEach(function(key, value) { - result[key] = value; - }); - return result; - }, - // :: number - // The amount of keys in this map. - get size() { - return this.content.length >> 1; - } -}; -OrderedMap.from = function(value) { - if (value instanceof OrderedMap) return value; - var content = []; - if (value) for (var prop in value) content.push(prop, value[prop]); - return new OrderedMap(content); -}; -function findDiffStart(a, b, pos) { - for (let i = 0; ; i++) { - if (i == a.childCount || i == b.childCount) - return a.childCount == b.childCount ? null : pos; - let childA = a.child(i), childB = b.child(i); - if (childA == childB) { - pos += childA.nodeSize; - continue; - } - if (!childA.sameMarkup(childB)) - return pos; - if (childA.isText && childA.text != childB.text) { - for (let j = 0; childA.text[j] == childB.text[j]; j++) - pos++; - return pos; - } - if (childA.content.size || childB.content.size) { - let inner = findDiffStart(childA.content, childB.content, pos + 1); - if (inner != null) - return inner; - } - pos += childA.nodeSize; - } -} -function findDiffEnd(a, b, posA, posB) { - for (let iA = a.childCount, iB = b.childCount; ; ) { - if (iA == 0 || iB == 0) - return iA == iB ? null : { a: posA, b: posB }; - let childA = a.child(--iA), childB = b.child(--iB), size = childA.nodeSize; - if (childA == childB) { - posA -= size; - posB -= size; - continue; - } - if (!childA.sameMarkup(childB)) - return { a: posA, b: posB }; - if (childA.isText && childA.text != childB.text) { - let same = 0, minSize = Math.min(childA.text.length, childB.text.length); - while (same < minSize && childA.text[childA.text.length - same - 1] == childB.text[childB.text.length - same - 1]) { - same++; - posA--; - posB--; - } - return { a: posA, b: posB }; - } - if (childA.content.size || childB.content.size) { - let inner = findDiffEnd(childA.content, childB.content, posA - 1, posB - 1); - if (inner) - return inner; - } - posA -= size; - posB -= size; - } -} -class Fragment { - /** - @internal - */ - constructor(content, size) { - this.content = content; - this.size = size || 0; - if (size == null) - for (let i = 0; i < content.length; i++) - this.size += content[i].nodeSize; - } - /** - Invoke a callback for all descendant nodes between the given two - positions (relative to start of this fragment). Doesn't descend - into a node when the callback returns `false`. - */ - nodesBetween(from2, to, f, nodeStart = 0, parent) { - for (let i = 0, pos = 0; pos < to; i++) { - let child = this.content[i], end = pos + child.nodeSize; - if (end > from2 && f(child, nodeStart + pos, parent || null, i) !== false && child.content.size) { - let start = pos + 1; - child.nodesBetween(Math.max(0, from2 - start), Math.min(child.content.size, to - start), f, nodeStart + start); - } - pos = end; - } - } - /** - Call the given callback for every descendant node. `pos` will be - relative to the start of the fragment. The callback may return - `false` to prevent traversal of a given node's children. - */ - descendants(f) { - this.nodesBetween(0, this.size, f); - } - /** - Extract the text between `from` and `to`. See the same method on - [`Node`](https://prosemirror.net/docs/ref/#model.Node.textBetween). - */ - textBetween(from2, to, blockSeparator, leafText) { - let text = "", first2 = true; - this.nodesBetween(from2, to, (node, pos) => { - let nodeText = node.isText ? node.text.slice(Math.max(from2, pos) - pos, to - pos) : !node.isLeaf ? "" : leafText ? typeof leafText === "function" ? leafText(node) : leafText : node.type.spec.leafText ? node.type.spec.leafText(node) : ""; - if (node.isBlock && (node.isLeaf && nodeText || node.isTextblock) && blockSeparator) { - if (first2) - first2 = false; - else - text += blockSeparator; - } - text += nodeText; - }, 0); - return text; - } - /** - Create a new fragment containing the combined content of this - fragment and the other. - */ - append(other) { - if (!other.size) - return this; - if (!this.size) - return other; - let last = this.lastChild, first2 = other.firstChild, content = this.content.slice(), i = 0; - if (last.isText && last.sameMarkup(first2)) { - content[content.length - 1] = last.withText(last.text + first2.text); - i = 1; - } - for (; i < other.content.length; i++) - content.push(other.content[i]); - return new Fragment(content, this.size + other.size); - } - /** - Cut out the sub-fragment between the two given positions. - */ - cut(from2, to = this.size) { - if (from2 == 0 && to == this.size) - return this; - let result = [], size = 0; - if (to > from2) - for (let i = 0, pos = 0; pos < to; i++) { - let child = this.content[i], end = pos + child.nodeSize; - if (end > from2) { - if (pos < from2 || end > to) { - if (child.isText) - child = child.cut(Math.max(0, from2 - pos), Math.min(child.text.length, to - pos)); - else - child = child.cut(Math.max(0, from2 - pos - 1), Math.min(child.content.size, to - pos - 1)); - } - result.push(child); - size += child.nodeSize; - } - pos = end; - } - return new Fragment(result, size); - } - /** - @internal - */ - cutByIndex(from2, to) { - if (from2 == to) - return Fragment.empty; - if (from2 == 0 && to == this.content.length) - return this; - return new Fragment(this.content.slice(from2, to)); - } - /** - Create a new fragment in which the node at the given index is - replaced by the given node. - */ - replaceChild(index, node) { - let current = this.content[index]; - if (current == node) - return this; - let copy2 = this.content.slice(); - let size = this.size + node.nodeSize - current.nodeSize; - copy2[index] = node; - return new Fragment(copy2, size); - } - /** - Create a new fragment by prepending the given node to this - fragment. - */ - addToStart(node) { - return new Fragment([node].concat(this.content), this.size + node.nodeSize); - } - /** - Create a new fragment by appending the given node to this - fragment. - */ - addToEnd(node) { - return new Fragment(this.content.concat(node), this.size + node.nodeSize); - } - /** - Compare this fragment to another one. - */ - eq(other) { - if (this.content.length != other.content.length) - return false; - for (let i = 0; i < this.content.length; i++) - if (!this.content[i].eq(other.content[i])) - return false; - return true; - } - /** - The first child of the fragment, or `null` if it is empty. - */ - get firstChild() { - return this.content.length ? this.content[0] : null; - } - /** - The last child of the fragment, or `null` if it is empty. - */ - get lastChild() { - return this.content.length ? this.content[this.content.length - 1] : null; - } - /** - The number of child nodes in this fragment. - */ - get childCount() { - return this.content.length; - } - /** - Get the child node at the given index. Raise an error when the - index is out of range. - */ - child(index) { - let found2 = this.content[index]; - if (!found2) - throw new RangeError("Index " + index + " out of range for " + this); - return found2; - } - /** - Get the child node at the given index, if it exists. - */ - maybeChild(index) { - return this.content[index] || null; - } - /** - Call `f` for every child node, passing the node, its offset - into this parent node, and its index. - */ - forEach(f) { - for (let i = 0, p = 0; i < this.content.length; i++) { - let child = this.content[i]; - f(child, p, i); - p += child.nodeSize; - } - } - /** - Find the first position at which this fragment and another - fragment differ, or `null` if they are the same. - */ - findDiffStart(other, pos = 0) { - return findDiffStart(this, other, pos); - } - /** - Find the first position, searching from the end, at which this - fragment and the given fragment differ, or `null` if they are - the same. Since this position will not be the same in both - nodes, an object with two separate positions is returned. - */ - findDiffEnd(other, pos = this.size, otherPos = other.size) { - return findDiffEnd(this, other, pos, otherPos); - } - /** - Find the index and inner offset corresponding to a given relative - position in this fragment. The result object will be reused - (overwritten) the next time the function is called. @internal - */ - findIndex(pos) { - if (pos == 0) - return retIndex(0, pos); - if (pos == this.size) - return retIndex(this.content.length, pos); - if (pos > this.size || pos < 0) - throw new RangeError(`Position ${pos} outside of fragment (${this})`); - for (let i = 0, curPos = 0; ; i++) { - let cur = this.child(i), end = curPos + cur.nodeSize; - if (end >= pos) { - if (end == pos) - return retIndex(i + 1, end); - return retIndex(i, curPos); - } - curPos = end; - } - } - /** - Return a debugging string that describes this fragment. - */ - toString() { - return "<" + this.toStringInner() + ">"; - } - /** - @internal - */ - toStringInner() { - return this.content.join(", "); - } - /** - Create a JSON-serializeable representation of this fragment. - */ - toJSON() { - return this.content.length ? this.content.map((n) => n.toJSON()) : null; - } - /** - Deserialize a fragment from its JSON representation. - */ - static fromJSON(schema, value) { - if (!value) - return Fragment.empty; - if (!Array.isArray(value)) - throw new RangeError("Invalid input for Fragment.fromJSON"); - return new Fragment(value.map(schema.nodeFromJSON)); - } - /** - Build a fragment from an array of nodes. Ensures that adjacent - text nodes with the same marks are joined together. - */ - static fromArray(array) { - if (!array.length) - return Fragment.empty; - let joined, size = 0; - for (let i = 0; i < array.length; i++) { - let node = array[i]; - size += node.nodeSize; - if (i && node.isText && array[i - 1].sameMarkup(node)) { - if (!joined) - joined = array.slice(0, i); - joined[joined.length - 1] = node.withText(joined[joined.length - 1].text + node.text); - } else if (joined) { - joined.push(node); - } - } - return new Fragment(joined || array, size); - } - /** - Create a fragment from something that can be interpreted as a - set of nodes. For `null`, it returns the empty fragment. For a - fragment, the fragment itself. For a node or array of nodes, a - fragment containing those nodes. - */ - static from(nodes) { - if (!nodes) - return Fragment.empty; - if (nodes instanceof Fragment) - return nodes; - if (Array.isArray(nodes)) - return this.fromArray(nodes); - if (nodes.attrs) - return new Fragment([nodes], nodes.nodeSize); - throw new RangeError("Can not convert " + nodes + " to a Fragment" + (nodes.nodesBetween ? " (looks like multiple versions of prosemirror-model were loaded)" : "")); - } -} -Fragment.empty = new Fragment([], 0); -const found = { index: 0, offset: 0 }; -function retIndex(index, offset) { - found.index = index; - found.offset = offset; - return found; -} -function compareDeep(a, b) { - if (a === b) - return true; - if (!(a && typeof a == "object") || !(b && typeof b == "object")) - return false; - let array = Array.isArray(a); - if (Array.isArray(b) != array) - return false; - if (array) { - if (a.length != b.length) - return false; - for (let i = 0; i < a.length; i++) - if (!compareDeep(a[i], b[i])) - return false; - } else { - for (let p in a) - if (!(p in b) || !compareDeep(a[p], b[p])) - return false; - for (let p in b) - if (!(p in a)) - return false; - } - return true; -} -let Mark$1 = class Mark { - /** - @internal - */ - constructor(type, attrs) { - this.type = type; - this.attrs = attrs; - } - /** - Given a set of marks, create a new set which contains this one as - well, in the right position. If this mark is already in the set, - the set itself is returned. If any marks that are set to be - [exclusive](https://prosemirror.net/docs/ref/#model.MarkSpec.excludes) with this mark are present, - those are replaced by this one. - */ - addToSet(set) { - let copy2, placed = false; - for (let i = 0; i < set.length; i++) { - let other = set[i]; - if (this.eq(other)) - return set; - if (this.type.excludes(other.type)) { - if (!copy2) - copy2 = set.slice(0, i); - } else if (other.type.excludes(this.type)) { - return set; - } else { - if (!placed && other.type.rank > this.type.rank) { - if (!copy2) - copy2 = set.slice(0, i); - copy2.push(this); - placed = true; - } - if (copy2) - copy2.push(other); - } - } - if (!copy2) - copy2 = set.slice(); - if (!placed) - copy2.push(this); - return copy2; - } - /** - Remove this mark from the given set, returning a new set. If this - mark is not in the set, the set itself is returned. - */ - removeFromSet(set) { - for (let i = 0; i < set.length; i++) - if (this.eq(set[i])) - return set.slice(0, i).concat(set.slice(i + 1)); - return set; - } - /** - Test whether this mark is in the given set of marks. - */ - isInSet(set) { - for (let i = 0; i < set.length; i++) - if (this.eq(set[i])) - return true; - return false; - } - /** - Test whether this mark has the same type and attributes as - another mark. - */ - eq(other) { - return this == other || this.type == other.type && compareDeep(this.attrs, other.attrs); - } - /** - Convert this mark to a JSON-serializeable representation. - */ - toJSON() { - let obj = { type: this.type.name }; - for (let _ in this.attrs) { - obj.attrs = this.attrs; - break; - } - return obj; - } - /** - Deserialize a mark from JSON. - */ - static fromJSON(schema, json) { - if (!json) - throw new RangeError("Invalid input for Mark.fromJSON"); - let type = schema.marks[json.type]; - if (!type) - throw new RangeError(`There is no mark type ${json.type} in this schema`); - let mark = type.create(json.attrs); - type.checkAttrs(mark.attrs); - return mark; - } - /** - Test whether two sets of marks are identical. - */ - static sameSet(a, b) { - if (a == b) - return true; - if (a.length != b.length) - return false; - for (let i = 0; i < a.length; i++) - if (!a[i].eq(b[i])) - return false; - return true; - } - /** - Create a properly sorted mark set from null, a single mark, or an - unsorted array of marks. - */ - static setFrom(marks) { - if (!marks || Array.isArray(marks) && marks.length == 0) - return Mark.none; - if (marks instanceof Mark) - return [marks]; - let copy2 = marks.slice(); - copy2.sort((a, b) => a.type.rank - b.type.rank); - return copy2; - } -}; -Mark$1.none = []; -class ReplaceError extends Error { -} -class Slice { - /** - Create a slice. When specifying a non-zero open depth, you must - make sure that there are nodes of at least that depth at the - appropriate side of the fragment—i.e. if the fragment is an - empty paragraph node, `openStart` and `openEnd` can't be greater - than 1. - - It is not necessary for the content of open nodes to conform to - the schema's content constraints, though it should be a valid - start/end/middle for such a node, depending on which sides are - open. - */ - constructor(content, openStart, openEnd) { - this.content = content; - this.openStart = openStart; - this.openEnd = openEnd; - } - /** - The size this slice would add when inserted into a document. - */ - get size() { - return this.content.size - this.openStart - this.openEnd; - } - /** - @internal - */ - insertAt(pos, fragment) { - let content = insertInto(this.content, pos + this.openStart, fragment); - return content && new Slice(content, this.openStart, this.openEnd); - } - /** - @internal - */ - removeBetween(from2, to) { - return new Slice(removeRange(this.content, from2 + this.openStart, to + this.openStart), this.openStart, this.openEnd); - } - /** - Tests whether this slice is equal to another slice. - */ - eq(other) { - return this.content.eq(other.content) && this.openStart == other.openStart && this.openEnd == other.openEnd; - } - /** - @internal - */ - toString() { - return this.content + "(" + this.openStart + "," + this.openEnd + ")"; - } - /** - Convert a slice to a JSON-serializable representation. - */ - toJSON() { - if (!this.content.size) - return null; - let json = { content: this.content.toJSON() }; - if (this.openStart > 0) - json.openStart = this.openStart; - if (this.openEnd > 0) - json.openEnd = this.openEnd; - return json; - } - /** - Deserialize a slice from its JSON representation. - */ - static fromJSON(schema, json) { - if (!json) - return Slice.empty; - let openStart = json.openStart || 0, openEnd = json.openEnd || 0; - if (typeof openStart != "number" || typeof openEnd != "number") - throw new RangeError("Invalid input for Slice.fromJSON"); - return new Slice(Fragment.fromJSON(schema, json.content), openStart, openEnd); - } - /** - Create a slice from a fragment by taking the maximum possible - open value on both side of the fragment. - */ - static maxOpen(fragment, openIsolating = true) { - let openStart = 0, openEnd = 0; - for (let n = fragment.firstChild; n && !n.isLeaf && (openIsolating || !n.type.spec.isolating); n = n.firstChild) - openStart++; - for (let n = fragment.lastChild; n && !n.isLeaf && (openIsolating || !n.type.spec.isolating); n = n.lastChild) - openEnd++; - return new Slice(fragment, openStart, openEnd); - } -} -Slice.empty = new Slice(Fragment.empty, 0, 0); -function removeRange(content, from2, to) { - let { index, offset } = content.findIndex(from2), child = content.maybeChild(index); - let { index: indexTo, offset: offsetTo } = content.findIndex(to); - if (offset == from2 || child.isText) { - if (offsetTo != to && !content.child(indexTo).isText) - throw new RangeError("Removing non-flat range"); - return content.cut(0, from2).append(content.cut(to)); - } - if (index != indexTo) - throw new RangeError("Removing non-flat range"); - return content.replaceChild(index, child.copy(removeRange(child.content, from2 - offset - 1, to - offset - 1))); -} -function insertInto(content, dist, insert, parent) { - let { index, offset } = content.findIndex(dist), child = content.maybeChild(index); - if (offset == dist || child.isText) { - if (parent && !parent.canReplace(index, index, insert)) - return null; - return content.cut(0, dist).append(insert).append(content.cut(dist)); - } - let inner = insertInto(child.content, dist - offset - 1, insert, child); - return inner && content.replaceChild(index, child.copy(inner)); -} -function replace($from, $to, slice2) { - if (slice2.openStart > $from.depth) - throw new ReplaceError("Inserted content deeper than insertion position"); - if ($from.depth - slice2.openStart != $to.depth - slice2.openEnd) - throw new ReplaceError("Inconsistent open depths"); - return replaceOuter($from, $to, slice2, 0); -} -function replaceOuter($from, $to, slice2, depth) { - let index = $from.index(depth), node = $from.node(depth); - if (index == $to.index(depth) && depth < $from.depth - slice2.openStart) { - let inner = replaceOuter($from, $to, slice2, depth + 1); - return node.copy(node.content.replaceChild(index, inner)); - } else if (!slice2.content.size) { - return close(node, replaceTwoWay($from, $to, depth)); - } else if (!slice2.openStart && !slice2.openEnd && $from.depth == depth && $to.depth == depth) { - let parent = $from.parent, content = parent.content; - return close(parent, content.cut(0, $from.parentOffset).append(slice2.content).append(content.cut($to.parentOffset))); - } else { - let { start, end } = prepareSliceForReplace(slice2, $from); - return close(node, replaceThreeWay($from, start, end, $to, depth)); - } -} -function checkJoin(main, sub) { - if (!sub.type.compatibleContent(main.type)) - throw new ReplaceError("Cannot join " + sub.type.name + " onto " + main.type.name); -} -function joinable$1($before, $after, depth) { - let node = $before.node(depth); - checkJoin(node, $after.node(depth)); - return node; -} -function addNode(child, target) { - let last = target.length - 1; - if (last >= 0 && child.isText && child.sameMarkup(target[last])) - target[last] = child.withText(target[last].text + child.text); - else - target.push(child); -} -function addRange($start, $end, depth, target) { - let node = ($end || $start).node(depth); - let startIndex = 0, endIndex = $end ? $end.index(depth) : node.childCount; - if ($start) { - startIndex = $start.index(depth); - if ($start.depth > depth) { - startIndex++; - } else if ($start.textOffset) { - addNode($start.nodeAfter, target); - startIndex++; - } - } - for (let i = startIndex; i < endIndex; i++) - addNode(node.child(i), target); - if ($end && $end.depth == depth && $end.textOffset) - addNode($end.nodeBefore, target); -} -function close(node, content) { - node.type.checkContent(content); - return node.copy(content); -} -function replaceThreeWay($from, $start, $end, $to, depth) { - let openStart = $from.depth > depth && joinable$1($from, $start, depth + 1); - let openEnd = $to.depth > depth && joinable$1($end, $to, depth + 1); - let content = []; - addRange(null, $from, depth, content); - if (openStart && openEnd && $start.index(depth) == $end.index(depth)) { - checkJoin(openStart, openEnd); - addNode(close(openStart, replaceThreeWay($from, $start, $end, $to, depth + 1)), content); - } else { - if (openStart) - addNode(close(openStart, replaceTwoWay($from, $start, depth + 1)), content); - addRange($start, $end, depth, content); - if (openEnd) - addNode(close(openEnd, replaceTwoWay($end, $to, depth + 1)), content); - } - addRange($to, null, depth, content); - return new Fragment(content); -} -function replaceTwoWay($from, $to, depth) { - let content = []; - addRange(null, $from, depth, content); - if ($from.depth > depth) { - let type = joinable$1($from, $to, depth + 1); - addNode(close(type, replaceTwoWay($from, $to, depth + 1)), content); - } - addRange($to, null, depth, content); - return new Fragment(content); -} -function prepareSliceForReplace(slice2, $along) { - let extra = $along.depth - slice2.openStart, parent = $along.node(extra); - let node = parent.copy(slice2.content); - for (let i = extra - 1; i >= 0; i--) - node = $along.node(i).copy(Fragment.from(node)); - return { - start: node.resolveNoCache(slice2.openStart + extra), - end: node.resolveNoCache(node.content.size - slice2.openEnd - extra) - }; -} -class ResolvedPos { - /** - @internal - */ - constructor(pos, path, parentOffset) { - this.pos = pos; - this.path = path; - this.parentOffset = parentOffset; - this.depth = path.length / 3 - 1; - } - /** - @internal - */ - resolveDepth(val) { - if (val == null) - return this.depth; - if (val < 0) - return this.depth + val; - return val; - } - /** - The parent node that the position points into. Note that even if - a position points into a text node, that node is not considered - the parent—text nodes are ‘flat’ in this model, and have no content. - */ - get parent() { - return this.node(this.depth); - } - /** - The root node in which the position was resolved. - */ - get doc() { - return this.node(0); - } - /** - The ancestor node at the given level. `p.node(p.depth)` is the - same as `p.parent`. - */ - node(depth) { - return this.path[this.resolveDepth(depth) * 3]; - } - /** - The index into the ancestor at the given level. If this points - at the 3rd node in the 2nd paragraph on the top level, for - example, `p.index(0)` is 1 and `p.index(1)` is 2. - */ - index(depth) { - return this.path[this.resolveDepth(depth) * 3 + 1]; - } - /** - The index pointing after this position into the ancestor at the - given level. - */ - indexAfter(depth) { - depth = this.resolveDepth(depth); - return this.index(depth) + (depth == this.depth && !this.textOffset ? 0 : 1); - } - /** - The (absolute) position at the start of the node at the given - level. - */ - start(depth) { - depth = this.resolveDepth(depth); - return depth == 0 ? 0 : this.path[depth * 3 - 1] + 1; - } - /** - The (absolute) position at the end of the node at the given - level. - */ - end(depth) { - depth = this.resolveDepth(depth); - return this.start(depth) + this.node(depth).content.size; - } - /** - The (absolute) position directly before the wrapping node at the - given level, or, when `depth` is `this.depth + 1`, the original - position. - */ - before(depth) { - depth = this.resolveDepth(depth); - if (!depth) - throw new RangeError("There is no position before the top-level node"); - return depth == this.depth + 1 ? this.pos : this.path[depth * 3 - 1]; - } - /** - The (absolute) position directly after the wrapping node at the - given level, or the original position when `depth` is `this.depth + 1`. - */ - after(depth) { - depth = this.resolveDepth(depth); - if (!depth) - throw new RangeError("There is no position after the top-level node"); - return depth == this.depth + 1 ? this.pos : this.path[depth * 3 - 1] + this.path[depth * 3].nodeSize; - } - /** - When this position points into a text node, this returns the - distance between the position and the start of the text node. - Will be zero for positions that point between nodes. - */ - get textOffset() { - return this.pos - this.path[this.path.length - 1]; - } - /** - Get the node directly after the position, if any. If the position - points into a text node, only the part of that node after the - position is returned. - */ - get nodeAfter() { - let parent = this.parent, index = this.index(this.depth); - if (index == parent.childCount) - return null; - let dOff = this.pos - this.path[this.path.length - 1], child = parent.child(index); - return dOff ? parent.child(index).cut(dOff) : child; - } - /** - Get the node directly before the position, if any. If the - position points into a text node, only the part of that node - before the position is returned. - */ - get nodeBefore() { - let index = this.index(this.depth); - let dOff = this.pos - this.path[this.path.length - 1]; - if (dOff) - return this.parent.child(index).cut(0, dOff); - return index == 0 ? null : this.parent.child(index - 1); - } - /** - Get the position at the given index in the parent node at the - given depth (which defaults to `this.depth`). - */ - posAtIndex(index, depth) { - depth = this.resolveDepth(depth); - let node = this.path[depth * 3], pos = depth == 0 ? 0 : this.path[depth * 3 - 1] + 1; - for (let i = 0; i < index; i++) - pos += node.child(i).nodeSize; - return pos; - } - /** - Get the marks at this position, factoring in the surrounding - marks' [`inclusive`](https://prosemirror.net/docs/ref/#model.MarkSpec.inclusive) property. If the - position is at the start of a non-empty node, the marks of the - node after it (if any) are returned. - */ - marks() { - let parent = this.parent, index = this.index(); - if (parent.content.size == 0) - return Mark$1.none; - if (this.textOffset) - return parent.child(index).marks; - let main = parent.maybeChild(index - 1), other = parent.maybeChild(index); - if (!main) { - let tmp = main; - main = other; - other = tmp; - } - let marks = main.marks; - for (var i = 0; i < marks.length; i++) - if (marks[i].type.spec.inclusive === false && (!other || !marks[i].isInSet(other.marks))) - marks = marks[i--].removeFromSet(marks); - return marks; - } - /** - Get the marks after the current position, if any, except those - that are non-inclusive and not present at position `$end`. This - is mostly useful for getting the set of marks to preserve after a - deletion. Will return `null` if this position is at the end of - its parent node or its parent node isn't a textblock (in which - case no marks should be preserved). - */ - marksAcross($end) { - let after = this.parent.maybeChild(this.index()); - if (!after || !after.isInline) - return null; - let marks = after.marks, next = $end.parent.maybeChild($end.index()); - for (var i = 0; i < marks.length; i++) - if (marks[i].type.spec.inclusive === false && (!next || !marks[i].isInSet(next.marks))) - marks = marks[i--].removeFromSet(marks); - return marks; - } - /** - The depth up to which this position and the given (non-resolved) - position share the same parent nodes. - */ - sharedDepth(pos) { - for (let depth = this.depth; depth > 0; depth--) - if (this.start(depth) <= pos && this.end(depth) >= pos) - return depth; - return 0; - } - /** - Returns a range based on the place where this position and the - given position diverge around block content. If both point into - the same textblock, for example, a range around that textblock - will be returned. If they point into different blocks, the range - around those blocks in their shared ancestor is returned. You can - pass in an optional predicate that will be called with a parent - node to see if a range into that parent is acceptable. - */ - blockRange(other = this, pred) { - if (other.pos < this.pos) - return other.blockRange(this); - for (let d = this.depth - (this.parent.inlineContent || this.pos == other.pos ? 1 : 0); d >= 0; d--) - if (other.pos <= this.end(d) && (!pred || pred(this.node(d)))) - return new NodeRange(this, other, d); - return null; - } - /** - Query whether the given position shares the same parent node. - */ - sameParent(other) { - return this.pos - this.parentOffset == other.pos - other.parentOffset; - } - /** - Return the greater of this and the given position. - */ - max(other) { - return other.pos > this.pos ? other : this; - } - /** - Return the smaller of this and the given position. - */ - min(other) { - return other.pos < this.pos ? other : this; - } - /** - @internal - */ - toString() { - let str = ""; - for (let i = 1; i <= this.depth; i++) - str += (str ? "/" : "") + this.node(i).type.name + "_" + this.index(i - 1); - return str + ":" + this.parentOffset; - } - /** - @internal - */ - static resolve(doc2, pos) { - if (!(pos >= 0 && pos <= doc2.content.size)) - throw new RangeError("Position " + pos + " out of range"); - let path = []; - let start = 0, parentOffset = pos; - for (let node = doc2; ; ) { - let { index, offset } = node.content.findIndex(parentOffset); - let rem = parentOffset - offset; - path.push(node, index, start + offset); - if (!rem) - break; - node = node.child(index); - if (node.isText) - break; - parentOffset = rem - 1; - start += offset + 1; - } - return new ResolvedPos(pos, path, parentOffset); - } - /** - @internal - */ - static resolveCached(doc2, pos) { - let cache = resolveCache.get(doc2); - if (cache) { - for (let i = 0; i < cache.elts.length; i++) { - let elt = cache.elts[i]; - if (elt.pos == pos) - return elt; - } - } else { - resolveCache.set(doc2, cache = new ResolveCache()); - } - let result = cache.elts[cache.i] = ResolvedPos.resolve(doc2, pos); - cache.i = (cache.i + 1) % resolveCacheSize; - return result; - } -} -class ResolveCache { - constructor() { - this.elts = []; - this.i = 0; - } -} -const resolveCacheSize = 12, resolveCache = /* @__PURE__ */ new WeakMap(); -class NodeRange { - /** - Construct a node range. `$from` and `$to` should point into the - same node until at least the given `depth`, since a node range - denotes an adjacent set of nodes in a single parent node. - */ - constructor($from, $to, depth) { - this.$from = $from; - this.$to = $to; - this.depth = depth; - } - /** - The position at the start of the range. - */ - get start() { - return this.$from.before(this.depth + 1); - } - /** - The position at the end of the range. - */ - get end() { - return this.$to.after(this.depth + 1); - } - /** - The parent node that the range points into. - */ - get parent() { - return this.$from.node(this.depth); - } - /** - The start index of the range in the parent node. - */ - get startIndex() { - return this.$from.index(this.depth); - } - /** - The end index of the range in the parent node. - */ - get endIndex() { - return this.$to.indexAfter(this.depth); - } -} -const emptyAttrs = /* @__PURE__ */ Object.create(null); -class Node { - /** - @internal - */ - constructor(type, attrs, content, marks = Mark$1.none) { - this.type = type; - this.attrs = attrs; - this.marks = marks; - this.content = content || Fragment.empty; - } - /** - The array of this node's child nodes. - */ - get children() { - return this.content.content; - } - /** - The size of this node, as defined by the integer-based [indexing - scheme](https://prosemirror.net/docs/guide/#doc.indexing). For text nodes, this is the - amount of characters. For other leaf nodes, it is one. For - non-leaf nodes, it is the size of the content plus two (the - start and end token). - */ - get nodeSize() { - return this.isLeaf ? 1 : 2 + this.content.size; - } - /** - The number of children that the node has. - */ - get childCount() { - return this.content.childCount; - } - /** - Get the child node at the given index. Raises an error when the - index is out of range. - */ - child(index) { - return this.content.child(index); - } - /** - Get the child node at the given index, if it exists. - */ - maybeChild(index) { - return this.content.maybeChild(index); - } - /** - Call `f` for every child node, passing the node, its offset - into this parent node, and its index. - */ - forEach(f) { - this.content.forEach(f); - } - /** - Invoke a callback for all descendant nodes recursively between - the given two positions that are relative to start of this - node's content. The callback is invoked with the node, its - position relative to the original node (method receiver), - its parent node, and its child index. When the callback returns - false for a given node, that node's children will not be - recursed over. The last parameter can be used to specify a - starting position to count from. - */ - nodesBetween(from2, to, f, startPos = 0) { - this.content.nodesBetween(from2, to, f, startPos, this); - } - /** - Call the given callback for every descendant node. Doesn't - descend into a node when the callback returns `false`. - */ - descendants(f) { - this.nodesBetween(0, this.content.size, f); - } - /** - Concatenates all the text nodes found in this fragment and its - children. - */ - get textContent() { - return this.isLeaf && this.type.spec.leafText ? this.type.spec.leafText(this) : this.textBetween(0, this.content.size, ""); - } - /** - Get all text between positions `from` and `to`. When - `blockSeparator` is given, it will be inserted to separate text - from different block nodes. If `leafText` is given, it'll be - inserted for every non-text leaf node encountered, otherwise - [`leafText`](https://prosemirror.net/docs/ref/#model.NodeSpec.leafText) will be used. - */ - textBetween(from2, to, blockSeparator, leafText) { - return this.content.textBetween(from2, to, blockSeparator, leafText); - } - /** - Returns this node's first child, or `null` if there are no - children. - */ - get firstChild() { - return this.content.firstChild; - } - /** - Returns this node's last child, or `null` if there are no - children. - */ - get lastChild() { - return this.content.lastChild; - } - /** - Test whether two nodes represent the same piece of document. - */ - eq(other) { - return this == other || this.sameMarkup(other) && this.content.eq(other.content); - } - /** - Compare the markup (type, attributes, and marks) of this node to - those of another. Returns `true` if both have the same markup. - */ - sameMarkup(other) { - return this.hasMarkup(other.type, other.attrs, other.marks); - } - /** - Check whether this node's markup correspond to the given type, - attributes, and marks. - */ - hasMarkup(type, attrs, marks) { - return this.type == type && compareDeep(this.attrs, attrs || type.defaultAttrs || emptyAttrs) && Mark$1.sameSet(this.marks, marks || Mark$1.none); - } - /** - Create a new node with the same markup as this node, containing - the given content (or empty, if no content is given). - */ - copy(content = null) { - if (content == this.content) - return this; - return new Node(this.type, this.attrs, content, this.marks); - } - /** - Create a copy of this node, with the given set of marks instead - of the node's own marks. - */ - mark(marks) { - return marks == this.marks ? this : new Node(this.type, this.attrs, this.content, marks); - } - /** - Create a copy of this node with only the content between the - given positions. If `to` is not given, it defaults to the end of - the node. - */ - cut(from2, to = this.content.size) { - if (from2 == 0 && to == this.content.size) - return this; - return this.copy(this.content.cut(from2, to)); - } - /** - Cut out the part of the document between the given positions, and - return it as a `Slice` object. - */ - slice(from2, to = this.content.size, includeParents = false) { - if (from2 == to) - return Slice.empty; - let $from = this.resolve(from2), $to = this.resolve(to); - let depth = includeParents ? 0 : $from.sharedDepth(to); - let start = $from.start(depth), node = $from.node(depth); - let content = node.content.cut($from.pos - start, $to.pos - start); - return new Slice(content, $from.depth - depth, $to.depth - depth); - } - /** - Replace the part of the document between the given positions with - the given slice. The slice must 'fit', meaning its open sides - must be able to connect to the surrounding content, and its - content nodes must be valid children for the node they are placed - into. If any of this is violated, an error of type - [`ReplaceError`](https://prosemirror.net/docs/ref/#model.ReplaceError) is thrown. - */ - replace(from2, to, slice2) { - return replace(this.resolve(from2), this.resolve(to), slice2); - } - /** - Find the node directly after the given position. - */ - nodeAt(pos) { - for (let node = this; ; ) { - let { index, offset } = node.content.findIndex(pos); - node = node.maybeChild(index); - if (!node) - return null; - if (offset == pos || node.isText) - return node; - pos -= offset + 1; - } - } - /** - Find the (direct) child node after the given offset, if any, - and return it along with its index and offset relative to this - node. - */ - childAfter(pos) { - let { index, offset } = this.content.findIndex(pos); - return { node: this.content.maybeChild(index), index, offset }; - } - /** - Find the (direct) child node before the given offset, if any, - and return it along with its index and offset relative to this - node. - */ - childBefore(pos) { - if (pos == 0) - return { node: null, index: 0, offset: 0 }; - let { index, offset } = this.content.findIndex(pos); - if (offset < pos) - return { node: this.content.child(index), index, offset }; - let node = this.content.child(index - 1); - return { node, index: index - 1, offset: offset - node.nodeSize }; - } - /** - Resolve the given position in the document, returning an - [object](https://prosemirror.net/docs/ref/#model.ResolvedPos) with information about its context. - */ - resolve(pos) { - return ResolvedPos.resolveCached(this, pos); - } - /** - @internal - */ - resolveNoCache(pos) { - return ResolvedPos.resolve(this, pos); - } - /** - Test whether a given mark or mark type occurs in this document - between the two given positions. - */ - rangeHasMark(from2, to, type) { - let found2 = false; - if (to > from2) - this.nodesBetween(from2, to, (node) => { - if (type.isInSet(node.marks)) - found2 = true; - return !found2; - }); - return found2; - } - /** - True when this is a block (non-inline node) - */ - get isBlock() { - return this.type.isBlock; - } - /** - True when this is a textblock node, a block node with inline - content. - */ - get isTextblock() { - return this.type.isTextblock; - } - /** - True when this node allows inline content. - */ - get inlineContent() { - return this.type.inlineContent; - } - /** - True when this is an inline node (a text node or a node that can - appear among text). - */ - get isInline() { - return this.type.isInline; - } - /** - True when this is a text node. - */ - get isText() { - return this.type.isText; - } - /** - True when this is a leaf node. - */ - get isLeaf() { - return this.type.isLeaf; - } - /** - True when this is an atom, i.e. when it does not have directly - editable content. This is usually the same as `isLeaf`, but can - be configured with the [`atom` property](https://prosemirror.net/docs/ref/#model.NodeSpec.atom) - on a node's spec (typically used when the node is displayed as - an uneditable [node view](https://prosemirror.net/docs/ref/#view.NodeView)). - */ - get isAtom() { - return this.type.isAtom; - } - /** - Return a string representation of this node for debugging - purposes. - */ - toString() { - if (this.type.spec.toDebugString) - return this.type.spec.toDebugString(this); - let name = this.type.name; - if (this.content.size) - name += "(" + this.content.toStringInner() + ")"; - return wrapMarks(this.marks, name); - } - /** - Get the content match in this node at the given index. - */ - contentMatchAt(index) { - let match = this.type.contentMatch.matchFragment(this.content, 0, index); - if (!match) - throw new Error("Called contentMatchAt on a node with invalid content"); - return match; - } - /** - Test whether replacing the range between `from` and `to` (by - child index) with the given replacement fragment (which defaults - to the empty fragment) would leave the node's content valid. You - can optionally pass `start` and `end` indices into the - replacement fragment. - */ - canReplace(from2, to, replacement = Fragment.empty, start = 0, end = replacement.childCount) { - let one = this.contentMatchAt(from2).matchFragment(replacement, start, end); - let two = one && one.matchFragment(this.content, to); - if (!two || !two.validEnd) - return false; - for (let i = start; i < end; i++) - if (!this.type.allowsMarks(replacement.child(i).marks)) - return false; - return true; - } - /** - Test whether replacing the range `from` to `to` (by index) with - a node of the given type would leave the node's content valid. - */ - canReplaceWith(from2, to, type, marks) { - if (marks && !this.type.allowsMarks(marks)) - return false; - let start = this.contentMatchAt(from2).matchType(type); - let end = start && start.matchFragment(this.content, to); - return end ? end.validEnd : false; - } - /** - Test whether the given node's content could be appended to this - node. If that node is empty, this will only return true if there - is at least one node type that can appear in both nodes (to avoid - merging completely incompatible nodes). - */ - canAppend(other) { - if (other.content.size) - return this.canReplace(this.childCount, this.childCount, other.content); - else - return this.type.compatibleContent(other.type); - } - /** - Check whether this node and its descendants conform to the - schema, and raise an exception when they do not. - */ - check() { - this.type.checkContent(this.content); - this.type.checkAttrs(this.attrs); - let copy2 = Mark$1.none; - for (let i = 0; i < this.marks.length; i++) { - let mark = this.marks[i]; - mark.type.checkAttrs(mark.attrs); - copy2 = mark.addToSet(copy2); - } - if (!Mark$1.sameSet(copy2, this.marks)) - throw new RangeError(`Invalid collection of marks for node ${this.type.name}: ${this.marks.map((m) => m.type.name)}`); - this.content.forEach((node) => node.check()); - } - /** - Return a JSON-serializeable representation of this node. - */ - toJSON() { - let obj = { type: this.type.name }; - for (let _ in this.attrs) { - obj.attrs = this.attrs; - break; - } - if (this.content.size) - obj.content = this.content.toJSON(); - if (this.marks.length) - obj.marks = this.marks.map((n) => n.toJSON()); - return obj; - } - /** - Deserialize a node from its JSON representation. - */ - static fromJSON(schema, json) { - if (!json) - throw new RangeError("Invalid input for Node.fromJSON"); - let marks = void 0; - if (json.marks) { - if (!Array.isArray(json.marks)) - throw new RangeError("Invalid mark data for Node.fromJSON"); - marks = json.marks.map(schema.markFromJSON); - } - if (json.type == "text") { - if (typeof json.text != "string") - throw new RangeError("Invalid text node in JSON"); - return schema.text(json.text, marks); - } - let content = Fragment.fromJSON(schema, json.content); - let node = schema.nodeType(json.type).create(json.attrs, content, marks); - node.type.checkAttrs(node.attrs); - return node; - } -} -Node.prototype.text = void 0; -class TextNode extends Node { - /** - @internal - */ - constructor(type, attrs, content, marks) { - super(type, attrs, null, marks); - if (!content) - throw new RangeError("Empty text nodes are not allowed"); - this.text = content; - } - toString() { - if (this.type.spec.toDebugString) - return this.type.spec.toDebugString(this); - return wrapMarks(this.marks, JSON.stringify(this.text)); - } - get textContent() { - return this.text; - } - textBetween(from2, to) { - return this.text.slice(from2, to); - } - get nodeSize() { - return this.text.length; - } - mark(marks) { - return marks == this.marks ? this : new TextNode(this.type, this.attrs, this.text, marks); - } - withText(text) { - if (text == this.text) - return this; - return new TextNode(this.type, this.attrs, text, this.marks); - } - cut(from2 = 0, to = this.text.length) { - if (from2 == 0 && to == this.text.length) - return this; - return this.withText(this.text.slice(from2, to)); - } - eq(other) { - return this.sameMarkup(other) && this.text == other.text; - } - toJSON() { - let base2 = super.toJSON(); - base2.text = this.text; - return base2; - } -} -function wrapMarks(marks, str) { - for (let i = marks.length - 1; i >= 0; i--) - str = marks[i].type.name + "(" + str + ")"; - return str; -} -class ContentMatch { - /** - @internal - */ - constructor(validEnd) { - this.validEnd = validEnd; - this.next = []; - this.wrapCache = []; - } - /** - @internal - */ - static parse(string, nodeTypes) { - let stream = new TokenStream(string, nodeTypes); - if (stream.next == null) - return ContentMatch.empty; - let expr = parseExpr(stream); - if (stream.next) - stream.err("Unexpected trailing text"); - let match = dfa(nfa(expr)); - checkForDeadEnds(match, stream); - return match; - } - /** - Match a node type, returning a match after that node if - successful. - */ - matchType(type) { - for (let i = 0; i < this.next.length; i++) - if (this.next[i].type == type) - return this.next[i].next; - return null; - } - /** - Try to match a fragment. Returns the resulting match when - successful. - */ - matchFragment(frag, start = 0, end = frag.childCount) { - let cur = this; - for (let i = start; cur && i < end; i++) - cur = cur.matchType(frag.child(i).type); - return cur; - } - /** - @internal - */ - get inlineContent() { - return this.next.length != 0 && this.next[0].type.isInline; - } - /** - Get the first matching node type at this match position that can - be generated. - */ - get defaultType() { - for (let i = 0; i < this.next.length; i++) { - let { type } = this.next[i]; - if (!(type.isText || type.hasRequiredAttrs())) - return type; - } - return null; - } - /** - @internal - */ - compatible(other) { - for (let i = 0; i < this.next.length; i++) - for (let j = 0; j < other.next.length; j++) - if (this.next[i].type == other.next[j].type) - return true; - return false; - } - /** - Try to match the given fragment, and if that fails, see if it can - be made to match by inserting nodes in front of it. When - successful, return a fragment of inserted nodes (which may be - empty if nothing had to be inserted). When `toEnd` is true, only - return a fragment if the resulting match goes to the end of the - content expression. - */ - fillBefore(after, toEnd = false, startIndex = 0) { - let seen = [this]; - function search(match, types) { - let finished = match.matchFragment(after, startIndex); - if (finished && (!toEnd || finished.validEnd)) - return Fragment.from(types.map((tp) => tp.createAndFill())); - for (let i = 0; i < match.next.length; i++) { - let { type, next } = match.next[i]; - if (!(type.isText || type.hasRequiredAttrs()) && seen.indexOf(next) == -1) { - seen.push(next); - let found2 = search(next, types.concat(type)); - if (found2) - return found2; - } - } - return null; - } - return search(this, []); - } - /** - Find a set of wrapping node types that would allow a node of the - given type to appear at this position. The result may be empty - (when it fits directly) and will be null when no such wrapping - exists. - */ - findWrapping(target) { - for (let i = 0; i < this.wrapCache.length; i += 2) - if (this.wrapCache[i] == target) - return this.wrapCache[i + 1]; - let computed = this.computeWrapping(target); - this.wrapCache.push(target, computed); - return computed; - } - /** - @internal - */ - computeWrapping(target) { - let seen = /* @__PURE__ */ Object.create(null), active = [{ match: this, type: null, via: null }]; - while (active.length) { - let current = active.shift(), match = current.match; - if (match.matchType(target)) { - let result = []; - for (let obj = current; obj.type; obj = obj.via) - result.push(obj.type); - return result.reverse(); - } - for (let i = 0; i < match.next.length; i++) { - let { type, next } = match.next[i]; - if (!type.isLeaf && !type.hasRequiredAttrs() && !(type.name in seen) && (!current.type || next.validEnd)) { - active.push({ match: type.contentMatch, type, via: current }); - seen[type.name] = true; - } - } - } - return null; - } - /** - The number of outgoing edges this node has in the finite - automaton that describes the content expression. - */ - get edgeCount() { - return this.next.length; - } - /** - Get the _n_​th outgoing edge from this node in the finite - automaton that describes the content expression. - */ - edge(n) { - if (n >= this.next.length) - throw new RangeError(`There's no ${n}th edge in this content match`); - return this.next[n]; - } - /** - @internal - */ - toString() { - let seen = []; - function scan(m) { - seen.push(m); - for (let i = 0; i < m.next.length; i++) - if (seen.indexOf(m.next[i].next) == -1) - scan(m.next[i].next); - } - scan(this); - return seen.map((m, i) => { - let out = i + (m.validEnd ? "*" : " ") + " "; - for (let i2 = 0; i2 < m.next.length; i2++) - out += (i2 ? ", " : "") + m.next[i2].type.name + "->" + seen.indexOf(m.next[i2].next); - return out; - }).join("\n"); - } -} -ContentMatch.empty = new ContentMatch(true); -class TokenStream { - constructor(string, nodeTypes) { - this.string = string; - this.nodeTypes = nodeTypes; - this.inline = null; - this.pos = 0; - this.tokens = string.split(/\s*(?=\b|\W|$)/); - if (this.tokens[this.tokens.length - 1] == "") - this.tokens.pop(); - if (this.tokens[0] == "") - this.tokens.shift(); - } - get next() { - return this.tokens[this.pos]; - } - eat(tok) { - return this.next == tok && (this.pos++ || true); - } - err(str) { - throw new SyntaxError(str + " (in content expression '" + this.string + "')"); - } -} -function parseExpr(stream) { - let exprs = []; - do { - exprs.push(parseExprSeq(stream)); - } while (stream.eat("|")); - return exprs.length == 1 ? exprs[0] : { type: "choice", exprs }; -} -function parseExprSeq(stream) { - let exprs = []; - do { - exprs.push(parseExprSubscript(stream)); - } while (stream.next && stream.next != ")" && stream.next != "|"); - return exprs.length == 1 ? exprs[0] : { type: "seq", exprs }; -} -function parseExprSubscript(stream) { - let expr = parseExprAtom(stream); - for (; ; ) { - if (stream.eat("+")) - expr = { type: "plus", expr }; - else if (stream.eat("*")) - expr = { type: "star", expr }; - else if (stream.eat("?")) - expr = { type: "opt", expr }; - else if (stream.eat("{")) - expr = parseExprRange(stream, expr); - else - break; - } - return expr; -} -function parseNum(stream) { - if (/\D/.test(stream.next)) - stream.err("Expected number, got '" + stream.next + "'"); - let result = Number(stream.next); - stream.pos++; - return result; -} -function parseExprRange(stream, expr) { - let min = parseNum(stream), max = min; - if (stream.eat(",")) { - if (stream.next != "}") - max = parseNum(stream); - else - max = -1; - } - if (!stream.eat("}")) - stream.err("Unclosed braced range"); - return { type: "range", min, max, expr }; -} -function resolveName(stream, name) { - let types = stream.nodeTypes, type = types[name]; - if (type) - return [type]; - let result = []; - for (let typeName in types) { - let type2 = types[typeName]; - if (type2.isInGroup(name)) - result.push(type2); - } - if (result.length == 0) - stream.err("No node type or group '" + name + "' found"); - return result; -} -function parseExprAtom(stream) { - if (stream.eat("(")) { - let expr = parseExpr(stream); - if (!stream.eat(")")) - stream.err("Missing closing paren"); - return expr; - } else if (!/\W/.test(stream.next)) { - let exprs = resolveName(stream, stream.next).map((type) => { - if (stream.inline == null) - stream.inline = type.isInline; - else if (stream.inline != type.isInline) - stream.err("Mixing inline and block content"); - return { type: "name", value: type }; - }); - stream.pos++; - return exprs.length == 1 ? exprs[0] : { type: "choice", exprs }; - } else { - stream.err("Unexpected token '" + stream.next + "'"); - } -} -function nfa(expr) { - let nfa2 = [[]]; - connect(compile(expr, 0), node()); - return nfa2; - function node() { - return nfa2.push([]) - 1; - } - function edge(from2, to, term) { - let edge2 = { term, to }; - nfa2[from2].push(edge2); - return edge2; - } - function connect(edges, to) { - edges.forEach((edge2) => edge2.to = to); - } - function compile(expr2, from2) { - if (expr2.type == "choice") { - return expr2.exprs.reduce((out, expr3) => out.concat(compile(expr3, from2)), []); - } else if (expr2.type == "seq") { - for (let i = 0; ; i++) { - let next = compile(expr2.exprs[i], from2); - if (i == expr2.exprs.length - 1) - return next; - connect(next, from2 = node()); - } - } else if (expr2.type == "star") { - let loop = node(); - edge(from2, loop); - connect(compile(expr2.expr, loop), loop); - return [edge(loop)]; - } else if (expr2.type == "plus") { - let loop = node(); - connect(compile(expr2.expr, from2), loop); - connect(compile(expr2.expr, loop), loop); - return [edge(loop)]; - } else if (expr2.type == "opt") { - return [edge(from2)].concat(compile(expr2.expr, from2)); - } else if (expr2.type == "range") { - let cur = from2; - for (let i = 0; i < expr2.min; i++) { - let next = node(); - connect(compile(expr2.expr, cur), next); - cur = next; - } - if (expr2.max == -1) { - connect(compile(expr2.expr, cur), cur); - } else { - for (let i = expr2.min; i < expr2.max; i++) { - let next = node(); - edge(cur, next); - connect(compile(expr2.expr, cur), next); - cur = next; - } - } - return [edge(cur)]; - } else if (expr2.type == "name") { - return [edge(from2, void 0, expr2.value)]; - } else { - throw new Error("Unknown expr type"); - } - } -} -function cmp(a, b) { - return b - a; -} -function nullFrom(nfa2, node) { - let result = []; - scan(node); - return result.sort(cmp); - function scan(node2) { - let edges = nfa2[node2]; - if (edges.length == 1 && !edges[0].term) - return scan(edges[0].to); - result.push(node2); - for (let i = 0; i < edges.length; i++) { - let { term, to } = edges[i]; - if (!term && result.indexOf(to) == -1) - scan(to); - } - } -} -function dfa(nfa2) { - let labeled = /* @__PURE__ */ Object.create(null); - return explore(nullFrom(nfa2, 0)); - function explore(states) { - let out = []; - states.forEach((node) => { - nfa2[node].forEach(({ term, to }) => { - if (!term) - return; - let set; - for (let i = 0; i < out.length; i++) - if (out[i][0] == term) - set = out[i][1]; - nullFrom(nfa2, to).forEach((node2) => { - if (!set) - out.push([term, set = []]); - if (set.indexOf(node2) == -1) - set.push(node2); - }); - }); - }); - let state = labeled[states.join(",")] = new ContentMatch(states.indexOf(nfa2.length - 1) > -1); - for (let i = 0; i < out.length; i++) { - let states2 = out[i][1].sort(cmp); - state.next.push({ type: out[i][0], next: labeled[states2.join(",")] || explore(states2) }); - } - return state; - } -} -function checkForDeadEnds(match, stream) { - for (let i = 0, work = [match]; i < work.length; i++) { - let state = work[i], dead = !state.validEnd, nodes = []; - for (let j = 0; j < state.next.length; j++) { - let { type, next } = state.next[j]; - nodes.push(type.name); - if (dead && !(type.isText || type.hasRequiredAttrs())) - dead = false; - if (work.indexOf(next) == -1) - work.push(next); - } - if (dead) - stream.err("Only non-generatable nodes (" + nodes.join(", ") + ") in a required position (see https://prosemirror.net/docs/guide/#generatable)"); - } -} -function defaultAttrs(attrs) { - let defaults2 = /* @__PURE__ */ Object.create(null); - for (let attrName in attrs) { - let attr = attrs[attrName]; - if (!attr.hasDefault) - return null; - defaults2[attrName] = attr.default; - } - return defaults2; -} -function computeAttrs(attrs, value) { - let built = /* @__PURE__ */ Object.create(null); - for (let name in attrs) { - let given = value && value[name]; - if (given === void 0) { - let attr = attrs[name]; - if (attr.hasDefault) - given = attr.default; - else - throw new RangeError("No value supplied for attribute " + name); - } - built[name] = given; - } - return built; -} -function checkAttrs(attrs, values, type, name) { - for (let name2 in values) - if (!(name2 in attrs)) - throw new RangeError(`Unsupported attribute ${name2} for ${type} of type ${name2}`); - for (let name2 in attrs) { - let attr = attrs[name2]; - if (attr.validate) - attr.validate(values[name2]); - } -} -function initAttrs(typeName, attrs) { - let result = /* @__PURE__ */ Object.create(null); - if (attrs) - for (let name in attrs) - result[name] = new Attribute(typeName, name, attrs[name]); - return result; -} -let NodeType$1 = class NodeType { - /** - @internal - */ - constructor(name, schema, spec) { - this.name = name; - this.schema = schema; - this.spec = spec; - this.markSet = null; - this.groups = spec.group ? spec.group.split(" ") : []; - this.attrs = initAttrs(name, spec.attrs); - this.defaultAttrs = defaultAttrs(this.attrs); - this.contentMatch = null; - this.inlineContent = null; - this.isBlock = !(spec.inline || name == "text"); - this.isText = name == "text"; - } - /** - True if this is an inline type. - */ - get isInline() { - return !this.isBlock; - } - /** - True if this is a textblock type, a block that contains inline - content. - */ - get isTextblock() { - return this.isBlock && this.inlineContent; - } - /** - True for node types that allow no content. - */ - get isLeaf() { - return this.contentMatch == ContentMatch.empty; - } - /** - True when this node is an atom, i.e. when it does not have - directly editable content. - */ - get isAtom() { - return this.isLeaf || !!this.spec.atom; - } - /** - Return true when this node type is part of the given - [group](https://prosemirror.net/docs/ref/#model.NodeSpec.group). - */ - isInGroup(group) { - return this.groups.indexOf(group) > -1; - } - /** - The node type's [whitespace](https://prosemirror.net/docs/ref/#model.NodeSpec.whitespace) option. - */ - get whitespace() { - return this.spec.whitespace || (this.spec.code ? "pre" : "normal"); - } - /** - Tells you whether this node type has any required attributes. - */ - hasRequiredAttrs() { - for (let n in this.attrs) - if (this.attrs[n].isRequired) - return true; - return false; - } - /** - Indicates whether this node allows some of the same content as - the given node type. - */ - compatibleContent(other) { - return this == other || this.contentMatch.compatible(other.contentMatch); - } - /** - @internal - */ - computeAttrs(attrs) { - if (!attrs && this.defaultAttrs) - return this.defaultAttrs; - else - return computeAttrs(this.attrs, attrs); - } - /** - Create a `Node` of this type. The given attributes are - checked and defaulted (you can pass `null` to use the type's - defaults entirely, if no required attributes exist). `content` - may be a `Fragment`, a node, an array of nodes, or - `null`. Similarly `marks` may be `null` to default to the empty - set of marks. - */ - create(attrs = null, content, marks) { - if (this.isText) - throw new Error("NodeType.create can't construct text nodes"); - return new Node(this, this.computeAttrs(attrs), Fragment.from(content), Mark$1.setFrom(marks)); - } - /** - Like [`create`](https://prosemirror.net/docs/ref/#model.NodeType.create), but check the given content - against the node type's content restrictions, and throw an error - if it doesn't match. - */ - createChecked(attrs = null, content, marks) { - content = Fragment.from(content); - this.checkContent(content); - return new Node(this, this.computeAttrs(attrs), content, Mark$1.setFrom(marks)); - } - /** - Like [`create`](https://prosemirror.net/docs/ref/#model.NodeType.create), but see if it is - necessary to add nodes to the start or end of the given fragment - to make it fit the node. If no fitting wrapping can be found, - return null. Note that, due to the fact that required nodes can - always be created, this will always succeed if you pass null or - `Fragment.empty` as content. - */ - createAndFill(attrs = null, content, marks) { - attrs = this.computeAttrs(attrs); - content = Fragment.from(content); - if (content.size) { - let before = this.contentMatch.fillBefore(content); - if (!before) - return null; - content = before.append(content); - } - let matched = this.contentMatch.matchFragment(content); - let after = matched && matched.fillBefore(Fragment.empty, true); - if (!after) - return null; - return new Node(this, attrs, content.append(after), Mark$1.setFrom(marks)); - } - /** - Returns true if the given fragment is valid content for this node - type. - */ - validContent(content) { - let result = this.contentMatch.matchFragment(content); - if (!result || !result.validEnd) - return false; - for (let i = 0; i < content.childCount; i++) - if (!this.allowsMarks(content.child(i).marks)) - return false; - return true; - } - /** - Throws a RangeError if the given fragment is not valid content for this - node type. - @internal - */ - checkContent(content) { - if (!this.validContent(content)) - throw new RangeError(`Invalid content for node ${this.name}: ${content.toString().slice(0, 50)}`); - } - /** - @internal - */ - checkAttrs(attrs) { - checkAttrs(this.attrs, attrs, "node", this.name); - } - /** - Check whether the given mark type is allowed in this node. - */ - allowsMarkType(markType) { - return this.markSet == null || this.markSet.indexOf(markType) > -1; - } - /** - Test whether the given set of marks are allowed in this node. - */ - allowsMarks(marks) { - if (this.markSet == null) - return true; - for (let i = 0; i < marks.length; i++) - if (!this.allowsMarkType(marks[i].type)) - return false; - return true; - } - /** - Removes the marks that are not allowed in this node from the given set. - */ - allowedMarks(marks) { - if (this.markSet == null) - return marks; - let copy2; - for (let i = 0; i < marks.length; i++) { - if (!this.allowsMarkType(marks[i].type)) { - if (!copy2) - copy2 = marks.slice(0, i); - } else if (copy2) { - copy2.push(marks[i]); - } - } - return !copy2 ? marks : copy2.length ? copy2 : Mark$1.none; - } - /** - @internal - */ - static compile(nodes, schema) { - let result = /* @__PURE__ */ Object.create(null); - nodes.forEach((name, spec) => result[name] = new NodeType(name, schema, spec)); - let topType = schema.spec.topNode || "doc"; - if (!result[topType]) - throw new RangeError("Schema is missing its top node type ('" + topType + "')"); - if (!result.text) - throw new RangeError("Every schema needs a 'text' type"); - for (let _ in result.text.attrs) - throw new RangeError("The text node type should not have attributes"); - return result; - } -}; -function validateType(typeName, attrName, type) { - let types = type.split("|"); - return (value) => { - let name = value === null ? "null" : typeof value; - if (types.indexOf(name) < 0) - throw new RangeError(`Expected value of type ${types} for attribute ${attrName} on type ${typeName}, got ${name}`); - }; -} -class Attribute { - constructor(typeName, attrName, options) { - this.hasDefault = Object.prototype.hasOwnProperty.call(options, "default"); - this.default = options.default; - this.validate = typeof options.validate == "string" ? validateType(typeName, attrName, options.validate) : options.validate; - } - get isRequired() { - return !this.hasDefault; - } -} -class MarkType { - /** - @internal - */ - constructor(name, rank, schema, spec) { - this.name = name; - this.rank = rank; - this.schema = schema; - this.spec = spec; - this.attrs = initAttrs(name, spec.attrs); - this.excluded = null; - let defaults2 = defaultAttrs(this.attrs); - this.instance = defaults2 ? new Mark$1(this, defaults2) : null; - } - /** - Create a mark of this type. `attrs` may be `null` or an object - containing only some of the mark's attributes. The others, if - they have defaults, will be added. - */ - create(attrs = null) { - if (!attrs && this.instance) - return this.instance; - return new Mark$1(this, computeAttrs(this.attrs, attrs)); - } - /** - @internal - */ - static compile(marks, schema) { - let result = /* @__PURE__ */ Object.create(null), rank = 0; - marks.forEach((name, spec) => result[name] = new MarkType(name, rank++, schema, spec)); - return result; - } - /** - When there is a mark of this type in the given set, a new set - without it is returned. Otherwise, the input set is returned. - */ - removeFromSet(set) { - for (var i = 0; i < set.length; i++) - if (set[i].type == this) { - set = set.slice(0, i).concat(set.slice(i + 1)); - i--; - } - return set; - } - /** - Tests whether there is a mark of this type in the given set. - */ - isInSet(set) { - for (let i = 0; i < set.length; i++) - if (set[i].type == this) - return set[i]; - } - /** - @internal - */ - checkAttrs(attrs) { - checkAttrs(this.attrs, attrs, "mark", this.name); - } - /** - Queries whether a given mark type is - [excluded](https://prosemirror.net/docs/ref/#model.MarkSpec.excludes) by this one. - */ - excludes(other) { - return this.excluded.indexOf(other) > -1; - } -} -class Schema { - /** - Construct a schema from a schema [specification](https://prosemirror.net/docs/ref/#model.SchemaSpec). - */ - constructor(spec) { - this.linebreakReplacement = null; - this.cached = /* @__PURE__ */ Object.create(null); - let instanceSpec = this.spec = {}; - for (let prop in spec) - instanceSpec[prop] = spec[prop]; - instanceSpec.nodes = OrderedMap.from(spec.nodes), instanceSpec.marks = OrderedMap.from(spec.marks || {}), this.nodes = NodeType$1.compile(this.spec.nodes, this); - this.marks = MarkType.compile(this.spec.marks, this); - let contentExprCache = /* @__PURE__ */ Object.create(null); - for (let prop in this.nodes) { - if (prop in this.marks) - throw new RangeError(prop + " can not be both a node and a mark"); - let type = this.nodes[prop], contentExpr = type.spec.content || "", markExpr = type.spec.marks; - type.contentMatch = contentExprCache[contentExpr] || (contentExprCache[contentExpr] = ContentMatch.parse(contentExpr, this.nodes)); - type.inlineContent = type.contentMatch.inlineContent; - if (type.spec.linebreakReplacement) { - if (this.linebreakReplacement) - throw new RangeError("Multiple linebreak nodes defined"); - if (!type.isInline || !type.isLeaf) - throw new RangeError("Linebreak replacement nodes must be inline leaf nodes"); - this.linebreakReplacement = type; - } - type.markSet = markExpr == "_" ? null : markExpr ? gatherMarks(this, markExpr.split(" ")) : markExpr == "" || !type.inlineContent ? [] : null; - } - for (let prop in this.marks) { - let type = this.marks[prop], excl = type.spec.excludes; - type.excluded = excl == null ? [type] : excl == "" ? [] : gatherMarks(this, excl.split(" ")); - } - this.nodeFromJSON = (json) => Node.fromJSON(this, json); - this.markFromJSON = (json) => Mark$1.fromJSON(this, json); - this.topNodeType = this.nodes[this.spec.topNode || "doc"]; - this.cached.wrappings = /* @__PURE__ */ Object.create(null); - } - /** - Create a node in this schema. The `type` may be a string or a - `NodeType` instance. Attributes will be extended with defaults, - `content` may be a `Fragment`, `null`, a `Node`, or an array of - nodes. - */ - node(type, attrs = null, content, marks) { - if (typeof type == "string") - type = this.nodeType(type); - else if (!(type instanceof NodeType$1)) - throw new RangeError("Invalid node type: " + type); - else if (type.schema != this) - throw new RangeError("Node type from different schema used (" + type.name + ")"); - return type.createChecked(attrs, content, marks); - } - /** - Create a text node in the schema. Empty text nodes are not - allowed. - */ - text(text, marks) { - let type = this.nodes.text; - return new TextNode(type, type.defaultAttrs, text, Mark$1.setFrom(marks)); - } - /** - Create a mark with the given type and attributes. - */ - mark(type, attrs) { - if (typeof type == "string") - type = this.marks[type]; - return type.create(attrs); - } - /** - @internal - */ - nodeType(name) { - let found2 = this.nodes[name]; - if (!found2) - throw new RangeError("Unknown node type: " + name); - return found2; - } -} -function gatherMarks(schema, marks) { - let found2 = []; - for (let i = 0; i < marks.length; i++) { - let name = marks[i], mark = schema.marks[name], ok = mark; - if (mark) { - found2.push(mark); - } else { - for (let prop in schema.marks) { - let mark2 = schema.marks[prop]; - if (name == "_" || mark2.spec.group && mark2.spec.group.split(" ").indexOf(name) > -1) - found2.push(ok = mark2); - } - } - if (!ok) - throw new SyntaxError("Unknown mark type: '" + marks[i] + "'"); - } - return found2; -} -function isTagRule(rule) { - return rule.tag != null; -} -function isStyleRule(rule) { - return rule.style != null; -} -class DOMParser { - /** - Create a parser that targets the given schema, using the given - parsing rules. - */ - constructor(schema, rules) { - this.schema = schema; - this.rules = rules; - this.tags = []; - this.styles = []; - let matchedStyles = this.matchedStyles = []; - rules.forEach((rule) => { - if (isTagRule(rule)) { - this.tags.push(rule); - } else if (isStyleRule(rule)) { - let prop = /[^=]*/.exec(rule.style)[0]; - if (matchedStyles.indexOf(prop) < 0) - matchedStyles.push(prop); - this.styles.push(rule); - } - }); - this.normalizeLists = !this.tags.some((r) => { - if (!/^(ul|ol)\b/.test(r.tag) || !r.node) - return false; - let node = schema.nodes[r.node]; - return node.contentMatch.matchType(node); - }); - } - /** - Parse a document from the content of a DOM node. - */ - parse(dom, options = {}) { - let context = new ParseContext(this, options, false); - context.addAll(dom, Mark$1.none, options.from, options.to); - return context.finish(); - } - /** - Parses the content of the given DOM node, like - [`parse`](https://prosemirror.net/docs/ref/#model.DOMParser.parse), and takes the same set of - options. But unlike that method, which produces a whole node, - this one returns a slice that is open at the sides, meaning that - the schema constraints aren't applied to the start of nodes to - the left of the input and the end of nodes at the end. - */ - parseSlice(dom, options = {}) { - let context = new ParseContext(this, options, true); - context.addAll(dom, Mark$1.none, options.from, options.to); - return Slice.maxOpen(context.finish()); - } - /** - @internal - */ - matchTag(dom, context, after) { - for (let i = after ? this.tags.indexOf(after) + 1 : 0; i < this.tags.length; i++) { - let rule = this.tags[i]; - if (matches(dom, rule.tag) && (rule.namespace === void 0 || dom.namespaceURI == rule.namespace) && (!rule.context || context.matchesContext(rule.context))) { - if (rule.getAttrs) { - let result = rule.getAttrs(dom); - if (result === false) - continue; - rule.attrs = result || void 0; - } - return rule; - } - } - } - /** - @internal - */ - matchStyle(prop, value, context, after) { - for (let i = after ? this.styles.indexOf(after) + 1 : 0; i < this.styles.length; i++) { - let rule = this.styles[i], style2 = rule.style; - if (style2.indexOf(prop) != 0 || rule.context && !context.matchesContext(rule.context) || // Test that the style string either precisely matches the prop, - // or has an '=' sign after the prop, followed by the given - // value. - style2.length > prop.length && (style2.charCodeAt(prop.length) != 61 || style2.slice(prop.length + 1) != value)) - continue; - if (rule.getAttrs) { - let result = rule.getAttrs(value); - if (result === false) - continue; - rule.attrs = result || void 0; - } - return rule; - } - } - /** - @internal - */ - static schemaRules(schema) { - let result = []; - function insert(rule) { - let priority = rule.priority == null ? 50 : rule.priority, i = 0; - for (; i < result.length; i++) { - let next = result[i], nextPriority = next.priority == null ? 50 : next.priority; - if (nextPriority < priority) - break; - } - result.splice(i, 0, rule); - } - for (let name in schema.marks) { - let rules = schema.marks[name].spec.parseDOM; - if (rules) - rules.forEach((rule) => { - insert(rule = copy(rule)); - if (!(rule.mark || rule.ignore || rule.clearMark)) - rule.mark = name; - }); - } - for (let name in schema.nodes) { - let rules = schema.nodes[name].spec.parseDOM; - if (rules) - rules.forEach((rule) => { - insert(rule = copy(rule)); - if (!(rule.node || rule.ignore || rule.mark)) - rule.node = name; - }); - } - return result; - } - /** - Construct a DOM parser using the parsing rules listed in a - schema's [node specs](https://prosemirror.net/docs/ref/#model.NodeSpec.parseDOM), reordered by - [priority](https://prosemirror.net/docs/ref/#model.GenericParseRule.priority). - */ - static fromSchema(schema) { - return schema.cached.domParser || (schema.cached.domParser = new DOMParser(schema, DOMParser.schemaRules(schema))); - } -} -const blockTags = { - address: true, - article: true, - aside: true, - blockquote: true, - canvas: true, - dd: true, - div: true, - dl: true, - fieldset: true, - figcaption: true, - figure: true, - footer: true, - form: true, - h1: true, - h2: true, - h3: true, - h4: true, - h5: true, - h6: true, - header: true, - hgroup: true, - hr: true, - li: true, - noscript: true, - ol: true, - output: true, - p: true, - pre: true, - section: true, - table: true, - tfoot: true, - ul: true -}; -const ignoreTags = { - head: true, - noscript: true, - object: true, - script: true, - style: true, - title: true -}; -const listTags = { ol: true, ul: true }; -const OPT_PRESERVE_WS = 1, OPT_PRESERVE_WS_FULL = 2, OPT_OPEN_LEFT = 4; -function wsOptionsFor(type, preserveWhitespace, base2) { - if (preserveWhitespace != null) - return (preserveWhitespace ? OPT_PRESERVE_WS : 0) | (preserveWhitespace === "full" ? OPT_PRESERVE_WS_FULL : 0); - return type && type.whitespace == "pre" ? OPT_PRESERVE_WS | OPT_PRESERVE_WS_FULL : base2 & ~OPT_OPEN_LEFT; -} -class NodeContext { - constructor(type, attrs, marks, solid, match, options) { - this.type = type; - this.attrs = attrs; - this.marks = marks; - this.solid = solid; - this.options = options; - this.content = []; - this.activeMarks = Mark$1.none; - this.match = match || (options & OPT_OPEN_LEFT ? null : type.contentMatch); - } - findWrapping(node) { - if (!this.match) { - if (!this.type) - return []; - let fill = this.type.contentMatch.fillBefore(Fragment.from(node)); - if (fill) { - this.match = this.type.contentMatch.matchFragment(fill); - } else { - let start = this.type.contentMatch, wrap2; - if (wrap2 = start.findWrapping(node.type)) { - this.match = start; - return wrap2; - } else { - return null; - } - } - } - return this.match.findWrapping(node.type); - } - finish(openEnd) { - if (!(this.options & OPT_PRESERVE_WS)) { - let last = this.content[this.content.length - 1], m; - if (last && last.isText && (m = /[ \t\r\n\u000c]+$/.exec(last.text))) { - let text = last; - if (last.text.length == m[0].length) - this.content.pop(); - else - this.content[this.content.length - 1] = text.withText(text.text.slice(0, text.text.length - m[0].length)); - } - } - let content = Fragment.from(this.content); - if (!openEnd && this.match) - content = content.append(this.match.fillBefore(Fragment.empty, true)); - return this.type ? this.type.create(this.attrs, content, this.marks) : content; - } - inlineContext(node) { - if (this.type) - return this.type.inlineContent; - if (this.content.length) - return this.content[0].isInline; - return node.parentNode && !blockTags.hasOwnProperty(node.parentNode.nodeName.toLowerCase()); - } -} -class ParseContext { - constructor(parser, options, isOpen) { - this.parser = parser; - this.options = options; - this.isOpen = isOpen; - this.open = 0; - this.localPreserveWS = false; - let topNode = options.topNode, topContext; - let topOptions = wsOptionsFor(null, options.preserveWhitespace, 0) | (isOpen ? OPT_OPEN_LEFT : 0); - if (topNode) - topContext = new NodeContext(topNode.type, topNode.attrs, Mark$1.none, true, options.topMatch || topNode.type.contentMatch, topOptions); - else if (isOpen) - topContext = new NodeContext(null, null, Mark$1.none, true, null, topOptions); - else - topContext = new NodeContext(parser.schema.topNodeType, null, Mark$1.none, true, null, topOptions); - this.nodes = [topContext]; - this.find = options.findPositions; - this.needsBlock = false; - } - get top() { - return this.nodes[this.open]; - } - // Add a DOM node to the content. Text is inserted as text node, - // otherwise, the node is passed to `addElement` or, if it has a - // `style` attribute, `addElementWithStyles`. - addDOM(dom, marks) { - if (dom.nodeType == 3) - this.addTextNode(dom, marks); - else if (dom.nodeType == 1) - this.addElement(dom, marks); - } - addTextNode(dom, marks) { - let value = dom.nodeValue; - let top = this.top, preserveWS = top.options & OPT_PRESERVE_WS_FULL ? "full" : this.localPreserveWS || (top.options & OPT_PRESERVE_WS) > 0; - let { schema } = this.parser; - if (preserveWS === "full" || top.inlineContext(dom) || /[^ \t\r\n\u000c]/.test(value)) { - if (!preserveWS) { - value = value.replace(/[ \t\r\n\u000c]+/g, " "); - if (/^[ \t\r\n\u000c]/.test(value) && this.open == this.nodes.length - 1) { - let nodeBefore = top.content[top.content.length - 1]; - let domNodeBefore = dom.previousSibling; - if (!nodeBefore || domNodeBefore && domNodeBefore.nodeName == "BR" || nodeBefore.isText && /[ \t\r\n\u000c]$/.test(nodeBefore.text)) - value = value.slice(1); - } - } else if (preserveWS === "full") { - value = value.replace(/\r\n?/g, "\n"); - } else if (schema.linebreakReplacement && /[\r\n]/.test(value) && this.top.findWrapping(schema.linebreakReplacement.create())) { - let lines = value.split(/\r?\n|\r/); - for (let i = 0; i < lines.length; i++) { - if (i) - this.insertNode(schema.linebreakReplacement.create(), marks, true); - if (lines[i]) - this.insertNode(schema.text(lines[i]), marks, !/\S/.test(lines[i])); - } - value = ""; - } else { - value = value.replace(/\r?\n|\r/g, " "); - } - if (value) - this.insertNode(schema.text(value), marks, !/\S/.test(value)); - this.findInText(dom); - } else { - this.findInside(dom); - } - } - // Try to find a handler for the given tag and use that to parse. If - // none is found, the element's content nodes are added directly. - addElement(dom, marks, matchAfter) { - let outerWS = this.localPreserveWS, top = this.top; - if (dom.tagName == "PRE" || /pre/.test(dom.style && dom.style.whiteSpace)) - this.localPreserveWS = true; - let name = dom.nodeName.toLowerCase(), ruleID; - if (listTags.hasOwnProperty(name) && this.parser.normalizeLists) - normalizeList(dom); - let rule = this.options.ruleFromNode && this.options.ruleFromNode(dom) || (ruleID = this.parser.matchTag(dom, this, matchAfter)); - out: if (rule ? rule.ignore : ignoreTags.hasOwnProperty(name)) { - this.findInside(dom); - this.ignoreFallback(dom, marks); - } else if (!rule || rule.skip || rule.closeParent) { - if (rule && rule.closeParent) - this.open = Math.max(0, this.open - 1); - else if (rule && rule.skip.nodeType) - dom = rule.skip; - let sync, oldNeedsBlock = this.needsBlock; - if (blockTags.hasOwnProperty(name)) { - if (top.content.length && top.content[0].isInline && this.open) { - this.open--; - top = this.top; - } - sync = true; - if (!top.type) - this.needsBlock = true; - } else if (!dom.firstChild) { - this.leafFallback(dom, marks); - break out; - } - let innerMarks = rule && rule.skip ? marks : this.readStyles(dom, marks); - if (innerMarks) - this.addAll(dom, innerMarks); - if (sync) - this.sync(top); - this.needsBlock = oldNeedsBlock; - } else { - let innerMarks = this.readStyles(dom, marks); - if (innerMarks) - this.addElementByRule(dom, rule, innerMarks, rule.consuming === false ? ruleID : void 0); - } - this.localPreserveWS = outerWS; - } - // Called for leaf DOM nodes that would otherwise be ignored - leafFallback(dom, marks) { - if (dom.nodeName == "BR" && this.top.type && this.top.type.inlineContent) - this.addTextNode(dom.ownerDocument.createTextNode("\n"), marks); - } - // Called for ignored nodes - ignoreFallback(dom, marks) { - if (dom.nodeName == "BR" && (!this.top.type || !this.top.type.inlineContent)) - this.findPlace(this.parser.schema.text("-"), marks, true); - } - // Run any style parser associated with the node's styles. Either - // return an updated array of marks, or null to indicate some of the - // styles had a rule with `ignore` set. - readStyles(dom, marks) { - let styles = dom.style; - if (styles && styles.length) - for (let i = 0; i < this.parser.matchedStyles.length; i++) { - let name = this.parser.matchedStyles[i], value = styles.getPropertyValue(name); - if (value) - for (let after = void 0; ; ) { - let rule = this.parser.matchStyle(name, value, this, after); - if (!rule) - break; - if (rule.ignore) - return null; - if (rule.clearMark) - marks = marks.filter((m) => !rule.clearMark(m)); - else - marks = marks.concat(this.parser.schema.marks[rule.mark].create(rule.attrs)); - if (rule.consuming === false) - after = rule; - else - break; - } - } - return marks; - } - // Look up a handler for the given node. If none are found, return - // false. Otherwise, apply it, use its return value to drive the way - // the node's content is wrapped, and return true. - addElementByRule(dom, rule, marks, continueAfter) { - let sync, nodeType; - if (rule.node) { - nodeType = this.parser.schema.nodes[rule.node]; - if (!nodeType.isLeaf) { - let inner = this.enter(nodeType, rule.attrs || null, marks, rule.preserveWhitespace); - if (inner) { - sync = true; - marks = inner; - } - } else if (!this.insertNode(nodeType.create(rule.attrs), marks, dom.nodeName == "BR")) { - this.leafFallback(dom, marks); - } - } else { - let markType = this.parser.schema.marks[rule.mark]; - marks = marks.concat(markType.create(rule.attrs)); - } - let startIn = this.top; - if (nodeType && nodeType.isLeaf) { - this.findInside(dom); - } else if (continueAfter) { - this.addElement(dom, marks, continueAfter); - } else if (rule.getContent) { - this.findInside(dom); - rule.getContent(dom, this.parser.schema).forEach((node) => this.insertNode(node, marks, false)); - } else { - let contentDOM = dom; - if (typeof rule.contentElement == "string") - contentDOM = dom.querySelector(rule.contentElement); - else if (typeof rule.contentElement == "function") - contentDOM = rule.contentElement(dom); - else if (rule.contentElement) - contentDOM = rule.contentElement; - this.findAround(dom, contentDOM, true); - this.addAll(contentDOM, marks); - this.findAround(dom, contentDOM, false); - } - if (sync && this.sync(startIn)) - this.open--; - } - // Add all child nodes between `startIndex` and `endIndex` (or the - // whole node, if not given). If `sync` is passed, use it to - // synchronize after every block element. - addAll(parent, marks, startIndex, endIndex) { - let index = startIndex || 0; - for (let dom = startIndex ? parent.childNodes[startIndex] : parent.firstChild, end = endIndex == null ? null : parent.childNodes[endIndex]; dom != end; dom = dom.nextSibling, ++index) { - this.findAtPoint(parent, index); - this.addDOM(dom, marks); - } - this.findAtPoint(parent, index); - } - // Try to find a way to fit the given node type into the current - // context. May add intermediate wrappers and/or leave non-solid - // nodes that we're in. - findPlace(node, marks, cautious) { - let route, sync; - for (let depth = this.open, penalty = 0; depth >= 0; depth--) { - let cx = this.nodes[depth]; - let found2 = cx.findWrapping(node); - if (found2 && (!route || route.length > found2.length + penalty)) { - route = found2; - sync = cx; - if (!found2.length) - break; - } - if (cx.solid) { - if (cautious) - break; - penalty += 2; - } - } - if (!route) - return null; - this.sync(sync); - for (let i = 0; i < route.length; i++) - marks = this.enterInner(route[i], null, marks, false); - return marks; - } - // Try to insert the given node, adjusting the context when needed. - insertNode(node, marks, cautious) { - if (node.isInline && this.needsBlock && !this.top.type) { - let block = this.textblockFromContext(); - if (block) - marks = this.enterInner(block, null, marks); - } - let innerMarks = this.findPlace(node, marks, cautious); - if (innerMarks) { - this.closeExtra(); - let top = this.top; - if (top.match) - top.match = top.match.matchType(node.type); - let nodeMarks = Mark$1.none; - for (let m of innerMarks.concat(node.marks)) - if (top.type ? top.type.allowsMarkType(m.type) : markMayApply(m.type, node.type)) - nodeMarks = m.addToSet(nodeMarks); - top.content.push(node.mark(nodeMarks)); - return true; - } - return false; - } - // Try to start a node of the given type, adjusting the context when - // necessary. - enter(type, attrs, marks, preserveWS) { - let innerMarks = this.findPlace(type.create(attrs), marks, false); - if (innerMarks) - innerMarks = this.enterInner(type, attrs, marks, true, preserveWS); - return innerMarks; - } - // Open a node of the given type - enterInner(type, attrs, marks, solid = false, preserveWS) { - this.closeExtra(); - let top = this.top; - top.match = top.match && top.match.matchType(type); - let options = wsOptionsFor(type, preserveWS, top.options); - if (top.options & OPT_OPEN_LEFT && top.content.length == 0) - options |= OPT_OPEN_LEFT; - let applyMarks = Mark$1.none; - marks = marks.filter((m) => { - if (top.type ? top.type.allowsMarkType(m.type) : markMayApply(m.type, type)) { - applyMarks = m.addToSet(applyMarks); - return false; - } - return true; - }); - this.nodes.push(new NodeContext(type, attrs, applyMarks, solid, null, options)); - this.open++; - return marks; - } - // Make sure all nodes above this.open are finished and added to - // their parents - closeExtra(openEnd = false) { - let i = this.nodes.length - 1; - if (i > this.open) { - for (; i > this.open; i--) - this.nodes[i - 1].content.push(this.nodes[i].finish(openEnd)); - this.nodes.length = this.open + 1; - } - } - finish() { - this.open = 0; - this.closeExtra(this.isOpen); - return this.nodes[0].finish(!!(this.isOpen || this.options.topOpen)); - } - sync(to) { - for (let i = this.open; i >= 0; i--) { - if (this.nodes[i] == to) { - this.open = i; - return true; - } else if (this.localPreserveWS) { - this.nodes[i].options |= OPT_PRESERVE_WS; - } - } - return false; - } - get currentPos() { - this.closeExtra(); - let pos = 0; - for (let i = this.open; i >= 0; i--) { - let content = this.nodes[i].content; - for (let j = content.length - 1; j >= 0; j--) - pos += content[j].nodeSize; - if (i) - pos++; - } - return pos; - } - findAtPoint(parent, offset) { - if (this.find) - for (let i = 0; i < this.find.length; i++) { - if (this.find[i].node == parent && this.find[i].offset == offset) - this.find[i].pos = this.currentPos; - } - } - findInside(parent) { - if (this.find) - for (let i = 0; i < this.find.length; i++) { - if (this.find[i].pos == null && parent.nodeType == 1 && parent.contains(this.find[i].node)) - this.find[i].pos = this.currentPos; - } - } - findAround(parent, content, before) { - if (parent != content && this.find) - for (let i = 0; i < this.find.length; i++) { - if (this.find[i].pos == null && parent.nodeType == 1 && parent.contains(this.find[i].node)) { - let pos = content.compareDocumentPosition(this.find[i].node); - if (pos & (before ? 2 : 4)) - this.find[i].pos = this.currentPos; - } - } - } - findInText(textNode) { - if (this.find) - for (let i = 0; i < this.find.length; i++) { - if (this.find[i].node == textNode) - this.find[i].pos = this.currentPos - (textNode.nodeValue.length - this.find[i].offset); - } - } - // Determines whether the given context string matches this context. - matchesContext(context) { - if (context.indexOf("|") > -1) - return context.split(/\s*\|\s*/).some(this.matchesContext, this); - let parts = context.split("/"); - let option = this.options.context; - let useRoot = !this.isOpen && (!option || option.parent.type == this.nodes[0].type); - let minDepth = -(option ? option.depth + 1 : 0) + (useRoot ? 0 : 1); - let match = (i, depth) => { - for (; i >= 0; i--) { - let part = parts[i]; - if (part == "") { - if (i == parts.length - 1 || i == 0) - continue; - for (; depth >= minDepth; depth--) - if (match(i - 1, depth)) - return true; - return false; - } else { - let next = depth > 0 || depth == 0 && useRoot ? this.nodes[depth].type : option && depth >= minDepth ? option.node(depth - minDepth).type : null; - if (!next || next.name != part && !next.isInGroup(part)) - return false; - depth--; - } - } - return true; - }; - return match(parts.length - 1, this.open); - } - textblockFromContext() { - let $context = this.options.context; - if ($context) - for (let d = $context.depth; d >= 0; d--) { - let deflt = $context.node(d).contentMatchAt($context.indexAfter(d)).defaultType; - if (deflt && deflt.isTextblock && deflt.defaultAttrs) - return deflt; - } - for (let name in this.parser.schema.nodes) { - let type = this.parser.schema.nodes[name]; - if (type.isTextblock && type.defaultAttrs) - return type; - } - } -} -function normalizeList(dom) { - for (let child = dom.firstChild, prevItem = null; child; child = child.nextSibling) { - let name = child.nodeType == 1 ? child.nodeName.toLowerCase() : null; - if (name && listTags.hasOwnProperty(name) && prevItem) { - prevItem.appendChild(child); - child = prevItem; - } else if (name == "li") { - prevItem = child; - } else if (name) { - prevItem = null; - } - } -} -function matches(dom, selector) { - return (dom.matches || dom.msMatchesSelector || dom.webkitMatchesSelector || dom.mozMatchesSelector).call(dom, selector); -} -function copy(obj) { - let copy2 = {}; - for (let prop in obj) - copy2[prop] = obj[prop]; - return copy2; -} -function markMayApply(markType, nodeType) { - let nodes = nodeType.schema.nodes; - for (let name in nodes) { - let parent = nodes[name]; - if (!parent.allowsMarkType(markType)) - continue; - let seen = [], scan = (match) => { - seen.push(match); - for (let i = 0; i < match.edgeCount; i++) { - let { type, next } = match.edge(i); - if (type == nodeType) - return true; - if (seen.indexOf(next) < 0 && scan(next)) - return true; - } - }; - if (scan(parent.contentMatch)) - return true; - } -} -class DOMSerializer { - /** - Create a serializer. `nodes` should map node names to functions - that take a node and return a description of the corresponding - DOM. `marks` does the same for mark names, but also gets an - argument that tells it whether the mark's content is block or - inline content (for typical use, it'll always be inline). A mark - serializer may be `null` to indicate that marks of that type - should not be serialized. - */ - constructor(nodes, marks) { - this.nodes = nodes; - this.marks = marks; - } - /** - Serialize the content of this fragment to a DOM fragment. When - not in the browser, the `document` option, containing a DOM - document, should be passed so that the serializer can create - nodes. - */ - serializeFragment(fragment, options = {}, target) { - if (!target) - target = doc$1(options).createDocumentFragment(); - let top = target, active = []; - fragment.forEach((node) => { - if (active.length || node.marks.length) { - let keep = 0, rendered = 0; - while (keep < active.length && rendered < node.marks.length) { - let next = node.marks[rendered]; - if (!this.marks[next.type.name]) { - rendered++; - continue; - } - if (!next.eq(active[keep][0]) || next.type.spec.spanning === false) - break; - keep++; - rendered++; - } - while (keep < active.length) - top = active.pop()[1]; - while (rendered < node.marks.length) { - let add = node.marks[rendered++]; - let markDOM = this.serializeMark(add, node.isInline, options); - if (markDOM) { - active.push([add, top]); - top.appendChild(markDOM.dom); - top = markDOM.contentDOM || markDOM.dom; - } - } - } - top.appendChild(this.serializeNodeInner(node, options)); - }); - return target; - } - /** - @internal - */ - serializeNodeInner(node, options) { - let { dom, contentDOM } = renderSpec(doc$1(options), this.nodes[node.type.name](node), null, node.attrs); - if (contentDOM) { - if (node.isLeaf) - throw new RangeError("Content hole not allowed in a leaf node spec"); - this.serializeFragment(node.content, options, contentDOM); - } - return dom; - } - /** - Serialize this node to a DOM node. This can be useful when you - need to serialize a part of a document, as opposed to the whole - document. To serialize a whole document, use - [`serializeFragment`](https://prosemirror.net/docs/ref/#model.DOMSerializer.serializeFragment) on - its [content](https://prosemirror.net/docs/ref/#model.Node.content). - */ - serializeNode(node, options = {}) { - let dom = this.serializeNodeInner(node, options); - for (let i = node.marks.length - 1; i >= 0; i--) { - let wrap2 = this.serializeMark(node.marks[i], node.isInline, options); - if (wrap2) { - (wrap2.contentDOM || wrap2.dom).appendChild(dom); - dom = wrap2.dom; - } - } - return dom; - } - /** - @internal - */ - serializeMark(mark, inline, options = {}) { - let toDOM = this.marks[mark.type.name]; - return toDOM && renderSpec(doc$1(options), toDOM(mark, inline), null, mark.attrs); - } - static renderSpec(doc2, structure, xmlNS = null, blockArraysIn) { - return renderSpec(doc2, structure, xmlNS, blockArraysIn); - } - /** - Build a serializer using the [`toDOM`](https://prosemirror.net/docs/ref/#model.NodeSpec.toDOM) - properties in a schema's node and mark specs. - */ - static fromSchema(schema) { - return schema.cached.domSerializer || (schema.cached.domSerializer = new DOMSerializer(this.nodesFromSchema(schema), this.marksFromSchema(schema))); - } - /** - Gather the serializers in a schema's node specs into an object. - This can be useful as a base to build a custom serializer from. - */ - static nodesFromSchema(schema) { - let result = gatherToDOM(schema.nodes); - if (!result.text) - result.text = (node) => node.text; - return result; - } - /** - Gather the serializers in a schema's mark specs into an object. - */ - static marksFromSchema(schema) { - return gatherToDOM(schema.marks); - } -} -function gatherToDOM(obj) { - let result = {}; - for (let name in obj) { - let toDOM = obj[name].spec.toDOM; - if (toDOM) - result[name] = toDOM; - } - return result; -} -function doc$1(options) { - return options.document || window.document; -} -const suspiciousAttributeCache = /* @__PURE__ */ new WeakMap(); -function suspiciousAttributes(attrs) { - let value = suspiciousAttributeCache.get(attrs); - if (value === void 0) - suspiciousAttributeCache.set(attrs, value = suspiciousAttributesInner(attrs)); - return value; -} -function suspiciousAttributesInner(attrs) { - let result = null; - function scan(value) { - if (value && typeof value == "object") { - if (Array.isArray(value)) { - if (typeof value[0] == "string") { - if (!result) - result = []; - result.push(value); - } else { - for (let i = 0; i < value.length; i++) - scan(value[i]); - } - } else { - for (let prop in value) - scan(value[prop]); - } - } - } - scan(attrs); - return result; -} -function renderSpec(doc2, structure, xmlNS, blockArraysIn) { - if (typeof structure == "string") - return { dom: doc2.createTextNode(structure) }; - if (structure.nodeType != null) - return { dom: structure }; - if (structure.dom && structure.dom.nodeType != null) - return structure; - let tagName = structure[0], suspicious; - if (typeof tagName != "string") - throw new RangeError("Invalid array passed to renderSpec"); - if (blockArraysIn && (suspicious = suspiciousAttributes(blockArraysIn)) && suspicious.indexOf(structure) > -1) - throw new RangeError("Using an array from an attribute object as a DOM spec. This may be an attempted cross site scripting attack."); - let space = tagName.indexOf(" "); - if (space > 0) { - xmlNS = tagName.slice(0, space); - tagName = tagName.slice(space + 1); - } - let contentDOM; - let dom = xmlNS ? doc2.createElementNS(xmlNS, tagName) : doc2.createElement(tagName); - let attrs = structure[1], start = 1; - if (attrs && typeof attrs == "object" && attrs.nodeType == null && !Array.isArray(attrs)) { - start = 2; - for (let name in attrs) - if (attrs[name] != null) { - let space2 = name.indexOf(" "); - if (space2 > 0) - dom.setAttributeNS(name.slice(0, space2), name.slice(space2 + 1), attrs[name]); - else if (name == "style" && dom.style) - dom.style.cssText = attrs[name]; - else - dom.setAttribute(name, attrs[name]); - } - } - for (let i = start; i < structure.length; i++) { - let child = structure[i]; - if (child === 0) { - if (i < structure.length - 1 || i > start) - throw new RangeError("Content hole must be the only child of its parent node"); - return { dom, contentDOM: dom }; - } else { - let { dom: inner, contentDOM: innerContent } = renderSpec(doc2, child, xmlNS, blockArraysIn); - dom.appendChild(inner); - if (innerContent) { - if (contentDOM) - throw new RangeError("Multiple content holes"); - contentDOM = innerContent; - } - } - } - return { dom, contentDOM }; -} -const lower16 = 65535; -const factor16 = Math.pow(2, 16); -function makeRecover(index, offset) { - return index + offset * factor16; -} -function recoverIndex(value) { - return value & lower16; -} -function recoverOffset(value) { - return (value - (value & lower16)) / factor16; -} -const DEL_BEFORE = 1, DEL_AFTER = 2, DEL_ACROSS = 4, DEL_SIDE = 8; -class MapResult { - /** - @internal - */ - constructor(pos, delInfo, recover) { - this.pos = pos; - this.delInfo = delInfo; - this.recover = recover; - } - /** - Tells you whether the position was deleted, that is, whether the - step removed the token on the side queried (via the `assoc`) - argument from the document. - */ - get deleted() { - return (this.delInfo & DEL_SIDE) > 0; - } - /** - Tells you whether the token before the mapped position was deleted. - */ - get deletedBefore() { - return (this.delInfo & (DEL_BEFORE | DEL_ACROSS)) > 0; - } - /** - True when the token after the mapped position was deleted. - */ - get deletedAfter() { - return (this.delInfo & (DEL_AFTER | DEL_ACROSS)) > 0; - } - /** - Tells whether any of the steps mapped through deletes across the - position (including both the token before and after the - position). - */ - get deletedAcross() { - return (this.delInfo & DEL_ACROSS) > 0; - } -} -class StepMap { - /** - Create a position map. The modifications to the document are - represented as an array of numbers, in which each group of three - represents a modified chunk as `[start, oldSize, newSize]`. - */ - constructor(ranges, inverted = false) { - this.ranges = ranges; - this.inverted = inverted; - if (!ranges.length && StepMap.empty) - return StepMap.empty; - } - /** - @internal - */ - recover(value) { - let diff = 0, index = recoverIndex(value); - if (!this.inverted) - for (let i = 0; i < index; i++) - diff += this.ranges[i * 3 + 2] - this.ranges[i * 3 + 1]; - return this.ranges[index * 3] + diff + recoverOffset(value); - } - mapResult(pos, assoc = 1) { - return this._map(pos, assoc, false); - } - map(pos, assoc = 1) { - return this._map(pos, assoc, true); - } - /** - @internal - */ - _map(pos, assoc, simple) { - let diff = 0, oldIndex = this.inverted ? 2 : 1, newIndex = this.inverted ? 1 : 2; - for (let i = 0; i < this.ranges.length; i += 3) { - let start = this.ranges[i] - (this.inverted ? diff : 0); - if (start > pos) - break; - let oldSize = this.ranges[i + oldIndex], newSize = this.ranges[i + newIndex], end = start + oldSize; - if (pos <= end) { - let side = !oldSize ? assoc : pos == start ? -1 : pos == end ? 1 : assoc; - let result = start + diff + (side < 0 ? 0 : newSize); - if (simple) - return result; - let recover = pos == (assoc < 0 ? start : end) ? null : makeRecover(i / 3, pos - start); - let del = pos == start ? DEL_AFTER : pos == end ? DEL_BEFORE : DEL_ACROSS; - if (assoc < 0 ? pos != start : pos != end) - del |= DEL_SIDE; - return new MapResult(result, del, recover); - } - diff += newSize - oldSize; - } - return simple ? pos + diff : new MapResult(pos + diff, 0, null); - } - /** - @internal - */ - touches(pos, recover) { - let diff = 0, index = recoverIndex(recover); - let oldIndex = this.inverted ? 2 : 1, newIndex = this.inverted ? 1 : 2; - for (let i = 0; i < this.ranges.length; i += 3) { - let start = this.ranges[i] - (this.inverted ? diff : 0); - if (start > pos) - break; - let oldSize = this.ranges[i + oldIndex], end = start + oldSize; - if (pos <= end && i == index * 3) - return true; - diff += this.ranges[i + newIndex] - oldSize; - } - return false; - } - /** - Calls the given function on each of the changed ranges included in - this map. - */ - forEach(f) { - let oldIndex = this.inverted ? 2 : 1, newIndex = this.inverted ? 1 : 2; - for (let i = 0, diff = 0; i < this.ranges.length; i += 3) { - let start = this.ranges[i], oldStart = start - (this.inverted ? diff : 0), newStart = start + (this.inverted ? 0 : diff); - let oldSize = this.ranges[i + oldIndex], newSize = this.ranges[i + newIndex]; - f(oldStart, oldStart + oldSize, newStart, newStart + newSize); - diff += newSize - oldSize; - } - } - /** - Create an inverted version of this map. The result can be used to - map positions in the post-step document to the pre-step document. - */ - invert() { - return new StepMap(this.ranges, !this.inverted); - } - /** - @internal - */ - toString() { - return (this.inverted ? "-" : "") + JSON.stringify(this.ranges); - } - /** - Create a map that moves all positions by offset `n` (which may be - negative). This can be useful when applying steps meant for a - sub-document to a larger document, or vice-versa. - */ - static offset(n) { - return n == 0 ? StepMap.empty : new StepMap(n < 0 ? [0, -n, 0] : [0, 0, n]); - } -} -StepMap.empty = new StepMap([]); -class Mapping { - /** - Create a new mapping with the given position maps. - */ - constructor(maps, mirror, from2 = 0, to = maps ? maps.length : 0) { - this.mirror = mirror; - this.from = from2; - this.to = to; - this._maps = maps || []; - this.ownData = !(maps || mirror); - } - /** - The step maps in this mapping. - */ - get maps() { - return this._maps; - } - /** - Create a mapping that maps only through a part of this one. - */ - slice(from2 = 0, to = this.maps.length) { - return new Mapping(this._maps, this.mirror, from2, to); - } - /** - Add a step map to the end of this mapping. If `mirrors` is - given, it should be the index of the step map that is the mirror - image of this one. - */ - appendMap(map2, mirrors) { - if (!this.ownData) { - this._maps = this._maps.slice(); - this.mirror = this.mirror && this.mirror.slice(); - this.ownData = true; - } - this.to = this._maps.push(map2); - if (mirrors != null) - this.setMirror(this._maps.length - 1, mirrors); - } - /** - Add all the step maps in a given mapping to this one (preserving - mirroring information). - */ - appendMapping(mapping) { - for (let i = 0, startSize = this._maps.length; i < mapping._maps.length; i++) { - let mirr = mapping.getMirror(i); - this.appendMap(mapping._maps[i], mirr != null && mirr < i ? startSize + mirr : void 0); - } - } - /** - Finds the offset of the step map that mirrors the map at the - given offset, in this mapping (as per the second argument to - `appendMap`). - */ - getMirror(n) { - if (this.mirror) { - for (let i = 0; i < this.mirror.length; i++) - if (this.mirror[i] == n) - return this.mirror[i + (i % 2 ? -1 : 1)]; - } - } - /** - @internal - */ - setMirror(n, m) { - if (!this.mirror) - this.mirror = []; - this.mirror.push(n, m); - } - /** - Append the inverse of the given mapping to this one. - */ - appendMappingInverted(mapping) { - for (let i = mapping.maps.length - 1, totalSize = this._maps.length + mapping._maps.length; i >= 0; i--) { - let mirr = mapping.getMirror(i); - this.appendMap(mapping._maps[i].invert(), mirr != null && mirr > i ? totalSize - mirr - 1 : void 0); - } - } - /** - Create an inverted version of this mapping. - */ - invert() { - let inverse = new Mapping(); - inverse.appendMappingInverted(this); - return inverse; - } - /** - Map a position through this mapping. - */ - map(pos, assoc = 1) { - if (this.mirror) - return this._map(pos, assoc, true); - for (let i = this.from; i < this.to; i++) - pos = this._maps[i].map(pos, assoc); - return pos; - } - /** - Map a position through this mapping, returning a mapping - result. - */ - mapResult(pos, assoc = 1) { - return this._map(pos, assoc, false); - } - /** - @internal - */ - _map(pos, assoc, simple) { - let delInfo = 0; - for (let i = this.from; i < this.to; i++) { - let map2 = this._maps[i], result = map2.mapResult(pos, assoc); - if (result.recover != null) { - let corr = this.getMirror(i); - if (corr != null && corr > i && corr < this.to) { - i = corr; - pos = this._maps[corr].recover(result.recover); - continue; - } - } - delInfo |= result.delInfo; - pos = result.pos; - } - return simple ? pos : new MapResult(pos, delInfo, null); - } -} -const stepsByID = /* @__PURE__ */ Object.create(null); -class Step { - /** - Get the step map that represents the changes made by this step, - and which can be used to transform between positions in the old - and the new document. - */ - getMap() { - return StepMap.empty; - } - /** - Try to merge this step with another one, to be applied directly - after it. Returns the merged step when possible, null if the - steps can't be merged. - */ - merge(other) { - return null; - } - /** - Deserialize a step from its JSON representation. Will call - through to the step class' own implementation of this method. - */ - static fromJSON(schema, json) { - if (!json || !json.stepType) - throw new RangeError("Invalid input for Step.fromJSON"); - let type = stepsByID[json.stepType]; - if (!type) - throw new RangeError(`No step type ${json.stepType} defined`); - return type.fromJSON(schema, json); - } - /** - To be able to serialize steps to JSON, each step needs a string - ID to attach to its JSON representation. Use this method to - register an ID for your step classes. Try to pick something - that's unlikely to clash with steps from other modules. - */ - static jsonID(id, stepClass) { - if (id in stepsByID) - throw new RangeError("Duplicate use of step JSON ID " + id); - stepsByID[id] = stepClass; - stepClass.prototype.jsonID = id; - return stepClass; - } -} -class StepResult { - /** - @internal - */ - constructor(doc2, failed) { - this.doc = doc2; - this.failed = failed; - } - /** - Create a successful step result. - */ - static ok(doc2) { - return new StepResult(doc2, null); - } - /** - Create a failed step result. - */ - static fail(message) { - return new StepResult(null, message); - } - /** - Call [`Node.replace`](https://prosemirror.net/docs/ref/#model.Node.replace) with the given - arguments. Create a successful result if it succeeds, and a - failed one if it throws a `ReplaceError`. - */ - static fromReplace(doc2, from2, to, slice2) { - try { - return StepResult.ok(doc2.replace(from2, to, slice2)); - } catch (e) { - if (e instanceof ReplaceError) - return StepResult.fail(e.message); - throw e; - } - } -} -function mapFragment(fragment, f, parent) { - let mapped = []; - for (let i = 0; i < fragment.childCount; i++) { - let child = fragment.child(i); - if (child.content.size) - child = child.copy(mapFragment(child.content, f, child)); - if (child.isInline) - child = f(child, parent, i); - mapped.push(child); - } - return Fragment.fromArray(mapped); -} -class AddMarkStep extends Step { - /** - Create a mark step. - */ - constructor(from2, to, mark) { - super(); - this.from = from2; - this.to = to; - this.mark = mark; - } - apply(doc2) { - let oldSlice = doc2.slice(this.from, this.to), $from = doc2.resolve(this.from); - let parent = $from.node($from.sharedDepth(this.to)); - let slice2 = new Slice(mapFragment(oldSlice.content, (node, parent2) => { - if (!node.isAtom || !parent2.type.allowsMarkType(this.mark.type)) - return node; - return node.mark(this.mark.addToSet(node.marks)); - }, parent), oldSlice.openStart, oldSlice.openEnd); - return StepResult.fromReplace(doc2, this.from, this.to, slice2); - } - invert() { - return new RemoveMarkStep(this.from, this.to, this.mark); - } - map(mapping) { - let from2 = mapping.mapResult(this.from, 1), to = mapping.mapResult(this.to, -1); - if (from2.deleted && to.deleted || from2.pos >= to.pos) - return null; - return new AddMarkStep(from2.pos, to.pos, this.mark); - } - merge(other) { - if (other instanceof AddMarkStep && other.mark.eq(this.mark) && this.from <= other.to && this.to >= other.from) - return new AddMarkStep(Math.min(this.from, other.from), Math.max(this.to, other.to), this.mark); - return null; - } - toJSON() { - return { - stepType: "addMark", - mark: this.mark.toJSON(), - from: this.from, - to: this.to - }; - } - /** - @internal - */ - static fromJSON(schema, json) { - if (typeof json.from != "number" || typeof json.to != "number") - throw new RangeError("Invalid input for AddMarkStep.fromJSON"); - return new AddMarkStep(json.from, json.to, schema.markFromJSON(json.mark)); - } -} -Step.jsonID("addMark", AddMarkStep); -class RemoveMarkStep extends Step { - /** - Create a mark-removing step. - */ - constructor(from2, to, mark) { - super(); - this.from = from2; - this.to = to; - this.mark = mark; - } - apply(doc2) { - let oldSlice = doc2.slice(this.from, this.to); - let slice2 = new Slice(mapFragment(oldSlice.content, (node) => { - return node.mark(this.mark.removeFromSet(node.marks)); - }, doc2), oldSlice.openStart, oldSlice.openEnd); - return StepResult.fromReplace(doc2, this.from, this.to, slice2); - } - invert() { - return new AddMarkStep(this.from, this.to, this.mark); - } - map(mapping) { - let from2 = mapping.mapResult(this.from, 1), to = mapping.mapResult(this.to, -1); - if (from2.deleted && to.deleted || from2.pos >= to.pos) - return null; - return new RemoveMarkStep(from2.pos, to.pos, this.mark); - } - merge(other) { - if (other instanceof RemoveMarkStep && other.mark.eq(this.mark) && this.from <= other.to && this.to >= other.from) - return new RemoveMarkStep(Math.min(this.from, other.from), Math.max(this.to, other.to), this.mark); - return null; - } - toJSON() { - return { - stepType: "removeMark", - mark: this.mark.toJSON(), - from: this.from, - to: this.to - }; - } - /** - @internal - */ - static fromJSON(schema, json) { - if (typeof json.from != "number" || typeof json.to != "number") - throw new RangeError("Invalid input for RemoveMarkStep.fromJSON"); - return new RemoveMarkStep(json.from, json.to, schema.markFromJSON(json.mark)); - } -} -Step.jsonID("removeMark", RemoveMarkStep); -class AddNodeMarkStep extends Step { - /** - Create a node mark step. - */ - constructor(pos, mark) { - super(); - this.pos = pos; - this.mark = mark; - } - apply(doc2) { - let node = doc2.nodeAt(this.pos); - if (!node) - return StepResult.fail("No node at mark step's position"); - let updated = node.type.create(node.attrs, null, this.mark.addToSet(node.marks)); - return StepResult.fromReplace(doc2, this.pos, this.pos + 1, new Slice(Fragment.from(updated), 0, node.isLeaf ? 0 : 1)); - } - invert(doc2) { - let node = doc2.nodeAt(this.pos); - if (node) { - let newSet = this.mark.addToSet(node.marks); - if (newSet.length == node.marks.length) { - for (let i = 0; i < node.marks.length; i++) - if (!node.marks[i].isInSet(newSet)) - return new AddNodeMarkStep(this.pos, node.marks[i]); - return new AddNodeMarkStep(this.pos, this.mark); - } - } - return new RemoveNodeMarkStep(this.pos, this.mark); - } - map(mapping) { - let pos = mapping.mapResult(this.pos, 1); - return pos.deletedAfter ? null : new AddNodeMarkStep(pos.pos, this.mark); - } - toJSON() { - return { stepType: "addNodeMark", pos: this.pos, mark: this.mark.toJSON() }; - } - /** - @internal - */ - static fromJSON(schema, json) { - if (typeof json.pos != "number") - throw new RangeError("Invalid input for AddNodeMarkStep.fromJSON"); - return new AddNodeMarkStep(json.pos, schema.markFromJSON(json.mark)); - } -} -Step.jsonID("addNodeMark", AddNodeMarkStep); -class RemoveNodeMarkStep extends Step { - /** - Create a mark-removing step. - */ - constructor(pos, mark) { - super(); - this.pos = pos; - this.mark = mark; - } - apply(doc2) { - let node = doc2.nodeAt(this.pos); - if (!node) - return StepResult.fail("No node at mark step's position"); - let updated = node.type.create(node.attrs, null, this.mark.removeFromSet(node.marks)); - return StepResult.fromReplace(doc2, this.pos, this.pos + 1, new Slice(Fragment.from(updated), 0, node.isLeaf ? 0 : 1)); - } - invert(doc2) { - let node = doc2.nodeAt(this.pos); - if (!node || !this.mark.isInSet(node.marks)) - return this; - return new AddNodeMarkStep(this.pos, this.mark); - } - map(mapping) { - let pos = mapping.mapResult(this.pos, 1); - return pos.deletedAfter ? null : new RemoveNodeMarkStep(pos.pos, this.mark); - } - toJSON() { - return { stepType: "removeNodeMark", pos: this.pos, mark: this.mark.toJSON() }; - } - /** - @internal - */ - static fromJSON(schema, json) { - if (typeof json.pos != "number") - throw new RangeError("Invalid input for RemoveNodeMarkStep.fromJSON"); - return new RemoveNodeMarkStep(json.pos, schema.markFromJSON(json.mark)); - } -} -Step.jsonID("removeNodeMark", RemoveNodeMarkStep); -class ReplaceStep extends Step { - /** - The given `slice` should fit the 'gap' between `from` and - `to`—the depths must line up, and the surrounding nodes must be - able to be joined with the open sides of the slice. When - `structure` is true, the step will fail if the content between - from and to is not just a sequence of closing and then opening - tokens (this is to guard against rebased replace steps - overwriting something they weren't supposed to). - */ - constructor(from2, to, slice2, structure = false) { - super(); - this.from = from2; - this.to = to; - this.slice = slice2; - this.structure = structure; - } - apply(doc2) { - if (this.structure && contentBetween(doc2, this.from, this.to)) - return StepResult.fail("Structure replace would overwrite content"); - return StepResult.fromReplace(doc2, this.from, this.to, this.slice); - } - getMap() { - return new StepMap([this.from, this.to - this.from, this.slice.size]); - } - invert(doc2) { - return new ReplaceStep(this.from, this.from + this.slice.size, doc2.slice(this.from, this.to)); - } - map(mapping) { - let to = mapping.mapResult(this.to, -1); - let from2 = this.from == this.to && ReplaceStep.MAP_BIAS < 0 ? to : mapping.mapResult(this.from, 1); - if (from2.deletedAcross && to.deletedAcross) - return null; - return new ReplaceStep(from2.pos, Math.max(from2.pos, to.pos), this.slice, this.structure); - } - merge(other) { - if (!(other instanceof ReplaceStep) || other.structure || this.structure) - return null; - if (this.from + this.slice.size == other.from && !this.slice.openEnd && !other.slice.openStart) { - let slice2 = this.slice.size + other.slice.size == 0 ? Slice.empty : new Slice(this.slice.content.append(other.slice.content), this.slice.openStart, other.slice.openEnd); - return new ReplaceStep(this.from, this.to + (other.to - other.from), slice2, this.structure); - } else if (other.to == this.from && !this.slice.openStart && !other.slice.openEnd) { - let slice2 = this.slice.size + other.slice.size == 0 ? Slice.empty : new Slice(other.slice.content.append(this.slice.content), other.slice.openStart, this.slice.openEnd); - return new ReplaceStep(other.from, this.to, slice2, this.structure); - } else { - return null; - } - } - toJSON() { - let json = { stepType: "replace", from: this.from, to: this.to }; - if (this.slice.size) - json.slice = this.slice.toJSON(); - if (this.structure) - json.structure = true; - return json; - } - /** - @internal - */ - static fromJSON(schema, json) { - if (typeof json.from != "number" || typeof json.to != "number") - throw new RangeError("Invalid input for ReplaceStep.fromJSON"); - return new ReplaceStep(json.from, json.to, Slice.fromJSON(schema, json.slice), !!json.structure); - } -} -ReplaceStep.MAP_BIAS = 1; -Step.jsonID("replace", ReplaceStep); -class ReplaceAroundStep extends Step { - /** - Create a replace-around step with the given range and gap. - `insert` should be the point in the slice into which the content - of the gap should be moved. `structure` has the same meaning as - it has in the [`ReplaceStep`](https://prosemirror.net/docs/ref/#transform.ReplaceStep) class. - */ - constructor(from2, to, gapFrom, gapTo, slice2, insert, structure = false) { - super(); - this.from = from2; - this.to = to; - this.gapFrom = gapFrom; - this.gapTo = gapTo; - this.slice = slice2; - this.insert = insert; - this.structure = structure; - } - apply(doc2) { - if (this.structure && (contentBetween(doc2, this.from, this.gapFrom) || contentBetween(doc2, this.gapTo, this.to))) - return StepResult.fail("Structure gap-replace would overwrite content"); - let gap = doc2.slice(this.gapFrom, this.gapTo); - if (gap.openStart || gap.openEnd) - return StepResult.fail("Gap is not a flat range"); - let inserted = this.slice.insertAt(this.insert, gap.content); - if (!inserted) - return StepResult.fail("Content does not fit in gap"); - return StepResult.fromReplace(doc2, this.from, this.to, inserted); - } - getMap() { - return new StepMap([ - this.from, - this.gapFrom - this.from, - this.insert, - this.gapTo, - this.to - this.gapTo, - this.slice.size - this.insert - ]); - } - invert(doc2) { - let gap = this.gapTo - this.gapFrom; - return new ReplaceAroundStep(this.from, this.from + this.slice.size + gap, this.from + this.insert, this.from + this.insert + gap, doc2.slice(this.from, this.to).removeBetween(this.gapFrom - this.from, this.gapTo - this.from), this.gapFrom - this.from, this.structure); - } - map(mapping) { - let from2 = mapping.mapResult(this.from, 1), to = mapping.mapResult(this.to, -1); - let gapFrom = this.from == this.gapFrom ? from2.pos : mapping.map(this.gapFrom, -1); - let gapTo = this.to == this.gapTo ? to.pos : mapping.map(this.gapTo, 1); - if (from2.deletedAcross && to.deletedAcross || gapFrom < from2.pos || gapTo > to.pos) - return null; - return new ReplaceAroundStep(from2.pos, to.pos, gapFrom, gapTo, this.slice, this.insert, this.structure); - } - toJSON() { - let json = { - stepType: "replaceAround", - from: this.from, - to: this.to, - gapFrom: this.gapFrom, - gapTo: this.gapTo, - insert: this.insert - }; - if (this.slice.size) - json.slice = this.slice.toJSON(); - if (this.structure) - json.structure = true; - return json; - } - /** - @internal - */ - static fromJSON(schema, json) { - if (typeof json.from != "number" || typeof json.to != "number" || typeof json.gapFrom != "number" || typeof json.gapTo != "number" || typeof json.insert != "number") - throw new RangeError("Invalid input for ReplaceAroundStep.fromJSON"); - return new ReplaceAroundStep(json.from, json.to, json.gapFrom, json.gapTo, Slice.fromJSON(schema, json.slice), json.insert, !!json.structure); - } -} -Step.jsonID("replaceAround", ReplaceAroundStep); -function contentBetween(doc2, from2, to) { - let $from = doc2.resolve(from2), dist = to - from2, depth = $from.depth; - while (dist > 0 && depth > 0 && $from.indexAfter(depth) == $from.node(depth).childCount) { - depth--; - dist--; - } - if (dist > 0) { - let next = $from.node(depth).maybeChild($from.indexAfter(depth)); - while (dist > 0) { - if (!next || next.isLeaf) - return true; - next = next.firstChild; - dist--; - } - } - return false; -} -function addMark(tr2, from2, to, mark) { - let removed = [], added = []; - let removing, adding; - tr2.doc.nodesBetween(from2, to, (node, pos, parent) => { - if (!node.isInline) - return; - let marks = node.marks; - if (!mark.isInSet(marks) && parent.type.allowsMarkType(mark.type)) { - let start = Math.max(pos, from2), end = Math.min(pos + node.nodeSize, to); - let newSet = mark.addToSet(marks); - for (let i = 0; i < marks.length; i++) { - if (!marks[i].isInSet(newSet)) { - if (removing && removing.to == start && removing.mark.eq(marks[i])) - removing.to = end; - else - removed.push(removing = new RemoveMarkStep(start, end, marks[i])); - } - } - if (adding && adding.to == start) - adding.to = end; - else - added.push(adding = new AddMarkStep(start, end, mark)); - } - }); - removed.forEach((s) => tr2.step(s)); - added.forEach((s) => tr2.step(s)); -} -function removeMark(tr2, from2, to, mark) { - let matched = [], step = 0; - tr2.doc.nodesBetween(from2, to, (node, pos) => { - if (!node.isInline) - return; - step++; - let toRemove = null; - if (mark instanceof MarkType) { - let set = node.marks, found2; - while (found2 = mark.isInSet(set)) { - (toRemove || (toRemove = [])).push(found2); - set = found2.removeFromSet(set); - } - } else if (mark) { - if (mark.isInSet(node.marks)) - toRemove = [mark]; - } else { - toRemove = node.marks; - } - if (toRemove && toRemove.length) { - let end = Math.min(pos + node.nodeSize, to); - for (let i = 0; i < toRemove.length; i++) { - let style2 = toRemove[i], found2; - for (let j = 0; j < matched.length; j++) { - let m = matched[j]; - if (m.step == step - 1 && style2.eq(matched[j].style)) - found2 = m; - } - if (found2) { - found2.to = end; - found2.step = step; - } else { - matched.push({ style: style2, from: Math.max(pos, from2), to: end, step }); - } - } - } - }); - matched.forEach((m) => tr2.step(new RemoveMarkStep(m.from, m.to, m.style))); -} -function clearIncompatible(tr2, pos, parentType, match = parentType.contentMatch, clearNewlines = true) { - let node = tr2.doc.nodeAt(pos); - let replSteps = [], cur = pos + 1; - for (let i = 0; i < node.childCount; i++) { - let child = node.child(i), end = cur + child.nodeSize; - let allowed = match.matchType(child.type); - if (!allowed) { - replSteps.push(new ReplaceStep(cur, end, Slice.empty)); - } else { - match = allowed; - for (let j = 0; j < child.marks.length; j++) - if (!parentType.allowsMarkType(child.marks[j].type)) - tr2.step(new RemoveMarkStep(cur, end, child.marks[j])); - if (clearNewlines && child.isText && parentType.whitespace != "pre") { - let m, newline = /\r?\n|\r/g, slice2; - while (m = newline.exec(child.text)) { - if (!slice2) - slice2 = new Slice(Fragment.from(parentType.schema.text(" ", parentType.allowedMarks(child.marks))), 0, 0); - replSteps.push(new ReplaceStep(cur + m.index, cur + m.index + m[0].length, slice2)); - } - } - } - cur = end; - } - if (!match.validEnd) { - let fill = match.fillBefore(Fragment.empty, true); - tr2.replace(cur, cur, new Slice(fill, 0, 0)); - } - for (let i = replSteps.length - 1; i >= 0; i--) - tr2.step(replSteps[i]); -} -function canCut(node, start, end) { - return (start == 0 || node.canReplace(start, node.childCount)) && (end == node.childCount || node.canReplace(0, end)); -} -function liftTarget(range) { - let parent = range.parent; - let content = parent.content.cutByIndex(range.startIndex, range.endIndex); - for (let depth = range.depth, contentBefore = 0, contentAfter = 0; ; --depth) { - let node = range.$from.node(depth); - let index = range.$from.index(depth) + contentBefore, endIndex = range.$to.indexAfter(depth) - contentAfter; - if (depth < range.depth && node.canReplace(index, endIndex, content)) - return depth; - if (depth == 0 || node.type.spec.isolating || !canCut(node, index, endIndex)) - break; - if (index) - contentBefore = 1; - if (endIndex < node.childCount) - contentAfter = 1; - } - return null; -} -function lift$2(tr2, range, target) { - let { $from, $to, depth } = range; - let gapStart = $from.before(depth + 1), gapEnd = $to.after(depth + 1); - let start = gapStart, end = gapEnd; - let before = Fragment.empty, openStart = 0; - for (let d = depth, splitting = false; d > target; d--) - if (splitting || $from.index(d) > 0) { - splitting = true; - before = Fragment.from($from.node(d).copy(before)); - openStart++; - } else { - start--; - } - let after = Fragment.empty, openEnd = 0; - for (let d = depth, splitting = false; d > target; d--) - if (splitting || $to.after(d + 1) < $to.end(d)) { - splitting = true; - after = Fragment.from($to.node(d).copy(after)); - openEnd++; - } else { - end++; - } - tr2.step(new ReplaceAroundStep(start, end, gapStart, gapEnd, new Slice(before.append(after), openStart, openEnd), before.size - openStart, true)); -} -function findWrapping(range, nodeType, attrs = null, innerRange = range) { - let around = findWrappingOutside(range, nodeType); - let inner = around && findWrappingInside(innerRange, nodeType); - if (!inner) - return null; - return around.map(withAttrs).concat({ type: nodeType, attrs }).concat(inner.map(withAttrs)); -} -function withAttrs(type) { - return { type, attrs: null }; -} -function findWrappingOutside(range, type) { - let { parent, startIndex, endIndex } = range; - let around = parent.contentMatchAt(startIndex).findWrapping(type); - if (!around) - return null; - let outer = around.length ? around[0] : type; - return parent.canReplaceWith(startIndex, endIndex, outer) ? around : null; -} -function findWrappingInside(range, type) { - let { parent, startIndex, endIndex } = range; - let inner = parent.child(startIndex); - let inside = type.contentMatch.findWrapping(inner.type); - if (!inside) - return null; - let lastType = inside.length ? inside[inside.length - 1] : type; - let innerMatch = lastType.contentMatch; - for (let i = startIndex; innerMatch && i < endIndex; i++) - innerMatch = innerMatch.matchType(parent.child(i).type); - if (!innerMatch || !innerMatch.validEnd) - return null; - return inside; -} -function wrap(tr2, range, wrappers) { - let content = Fragment.empty; - for (let i = wrappers.length - 1; i >= 0; i--) { - if (content.size) { - let match = wrappers[i].type.contentMatch.matchFragment(content); - if (!match || !match.validEnd) - throw new RangeError("Wrapper type given to Transform.wrap does not form valid content of its parent wrapper"); - } - content = Fragment.from(wrappers[i].type.create(wrappers[i].attrs, content)); - } - let start = range.start, end = range.end; - tr2.step(new ReplaceAroundStep(start, end, start, end, new Slice(content, 0, 0), wrappers.length, true)); -} -function setBlockType$1(tr2, from2, to, type, attrs) { - if (!type.isTextblock) - throw new RangeError("Type given to setBlockType should be a textblock"); - let mapFrom = tr2.steps.length; - tr2.doc.nodesBetween(from2, to, (node, pos) => { - let attrsHere = typeof attrs == "function" ? attrs(node) : attrs; - if (node.isTextblock && !node.hasMarkup(type, attrsHere) && canChangeType(tr2.doc, tr2.mapping.slice(mapFrom).map(pos), type)) { - let convertNewlines = null; - if (type.schema.linebreakReplacement) { - let pre = type.whitespace == "pre", supportLinebreak = !!type.contentMatch.matchType(type.schema.linebreakReplacement); - if (pre && !supportLinebreak) - convertNewlines = false; - else if (!pre && supportLinebreak) - convertNewlines = true; - } - if (convertNewlines === false) - replaceLinebreaks(tr2, node, pos, mapFrom); - clearIncompatible(tr2, tr2.mapping.slice(mapFrom).map(pos, 1), type, void 0, convertNewlines === null); - let mapping = tr2.mapping.slice(mapFrom); - let startM = mapping.map(pos, 1), endM = mapping.map(pos + node.nodeSize, 1); - tr2.step(new ReplaceAroundStep(startM, endM, startM + 1, endM - 1, new Slice(Fragment.from(type.create(attrsHere, null, node.marks)), 0, 0), 1, true)); - if (convertNewlines === true) - replaceNewlines(tr2, node, pos, mapFrom); - return false; - } - }); -} -function replaceNewlines(tr2, node, pos, mapFrom) { - node.forEach((child, offset) => { - if (child.isText) { - let m, newline = /\r?\n|\r/g; - while (m = newline.exec(child.text)) { - let start = tr2.mapping.slice(mapFrom).map(pos + 1 + offset + m.index); - tr2.replaceWith(start, start + 1, node.type.schema.linebreakReplacement.create()); - } - } - }); -} -function replaceLinebreaks(tr2, node, pos, mapFrom) { - node.forEach((child, offset) => { - if (child.type == child.type.schema.linebreakReplacement) { - let start = tr2.mapping.slice(mapFrom).map(pos + 1 + offset); - tr2.replaceWith(start, start + 1, node.type.schema.text("\n")); - } - }); -} -function canChangeType(doc2, pos, type) { - let $pos = doc2.resolve(pos), index = $pos.index(); - return $pos.parent.canReplaceWith(index, index + 1, type); -} -function setNodeMarkup(tr2, pos, type, attrs, marks) { - let node = tr2.doc.nodeAt(pos); - if (!node) - throw new RangeError("No node at given position"); - if (!type) - type = node.type; - let newNode = type.create(attrs, null, marks || node.marks); - if (node.isLeaf) - return tr2.replaceWith(pos, pos + node.nodeSize, newNode); - if (!type.validContent(node.content)) - throw new RangeError("Invalid content for node type " + type.name); - tr2.step(new ReplaceAroundStep(pos, pos + node.nodeSize, pos + 1, pos + node.nodeSize - 1, new Slice(Fragment.from(newNode), 0, 0), 1, true)); -} -function canSplit(doc2, pos, depth = 1, typesAfter) { - let $pos = doc2.resolve(pos), base2 = $pos.depth - depth; - let innerType = typesAfter && typesAfter[typesAfter.length - 1] || $pos.parent; - if (base2 < 0 || $pos.parent.type.spec.isolating || !$pos.parent.canReplace($pos.index(), $pos.parent.childCount) || !innerType.type.validContent($pos.parent.content.cutByIndex($pos.index(), $pos.parent.childCount))) - return false; - for (let d = $pos.depth - 1, i = depth - 2; d > base2; d--, i--) { - let node = $pos.node(d), index2 = $pos.index(d); - if (node.type.spec.isolating) - return false; - let rest = node.content.cutByIndex(index2, node.childCount); - let overrideChild = typesAfter && typesAfter[i + 1]; - if (overrideChild) - rest = rest.replaceChild(0, overrideChild.type.create(overrideChild.attrs)); - let after = typesAfter && typesAfter[i] || node; - if (!node.canReplace(index2 + 1, node.childCount) || !after.type.validContent(rest)) - return false; - } - let index = $pos.indexAfter(base2); - let baseType = typesAfter && typesAfter[0]; - return $pos.node(base2).canReplaceWith(index, index, baseType ? baseType.type : $pos.node(base2 + 1).type); -} -function split(tr2, pos, depth = 1, typesAfter) { - let $pos = tr2.doc.resolve(pos), before = Fragment.empty, after = Fragment.empty; - for (let d = $pos.depth, e = $pos.depth - depth, i = depth - 1; d > e; d--, i--) { - before = Fragment.from($pos.node(d).copy(before)); - let typeAfter = typesAfter && typesAfter[i]; - after = Fragment.from(typeAfter ? typeAfter.type.create(typeAfter.attrs, after) : $pos.node(d).copy(after)); - } - tr2.step(new ReplaceStep(pos, pos, new Slice(before.append(after), depth, depth), true)); -} -function canJoin(doc2, pos) { - let $pos = doc2.resolve(pos), index = $pos.index(); - return joinable($pos.nodeBefore, $pos.nodeAfter) && $pos.parent.canReplace(index, index + 1); -} -function canAppendWithSubstitutedLinebreaks(a, b) { - if (!b.content.size) - a.type.compatibleContent(b.type); - let match = a.contentMatchAt(a.childCount); - let { linebreakReplacement } = a.type.schema; - for (let i = 0; i < b.childCount; i++) { - let child = b.child(i); - let type = child.type == linebreakReplacement ? a.type.schema.nodes.text : child.type; - match = match.matchType(type); - if (!match) - return false; - if (!a.type.allowsMarks(child.marks)) - return false; - } - return match.validEnd; -} -function joinable(a, b) { - return !!(a && b && !a.isLeaf && canAppendWithSubstitutedLinebreaks(a, b)); -} -function joinPoint(doc2, pos, dir = -1) { - let $pos = doc2.resolve(pos); - for (let d = $pos.depth; ; d--) { - let before, after, index = $pos.index(d); - if (d == $pos.depth) { - before = $pos.nodeBefore; - after = $pos.nodeAfter; - } else if (dir > 0) { - before = $pos.node(d + 1); - index++; - after = $pos.node(d).maybeChild(index); - } else { - before = $pos.node(d).maybeChild(index - 1); - after = $pos.node(d + 1); - } - if (before && !before.isTextblock && joinable(before, after) && $pos.node(d).canReplace(index, index + 1)) - return pos; - if (d == 0) - break; - pos = dir < 0 ? $pos.before(d) : $pos.after(d); - } -} -function join(tr2, pos, depth) { - let convertNewlines = null; - let { linebreakReplacement } = tr2.doc.type.schema; - let $before = tr2.doc.resolve(pos - depth), beforeType = $before.node().type; - if (linebreakReplacement && beforeType.inlineContent) { - let pre = beforeType.whitespace == "pre"; - let supportLinebreak = !!beforeType.contentMatch.matchType(linebreakReplacement); - if (pre && !supportLinebreak) - convertNewlines = false; - else if (!pre && supportLinebreak) - convertNewlines = true; - } - let mapFrom = tr2.steps.length; - if (convertNewlines === false) { - let $after = tr2.doc.resolve(pos + depth); - replaceLinebreaks(tr2, $after.node(), $after.before(), mapFrom); - } - if (beforeType.inlineContent) - clearIncompatible(tr2, pos + depth - 1, beforeType, $before.node().contentMatchAt($before.index()), convertNewlines == null); - let mapping = tr2.mapping.slice(mapFrom), start = mapping.map(pos - depth); - tr2.step(new ReplaceStep(start, mapping.map(pos + depth, -1), Slice.empty, true)); - if (convertNewlines === true) { - let $full = tr2.doc.resolve(start); - replaceNewlines(tr2, $full.node(), $full.before(), tr2.steps.length); - } - return tr2; -} -function insertPoint(doc2, pos, nodeType) { - let $pos = doc2.resolve(pos); - if ($pos.parent.canReplaceWith($pos.index(), $pos.index(), nodeType)) - return pos; - if ($pos.parentOffset == 0) - for (let d = $pos.depth - 1; d >= 0; d--) { - let index = $pos.index(d); - if ($pos.node(d).canReplaceWith(index, index, nodeType)) - return $pos.before(d + 1); - if (index > 0) - return null; - } - if ($pos.parentOffset == $pos.parent.content.size) - for (let d = $pos.depth - 1; d >= 0; d--) { - let index = $pos.indexAfter(d); - if ($pos.node(d).canReplaceWith(index, index, nodeType)) - return $pos.after(d + 1); - if (index < $pos.node(d).childCount) - return null; - } - return null; -} -function dropPoint(doc2, pos, slice2) { - let $pos = doc2.resolve(pos); - if (!slice2.content.size) - return pos; - let content = slice2.content; - for (let i = 0; i < slice2.openStart; i++) - content = content.firstChild.content; - for (let pass = 1; pass <= (slice2.openStart == 0 && slice2.size ? 2 : 1); pass++) { - for (let d = $pos.depth; d >= 0; d--) { - let bias = d == $pos.depth ? 0 : $pos.pos <= ($pos.start(d + 1) + $pos.end(d + 1)) / 2 ? -1 : 1; - let insertPos = $pos.index(d) + (bias > 0 ? 1 : 0); - let parent = $pos.node(d), fits = false; - if (pass == 1) { - fits = parent.canReplace(insertPos, insertPos, content); - } else { - let wrapping = parent.contentMatchAt(insertPos).findWrapping(content.firstChild.type); - fits = wrapping && parent.canReplaceWith(insertPos, insertPos, wrapping[0]); - } - if (fits) - return bias == 0 ? $pos.pos : bias < 0 ? $pos.before(d + 1) : $pos.after(d + 1); - } - } - return null; -} -function replaceStep(doc2, from2, to = from2, slice2 = Slice.empty) { - if (from2 == to && !slice2.size) - return null; - let $from = doc2.resolve(from2), $to = doc2.resolve(to); - if (fitsTrivially($from, $to, slice2)) - return new ReplaceStep(from2, to, slice2); - return new Fitter($from, $to, slice2).fit(); -} -function fitsTrivially($from, $to, slice2) { - return !slice2.openStart && !slice2.openEnd && $from.start() == $to.start() && $from.parent.canReplace($from.index(), $to.index(), slice2.content); -} -class Fitter { - constructor($from, $to, unplaced) { - this.$from = $from; - this.$to = $to; - this.unplaced = unplaced; - this.frontier = []; - this.placed = Fragment.empty; - for (let i = 0; i <= $from.depth; i++) { - let node = $from.node(i); - this.frontier.push({ - type: node.type, - match: node.contentMatchAt($from.indexAfter(i)) - }); - } - for (let i = $from.depth; i > 0; i--) - this.placed = Fragment.from($from.node(i).copy(this.placed)); - } - get depth() { - return this.frontier.length - 1; - } - fit() { - while (this.unplaced.size) { - let fit = this.findFittable(); - if (fit) - this.placeNodes(fit); - else - this.openMore() || this.dropNode(); - } - let moveInline = this.mustMoveInline(), placedSize = this.placed.size - this.depth - this.$from.depth; - let $from = this.$from, $to = this.close(moveInline < 0 ? this.$to : $from.doc.resolve(moveInline)); - if (!$to) - return null; - let content = this.placed, openStart = $from.depth, openEnd = $to.depth; - while (openStart && openEnd && content.childCount == 1) { - content = content.firstChild.content; - openStart--; - openEnd--; - } - let slice2 = new Slice(content, openStart, openEnd); - if (moveInline > -1) - return new ReplaceAroundStep($from.pos, moveInline, this.$to.pos, this.$to.end(), slice2, placedSize); - if (slice2.size || $from.pos != this.$to.pos) - return new ReplaceStep($from.pos, $to.pos, slice2); - return null; - } - // Find a position on the start spine of `this.unplaced` that has - // content that can be moved somewhere on the frontier. Returns two - // depths, one for the slice and one for the frontier. - findFittable() { - let startDepth = this.unplaced.openStart; - for (let cur = this.unplaced.content, d = 0, openEnd = this.unplaced.openEnd; d < startDepth; d++) { - let node = cur.firstChild; - if (cur.childCount > 1) - openEnd = 0; - if (node.type.spec.isolating && openEnd <= d) { - startDepth = d; - break; - } - cur = node.content; - } - for (let pass = 1; pass <= 2; pass++) { - for (let sliceDepth = pass == 1 ? startDepth : this.unplaced.openStart; sliceDepth >= 0; sliceDepth--) { - let fragment, parent = null; - if (sliceDepth) { - parent = contentAt(this.unplaced.content, sliceDepth - 1).firstChild; - fragment = parent.content; - } else { - fragment = this.unplaced.content; - } - let first2 = fragment.firstChild; - for (let frontierDepth = this.depth; frontierDepth >= 0; frontierDepth--) { - let { type, match } = this.frontier[frontierDepth], wrap2, inject = null; - if (pass == 1 && (first2 ? match.matchType(first2.type) || (inject = match.fillBefore(Fragment.from(first2), false)) : parent && type.compatibleContent(parent.type))) - return { sliceDepth, frontierDepth, parent, inject }; - else if (pass == 2 && first2 && (wrap2 = match.findWrapping(first2.type))) - return { sliceDepth, frontierDepth, parent, wrap: wrap2 }; - if (parent && match.matchType(parent.type)) - break; - } - } - } - } - openMore() { - let { content, openStart, openEnd } = this.unplaced; - let inner = contentAt(content, openStart); - if (!inner.childCount || inner.firstChild.isLeaf) - return false; - this.unplaced = new Slice(content, openStart + 1, Math.max(openEnd, inner.size + openStart >= content.size - openEnd ? openStart + 1 : 0)); - return true; - } - dropNode() { - let { content, openStart, openEnd } = this.unplaced; - let inner = contentAt(content, openStart); - if (inner.childCount <= 1 && openStart > 0) { - let openAtEnd = content.size - openStart <= openStart + inner.size; - this.unplaced = new Slice(dropFromFragment(content, openStart - 1, 1), openStart - 1, openAtEnd ? openStart - 1 : openEnd); - } else { - this.unplaced = new Slice(dropFromFragment(content, openStart, 1), openStart, openEnd); - } - } - // Move content from the unplaced slice at `sliceDepth` to the - // frontier node at `frontierDepth`. Close that frontier node when - // applicable. - placeNodes({ sliceDepth, frontierDepth, parent, inject, wrap: wrap2 }) { - while (this.depth > frontierDepth) - this.closeFrontierNode(); - if (wrap2) - for (let i = 0; i < wrap2.length; i++) - this.openFrontierNode(wrap2[i]); - let slice2 = this.unplaced, fragment = parent ? parent.content : slice2.content; - let openStart = slice2.openStart - sliceDepth; - let taken = 0, add = []; - let { match, type } = this.frontier[frontierDepth]; - if (inject) { - for (let i = 0; i < inject.childCount; i++) - add.push(inject.child(i)); - match = match.matchFragment(inject); - } - let openEndCount = fragment.size + sliceDepth - (slice2.content.size - slice2.openEnd); - while (taken < fragment.childCount) { - let next = fragment.child(taken), matches2 = match.matchType(next.type); - if (!matches2) - break; - taken++; - if (taken > 1 || openStart == 0 || next.content.size) { - match = matches2; - add.push(closeNodeStart(next.mark(type.allowedMarks(next.marks)), taken == 1 ? openStart : 0, taken == fragment.childCount ? openEndCount : -1)); - } - } - let toEnd = taken == fragment.childCount; - if (!toEnd) - openEndCount = -1; - this.placed = addToFragment(this.placed, frontierDepth, Fragment.from(add)); - this.frontier[frontierDepth].match = match; - if (toEnd && openEndCount < 0 && parent && parent.type == this.frontier[this.depth].type && this.frontier.length > 1) - this.closeFrontierNode(); - for (let i = 0, cur = fragment; i < openEndCount; i++) { - let node = cur.lastChild; - this.frontier.push({ type: node.type, match: node.contentMatchAt(node.childCount) }); - cur = node.content; - } - this.unplaced = !toEnd ? new Slice(dropFromFragment(slice2.content, sliceDepth, taken), slice2.openStart, slice2.openEnd) : sliceDepth == 0 ? Slice.empty : new Slice(dropFromFragment(slice2.content, sliceDepth - 1, 1), sliceDepth - 1, openEndCount < 0 ? slice2.openEnd : sliceDepth - 1); - } - mustMoveInline() { - if (!this.$to.parent.isTextblock) - return -1; - let top = this.frontier[this.depth], level; - if (!top.type.isTextblock || !contentAfterFits(this.$to, this.$to.depth, top.type, top.match, false) || this.$to.depth == this.depth && (level = this.findCloseLevel(this.$to)) && level.depth == this.depth) - return -1; - let { depth } = this.$to, after = this.$to.after(depth); - while (depth > 1 && after == this.$to.end(--depth)) - ++after; - return after; - } - findCloseLevel($to) { - scan: for (let i = Math.min(this.depth, $to.depth); i >= 0; i--) { - let { match, type } = this.frontier[i]; - let dropInner = i < $to.depth && $to.end(i + 1) == $to.pos + ($to.depth - (i + 1)); - let fit = contentAfterFits($to, i, type, match, dropInner); - if (!fit) - continue; - for (let d = i - 1; d >= 0; d--) { - let { match: match2, type: type2 } = this.frontier[d]; - let matches2 = contentAfterFits($to, d, type2, match2, true); - if (!matches2 || matches2.childCount) - continue scan; - } - return { depth: i, fit, move: dropInner ? $to.doc.resolve($to.after(i + 1)) : $to }; - } - } - close($to) { - let close2 = this.findCloseLevel($to); - if (!close2) - return null; - while (this.depth > close2.depth) - this.closeFrontierNode(); - if (close2.fit.childCount) - this.placed = addToFragment(this.placed, close2.depth, close2.fit); - $to = close2.move; - for (let d = close2.depth + 1; d <= $to.depth; d++) { - let node = $to.node(d), add = node.type.contentMatch.fillBefore(node.content, true, $to.index(d)); - this.openFrontierNode(node.type, node.attrs, add); - } - return $to; - } - openFrontierNode(type, attrs = null, content) { - let top = this.frontier[this.depth]; - top.match = top.match.matchType(type); - this.placed = addToFragment(this.placed, this.depth, Fragment.from(type.create(attrs, content))); - this.frontier.push({ type, match: type.contentMatch }); - } - closeFrontierNode() { - let open = this.frontier.pop(); - let add = open.match.fillBefore(Fragment.empty, true); - if (add.childCount) - this.placed = addToFragment(this.placed, this.frontier.length, add); - } -} -function dropFromFragment(fragment, depth, count) { - if (depth == 0) - return fragment.cutByIndex(count, fragment.childCount); - return fragment.replaceChild(0, fragment.firstChild.copy(dropFromFragment(fragment.firstChild.content, depth - 1, count))); -} -function addToFragment(fragment, depth, content) { - if (depth == 0) - return fragment.append(content); - return fragment.replaceChild(fragment.childCount - 1, fragment.lastChild.copy(addToFragment(fragment.lastChild.content, depth - 1, content))); -} -function contentAt(fragment, depth) { - for (let i = 0; i < depth; i++) - fragment = fragment.firstChild.content; - return fragment; -} -function closeNodeStart(node, openStart, openEnd) { - if (openStart <= 0) - return node; - let frag = node.content; - if (openStart > 1) - frag = frag.replaceChild(0, closeNodeStart(frag.firstChild, openStart - 1, frag.childCount == 1 ? openEnd - 1 : 0)); - if (openStart > 0) { - frag = node.type.contentMatch.fillBefore(frag).append(frag); - if (openEnd <= 0) - frag = frag.append(node.type.contentMatch.matchFragment(frag).fillBefore(Fragment.empty, true)); - } - return node.copy(frag); -} -function contentAfterFits($to, depth, type, match, open) { - let node = $to.node(depth), index = open ? $to.indexAfter(depth) : $to.index(depth); - if (index == node.childCount && !type.compatibleContent(node.type)) - return null; - let fit = match.fillBefore(node.content, true, index); - return fit && !invalidMarks(type, node.content, index) ? fit : null; -} -function invalidMarks(type, fragment, start) { - for (let i = start; i < fragment.childCount; i++) - if (!type.allowsMarks(fragment.child(i).marks)) - return true; - return false; -} -function definesContent(type) { - return type.spec.defining || type.spec.definingForContent; -} -function replaceRange(tr2, from2, to, slice2) { - if (!slice2.size) - return tr2.deleteRange(from2, to); - let $from = tr2.doc.resolve(from2), $to = tr2.doc.resolve(to); - if (fitsTrivially($from, $to, slice2)) - return tr2.step(new ReplaceStep(from2, to, slice2)); - let targetDepths = coveredDepths($from, $to); - if (targetDepths[targetDepths.length - 1] == 0) - targetDepths.pop(); - let preferredTarget = -($from.depth + 1); - targetDepths.unshift(preferredTarget); - for (let d = $from.depth, pos = $from.pos - 1; d > 0; d--, pos--) { - let spec = $from.node(d).type.spec; - if (spec.defining || spec.definingAsContext || spec.isolating) - break; - if (targetDepths.indexOf(d) > -1) - preferredTarget = d; - else if ($from.before(d) == pos) - targetDepths.splice(1, 0, -d); - } - let preferredTargetIndex = targetDepths.indexOf(preferredTarget); - let leftNodes = [], preferredDepth = slice2.openStart; - for (let content = slice2.content, i = 0; ; i++) { - let node = content.firstChild; - leftNodes.push(node); - if (i == slice2.openStart) - break; - content = node.content; - } - for (let d = preferredDepth - 1; d >= 0; d--) { - let leftNode = leftNodes[d], def = definesContent(leftNode.type); - if (def && !leftNode.sameMarkup($from.node(Math.abs(preferredTarget) - 1))) - preferredDepth = d; - else if (def || !leftNode.type.isTextblock) - break; - } - for (let j = slice2.openStart; j >= 0; j--) { - let openDepth = (j + preferredDepth + 1) % (slice2.openStart + 1); - let insert = leftNodes[openDepth]; - if (!insert) - continue; - for (let i = 0; i < targetDepths.length; i++) { - let targetDepth = targetDepths[(i + preferredTargetIndex) % targetDepths.length], expand = true; - if (targetDepth < 0) { - expand = false; - targetDepth = -targetDepth; - } - let parent = $from.node(targetDepth - 1), index = $from.index(targetDepth - 1); - if (parent.canReplaceWith(index, index, insert.type, insert.marks)) - return tr2.replace($from.before(targetDepth), expand ? $to.after(targetDepth) : to, new Slice(closeFragment(slice2.content, 0, slice2.openStart, openDepth), openDepth, slice2.openEnd)); - } - } - let startSteps = tr2.steps.length; - for (let i = targetDepths.length - 1; i >= 0; i--) { - tr2.replace(from2, to, slice2); - if (tr2.steps.length > startSteps) - break; - let depth = targetDepths[i]; - if (depth < 0) - continue; - from2 = $from.before(depth); - to = $to.after(depth); - } -} -function closeFragment(fragment, depth, oldOpen, newOpen, parent) { - if (depth < oldOpen) { - let first2 = fragment.firstChild; - fragment = fragment.replaceChild(0, first2.copy(closeFragment(first2.content, depth + 1, oldOpen, newOpen, first2))); - } - if (depth > newOpen) { - let match = parent.contentMatchAt(0); - let start = match.fillBefore(fragment).append(fragment); - fragment = start.append(match.matchFragment(start).fillBefore(Fragment.empty, true)); - } - return fragment; -} -function replaceRangeWith(tr2, from2, to, node) { - if (!node.isInline && from2 == to && tr2.doc.resolve(from2).parent.content.size) { - let point = insertPoint(tr2.doc, from2, node.type); - if (point != null) - from2 = to = point; - } - tr2.replaceRange(from2, to, new Slice(Fragment.from(node), 0, 0)); -} -function deleteRange$1(tr2, from2, to) { - let $from = tr2.doc.resolve(from2), $to = tr2.doc.resolve(to); - if ($from.parent.isTextblock && $to.parent.isTextblock && $from.start() != $to.start() && $from.parentOffset == 0 && $to.parentOffset == 0) { - let shared = $from.sharedDepth(to), isolated = false; - for (let d = $from.depth; d > shared; d--) - if ($from.node(d).type.spec.isolating) - isolated = true; - for (let d = $to.depth; d > shared; d--) - if ($to.node(d).type.spec.isolating) - isolated = true; - if (!isolated) { - for (let d = $from.depth; d > 0 && from2 == $from.start(d); d--) - from2 = $from.before(d); - for (let d = $to.depth; d > 0 && to == $to.start(d); d--) - to = $to.before(d); - $from = tr2.doc.resolve(from2); - $to = tr2.doc.resolve(to); - } - } - let covered = coveredDepths($from, $to); - for (let i = 0; i < covered.length; i++) { - let depth = covered[i], last = i == covered.length - 1; - if (last && depth == 0 || $from.node(depth).type.contentMatch.validEnd) - return tr2.delete($from.start(depth), $to.end(depth)); - if (depth > 0 && (last || $from.node(depth - 1).canReplace($from.index(depth - 1), $to.indexAfter(depth - 1)))) - return tr2.delete($from.before(depth), $to.after(depth)); - } - for (let d = 1; d <= $from.depth && d <= $to.depth; d++) { - if (from2 - $from.start(d) == $from.depth - d && to > $from.end(d) && $to.end(d) - to != $to.depth - d && $from.start(d - 1) == $to.start(d - 1) && $from.node(d - 1).canReplace($from.index(d - 1), $to.index(d - 1))) - return tr2.delete($from.before(d), to); - } - tr2.delete(from2, to); -} -function coveredDepths($from, $to) { - let result = [], minDepth = Math.min($from.depth, $to.depth); - for (let d = minDepth; d >= 0; d--) { - let start = $from.start(d); - if (start < $from.pos - ($from.depth - d) || $to.end(d) > $to.pos + ($to.depth - d) || $from.node(d).type.spec.isolating || $to.node(d).type.spec.isolating) - break; - if (start == $to.start(d) || d == $from.depth && d == $to.depth && $from.parent.inlineContent && $to.parent.inlineContent && d && $to.start(d - 1) == start - 1) - result.push(d); - } - return result; -} -class AttrStep extends Step { - /** - Construct an attribute step. - */ - constructor(pos, attr, value) { - super(); - this.pos = pos; - this.attr = attr; - this.value = value; - } - apply(doc2) { - let node = doc2.nodeAt(this.pos); - if (!node) - return StepResult.fail("No node at attribute step's position"); - let attrs = /* @__PURE__ */ Object.create(null); - for (let name in node.attrs) - attrs[name] = node.attrs[name]; - attrs[this.attr] = this.value; - let updated = node.type.create(attrs, null, node.marks); - return StepResult.fromReplace(doc2, this.pos, this.pos + 1, new Slice(Fragment.from(updated), 0, node.isLeaf ? 0 : 1)); - } - getMap() { - return StepMap.empty; - } - invert(doc2) { - return new AttrStep(this.pos, this.attr, doc2.nodeAt(this.pos).attrs[this.attr]); - } - map(mapping) { - let pos = mapping.mapResult(this.pos, 1); - return pos.deletedAfter ? null : new AttrStep(pos.pos, this.attr, this.value); - } - toJSON() { - return { stepType: "attr", pos: this.pos, attr: this.attr, value: this.value }; - } - static fromJSON(schema, json) { - if (typeof json.pos != "number" || typeof json.attr != "string") - throw new RangeError("Invalid input for AttrStep.fromJSON"); - return new AttrStep(json.pos, json.attr, json.value); - } -} -Step.jsonID("attr", AttrStep); -class DocAttrStep extends Step { - /** - Construct an attribute step. - */ - constructor(attr, value) { - super(); - this.attr = attr; - this.value = value; - } - apply(doc2) { - let attrs = /* @__PURE__ */ Object.create(null); - for (let name in doc2.attrs) - attrs[name] = doc2.attrs[name]; - attrs[this.attr] = this.value; - let updated = doc2.type.create(attrs, doc2.content, doc2.marks); - return StepResult.ok(updated); - } - getMap() { - return StepMap.empty; - } - invert(doc2) { - return new DocAttrStep(this.attr, doc2.attrs[this.attr]); - } - map(mapping) { - return this; - } - toJSON() { - return { stepType: "docAttr", attr: this.attr, value: this.value }; - } - static fromJSON(schema, json) { - if (typeof json.attr != "string") - throw new RangeError("Invalid input for DocAttrStep.fromJSON"); - return new DocAttrStep(json.attr, json.value); - } -} -Step.jsonID("docAttr", DocAttrStep); -let TransformError = class extends Error { -}; -TransformError = function TransformError2(message) { - let err = Error.call(this, message); - err.__proto__ = TransformError2.prototype; - return err; -}; -TransformError.prototype = Object.create(Error.prototype); -TransformError.prototype.constructor = TransformError; -TransformError.prototype.name = "TransformError"; -class Transform { - /** - Create a transform that starts with the given document. - */ - constructor(doc2) { - this.doc = doc2; - this.steps = []; - this.docs = []; - this.mapping = new Mapping(); - } - /** - The starting document. - */ - get before() { - return this.docs.length ? this.docs[0] : this.doc; - } - /** - Apply a new step in this transform, saving the result. Throws an - error when the step fails. - */ - step(step) { - let result = this.maybeStep(step); - if (result.failed) - throw new TransformError(result.failed); - return this; - } - /** - Try to apply a step in this transformation, ignoring it if it - fails. Returns the step result. - */ - maybeStep(step) { - let result = step.apply(this.doc); - if (!result.failed) - this.addStep(step, result.doc); - return result; - } - /** - True when the document has been changed (when there are any - steps). - */ - get docChanged() { - return this.steps.length > 0; - } - /** - Return a single range, in post-transform document positions, - that covers all content changed by this transform. Returns null - if no replacements are made. Note that this will ignore changes - that add/remove marks without replacing the underlying content. - */ - changedRange() { - let from2 = 1e9, to = -1e9; - for (let i = 0; i < this.mapping.maps.length; i++) { - let map2 = this.mapping.maps[i]; - if (i) { - from2 = map2.map(from2, 1); - to = map2.map(to, -1); - } - map2.forEach((_f, _t, fromB, toB) => { - from2 = Math.min(from2, fromB); - to = Math.max(to, toB); - }); - } - return from2 == 1e9 ? null : { from: from2, to }; - } - /** - @internal - */ - addStep(step, doc2) { - this.docs.push(this.doc); - this.steps.push(step); - this.mapping.appendMap(step.getMap()); - this.doc = doc2; - } - /** - Replace the part of the document between `from` and `to` with the - given `slice`. - */ - replace(from2, to = from2, slice2 = Slice.empty) { - let step = replaceStep(this.doc, from2, to, slice2); - if (step) - this.step(step); - return this; - } - /** - Replace the given range with the given content, which may be a - fragment, node, or array of nodes. - */ - replaceWith(from2, to, content) { - return this.replace(from2, to, new Slice(Fragment.from(content), 0, 0)); - } - /** - Delete the content between the given positions. - */ - delete(from2, to) { - return this.replace(from2, to, Slice.empty); - } - /** - Insert the given content at the given position. - */ - insert(pos, content) { - return this.replaceWith(pos, pos, content); - } - /** - Replace a range of the document with a given slice, using - `from`, `to`, and the slice's - [`openStart`](https://prosemirror.net/docs/ref/#model.Slice.openStart) property as hints, rather - than fixed start and end points. This method may grow the - replaced area or close open nodes in the slice in order to get a - fit that is more in line with WYSIWYG expectations, by dropping - fully covered parent nodes of the replaced region when they are - marked [non-defining as - context](https://prosemirror.net/docs/ref/#model.NodeSpec.definingAsContext), or including an - open parent node from the slice that _is_ marked as [defining - its content](https://prosemirror.net/docs/ref/#model.NodeSpec.definingForContent). - - This is the method, for example, to handle paste. The similar - [`replace`](https://prosemirror.net/docs/ref/#transform.Transform.replace) method is a more - primitive tool which will _not_ move the start and end of its given - range, and is useful in situations where you need more precise - control over what happens. - */ - replaceRange(from2, to, slice2) { - replaceRange(this, from2, to, slice2); - return this; - } - /** - Replace the given range with a node, but use `from` and `to` as - hints, rather than precise positions. When from and to are the same - and are at the start or end of a parent node in which the given - node doesn't fit, this method may _move_ them out towards a parent - that does allow the given node to be placed. When the given range - completely covers a parent node, this method may completely replace - that parent node. - */ - replaceRangeWith(from2, to, node) { - replaceRangeWith(this, from2, to, node); - return this; - } - /** - Delete the given range, expanding it to cover fully covered - parent nodes until a valid replace is found. - */ - deleteRange(from2, to) { - deleteRange$1(this, from2, to); - return this; - } - /** - Split the content in the given range off from its parent, if there - is sibling content before or after it, and move it up the tree to - the depth specified by `target`. You'll probably want to use - [`liftTarget`](https://prosemirror.net/docs/ref/#transform.liftTarget) to compute `target`, to make - sure the lift is valid. - */ - lift(range, target) { - lift$2(this, range, target); - return this; - } - /** - Join the blocks around the given position. If depth is 2, their - last and first siblings are also joined, and so on. - */ - join(pos, depth = 1) { - join(this, pos, depth); - return this; - } - /** - Wrap the given [range](https://prosemirror.net/docs/ref/#model.NodeRange) in the given set of wrappers. - The wrappers are assumed to be valid in this position, and should - probably be computed with [`findWrapping`](https://prosemirror.net/docs/ref/#transform.findWrapping). - */ - wrap(range, wrappers) { - wrap(this, range, wrappers); - return this; - } - /** - Set the type of all textblocks (partly) between `from` and `to` to - the given node type with the given attributes. - */ - setBlockType(from2, to = from2, type, attrs = null) { - setBlockType$1(this, from2, to, type, attrs); - return this; - } - /** - Change the type, attributes, and/or marks of the node at `pos`. - When `type` isn't given, the existing node type is preserved, - */ - setNodeMarkup(pos, type, attrs = null, marks) { - setNodeMarkup(this, pos, type, attrs, marks); - return this; - } - /** - Set a single attribute on a given node to a new value. - The `pos` addresses the document content. Use `setDocAttribute` - to set attributes on the document itself. - */ - setNodeAttribute(pos, attr, value) { - this.step(new AttrStep(pos, attr, value)); - return this; - } - /** - Set a single attribute on the document to a new value. - */ - setDocAttribute(attr, value) { - this.step(new DocAttrStep(attr, value)); - return this; - } - /** - Add a mark to the node at position `pos`. - */ - addNodeMark(pos, mark) { - this.step(new AddNodeMarkStep(pos, mark)); - return this; - } - /** - Remove a mark (or all marks of the given type) from the node at - position `pos`. - */ - removeNodeMark(pos, mark) { - let node = this.doc.nodeAt(pos); - if (!node) - throw new RangeError("No node at position " + pos); - if (mark instanceof Mark$1) { - if (mark.isInSet(node.marks)) - this.step(new RemoveNodeMarkStep(pos, mark)); - } else { - let set = node.marks, found2, steps = []; - while (found2 = mark.isInSet(set)) { - steps.push(new RemoveNodeMarkStep(pos, found2)); - set = found2.removeFromSet(set); - } - for (let i = steps.length - 1; i >= 0; i--) - this.step(steps[i]); - } - return this; - } - /** - Split the node at the given position, and optionally, if `depth` is - greater than one, any number of nodes above that. By default, the - parts split off will inherit the node type of the original node. - This can be changed by passing an array of types and attributes to - use after the split (with the outermost nodes coming first). - */ - split(pos, depth = 1, typesAfter) { - split(this, pos, depth, typesAfter); - return this; - } - /** - Add the given mark to the inline content between `from` and `to`. - */ - addMark(from2, to, mark) { - addMark(this, from2, to, mark); - return this; - } - /** - Remove marks from inline nodes between `from` and `to`. When - `mark` is a single mark, remove precisely that mark. When it is - a mark type, remove all marks of that type. When it is null, - remove all marks of any type. - */ - removeMark(from2, to, mark) { - removeMark(this, from2, to, mark); - return this; - } - /** - Removes all marks and nodes from the content of the node at - `pos` that don't match the given new parent node type. Accepts - an optional starting [content match](https://prosemirror.net/docs/ref/#model.ContentMatch) as - third argument. - */ - clearIncompatible(pos, parentType, match) { - clearIncompatible(this, pos, parentType, match); - return this; - } -} -const classesById = /* @__PURE__ */ Object.create(null); -class Selection { - /** - Initialize a selection with the head and anchor and ranges. If no - ranges are given, constructs a single range across `$anchor` and - `$head`. - */ - constructor($anchor, $head, ranges) { - this.$anchor = $anchor; - this.$head = $head; - this.ranges = ranges || [new SelectionRange($anchor.min($head), $anchor.max($head))]; - } - /** - The selection's anchor, as an unresolved position. - */ - get anchor() { - return this.$anchor.pos; - } - /** - The selection's head. - */ - get head() { - return this.$head.pos; - } - /** - The lower bound of the selection's main range. - */ - get from() { - return this.$from.pos; - } - /** - The upper bound of the selection's main range. - */ - get to() { - return this.$to.pos; - } - /** - The resolved lower bound of the selection's main range. - */ - get $from() { - return this.ranges[0].$from; - } - /** - The resolved upper bound of the selection's main range. - */ - get $to() { - return this.ranges[0].$to; - } - /** - Indicates whether the selection contains any content. - */ - get empty() { - let ranges = this.ranges; - for (let i = 0; i < ranges.length; i++) - if (ranges[i].$from.pos != ranges[i].$to.pos) - return false; - return true; - } - /** - Get the content of this selection as a slice. - */ - content() { - return this.$from.doc.slice(this.from, this.to, true); - } - /** - Replace the selection with a slice or, if no slice is given, - delete the selection. Will append to the given transaction. - */ - replace(tr2, content = Slice.empty) { - let lastNode = content.content.lastChild, lastParent = null; - for (let i = 0; i < content.openEnd; i++) { - lastParent = lastNode; - lastNode = lastNode.lastChild; - } - let mapFrom = tr2.steps.length, ranges = this.ranges; - for (let i = 0; i < ranges.length; i++) { - let { $from, $to } = ranges[i], mapping = tr2.mapping.slice(mapFrom); - tr2.replaceRange(mapping.map($from.pos), mapping.map($to.pos), i ? Slice.empty : content); - if (i == 0) - selectionToInsertionEnd$1(tr2, mapFrom, (lastNode ? lastNode.isInline : lastParent && lastParent.isTextblock) ? -1 : 1); - } - } - /** - Replace the selection with the given node, appending the changes - to the given transaction. - */ - replaceWith(tr2, node) { - let mapFrom = tr2.steps.length, ranges = this.ranges; - for (let i = 0; i < ranges.length; i++) { - let { $from, $to } = ranges[i], mapping = tr2.mapping.slice(mapFrom); - let from2 = mapping.map($from.pos), to = mapping.map($to.pos); - if (i) { - tr2.deleteRange(from2, to); - } else { - tr2.replaceRangeWith(from2, to, node); - selectionToInsertionEnd$1(tr2, mapFrom, node.isInline ? -1 : 1); - } - } - } - /** - Find a valid cursor or leaf node selection starting at the given - position and searching back if `dir` is negative, and forward if - positive. When `textOnly` is true, only consider cursor - selections. Will return null when no valid selection position is - found. - */ - static findFrom($pos, dir, textOnly = false) { - let inner = $pos.parent.inlineContent ? new TextSelection($pos) : findSelectionIn($pos.node(0), $pos.parent, $pos.pos, $pos.index(), dir, textOnly); - if (inner) - return inner; - for (let depth = $pos.depth - 1; depth >= 0; depth--) { - let found2 = dir < 0 ? findSelectionIn($pos.node(0), $pos.node(depth), $pos.before(depth + 1), $pos.index(depth), dir, textOnly) : findSelectionIn($pos.node(0), $pos.node(depth), $pos.after(depth + 1), $pos.index(depth) + 1, dir, textOnly); - if (found2) - return found2; - } - return null; - } - /** - Find a valid cursor or leaf node selection near the given - position. Searches forward first by default, but if `bias` is - negative, it will search backwards first. - */ - static near($pos, bias = 1) { - return this.findFrom($pos, bias) || this.findFrom($pos, -bias) || new AllSelection($pos.node(0)); - } - /** - Find the cursor or leaf node selection closest to the start of - the given document. Will return an - [`AllSelection`](https://prosemirror.net/docs/ref/#state.AllSelection) if no valid position - exists. - */ - static atStart(doc2) { - return findSelectionIn(doc2, doc2, 0, 0, 1) || new AllSelection(doc2); - } - /** - Find the cursor or leaf node selection closest to the end of the - given document. - */ - static atEnd(doc2) { - return findSelectionIn(doc2, doc2, doc2.content.size, doc2.childCount, -1) || new AllSelection(doc2); - } - /** - Deserialize the JSON representation of a selection. Must be - implemented for custom classes (as a static class method). - */ - static fromJSON(doc2, json) { - if (!json || !json.type) - throw new RangeError("Invalid input for Selection.fromJSON"); - let cls = classesById[json.type]; - if (!cls) - throw new RangeError(`No selection type ${json.type} defined`); - return cls.fromJSON(doc2, json); - } - /** - To be able to deserialize selections from JSON, custom selection - classes must register themselves with an ID string, so that they - can be disambiguated. Try to pick something that's unlikely to - clash with classes from other modules. - */ - static jsonID(id, selectionClass) { - if (id in classesById) - throw new RangeError("Duplicate use of selection JSON ID " + id); - classesById[id] = selectionClass; - selectionClass.prototype.jsonID = id; - return selectionClass; - } - /** - Get a [bookmark](https://prosemirror.net/docs/ref/#state.SelectionBookmark) for this selection, - which is a value that can be mapped without having access to a - current document, and later resolved to a real selection for a - given document again. (This is used mostly by the history to - track and restore old selections.) The default implementation of - this method just converts the selection to a text selection and - returns the bookmark for that. - */ - getBookmark() { - return TextSelection.between(this.$anchor, this.$head).getBookmark(); - } -} -Selection.prototype.visible = true; -class SelectionRange { - /** - Create a range. - */ - constructor($from, $to) { - this.$from = $from; - this.$to = $to; - } -} -let warnedAboutTextSelection = false; -function checkTextSelection($pos) { - if (!warnedAboutTextSelection && !$pos.parent.inlineContent) { - warnedAboutTextSelection = true; - console["warn"]("TextSelection endpoint not pointing into a node with inline content (" + $pos.parent.type.name + ")"); - } -} -class TextSelection extends Selection { - /** - Construct a text selection between the given points. - */ - constructor($anchor, $head = $anchor) { - checkTextSelection($anchor); - checkTextSelection($head); - super($anchor, $head); - } - /** - Returns a resolved position if this is a cursor selection (an - empty text selection), and null otherwise. - */ - get $cursor() { - return this.$anchor.pos == this.$head.pos ? this.$head : null; - } - map(doc2, mapping) { - let $head = doc2.resolve(mapping.map(this.head)); - if (!$head.parent.inlineContent) - return Selection.near($head); - let $anchor = doc2.resolve(mapping.map(this.anchor)); - return new TextSelection($anchor.parent.inlineContent ? $anchor : $head, $head); - } - replace(tr2, content = Slice.empty) { - super.replace(tr2, content); - if (content == Slice.empty) { - let marks = this.$from.marksAcross(this.$to); - if (marks) - tr2.ensureMarks(marks); - } - } - eq(other) { - return other instanceof TextSelection && other.anchor == this.anchor && other.head == this.head; - } - getBookmark() { - return new TextBookmark(this.anchor, this.head); - } - toJSON() { - return { type: "text", anchor: this.anchor, head: this.head }; - } - /** - @internal - */ - static fromJSON(doc2, json) { - if (typeof json.anchor != "number" || typeof json.head != "number") - throw new RangeError("Invalid input for TextSelection.fromJSON"); - return new TextSelection(doc2.resolve(json.anchor), doc2.resolve(json.head)); - } - /** - Create a text selection from non-resolved positions. - */ - static create(doc2, anchor, head = anchor) { - let $anchor = doc2.resolve(anchor); - return new this($anchor, head == anchor ? $anchor : doc2.resolve(head)); - } - /** - Return a text selection that spans the given positions or, if - they aren't text positions, find a text selection near them. - `bias` determines whether the method searches forward (default) - or backwards (negative number) first. Will fall back to calling - [`Selection.near`](https://prosemirror.net/docs/ref/#state.Selection^near) when the document - doesn't contain a valid text position. - */ - static between($anchor, $head, bias) { - let dPos = $anchor.pos - $head.pos; - if (!bias || dPos) - bias = dPos >= 0 ? 1 : -1; - if (!$head.parent.inlineContent) { - let found2 = Selection.findFrom($head, bias, true) || Selection.findFrom($head, -bias, true); - if (found2) - $head = found2.$head; - else - return Selection.near($head, bias); - } - if (!$anchor.parent.inlineContent) { - if (dPos == 0) { - $anchor = $head; - } else { - $anchor = (Selection.findFrom($anchor, -bias, true) || Selection.findFrom($anchor, bias, true)).$anchor; - if ($anchor.pos < $head.pos != dPos < 0) - $anchor = $head; - } - } - return new TextSelection($anchor, $head); - } -} -Selection.jsonID("text", TextSelection); -class TextBookmark { - constructor(anchor, head) { - this.anchor = anchor; - this.head = head; - } - map(mapping) { - return new TextBookmark(mapping.map(this.anchor), mapping.map(this.head)); - } - resolve(doc2) { - return TextSelection.between(doc2.resolve(this.anchor), doc2.resolve(this.head)); - } -} -class NodeSelection extends Selection { - /** - Create a node selection. Does not verify the validity of its - argument. - */ - constructor($pos) { - let node = $pos.nodeAfter; - let $end = $pos.node(0).resolve($pos.pos + node.nodeSize); - super($pos, $end); - this.node = node; - } - map(doc2, mapping) { - let { deleted, pos } = mapping.mapResult(this.anchor); - let $pos = doc2.resolve(pos); - if (deleted) - return Selection.near($pos); - return new NodeSelection($pos); - } - content() { - return new Slice(Fragment.from(this.node), 0, 0); - } - eq(other) { - return other instanceof NodeSelection && other.anchor == this.anchor; - } - toJSON() { - return { type: "node", anchor: this.anchor }; - } - getBookmark() { - return new NodeBookmark(this.anchor); - } - /** - @internal - */ - static fromJSON(doc2, json) { - if (typeof json.anchor != "number") - throw new RangeError("Invalid input for NodeSelection.fromJSON"); - return new NodeSelection(doc2.resolve(json.anchor)); - } - /** - Create a node selection from non-resolved positions. - */ - static create(doc2, from2) { - return new NodeSelection(doc2.resolve(from2)); - } - /** - Determines whether the given node may be selected as a node - selection. - */ - static isSelectable(node) { - return !node.isText && node.type.spec.selectable !== false; - } -} -NodeSelection.prototype.visible = false; -Selection.jsonID("node", NodeSelection); -class NodeBookmark { - constructor(anchor) { - this.anchor = anchor; - } - map(mapping) { - let { deleted, pos } = mapping.mapResult(this.anchor); - return deleted ? new TextBookmark(pos, pos) : new NodeBookmark(pos); - } - resolve(doc2) { - let $pos = doc2.resolve(this.anchor), node = $pos.nodeAfter; - if (node && NodeSelection.isSelectable(node)) - return new NodeSelection($pos); - return Selection.near($pos); - } -} -class AllSelection extends Selection { - /** - Create an all-selection over the given document. - */ - constructor(doc2) { - super(doc2.resolve(0), doc2.resolve(doc2.content.size)); - } - replace(tr2, content = Slice.empty) { - if (content == Slice.empty) { - tr2.delete(0, tr2.doc.content.size); - let sel = Selection.atStart(tr2.doc); - if (!sel.eq(tr2.selection)) - tr2.setSelection(sel); - } else { - super.replace(tr2, content); - } - } - toJSON() { - return { type: "all" }; - } - /** - @internal - */ - static fromJSON(doc2) { - return new AllSelection(doc2); - } - map(doc2) { - return new AllSelection(doc2); - } - eq(other) { - return other instanceof AllSelection; - } - getBookmark() { - return AllBookmark; - } -} -Selection.jsonID("all", AllSelection); -const AllBookmark = { - map() { - return this; - }, - resolve(doc2) { - return new AllSelection(doc2); - } -}; -function findSelectionIn(doc2, node, pos, index, dir, text = false) { - if (node.inlineContent) - return TextSelection.create(doc2, pos); - for (let i = index - (dir > 0 ? 0 : 1); dir > 0 ? i < node.childCount : i >= 0; i += dir) { - let child = node.child(i); - if (!child.isAtom) { - let inner = findSelectionIn(doc2, child, pos + dir, dir < 0 ? child.childCount : 0, dir, text); - if (inner) - return inner; - } else if (!text && NodeSelection.isSelectable(child)) { - return NodeSelection.create(doc2, pos - (dir < 0 ? child.nodeSize : 0)); - } - pos += child.nodeSize * dir; - } - return null; -} -function selectionToInsertionEnd$1(tr2, startLen, bias) { - let last = tr2.steps.length - 1; - if (last < startLen) - return; - let step = tr2.steps[last]; - if (!(step instanceof ReplaceStep || step instanceof ReplaceAroundStep)) - return; - let map2 = tr2.mapping.maps[last], end; - map2.forEach((_from, _to, _newFrom, newTo) => { - if (end == null) - end = newTo; - }); - tr2.setSelection(Selection.near(tr2.doc.resolve(end), bias)); -} -const UPDATED_SEL = 1, UPDATED_MARKS = 2, UPDATED_SCROLL = 4; -class Transaction extends Transform { - /** - @internal - */ - constructor(state) { - super(state.doc); - this.curSelectionFor = 0; - this.updated = 0; - this.meta = /* @__PURE__ */ Object.create(null); - this.time = Date.now(); - this.curSelection = state.selection; - this.storedMarks = state.storedMarks; - } - /** - The transaction's current selection. This defaults to the editor - selection [mapped](https://prosemirror.net/docs/ref/#state.Selection.map) through the steps in the - transaction, but can be overwritten with - [`setSelection`](https://prosemirror.net/docs/ref/#state.Transaction.setSelection). - */ - get selection() { - if (this.curSelectionFor < this.steps.length) { - this.curSelection = this.curSelection.map(this.doc, this.mapping.slice(this.curSelectionFor)); - this.curSelectionFor = this.steps.length; - } - return this.curSelection; - } - /** - Update the transaction's current selection. Will determine the - selection that the editor gets when the transaction is applied. - */ - setSelection(selection) { - if (selection.$from.doc != this.doc) - throw new RangeError("Selection passed to setSelection must point at the current document"); - this.curSelection = selection; - this.curSelectionFor = this.steps.length; - this.updated = (this.updated | UPDATED_SEL) & ~UPDATED_MARKS; - this.storedMarks = null; - return this; - } - /** - Whether the selection was explicitly updated by this transaction. - */ - get selectionSet() { - return (this.updated & UPDATED_SEL) > 0; - } - /** - Set the current stored marks. - */ - setStoredMarks(marks) { - this.storedMarks = marks; - this.updated |= UPDATED_MARKS; - return this; - } - /** - Make sure the current stored marks or, if that is null, the marks - at the selection, match the given set of marks. Does nothing if - this is already the case. - */ - ensureMarks(marks) { - if (!Mark$1.sameSet(this.storedMarks || this.selection.$from.marks(), marks)) - this.setStoredMarks(marks); - return this; - } - /** - Add a mark to the set of stored marks. - */ - addStoredMark(mark) { - return this.ensureMarks(mark.addToSet(this.storedMarks || this.selection.$head.marks())); - } - /** - Remove a mark or mark type from the set of stored marks. - */ - removeStoredMark(mark) { - return this.ensureMarks(mark.removeFromSet(this.storedMarks || this.selection.$head.marks())); - } - /** - Whether the stored marks were explicitly set for this transaction. - */ - get storedMarksSet() { - return (this.updated & UPDATED_MARKS) > 0; - } - /** - @internal - */ - addStep(step, doc2) { - super.addStep(step, doc2); - this.updated = this.updated & ~UPDATED_MARKS; - this.storedMarks = null; - } - /** - Update the timestamp for the transaction. - */ - setTime(time) { - this.time = time; - return this; - } - /** - Replace the current selection with the given slice. - */ - replaceSelection(slice2) { - this.selection.replace(this, slice2); - return this; - } - /** - Replace the selection with the given node. When `inheritMarks` is - true and the content is inline, it inherits the marks from the - place where it is inserted. - */ - replaceSelectionWith(node, inheritMarks = true) { - let selection = this.selection; - if (inheritMarks) - node = node.mark(this.storedMarks || (selection.empty ? selection.$from.marks() : selection.$from.marksAcross(selection.$to) || Mark$1.none)); - selection.replaceWith(this, node); - return this; - } - /** - Delete the selection. - */ - deleteSelection() { - this.selection.replace(this); - return this; - } - /** - Replace the given range, or the selection if no range is given, - with a text node containing the given string. - */ - insertText(text, from2, to) { - let schema = this.doc.type.schema; - if (from2 == null) { - if (!text) - return this.deleteSelection(); - return this.replaceSelectionWith(schema.text(text), true); - } else { - if (to == null) - to = from2; - if (!text) - return this.deleteRange(from2, to); - let marks = this.storedMarks; - if (!marks) { - let $from = this.doc.resolve(from2); - marks = to == from2 ? $from.marks() : $from.marksAcross(this.doc.resolve(to)); - } - this.replaceRangeWith(from2, to, schema.text(text, marks)); - if (!this.selection.empty && this.selection.to == from2 + text.length) - this.setSelection(Selection.near(this.selection.$to)); - return this; - } - } - /** - Store a metadata property in this transaction, keyed either by - name or by plugin. - */ - setMeta(key, value) { - this.meta[typeof key == "string" ? key : key.key] = value; - return this; - } - /** - Retrieve a metadata property for a given name or plugin. - */ - getMeta(key) { - return this.meta[typeof key == "string" ? key : key.key]; - } - /** - Returns true if this transaction doesn't contain any metadata, - and can thus safely be extended. - */ - get isGeneric() { - for (let _ in this.meta) - return false; - return true; - } - /** - Indicate that the editor should scroll the selection into view - when updated to the state produced by this transaction. - */ - scrollIntoView() { - this.updated |= UPDATED_SCROLL; - return this; - } - /** - True when this transaction has had `scrollIntoView` called on it. - */ - get scrolledIntoView() { - return (this.updated & UPDATED_SCROLL) > 0; - } -} -function bind(f, self2) { - return !self2 || !f ? f : f.bind(self2); -} -class FieldDesc { - constructor(name, desc, self2) { - this.name = name; - this.init = bind(desc.init, self2); - this.apply = bind(desc.apply, self2); - } -} -const baseFields = [ - new FieldDesc("doc", { - init(config) { - return config.doc || config.schema.topNodeType.createAndFill(); - }, - apply(tr2) { - return tr2.doc; - } - }), - new FieldDesc("selection", { - init(config, instance) { - return config.selection || Selection.atStart(instance.doc); - }, - apply(tr2) { - return tr2.selection; - } - }), - new FieldDesc("storedMarks", { - init(config) { - return config.storedMarks || null; - }, - apply(tr2, _marks, _old, state) { - return state.selection.$cursor ? tr2.storedMarks : null; - } - }), - new FieldDesc("scrollToSelection", { - init() { - return 0; - }, - apply(tr2, prev) { - return tr2.scrolledIntoView ? prev + 1 : prev; - } - }) -]; -class Configuration { - constructor(schema, plugins) { - this.schema = schema; - this.plugins = []; - this.pluginsByKey = /* @__PURE__ */ Object.create(null); - this.fields = baseFields.slice(); - if (plugins) - plugins.forEach((plugin) => { - if (this.pluginsByKey[plugin.key]) - throw new RangeError("Adding different instances of a keyed plugin (" + plugin.key + ")"); - this.plugins.push(plugin); - this.pluginsByKey[plugin.key] = plugin; - if (plugin.spec.state) - this.fields.push(new FieldDesc(plugin.key, plugin.spec.state, plugin)); - }); - } -} -class EditorState { - /** - @internal - */ - constructor(config) { - this.config = config; - } - /** - The schema of the state's document. - */ - get schema() { - return this.config.schema; - } - /** - The plugins that are active in this state. - */ - get plugins() { - return this.config.plugins; - } - /** - Apply the given transaction to produce a new state. - */ - apply(tr2) { - return this.applyTransaction(tr2).state; - } - /** - @internal - */ - filterTransaction(tr2, ignore = -1) { - for (let i = 0; i < this.config.plugins.length; i++) - if (i != ignore) { - let plugin = this.config.plugins[i]; - if (plugin.spec.filterTransaction && !plugin.spec.filterTransaction.call(plugin, tr2, this)) - return false; - } - return true; - } - /** - Verbose variant of [`apply`](https://prosemirror.net/docs/ref/#state.EditorState.apply) that - returns the precise transactions that were applied (which might - be influenced by the [transaction - hooks](https://prosemirror.net/docs/ref/#state.PluginSpec.filterTransaction) of - plugins) along with the new state. - */ - applyTransaction(rootTr) { - if (!this.filterTransaction(rootTr)) - return { state: this, transactions: [] }; - let trs = [rootTr], newState = this.applyInner(rootTr), seen = null; - for (; ; ) { - let haveNew = false; - for (let i = 0; i < this.config.plugins.length; i++) { - let plugin = this.config.plugins[i]; - if (plugin.spec.appendTransaction) { - let n = seen ? seen[i].n : 0, oldState = seen ? seen[i].state : this; - let tr2 = n < trs.length && plugin.spec.appendTransaction.call(plugin, n ? trs.slice(n) : trs, oldState, newState); - if (tr2 && newState.filterTransaction(tr2, i)) { - tr2.setMeta("appendedTransaction", rootTr); - if (!seen) { - seen = []; - for (let j = 0; j < this.config.plugins.length; j++) - seen.push(j < i ? { state: newState, n: trs.length } : { state: this, n: 0 }); - } - trs.push(tr2); - newState = newState.applyInner(tr2); - haveNew = true; - } - if (seen) - seen[i] = { state: newState, n: trs.length }; - } - } - if (!haveNew) - return { state: newState, transactions: trs }; - } - } - /** - @internal - */ - applyInner(tr2) { - if (!tr2.before.eq(this.doc)) - throw new RangeError("Applying a mismatched transaction"); - let newInstance = new EditorState(this.config), fields = this.config.fields; - for (let i = 0; i < fields.length; i++) { - let field = fields[i]; - newInstance[field.name] = field.apply(tr2, this[field.name], this, newInstance); - } - return newInstance; - } - /** - Accessor that constructs and returns a new [transaction](https://prosemirror.net/docs/ref/#state.Transaction) from this state. - */ - get tr() { - return new Transaction(this); - } - /** - Create a new state. - */ - static create(config) { - let $config = new Configuration(config.doc ? config.doc.type.schema : config.schema, config.plugins); - let instance = new EditorState($config); - for (let i = 0; i < $config.fields.length; i++) - instance[$config.fields[i].name] = $config.fields[i].init(config, instance); - return instance; - } - /** - Create a new state based on this one, but with an adjusted set - of active plugins. State fields that exist in both sets of - plugins are kept unchanged. Those that no longer exist are - dropped, and those that are new are initialized using their - [`init`](https://prosemirror.net/docs/ref/#state.StateField.init) method, passing in the new - configuration object.. - */ - reconfigure(config) { - let $config = new Configuration(this.schema, config.plugins); - let fields = $config.fields, instance = new EditorState($config); - for (let i = 0; i < fields.length; i++) { - let name = fields[i].name; - instance[name] = this.hasOwnProperty(name) ? this[name] : fields[i].init(config, instance); - } - return instance; - } - /** - Serialize this state to JSON. If you want to serialize the state - of plugins, pass an object mapping property names to use in the - resulting JSON object to plugin objects. The argument may also be - a string or number, in which case it is ignored, to support the - way `JSON.stringify` calls `toString` methods. - */ - toJSON(pluginFields) { - let result = { doc: this.doc.toJSON(), selection: this.selection.toJSON() }; - if (this.storedMarks) - result.storedMarks = this.storedMarks.map((m) => m.toJSON()); - if (pluginFields && typeof pluginFields == "object") - for (let prop in pluginFields) { - if (prop == "doc" || prop == "selection") - throw new RangeError("The JSON fields `doc` and `selection` are reserved"); - let plugin = pluginFields[prop], state = plugin.spec.state; - if (state && state.toJSON) - result[prop] = state.toJSON.call(plugin, this[plugin.key]); - } - return result; - } - /** - Deserialize a JSON representation of a state. `config` should - have at least a `schema` field, and should contain array of - plugins to initialize the state with. `pluginFields` can be used - to deserialize the state of plugins, by associating plugin - instances with the property names they use in the JSON object. - */ - static fromJSON(config, json, pluginFields) { - if (!json) - throw new RangeError("Invalid input for EditorState.fromJSON"); - if (!config.schema) - throw new RangeError("Required config field 'schema' missing"); - let $config = new Configuration(config.schema, config.plugins); - let instance = new EditorState($config); - $config.fields.forEach((field) => { - if (field.name == "doc") { - instance.doc = Node.fromJSON(config.schema, json.doc); - } else if (field.name == "selection") { - instance.selection = Selection.fromJSON(instance.doc, json.selection); - } else if (field.name == "storedMarks") { - if (json.storedMarks) - instance.storedMarks = json.storedMarks.map(config.schema.markFromJSON); - } else { - if (pluginFields) - for (let prop in pluginFields) { - let plugin = pluginFields[prop], state = plugin.spec.state; - if (plugin.key == field.name && state && state.fromJSON && Object.prototype.hasOwnProperty.call(json, prop)) { - instance[field.name] = state.fromJSON.call(plugin, config, json[prop], instance); - return; - } - } - instance[field.name] = field.init(config, instance); - } - }); - return instance; - } -} -function bindProps(obj, self2, target) { - for (let prop in obj) { - let val = obj[prop]; - if (val instanceof Function) - val = val.bind(self2); - else if (prop == "handleDOMEvents") - val = bindProps(val, self2, {}); - target[prop] = val; - } - return target; -} -class Plugin { - /** - Create a plugin. - */ - constructor(spec) { - this.spec = spec; - this.props = {}; - if (spec.props) - bindProps(spec.props, this, this.props); - this.key = spec.key ? spec.key.key : createKey("plugin"); - } - /** - Extract the plugin's state field from an editor state. - */ - getState(state) { - return state[this.key]; - } -} -const keys$1 = /* @__PURE__ */ Object.create(null); -function createKey(name) { - if (name in keys$1) - return name + "$" + ++keys$1[name]; - keys$1[name] = 0; - return name + "$"; -} -class PluginKey { - /** - Create a plugin key. - */ - constructor(name = "key") { - this.key = createKey(name); - } - /** - Get the active plugin with this key, if any, from an editor - state. - */ - get(state) { - return state.config.pluginsByKey[this.key]; - } - /** - Get the plugin's state from an editor state. - */ - getState(state) { - return state[this.key]; - } -} -const deleteSelection$1 = (state, dispatch) => { - if (state.selection.empty) - return false; - if (dispatch) - dispatch(state.tr.deleteSelection().scrollIntoView()); - return true; -}; -function atBlockStart(state, view) { - let { $cursor } = state.selection; - if (!$cursor || (view ? !view.endOfTextblock("backward", state) : $cursor.parentOffset > 0)) - return null; - return $cursor; -} -const joinBackward$1 = (state, dispatch, view) => { - let $cursor = atBlockStart(state, view); - if (!$cursor) - return false; - let $cut = findCutBefore($cursor); - if (!$cut) { - let range = $cursor.blockRange(), target = range && liftTarget(range); - if (target == null) - return false; - if (dispatch) - dispatch(state.tr.lift(range, target).scrollIntoView()); - return true; - } - let before = $cut.nodeBefore; - if (deleteBarrier(state, $cut, dispatch, -1)) - return true; - if ($cursor.parent.content.size == 0 && (textblockAt(before, "end") || NodeSelection.isSelectable(before))) { - for (let depth = $cursor.depth; ; depth--) { - let delStep = replaceStep(state.doc, $cursor.before(depth), $cursor.after(depth), Slice.empty); - if (delStep && delStep.slice.size < delStep.to - delStep.from) { - if (dispatch) { - let tr2 = state.tr.step(delStep); - tr2.setSelection(textblockAt(before, "end") ? Selection.findFrom(tr2.doc.resolve(tr2.mapping.map($cut.pos, -1)), -1) : NodeSelection.create(tr2.doc, $cut.pos - before.nodeSize)); - dispatch(tr2.scrollIntoView()); - } - return true; - } - if (depth == 1 || $cursor.node(depth - 1).childCount > 1) - break; - } - } - if (before.isAtom && $cut.depth == $cursor.depth - 1) { - if (dispatch) - dispatch(state.tr.delete($cut.pos - before.nodeSize, $cut.pos).scrollIntoView()); - return true; - } - return false; -}; -const joinTextblockBackward$1 = (state, dispatch, view) => { - let $cursor = atBlockStart(state, view); - if (!$cursor) - return false; - let $cut = findCutBefore($cursor); - return $cut ? joinTextblocksAround(state, $cut, dispatch) : false; -}; -const joinTextblockForward$1 = (state, dispatch, view) => { - let $cursor = atBlockEnd(state, view); - if (!$cursor) - return false; - let $cut = findCutAfter($cursor); - return $cut ? joinTextblocksAround(state, $cut, dispatch) : false; -}; -function joinTextblocksAround(state, $cut, dispatch) { - let before = $cut.nodeBefore, beforeText = before, beforePos = $cut.pos - 1; - for (; !beforeText.isTextblock; beforePos--) { - if (beforeText.type.spec.isolating) - return false; - let child = beforeText.lastChild; - if (!child) - return false; - beforeText = child; - } - let after = $cut.nodeAfter, afterText = after, afterPos = $cut.pos + 1; - for (; !afterText.isTextblock; afterPos++) { - if (afterText.type.spec.isolating) - return false; - let child = afterText.firstChild; - if (!child) - return false; - afterText = child; - } - let step = replaceStep(state.doc, beforePos, afterPos, Slice.empty); - if (!step || step.from != beforePos || step instanceof ReplaceStep && step.slice.size >= afterPos - beforePos) - return false; - if (dispatch) { - let tr2 = state.tr.step(step); - tr2.setSelection(TextSelection.create(tr2.doc, beforePos)); - dispatch(tr2.scrollIntoView()); - } - return true; -} -function textblockAt(node, side, only = false) { - for (let scan = node; scan; scan = side == "start" ? scan.firstChild : scan.lastChild) { - if (scan.isTextblock) - return true; - if (only && scan.childCount != 1) - return false; - } - return false; -} -const selectNodeBackward$1 = (state, dispatch, view) => { - let { $head, empty: empty2 } = state.selection, $cut = $head; - if (!empty2) - return false; - if ($head.parent.isTextblock) { - if (view ? !view.endOfTextblock("backward", state) : $head.parentOffset > 0) - return false; - $cut = findCutBefore($head); - } - let node = $cut && $cut.nodeBefore; - if (!node || !NodeSelection.isSelectable(node)) - return false; - if (dispatch) - dispatch(state.tr.setSelection(NodeSelection.create(state.doc, $cut.pos - node.nodeSize)).scrollIntoView()); - return true; -}; -function findCutBefore($pos) { - if (!$pos.parent.type.spec.isolating) - for (let i = $pos.depth - 1; i >= 0; i--) { - if ($pos.index(i) > 0) - return $pos.doc.resolve($pos.before(i + 1)); - if ($pos.node(i).type.spec.isolating) - break; - } - return null; -} -function atBlockEnd(state, view) { - let { $cursor } = state.selection; - if (!$cursor || (view ? !view.endOfTextblock("forward", state) : $cursor.parentOffset < $cursor.parent.content.size)) - return null; - return $cursor; -} -const joinForward$1 = (state, dispatch, view) => { - let $cursor = atBlockEnd(state, view); - if (!$cursor) - return false; - let $cut = findCutAfter($cursor); - if (!$cut) - return false; - let after = $cut.nodeAfter; - if (deleteBarrier(state, $cut, dispatch, 1)) - return true; - if ($cursor.parent.content.size == 0 && (textblockAt(after, "start") || NodeSelection.isSelectable(after))) { - let delStep = replaceStep(state.doc, $cursor.before(), $cursor.after(), Slice.empty); - if (delStep && delStep.slice.size < delStep.to - delStep.from) { - if (dispatch) { - let tr2 = state.tr.step(delStep); - tr2.setSelection(textblockAt(after, "start") ? Selection.findFrom(tr2.doc.resolve(tr2.mapping.map($cut.pos)), 1) : NodeSelection.create(tr2.doc, tr2.mapping.map($cut.pos))); - dispatch(tr2.scrollIntoView()); - } - return true; - } - } - if (after.isAtom && $cut.depth == $cursor.depth - 1) { - if (dispatch) - dispatch(state.tr.delete($cut.pos, $cut.pos + after.nodeSize).scrollIntoView()); - return true; - } - return false; -}; -const selectNodeForward$1 = (state, dispatch, view) => { - let { $head, empty: empty2 } = state.selection, $cut = $head; - if (!empty2) - return false; - if ($head.parent.isTextblock) { - if (view ? !view.endOfTextblock("forward", state) : $head.parentOffset < $head.parent.content.size) - return false; - $cut = findCutAfter($head); - } - let node = $cut && $cut.nodeAfter; - if (!node || !NodeSelection.isSelectable(node)) - return false; - if (dispatch) - dispatch(state.tr.setSelection(NodeSelection.create(state.doc, $cut.pos)).scrollIntoView()); - return true; -}; -function findCutAfter($pos) { - if (!$pos.parent.type.spec.isolating) - for (let i = $pos.depth - 1; i >= 0; i--) { - let parent = $pos.node(i); - if ($pos.index(i) + 1 < parent.childCount) - return $pos.doc.resolve($pos.after(i + 1)); - if (parent.type.spec.isolating) - break; - } - return null; -} -const joinUp$1 = (state, dispatch) => { - let sel = state.selection, nodeSel = sel instanceof NodeSelection, point; - if (nodeSel) { - if (sel.node.isTextblock || !canJoin(state.doc, sel.from)) - return false; - point = sel.from; - } else { - point = joinPoint(state.doc, sel.from, -1); - if (point == null) - return false; - } - if (dispatch) { - let tr2 = state.tr.join(point); - if (nodeSel) - tr2.setSelection(NodeSelection.create(tr2.doc, point - state.doc.resolve(point).nodeBefore.nodeSize)); - dispatch(tr2.scrollIntoView()); - } - return true; -}; -const joinDown$1 = (state, dispatch) => { - let sel = state.selection, point; - if (sel instanceof NodeSelection) { - if (sel.node.isTextblock || !canJoin(state.doc, sel.to)) - return false; - point = sel.to; - } else { - point = joinPoint(state.doc, sel.to, 1); - if (point == null) - return false; - } - if (dispatch) - dispatch(state.tr.join(point).scrollIntoView()); - return true; -}; -const lift$1 = (state, dispatch) => { - let { $from, $to } = state.selection; - let range = $from.blockRange($to), target = range && liftTarget(range); - if (target == null) - return false; - if (dispatch) - dispatch(state.tr.lift(range, target).scrollIntoView()); - return true; -}; -const newlineInCode$1 = (state, dispatch) => { - let { $head, $anchor } = state.selection; - if (!$head.parent.type.spec.code || !$head.sameParent($anchor)) - return false; - if (dispatch) - dispatch(state.tr.insertText("\n").scrollIntoView()); - return true; -}; -function defaultBlockAt$1(match) { - for (let i = 0; i < match.edgeCount; i++) { - let { type } = match.edge(i); - if (type.isTextblock && !type.hasRequiredAttrs()) - return type; - } - return null; -} -const exitCode$1 = (state, dispatch) => { - let { $head, $anchor } = state.selection; - if (!$head.parent.type.spec.code || !$head.sameParent($anchor)) - return false; - let above = $head.node(-1), after = $head.indexAfter(-1), type = defaultBlockAt$1(above.contentMatchAt(after)); - if (!type || !above.canReplaceWith(after, after, type)) - return false; - if (dispatch) { - let pos = $head.after(), tr2 = state.tr.replaceWith(pos, pos, type.createAndFill()); - tr2.setSelection(Selection.near(tr2.doc.resolve(pos), 1)); - dispatch(tr2.scrollIntoView()); - } - return true; -}; -const createParagraphNear$1 = (state, dispatch) => { - let sel = state.selection, { $from, $to } = sel; - if (sel instanceof AllSelection || $from.parent.inlineContent || $to.parent.inlineContent) - return false; - let type = defaultBlockAt$1($to.parent.contentMatchAt($to.indexAfter())); - if (!type || !type.isTextblock) - return false; - if (dispatch) { - let side = (!$from.parentOffset && $to.index() < $to.parent.childCount ? $from : $to).pos; - let tr2 = state.tr.insert(side, type.createAndFill()); - tr2.setSelection(TextSelection.create(tr2.doc, side + 1)); - dispatch(tr2.scrollIntoView()); - } - return true; -}; -const liftEmptyBlock$1 = (state, dispatch) => { - let { $cursor } = state.selection; - if (!$cursor || $cursor.parent.content.size) - return false; - if ($cursor.depth > 1 && $cursor.after() != $cursor.end(-1)) { - let before = $cursor.before(); - if (canSplit(state.doc, before)) { - if (dispatch) - dispatch(state.tr.split(before).scrollIntoView()); - return true; - } - } - let range = $cursor.blockRange(), target = range && liftTarget(range); - if (target == null) - return false; - if (dispatch) - dispatch(state.tr.lift(range, target).scrollIntoView()); - return true; -}; -function splitBlockAs(splitNode) { - return (state, dispatch) => { - let { $from, $to } = state.selection; - if (state.selection instanceof NodeSelection && state.selection.node.isBlock) { - if (!$from.parentOffset || !canSplit(state.doc, $from.pos)) - return false; - if (dispatch) - dispatch(state.tr.split($from.pos).scrollIntoView()); - return true; - } - if (!$from.depth) - return false; - let types = []; - let splitDepth, deflt, atEnd = false, atStart = false; - for (let d = $from.depth; ; d--) { - let node = $from.node(d); - if (node.isBlock) { - atEnd = $from.end(d) == $from.pos + ($from.depth - d); - atStart = $from.start(d) == $from.pos - ($from.depth - d); - deflt = defaultBlockAt$1($from.node(d - 1).contentMatchAt($from.indexAfter(d - 1))); - types.unshift(atEnd && deflt ? { type: deflt } : null); - splitDepth = d; - break; - } else { - if (d == 1) - return false; - types.unshift(null); - } - } - let tr2 = state.tr; - if (state.selection instanceof TextSelection || state.selection instanceof AllSelection) - tr2.deleteSelection(); - let splitPos = tr2.mapping.map($from.pos); - let can = canSplit(tr2.doc, splitPos, types.length, types); - if (!can) { - types[0] = deflt ? { type: deflt } : null; - can = canSplit(tr2.doc, splitPos, types.length, types); - } - if (!can) - return false; - tr2.split(splitPos, types.length, types); - if (!atEnd && atStart && $from.node(splitDepth).type != deflt) { - let first2 = tr2.mapping.map($from.before(splitDepth)), $first = tr2.doc.resolve(first2); - if (deflt && $from.node(splitDepth - 1).canReplaceWith($first.index(), $first.index() + 1, deflt)) - tr2.setNodeMarkup(tr2.mapping.map($from.before(splitDepth)), deflt); - } - if (dispatch) - dispatch(tr2.scrollIntoView()); - return true; - }; -} -const splitBlock$1 = splitBlockAs(); -const selectParentNode$1 = (state, dispatch) => { - let { $from, to } = state.selection, pos; - let same = $from.sharedDepth(to); - if (same == 0) - return false; - pos = $from.before(same); - if (dispatch) - dispatch(state.tr.setSelection(NodeSelection.create(state.doc, pos))); - return true; -}; -function joinMaybeClear(state, $pos, dispatch) { - let before = $pos.nodeBefore, after = $pos.nodeAfter, index = $pos.index(); - if (!before || !after || !before.type.compatibleContent(after.type)) - return false; - if (!before.content.size && $pos.parent.canReplace(index - 1, index)) { - if (dispatch) - dispatch(state.tr.delete($pos.pos - before.nodeSize, $pos.pos).scrollIntoView()); - return true; - } - if (!$pos.parent.canReplace(index, index + 1) || !(after.isTextblock || canJoin(state.doc, $pos.pos))) - return false; - if (dispatch) - dispatch(state.tr.join($pos.pos).scrollIntoView()); - return true; -} -function deleteBarrier(state, $cut, dispatch, dir) { - let before = $cut.nodeBefore, after = $cut.nodeAfter, conn, match; - let isolated = before.type.spec.isolating || after.type.spec.isolating; - if (!isolated && joinMaybeClear(state, $cut, dispatch)) - return true; - let canDelAfter = !isolated && $cut.parent.canReplace($cut.index(), $cut.index() + 1); - if (canDelAfter && (conn = (match = before.contentMatchAt(before.childCount)).findWrapping(after.type)) && match.matchType(conn[0] || after.type).validEnd) { - if (dispatch) { - let end = $cut.pos + after.nodeSize, wrap2 = Fragment.empty; - for (let i = conn.length - 1; i >= 0; i--) - wrap2 = Fragment.from(conn[i].create(null, wrap2)); - wrap2 = Fragment.from(before.copy(wrap2)); - let tr2 = state.tr.step(new ReplaceAroundStep($cut.pos - 1, end, $cut.pos, end, new Slice(wrap2, 1, 0), conn.length, true)); - let $joinAt = tr2.doc.resolve(end + 2 * conn.length); - if ($joinAt.nodeAfter && $joinAt.nodeAfter.type == before.type && canJoin(tr2.doc, $joinAt.pos)) - tr2.join($joinAt.pos); - dispatch(tr2.scrollIntoView()); - } - return true; - } - let selAfter = after.type.spec.isolating || dir > 0 && isolated ? null : Selection.findFrom($cut, 1); - let range = selAfter && selAfter.$from.blockRange(selAfter.$to), target = range && liftTarget(range); - if (target != null && target >= $cut.depth) { - if (dispatch) - dispatch(state.tr.lift(range, target).scrollIntoView()); - return true; - } - if (canDelAfter && textblockAt(after, "start", true) && textblockAt(before, "end")) { - let at = before, wrap2 = []; - for (; ; ) { - wrap2.push(at); - if (at.isTextblock) - break; - at = at.lastChild; - } - let afterText = after, afterDepth = 1; - for (; !afterText.isTextblock; afterText = afterText.firstChild) - afterDepth++; - if (at.canReplace(at.childCount, at.childCount, afterText.content)) { - if (dispatch) { - let end = Fragment.empty; - for (let i = wrap2.length - 1; i >= 0; i--) - end = Fragment.from(wrap2[i].copy(end)); - let tr2 = state.tr.step(new ReplaceAroundStep($cut.pos - wrap2.length, $cut.pos + after.nodeSize, $cut.pos + afterDepth, $cut.pos + after.nodeSize - afterDepth, new Slice(end, wrap2.length, 0), 0, true)); - dispatch(tr2.scrollIntoView()); - } - return true; - } - } - return false; -} -function selectTextblockSide(side) { - return function(state, dispatch) { - let sel = state.selection, $pos = side < 0 ? sel.$from : sel.$to; - let depth = $pos.depth; - while ($pos.node(depth).isInline) { - if (!depth) - return false; - depth--; - } - if (!$pos.node(depth).isTextblock) - return false; - if (dispatch) - dispatch(state.tr.setSelection(TextSelection.create(state.doc, side < 0 ? $pos.start(depth) : $pos.end(depth)))); - return true; - }; -} -const selectTextblockStart$1 = selectTextblockSide(-1); -const selectTextblockEnd$1 = selectTextblockSide(1); -function wrapIn$1(nodeType, attrs = null) { - return function(state, dispatch) { - let { $from, $to } = state.selection; - let range = $from.blockRange($to), wrapping = range && findWrapping(range, nodeType, attrs); - if (!wrapping) - return false; - if (dispatch) - dispatch(state.tr.wrap(range, wrapping).scrollIntoView()); - return true; - }; -} -function setBlockType(nodeType, attrs = null) { - return function(state, dispatch) { - let applicable = false; - for (let i = 0; i < state.selection.ranges.length && !applicable; i++) { - let { $from: { pos: from2 }, $to: { pos: to } } = state.selection.ranges[i]; - state.doc.nodesBetween(from2, to, (node, pos) => { - if (applicable) - return false; - if (!node.isTextblock || node.hasMarkup(nodeType, attrs)) - return; - if (node.type == nodeType) { - applicable = true; - } else { - let $pos = state.doc.resolve(pos), index = $pos.index(); - applicable = $pos.parent.canReplaceWith(index, index + 1, nodeType); - } - }); - } - if (!applicable) - return false; - if (dispatch) { - let tr2 = state.tr; - for (let i = 0; i < state.selection.ranges.length; i++) { - let { $from: { pos: from2 }, $to: { pos: to } } = state.selection.ranges[i]; - tr2.setBlockType(from2, to, nodeType, attrs); - } - dispatch(tr2.scrollIntoView()); - } - return true; - }; -} -function chainCommands(...commands) { - return function(state, dispatch, view) { - for (let i = 0; i < commands.length; i++) - if (commands[i](state, dispatch, view)) - return true; - return false; - }; -} -chainCommands(deleteSelection$1, joinBackward$1, selectNodeBackward$1); -chainCommands(deleteSelection$1, joinForward$1, selectNodeForward$1); -({ - "Enter": chainCommands(newlineInCode$1, createParagraphNear$1, liftEmptyBlock$1, splitBlock$1) -}); -typeof navigator != "undefined" ? /Mac|iP(hone|[oa]d)/.test(navigator.platform) : typeof os != "undefined" && os.platform ? os.platform() == "darwin" : false; -function wrapInList$1(listType, attrs = null) { - return function(state, dispatch) { - let { $from, $to } = state.selection; - let range = $from.blockRange($to); - if (!range) - return false; - let tr2 = dispatch ? state.tr : null; - if (!wrapRangeInList(tr2, range, listType, attrs)) - return false; - if (dispatch) - dispatch(tr2.scrollIntoView()); - return true; - }; -} -function wrapRangeInList(tr2, range, listType, attrs = null) { - let doJoin = false, outerRange = range, doc2 = range.$from.doc; - if (range.depth >= 2 && range.$from.node(range.depth - 1).type.compatibleContent(listType) && range.startIndex == 0) { - if (range.$from.index(range.depth - 1) == 0) - return false; - let $insert = doc2.resolve(range.start - 2); - outerRange = new NodeRange($insert, $insert, range.depth); - if (range.endIndex < range.parent.childCount) - range = new NodeRange(range.$from, doc2.resolve(range.$to.end(range.depth)), range.depth); - doJoin = true; - } - let wrap2 = findWrapping(outerRange, listType, attrs, range); - if (!wrap2) - return false; - if (tr2) - doWrapInList(tr2, range, wrap2, doJoin, listType); - return true; -} -function doWrapInList(tr2, range, wrappers, joinBefore, listType) { - let content = Fragment.empty; - for (let i = wrappers.length - 1; i >= 0; i--) - content = Fragment.from(wrappers[i].type.create(wrappers[i].attrs, content)); - tr2.step(new ReplaceAroundStep(range.start - (joinBefore ? 2 : 0), range.end, range.start, range.end, new Slice(content, 0, 0), wrappers.length, true)); - let found2 = 0; - for (let i = 0; i < wrappers.length; i++) - if (wrappers[i].type == listType) - found2 = i + 1; - let splitDepth = wrappers.length - found2; - let splitPos = range.start + wrappers.length - (joinBefore ? 2 : 0), parent = range.parent; - for (let i = range.startIndex, e = range.endIndex, first2 = true; i < e; i++, first2 = false) { - if (!first2 && canSplit(tr2.doc, splitPos, splitDepth)) { - tr2.split(splitPos, splitDepth); - splitPos += 2 * splitDepth; - } - splitPos += parent.child(i).nodeSize; - } - return tr2; -} -function liftListItem$1(itemType) { - return function(state, dispatch) { - let { $from, $to } = state.selection; - let range = $from.blockRange($to, (node) => node.childCount > 0 && node.firstChild.type == itemType); - if (!range) - return false; - if (!dispatch) - return true; - if ($from.node(range.depth - 1).type == itemType) - return liftToOuterList(state, dispatch, itemType, range); - else - return liftOutOfList(state, dispatch, range); - }; -} -function liftToOuterList(state, dispatch, itemType, range) { - let tr2 = state.tr, end = range.end, endOfList = range.$to.end(range.depth); - if (end < endOfList) { - tr2.step(new ReplaceAroundStep(end - 1, endOfList, end, endOfList, new Slice(Fragment.from(itemType.create(null, range.parent.copy())), 1, 0), 1, true)); - range = new NodeRange(tr2.doc.resolve(range.$from.pos), tr2.doc.resolve(endOfList), range.depth); - } - const target = liftTarget(range); - if (target == null) - return false; - tr2.lift(range, target); - let $after = tr2.doc.resolve(tr2.mapping.map(end, -1) - 1); - if (canJoin(tr2.doc, $after.pos) && $after.nodeBefore.type == $after.nodeAfter.type) - tr2.join($after.pos); - dispatch(tr2.scrollIntoView()); - return true; -} -function liftOutOfList(state, dispatch, range) { - let tr2 = state.tr, list = range.parent; - for (let pos = range.end, i = range.endIndex - 1, e = range.startIndex; i > e; i--) { - pos -= list.child(i).nodeSize; - tr2.delete(pos - 1, pos + 1); - } - let $start = tr2.doc.resolve(range.start), item = $start.nodeAfter; - if (tr2.mapping.map(range.end) != range.start + $start.nodeAfter.nodeSize) - return false; - let atStart = range.startIndex == 0, atEnd = range.endIndex == list.childCount; - let parent = $start.node(-1), indexBefore = $start.index(-1); - if (!parent.canReplace(indexBefore + (atStart ? 0 : 1), indexBefore + 1, item.content.append(atEnd ? Fragment.empty : Fragment.from(list)))) - return false; - let start = $start.pos, end = start + item.nodeSize; - tr2.step(new ReplaceAroundStep(start - (atStart ? 1 : 0), end + (atEnd ? 1 : 0), start + 1, end - 1, new Slice((atStart ? Fragment.empty : Fragment.from(list.copy(Fragment.empty))).append(atEnd ? Fragment.empty : Fragment.from(list.copy(Fragment.empty))), atStart ? 0 : 1, atEnd ? 0 : 1), atStart ? 0 : 1)); - dispatch(tr2.scrollIntoView()); - return true; -} -function sinkListItem$1(itemType) { - return function(state, dispatch) { - let { $from, $to } = state.selection; - let range = $from.blockRange($to, (node) => node.childCount > 0 && node.firstChild.type == itemType); - if (!range) - return false; - let startIndex = range.startIndex; - if (startIndex == 0) - return false; - let parent = range.parent, nodeBefore = parent.child(startIndex - 1); - if (nodeBefore.type != itemType) - return false; - if (dispatch) { - let nestedBefore = nodeBefore.lastChild && nodeBefore.lastChild.type == parent.type; - let inner = Fragment.from(nestedBefore ? itemType.create() : null); - let slice2 = new Slice(Fragment.from(itemType.create(null, Fragment.from(parent.type.create(null, inner)))), nestedBefore ? 3 : 1, 0); - let before = range.start, after = range.end; - dispatch(state.tr.step(new ReplaceAroundStep(before - (nestedBefore ? 3 : 1), after, before, after, slice2, 1, true)).scrollIntoView()); - } - return true; - }; -} -const domIndex = function(node) { - for (var index = 0; ; index++) { - node = node.previousSibling; - if (!node) - return index; - } -}; -const parentNode = function(node) { - let parent = node.assignedSlot || node.parentNode; - return parent && parent.nodeType == 11 ? parent.host : parent; -}; -let reusedRange = null; -const textRange = function(node, from2, to) { - let range = reusedRange || (reusedRange = document.createRange()); - range.setEnd(node, to == null ? node.nodeValue.length : to); - range.setStart(node, from2 || 0); - return range; -}; -const clearReusedRange = function() { - reusedRange = null; -}; -const isEquivalentPosition = function(node, off, targetNode, targetOff) { - return targetNode && (scanFor(node, off, targetNode, targetOff, -1) || scanFor(node, off, targetNode, targetOff, 1)); -}; -const atomElements = /^(img|br|input|textarea|hr)$/i; -function scanFor(node, off, targetNode, targetOff, dir) { - var _a; - for (; ; ) { - if (node == targetNode && off == targetOff) - return true; - if (off == (dir < 0 ? 0 : nodeSize(node))) { - let parent = node.parentNode; - if (!parent || parent.nodeType != 1 || hasBlockDesc(node) || atomElements.test(node.nodeName) || node.contentEditable == "false") - return false; - off = domIndex(node) + (dir < 0 ? 0 : 1); - node = parent; - } else if (node.nodeType == 1) { - let child = node.childNodes[off + (dir < 0 ? -1 : 0)]; - if (child.nodeType == 1 && child.contentEditable == "false") { - if ((_a = child.pmViewDesc) === null || _a === void 0 ? void 0 : _a.ignoreForSelection) - off += dir; - else - return false; - } else { - node = child; - off = dir < 0 ? nodeSize(node) : 0; - } - } else { - return false; - } - } -} -function nodeSize(node) { - return node.nodeType == 3 ? node.nodeValue.length : node.childNodes.length; -} -function textNodeBefore$1(node, offset) { - for (; ; ) { - if (node.nodeType == 3 && offset) - return node; - if (node.nodeType == 1 && offset > 0) { - if (node.contentEditable == "false") - return null; - node = node.childNodes[offset - 1]; - offset = nodeSize(node); - } else if (node.parentNode && !hasBlockDesc(node)) { - offset = domIndex(node); - node = node.parentNode; - } else { - return null; - } - } -} -function textNodeAfter$1(node, offset) { - for (; ; ) { - if (node.nodeType == 3 && offset < node.nodeValue.length) - return node; - if (node.nodeType == 1 && offset < node.childNodes.length) { - if (node.contentEditable == "false") - return null; - node = node.childNodes[offset]; - offset = 0; - } else if (node.parentNode && !hasBlockDesc(node)) { - offset = domIndex(node) + 1; - node = node.parentNode; - } else { - return null; - } - } -} -function isOnEdge(node, offset, parent) { - for (let atStart = offset == 0, atEnd = offset == nodeSize(node); atStart || atEnd; ) { - if (node == parent) - return true; - let index = domIndex(node); - node = node.parentNode; - if (!node) - return false; - atStart = atStart && index == 0; - atEnd = atEnd && index == nodeSize(node); - } -} -function hasBlockDesc(dom) { - let desc; - for (let cur = dom; cur; cur = cur.parentNode) - if (desc = cur.pmViewDesc) - break; - return desc && desc.node && desc.node.isBlock && (desc.dom == dom || desc.contentDOM == dom); -} -const selectionCollapsed = function(domSel) { - return domSel.focusNode && isEquivalentPosition(domSel.focusNode, domSel.focusOffset, domSel.anchorNode, domSel.anchorOffset); -}; -function keyEvent(keyCode, key) { - let event = document.createEvent("Event"); - event.initEvent("keydown", true, true); - event.keyCode = keyCode; - event.key = event.code = key; - return event; -} -function deepActiveElement(doc2) { - let elt = doc2.activeElement; - while (elt && elt.shadowRoot) - elt = elt.shadowRoot.activeElement; - return elt; -} -function caretFromPoint(doc2, x, y) { - if (doc2.caretPositionFromPoint) { - try { - let pos = doc2.caretPositionFromPoint(x, y); - if (pos) - return { node: pos.offsetNode, offset: Math.min(nodeSize(pos.offsetNode), pos.offset) }; - } catch (_) { - } - } - if (doc2.caretRangeFromPoint) { - let range = doc2.caretRangeFromPoint(x, y); - if (range) - return { node: range.startContainer, offset: Math.min(nodeSize(range.startContainer), range.startOffset) }; - } -} -const nav = typeof navigator != "undefined" ? navigator : null; -const doc = typeof document != "undefined" ? document : null; -const agent = nav && nav.userAgent || ""; -const ie_edge = /Edge\/(\d+)/.exec(agent); -const ie_upto10 = /MSIE \d/.exec(agent); -const ie_11up = /Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(agent); -const ie$1 = !!(ie_upto10 || ie_11up || ie_edge); -const ie_version = ie_upto10 ? document.documentMode : ie_11up ? +ie_11up[1] : ie_edge ? +ie_edge[1] : 0; -const gecko = !ie$1 && /gecko\/(\d+)/i.test(agent); -gecko && +(/Firefox\/(\d+)/.exec(agent) || [0, 0])[1]; -const _chrome = !ie$1 && /Chrome\/(\d+)/.exec(agent); -const chrome = !!_chrome; -const chrome_version = _chrome ? +_chrome[1] : 0; -const safari = !ie$1 && !!nav && /Apple Computer/.test(nav.vendor); -const ios = safari && (/Mobile\/\w+/.test(agent) || !!nav && nav.maxTouchPoints > 2); -const mac$2 = ios || (nav ? /Mac/.test(nav.platform) : false); -const windows$1 = nav ? /Win/.test(nav.platform) : false; -const android = /Android \d/.test(agent); -const webkit = !!doc && "webkitFontSmoothing" in doc.documentElement.style; -const webkit_version = webkit ? +(/\bAppleWebKit\/(\d+)/.exec(navigator.userAgent) || [0, 0])[1] : 0; -function windowRect(doc2) { - let vp = doc2.defaultView && doc2.defaultView.visualViewport; - if (vp) - return { - left: 0, - right: vp.width, - top: 0, - bottom: vp.height - }; - return { - left: 0, - right: doc2.documentElement.clientWidth, - top: 0, - bottom: doc2.documentElement.clientHeight - }; -} -function getSide(value, side) { - return typeof value == "number" ? value : value[side]; -} -function clientRect(node) { - let rect = node.getBoundingClientRect(); - let scaleX = rect.width / node.offsetWidth || 1; - let scaleY = rect.height / node.offsetHeight || 1; - return { - left: rect.left, - right: rect.left + node.clientWidth * scaleX, - top: rect.top, - bottom: rect.top + node.clientHeight * scaleY - }; -} -function scrollRectIntoView(view, rect, startDOM) { - let scrollThreshold = view.someProp("scrollThreshold") || 0, scrollMargin = view.someProp("scrollMargin") || 5; - let doc2 = view.dom.ownerDocument; - for (let parent = startDOM || view.dom; ; ) { - if (!parent) - break; - if (parent.nodeType != 1) { - parent = parentNode(parent); - continue; - } - let elt = parent; - let atTop = elt == doc2.body; - let bounding = atTop ? windowRect(doc2) : clientRect(elt); - let moveX = 0, moveY = 0; - if (rect.top < bounding.top + getSide(scrollThreshold, "top")) - moveY = -(bounding.top - rect.top + getSide(scrollMargin, "top")); - else if (rect.bottom > bounding.bottom - getSide(scrollThreshold, "bottom")) - moveY = rect.bottom - rect.top > bounding.bottom - bounding.top ? rect.top + getSide(scrollMargin, "top") - bounding.top : rect.bottom - bounding.bottom + getSide(scrollMargin, "bottom"); - if (rect.left < bounding.left + getSide(scrollThreshold, "left")) - moveX = -(bounding.left - rect.left + getSide(scrollMargin, "left")); - else if (rect.right > bounding.right - getSide(scrollThreshold, "right")) - moveX = rect.right - bounding.right + getSide(scrollMargin, "right"); - if (moveX || moveY) { - if (atTop) { - doc2.defaultView.scrollBy(moveX, moveY); - } else { - let startX = elt.scrollLeft, startY = elt.scrollTop; - if (moveY) - elt.scrollTop += moveY; - if (moveX) - elt.scrollLeft += moveX; - let dX = elt.scrollLeft - startX, dY = elt.scrollTop - startY; - rect = { left: rect.left - dX, top: rect.top - dY, right: rect.right - dX, bottom: rect.bottom - dY }; - } - } - let pos = atTop ? "fixed" : getComputedStyle(parent).position; - if (/^(fixed|sticky)$/.test(pos)) - break; - parent = pos == "absolute" ? parent.offsetParent : parentNode(parent); - } -} -function storeScrollPos(view) { - let rect = view.dom.getBoundingClientRect(), startY = Math.max(0, rect.top); - let refDOM, refTop; - for (let x = (rect.left + rect.right) / 2, y = startY + 1; y < Math.min(innerHeight, rect.bottom); y += 5) { - let dom = view.root.elementFromPoint(x, y); - if (!dom || dom == view.dom || !view.dom.contains(dom)) - continue; - let localRect = dom.getBoundingClientRect(); - if (localRect.top >= startY - 20) { - refDOM = dom; - refTop = localRect.top; - break; - } - } - return { refDOM, refTop, stack: scrollStack(view.dom) }; -} -function scrollStack(dom) { - let stack = [], doc2 = dom.ownerDocument; - for (let cur = dom; cur; cur = parentNode(cur)) { - stack.push({ dom: cur, top: cur.scrollTop, left: cur.scrollLeft }); - if (dom == doc2) - break; - } - return stack; -} -function resetScrollPos({ refDOM, refTop, stack }) { - let newRefTop = refDOM ? refDOM.getBoundingClientRect().top : 0; - restoreScrollStack(stack, newRefTop == 0 ? 0 : newRefTop - refTop); -} -function restoreScrollStack(stack, dTop) { - for (let i = 0; i < stack.length; i++) { - let { dom, top, left } = stack[i]; - if (dom.scrollTop != top + dTop) - dom.scrollTop = top + dTop; - if (dom.scrollLeft != left) - dom.scrollLeft = left; - } -} -let preventScrollSupported = null; -function focusPreventScroll(dom) { - if (dom.setActive) - return dom.setActive(); - if (preventScrollSupported) - return dom.focus(preventScrollSupported); - let stored = scrollStack(dom); - dom.focus(preventScrollSupported == null ? { - get preventScroll() { - preventScrollSupported = { preventScroll: true }; - return true; - } - } : void 0); - if (!preventScrollSupported) { - preventScrollSupported = false; - restoreScrollStack(stored, 0); - } -} -function findOffsetInNode(node, coords) { - let closest, dxClosest = 2e8, coordsClosest, offset = 0; - let rowBot = coords.top, rowTop = coords.top; - let firstBelow, coordsBelow; - for (let child = node.firstChild, childIndex = 0; child; child = child.nextSibling, childIndex++) { - let rects; - if (child.nodeType == 1) - rects = child.getClientRects(); - else if (child.nodeType == 3) - rects = textRange(child).getClientRects(); - else - continue; - for (let i = 0; i < rects.length; i++) { - let rect = rects[i]; - if (rect.top <= rowBot && rect.bottom >= rowTop) { - rowBot = Math.max(rect.bottom, rowBot); - rowTop = Math.min(rect.top, rowTop); - let dx = rect.left > coords.left ? rect.left - coords.left : rect.right < coords.left ? coords.left - rect.right : 0; - if (dx < dxClosest) { - closest = child; - dxClosest = dx; - coordsClosest = dx && closest.nodeType == 3 ? { - left: rect.right < coords.left ? rect.right : rect.left, - top: coords.top - } : coords; - if (child.nodeType == 1 && dx) - offset = childIndex + (coords.left >= (rect.left + rect.right) / 2 ? 1 : 0); - continue; - } - } else if (rect.top > coords.top && !firstBelow && rect.left <= coords.left && rect.right >= coords.left) { - firstBelow = child; - coordsBelow = { left: Math.max(rect.left, Math.min(rect.right, coords.left)), top: rect.top }; - } - if (!closest && (coords.left >= rect.right && coords.top >= rect.top || coords.left >= rect.left && coords.top >= rect.bottom)) - offset = childIndex + 1; - } - } - if (!closest && firstBelow) { - closest = firstBelow; - coordsClosest = coordsBelow; - dxClosest = 0; - } - if (closest && closest.nodeType == 3) - return findOffsetInText(closest, coordsClosest); - if (!closest || dxClosest && closest.nodeType == 1) - return { node, offset }; - return findOffsetInNode(closest, coordsClosest); -} -function findOffsetInText(node, coords) { - let len = node.nodeValue.length; - let range = document.createRange(), result; - for (let i = 0; i < len; i++) { - range.setEnd(node, i + 1); - range.setStart(node, i); - let rect = singleRect(range, 1); - if (rect.top == rect.bottom) - continue; - if (inRect(coords, rect)) { - result = { node, offset: i + (coords.left >= (rect.left + rect.right) / 2 ? 1 : 0) }; - break; - } - } - range.detach(); - return result || { node, offset: 0 }; -} -function inRect(coords, rect) { - return coords.left >= rect.left - 1 && coords.left <= rect.right + 1 && coords.top >= rect.top - 1 && coords.top <= rect.bottom + 1; -} -function targetKludge(dom, coords) { - let parent = dom.parentNode; - if (parent && /^li$/i.test(parent.nodeName) && coords.left < dom.getBoundingClientRect().left) - return parent; - return dom; -} -function posFromElement(view, elt, coords) { - let { node, offset } = findOffsetInNode(elt, coords), bias = -1; - if (node.nodeType == 1 && !node.firstChild) { - let rect = node.getBoundingClientRect(); - bias = rect.left != rect.right && coords.left > (rect.left + rect.right) / 2 ? 1 : -1; - } - return view.docView.posFromDOM(node, offset, bias); -} -function posFromCaret(view, node, offset, coords) { - let outsideBlock = -1; - for (let cur = node, sawBlock = false; ; ) { - if (cur == view.dom) - break; - let desc = view.docView.nearestDesc(cur, true), rect; - if (!desc) - return null; - if (desc.dom.nodeType == 1 && (desc.node.isBlock && desc.parent || !desc.contentDOM) && // Ignore elements with zero-size bounding rectangles - ((rect = desc.dom.getBoundingClientRect()).width || rect.height)) { - if (desc.node.isBlock && desc.parent && !/^T(R|BODY|HEAD|FOOT)$/.test(desc.dom.nodeName)) { - if (!sawBlock && rect.left > coords.left || rect.top > coords.top) - outsideBlock = desc.posBefore; - else if (!sawBlock && rect.right < coords.left || rect.bottom < coords.top) - outsideBlock = desc.posAfter; - sawBlock = true; - } - if (!desc.contentDOM && outsideBlock < 0 && !desc.node.isText) { - let before = desc.node.isBlock ? coords.top < (rect.top + rect.bottom) / 2 : coords.left < (rect.left + rect.right) / 2; - return before ? desc.posBefore : desc.posAfter; - } - } - cur = desc.dom.parentNode; - } - return outsideBlock > -1 ? outsideBlock : view.docView.posFromDOM(node, offset, -1); -} -function elementFromPoint(element, coords, box) { - let len = element.childNodes.length; - if (len && box.top < box.bottom) { - for (let startI = Math.max(0, Math.min(len - 1, Math.floor(len * (coords.top - box.top) / (box.bottom - box.top)) - 2)), i = startI; ; ) { - let child = element.childNodes[i]; - if (child.nodeType == 1) { - let rects = child.getClientRects(); - for (let j = 0; j < rects.length; j++) { - let rect = rects[j]; - if (inRect(coords, rect)) - return elementFromPoint(child, coords, rect); - } - } - if ((i = (i + 1) % len) == startI) - break; - } - } - return element; -} -function posAtCoords(view, coords) { - let doc2 = view.dom.ownerDocument, node, offset = 0; - let caret = caretFromPoint(doc2, coords.left, coords.top); - if (caret) - ({ node, offset } = caret); - let elt = (view.root.elementFromPoint ? view.root : doc2).elementFromPoint(coords.left, coords.top); - let pos; - if (!elt || !view.dom.contains(elt.nodeType != 1 ? elt.parentNode : elt)) { - let box = view.dom.getBoundingClientRect(); - if (!inRect(coords, box)) - return null; - elt = elementFromPoint(view.dom, coords, box); - if (!elt) - return null; - } - if (safari) { - for (let p = elt; node && p; p = parentNode(p)) - if (p.draggable) - node = void 0; - } - elt = targetKludge(elt, coords); - if (node) { - if (gecko && node.nodeType == 1) { - offset = Math.min(offset, node.childNodes.length); - if (offset < node.childNodes.length) { - let next = node.childNodes[offset], box; - if (next.nodeName == "IMG" && (box = next.getBoundingClientRect()).right <= coords.left && box.bottom > coords.top) - offset++; - } - } - let prev; - if (webkit && offset && node.nodeType == 1 && (prev = node.childNodes[offset - 1]).nodeType == 1 && prev.contentEditable == "false" && prev.getBoundingClientRect().top >= coords.top) - offset--; - if (node == view.dom && offset == node.childNodes.length - 1 && node.lastChild.nodeType == 1 && coords.top > node.lastChild.getBoundingClientRect().bottom) - pos = view.state.doc.content.size; - else if (offset == 0 || node.nodeType != 1 || node.childNodes[offset - 1].nodeName != "BR") - pos = posFromCaret(view, node, offset, coords); - } - if (pos == null) - pos = posFromElement(view, elt, coords); - let desc = view.docView.nearestDesc(elt, true); - return { pos, inside: desc ? desc.posAtStart - desc.border : -1 }; -} -function nonZero(rect) { - return rect.top < rect.bottom || rect.left < rect.right; -} -function singleRect(target, bias) { - let rects = target.getClientRects(); - if (rects.length) { - let first2 = rects[bias < 0 ? 0 : rects.length - 1]; - if (nonZero(first2)) - return first2; - } - return Array.prototype.find.call(rects, nonZero) || target.getBoundingClientRect(); -} -const BIDI = /[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/; -function coordsAtPos(view, pos, side) { - let { node, offset, atom } = view.docView.domFromPos(pos, side < 0 ? -1 : 1); - let supportEmptyRange = webkit || gecko; - if (node.nodeType == 3) { - if (supportEmptyRange && (BIDI.test(node.nodeValue) || (side < 0 ? !offset : offset == node.nodeValue.length))) { - let rect = singleRect(textRange(node, offset, offset), side); - if (gecko && offset && /\s/.test(node.nodeValue[offset - 1]) && offset < node.nodeValue.length) { - let rectBefore = singleRect(textRange(node, offset - 1, offset - 1), -1); - if (rectBefore.top == rect.top) { - let rectAfter = singleRect(textRange(node, offset, offset + 1), -1); - if (rectAfter.top != rect.top) - return flattenV(rectAfter, rectAfter.left < rectBefore.left); - } - } - return rect; - } else { - let from2 = offset, to = offset, takeSide = side < 0 ? 1 : -1; - if (side < 0 && !offset) { - to++; - takeSide = -1; - } else if (side >= 0 && offset == node.nodeValue.length) { - from2--; - takeSide = 1; - } else if (side < 0) { - from2--; - } else { - to++; - } - return flattenV(singleRect(textRange(node, from2, to), takeSide), takeSide < 0); - } - } - let $dom = view.state.doc.resolve(pos - (atom || 0)); - if (!$dom.parent.inlineContent) { - if (atom == null && offset && (side < 0 || offset == nodeSize(node))) { - let before = node.childNodes[offset - 1]; - if (before.nodeType == 1) - return flattenH(before.getBoundingClientRect(), false); - } - if (atom == null && offset < nodeSize(node)) { - let after = node.childNodes[offset]; - if (after.nodeType == 1) - return flattenH(after.getBoundingClientRect(), true); - } - return flattenH(node.getBoundingClientRect(), side >= 0); - } - if (atom == null && offset && (side < 0 || offset == nodeSize(node))) { - let before = node.childNodes[offset - 1]; - let target = before.nodeType == 3 ? textRange(before, nodeSize(before) - (supportEmptyRange ? 0 : 1)) : before.nodeType == 1 && (before.nodeName != "BR" || !before.nextSibling) ? before : null; - if (target) - return flattenV(singleRect(target, 1), false); - } - if (atom == null && offset < nodeSize(node)) { - let after = node.childNodes[offset]; - while (after.pmViewDesc && after.pmViewDesc.ignoreForCoords) - after = after.nextSibling; - let target = !after ? null : after.nodeType == 3 ? textRange(after, 0, supportEmptyRange ? 0 : 1) : after.nodeType == 1 ? after : null; - if (target) - return flattenV(singleRect(target, -1), true); - } - return flattenV(singleRect(node.nodeType == 3 ? textRange(node) : node, -side), side >= 0); -} -function flattenV(rect, left) { - if (rect.width == 0) - return rect; - let x = left ? rect.left : rect.right; - return { top: rect.top, bottom: rect.bottom, left: x, right: x }; -} -function flattenH(rect, top) { - if (rect.height == 0) - return rect; - let y = top ? rect.top : rect.bottom; - return { top: y, bottom: y, left: rect.left, right: rect.right }; -} -function withFlushedState(view, state, f) { - let viewState = view.state, active = view.root.activeElement; - if (viewState != state) - view.updateState(state); - if (active != view.dom) - view.focus(); - try { - return f(); - } finally { - if (viewState != state) - view.updateState(viewState); - if (active != view.dom && active) - active.focus(); - } -} -function endOfTextblockVertical(view, state, dir) { - let sel = state.selection; - let $pos = dir == "up" ? sel.$from : sel.$to; - return withFlushedState(view, state, () => { - let { node: dom } = view.docView.domFromPos($pos.pos, dir == "up" ? -1 : 1); - for (; ; ) { - let nearest = view.docView.nearestDesc(dom, true); - if (!nearest) - break; - if (nearest.node.isBlock) { - dom = nearest.contentDOM || nearest.dom; - break; - } - dom = nearest.dom.parentNode; - } - let coords = coordsAtPos(view, $pos.pos, 1); - for (let child = dom.firstChild; child; child = child.nextSibling) { - let boxes; - if (child.nodeType == 1) - boxes = child.getClientRects(); - else if (child.nodeType == 3) - boxes = textRange(child, 0, child.nodeValue.length).getClientRects(); - else - continue; - for (let i = 0; i < boxes.length; i++) { - let box = boxes[i]; - if (box.bottom > box.top + 1 && (dir == "up" ? coords.top - box.top > (box.bottom - coords.top) * 2 : box.bottom - coords.bottom > (coords.bottom - box.top) * 2)) - return false; - } - } - return true; - }); -} -const maybeRTL = /[\u0590-\u08ac]/; -function endOfTextblockHorizontal(view, state, dir) { - let { $head } = state.selection; - if (!$head.parent.isTextblock) - return false; - let offset = $head.parentOffset, atStart = !offset, atEnd = offset == $head.parent.content.size; - let sel = view.domSelection(); - if (!sel) - return $head.pos == $head.start() || $head.pos == $head.end(); - if (!maybeRTL.test($head.parent.textContent) || !sel.modify) - return dir == "left" || dir == "backward" ? atStart : atEnd; - return withFlushedState(view, state, () => { - let { focusNode: oldNode, focusOffset: oldOff, anchorNode, anchorOffset } = view.domSelectionRange(); - let oldBidiLevel = sel.caretBidiLevel; - sel.modify("move", dir, "character"); - let parentDOM = $head.depth ? view.docView.domAfterPos($head.before()) : view.dom; - let { focusNode: newNode, focusOffset: newOff } = view.domSelectionRange(); - let result = newNode && !parentDOM.contains(newNode.nodeType == 1 ? newNode : newNode.parentNode) || oldNode == newNode && oldOff == newOff; - try { - sel.collapse(anchorNode, anchorOffset); - if (oldNode && (oldNode != anchorNode || oldOff != anchorOffset) && sel.extend) - sel.extend(oldNode, oldOff); - } catch (_) { - } - if (oldBidiLevel != null) - sel.caretBidiLevel = oldBidiLevel; - return result; - }); -} -let cachedState = null; -let cachedDir = null; -let cachedResult = false; -function endOfTextblock(view, state, dir) { - if (cachedState == state && cachedDir == dir) - return cachedResult; - cachedState = state; - cachedDir = dir; - return cachedResult = dir == "up" || dir == "down" ? endOfTextblockVertical(view, state, dir) : endOfTextblockHorizontal(view, state, dir); -} -const NOT_DIRTY = 0, CHILD_DIRTY = 1, CONTENT_DIRTY = 2, NODE_DIRTY = 3; -class ViewDesc { - constructor(parent, children, dom, contentDOM) { - this.parent = parent; - this.children = children; - this.dom = dom; - this.contentDOM = contentDOM; - this.dirty = NOT_DIRTY; - dom.pmViewDesc = this; - } - // Used to check whether a given description corresponds to a - // widget/mark/node. - matchesWidget(widget) { - return false; - } - matchesMark(mark) { - return false; - } - matchesNode(node, outerDeco, innerDeco) { - return false; - } - matchesHack(nodeName) { - return false; - } - // When parsing in-editor content (in domchange.js), we allow - // descriptions to determine the parse rules that should be used to - // parse them. - parseRule() { - return null; - } - // Used by the editor's event handler to ignore events that come - // from certain descs. - stopEvent(event) { - return false; - } - // The size of the content represented by this desc. - get size() { - let size = 0; - for (let i = 0; i < this.children.length; i++) - size += this.children[i].size; - return size; - } - // For block nodes, this represents the space taken up by their - // start/end tokens. - get border() { - return 0; - } - destroy() { - this.parent = void 0; - if (this.dom.pmViewDesc == this) - this.dom.pmViewDesc = void 0; - for (let i = 0; i < this.children.length; i++) - this.children[i].destroy(); - } - posBeforeChild(child) { - for (let i = 0, pos = this.posAtStart; ; i++) { - let cur = this.children[i]; - if (cur == child) - return pos; - pos += cur.size; - } - } - get posBefore() { - return this.parent.posBeforeChild(this); - } - get posAtStart() { - return this.parent ? this.parent.posBeforeChild(this) + this.border : 0; - } - get posAfter() { - return this.posBefore + this.size; - } - get posAtEnd() { - return this.posAtStart + this.size - 2 * this.border; - } - localPosFromDOM(dom, offset, bias) { - if (this.contentDOM && this.contentDOM.contains(dom.nodeType == 1 ? dom : dom.parentNode)) { - if (bias < 0) { - let domBefore, desc; - if (dom == this.contentDOM) { - domBefore = dom.childNodes[offset - 1]; - } else { - while (dom.parentNode != this.contentDOM) - dom = dom.parentNode; - domBefore = dom.previousSibling; - } - while (domBefore && !((desc = domBefore.pmViewDesc) && desc.parent == this)) - domBefore = domBefore.previousSibling; - return domBefore ? this.posBeforeChild(desc) + desc.size : this.posAtStart; - } else { - let domAfter, desc; - if (dom == this.contentDOM) { - domAfter = dom.childNodes[offset]; - } else { - while (dom.parentNode != this.contentDOM) - dom = dom.parentNode; - domAfter = dom.nextSibling; - } - while (domAfter && !((desc = domAfter.pmViewDesc) && desc.parent == this)) - domAfter = domAfter.nextSibling; - return domAfter ? this.posBeforeChild(desc) : this.posAtEnd; - } - } - let atEnd; - if (dom == this.dom && this.contentDOM) { - atEnd = offset > domIndex(this.contentDOM); - } else if (this.contentDOM && this.contentDOM != this.dom && this.dom.contains(this.contentDOM)) { - atEnd = dom.compareDocumentPosition(this.contentDOM) & 2; - } else if (this.dom.firstChild) { - if (offset == 0) - for (let search = dom; ; search = search.parentNode) { - if (search == this.dom) { - atEnd = false; - break; - } - if (search.previousSibling) - break; - } - if (atEnd == null && offset == dom.childNodes.length) - for (let search = dom; ; search = search.parentNode) { - if (search == this.dom) { - atEnd = true; - break; - } - if (search.nextSibling) - break; - } - } - return (atEnd == null ? bias > 0 : atEnd) ? this.posAtEnd : this.posAtStart; - } - nearestDesc(dom, onlyNodes = false) { - for (let first2 = true, cur = dom; cur; cur = cur.parentNode) { - let desc = this.getDesc(cur), nodeDOM; - if (desc && (!onlyNodes || desc.node)) { - if (first2 && (nodeDOM = desc.nodeDOM) && !(nodeDOM.nodeType == 1 ? nodeDOM.contains(dom.nodeType == 1 ? dom : dom.parentNode) : nodeDOM == dom)) - first2 = false; - else - return desc; - } - } - } - getDesc(dom) { - let desc = dom.pmViewDesc; - for (let cur = desc; cur; cur = cur.parent) - if (cur == this) - return desc; - } - posFromDOM(dom, offset, bias) { - for (let scan = dom; scan; scan = scan.parentNode) { - let desc = this.getDesc(scan); - if (desc) - return desc.localPosFromDOM(dom, offset, bias); - } - return -1; - } - // Find the desc for the node after the given pos, if any. (When a - // parent node overrode rendering, there might not be one.) - descAt(pos) { - for (let i = 0, offset = 0; i < this.children.length; i++) { - let child = this.children[i], end = offset + child.size; - if (offset == pos && end != offset) { - while (!child.border && child.children.length) { - for (let i2 = 0; i2 < child.children.length; i2++) { - let inner = child.children[i2]; - if (inner.size) { - child = inner; - break; - } - } - } - return child; - } - if (pos < end) - return child.descAt(pos - offset - child.border); - offset = end; - } - } - domFromPos(pos, side) { - if (!this.contentDOM) - return { node: this.dom, offset: 0, atom: pos + 1 }; - let i = 0, offset = 0; - for (let curPos = 0; i < this.children.length; i++) { - let child = this.children[i], end = curPos + child.size; - if (end > pos || child instanceof TrailingHackViewDesc) { - offset = pos - curPos; - break; - } - curPos = end; - } - if (offset) - return this.children[i].domFromPos(offset - this.children[i].border, side); - for (let prev; i && !(prev = this.children[i - 1]).size && prev instanceof WidgetViewDesc && prev.side >= 0; i--) { - } - if (side <= 0) { - let prev, enter2 = true; - for (; ; i--, enter2 = false) { - prev = i ? this.children[i - 1] : null; - if (!prev || prev.dom.parentNode == this.contentDOM) - break; - } - if (prev && side && enter2 && !prev.border && !prev.domAtom) - return prev.domFromPos(prev.size, side); - return { node: this.contentDOM, offset: prev ? domIndex(prev.dom) + 1 : 0 }; - } else { - let next, enter2 = true; - for (; ; i++, enter2 = false) { - next = i < this.children.length ? this.children[i] : null; - if (!next || next.dom.parentNode == this.contentDOM) - break; - } - if (next && enter2 && !next.border && !next.domAtom) - return next.domFromPos(0, side); - return { node: this.contentDOM, offset: next ? domIndex(next.dom) : this.contentDOM.childNodes.length }; - } - } - // Used to find a DOM range in a single parent for a given changed - // range. - parseRange(from2, to, base2 = 0) { - if (this.children.length == 0) - return { node: this.contentDOM, from: from2, to, fromOffset: 0, toOffset: this.contentDOM.childNodes.length }; - let fromOffset = -1, toOffset = -1; - for (let offset = base2, i = 0; ; i++) { - let child = this.children[i], end = offset + child.size; - if (fromOffset == -1 && from2 <= end) { - let childBase = offset + child.border; - if (from2 >= childBase && to <= end - child.border && child.node && child.contentDOM && this.contentDOM.contains(child.contentDOM)) - return child.parseRange(from2, to, childBase); - from2 = offset; - for (let j = i; j > 0; j--) { - let prev = this.children[j - 1]; - if (prev.size && prev.dom.parentNode == this.contentDOM && !prev.emptyChildAt(1)) { - fromOffset = domIndex(prev.dom) + 1; - break; - } - from2 -= prev.size; - } - if (fromOffset == -1) - fromOffset = 0; - } - if (fromOffset > -1 && (end > to || i == this.children.length - 1)) { - to = end; - for (let j = i + 1; j < this.children.length; j++) { - let next = this.children[j]; - if (next.size && next.dom.parentNode == this.contentDOM && !next.emptyChildAt(-1)) { - toOffset = domIndex(next.dom); - break; - } - to += next.size; - } - if (toOffset == -1) - toOffset = this.contentDOM.childNodes.length; - break; - } - offset = end; - } - return { node: this.contentDOM, from: from2, to, fromOffset, toOffset }; - } - emptyChildAt(side) { - if (this.border || !this.contentDOM || !this.children.length) - return false; - let child = this.children[side < 0 ? 0 : this.children.length - 1]; - return child.size == 0 || child.emptyChildAt(side); - } - domAfterPos(pos) { - let { node, offset } = this.domFromPos(pos, 0); - if (node.nodeType != 1 || offset == node.childNodes.length) - throw new RangeError("No node after pos " + pos); - return node.childNodes[offset]; - } - // View descs are responsible for setting any selection that falls - // entirely inside of them, so that custom implementations can do - // custom things with the selection. Note that this falls apart when - // a selection starts in such a node and ends in another, in which - // case we just use whatever domFromPos produces as a best effort. - setSelection(anchor, head, view, force = false) { - let from2 = Math.min(anchor, head), to = Math.max(anchor, head); - for (let i = 0, offset = 0; i < this.children.length; i++) { - let child = this.children[i], end = offset + child.size; - if (from2 > offset && to < end) - return child.setSelection(anchor - offset - child.border, head - offset - child.border, view, force); - offset = end; - } - let anchorDOM = this.domFromPos(anchor, anchor ? -1 : 1); - let headDOM = head == anchor ? anchorDOM : this.domFromPos(head, head ? -1 : 1); - let domSel = view.root.getSelection(); - let selRange = view.domSelectionRange(); - let brKludge = false; - if ((gecko || safari) && anchor == head) { - let { node, offset } = anchorDOM; - if (node.nodeType == 3) { - brKludge = !!(offset && node.nodeValue[offset - 1] == "\n"); - if (brKludge && offset == node.nodeValue.length) { - for (let scan = node, after; scan; scan = scan.parentNode) { - if (after = scan.nextSibling) { - if (after.nodeName == "BR") - anchorDOM = headDOM = { node: after.parentNode, offset: domIndex(after) + 1 }; - break; - } - let desc = scan.pmViewDesc; - if (desc && desc.node && desc.node.isBlock) - break; - } - } - } else { - let prev = node.childNodes[offset - 1]; - brKludge = prev && (prev.nodeName == "BR" || prev.contentEditable == "false"); - } - } - if (gecko && selRange.focusNode && selRange.focusNode != headDOM.node && selRange.focusNode.nodeType == 1) { - let after = selRange.focusNode.childNodes[selRange.focusOffset]; - if (after && after.contentEditable == "false") - force = true; - } - if (!(force || brKludge && safari) && isEquivalentPosition(anchorDOM.node, anchorDOM.offset, selRange.anchorNode, selRange.anchorOffset) && isEquivalentPosition(headDOM.node, headDOM.offset, selRange.focusNode, selRange.focusOffset)) - return; - let domSelExtended = false; - if ((domSel.extend || anchor == head) && !(brKludge && gecko)) { - domSel.collapse(anchorDOM.node, anchorDOM.offset); - try { - if (anchor != head) - domSel.extend(headDOM.node, headDOM.offset); - domSelExtended = true; - } catch (_) { - } - } - if (!domSelExtended) { - if (anchor > head) { - let tmp = anchorDOM; - anchorDOM = headDOM; - headDOM = tmp; - } - let range = document.createRange(); - range.setEnd(headDOM.node, headDOM.offset); - range.setStart(anchorDOM.node, anchorDOM.offset); - domSel.removeAllRanges(); - domSel.addRange(range); - } - } - ignoreMutation(mutation) { - return !this.contentDOM && mutation.type != "selection"; - } - get contentLost() { - return this.contentDOM && this.contentDOM != this.dom && !this.dom.contains(this.contentDOM); - } - // Remove a subtree of the element tree that has been touched - // by a DOM change, so that the next update will redraw it. - markDirty(from2, to) { - for (let offset = 0, i = 0; i < this.children.length; i++) { - let child = this.children[i], end = offset + child.size; - if (offset == end ? from2 <= end && to >= offset : from2 < end && to > offset) { - let startInside = offset + child.border, endInside = end - child.border; - if (from2 >= startInside && to <= endInside) { - this.dirty = from2 == offset || to == end ? CONTENT_DIRTY : CHILD_DIRTY; - if (from2 == startInside && to == endInside && (child.contentLost || child.dom.parentNode != this.contentDOM)) - child.dirty = NODE_DIRTY; - else - child.markDirty(from2 - startInside, to - startInside); - return; - } else { - child.dirty = child.dom == child.contentDOM && child.dom.parentNode == this.contentDOM && !child.children.length ? CONTENT_DIRTY : NODE_DIRTY; - } - } - offset = end; - } - this.dirty = CONTENT_DIRTY; - } - markParentsDirty() { - let level = 1; - for (let node = this.parent; node; node = node.parent, level++) { - let dirty = level == 1 ? CONTENT_DIRTY : CHILD_DIRTY; - if (node.dirty < dirty) - node.dirty = dirty; - } - } - get domAtom() { - return false; - } - get ignoreForCoords() { - return false; - } - get ignoreForSelection() { - return false; - } - isText(text) { - return false; - } -} -class WidgetViewDesc extends ViewDesc { - constructor(parent, widget, view, pos) { - let self2, dom = widget.type.toDOM; - if (typeof dom == "function") - dom = dom(view, () => { - if (!self2) - return pos; - if (self2.parent) - return self2.parent.posBeforeChild(self2); - }); - if (!widget.type.spec.raw) { - if (dom.nodeType != 1) { - let wrap2 = document.createElement("span"); - wrap2.appendChild(dom); - dom = wrap2; - } - dom.contentEditable = "false"; - dom.classList.add("ProseMirror-widget"); - } - super(parent, [], dom, null); - this.widget = widget; - this.widget = widget; - self2 = this; - } - matchesWidget(widget) { - return this.dirty == NOT_DIRTY && widget.type.eq(this.widget.type); - } - parseRule() { - return { ignore: true }; - } - stopEvent(event) { - let stop = this.widget.spec.stopEvent; - return stop ? stop(event) : false; - } - ignoreMutation(mutation) { - return mutation.type != "selection" || this.widget.spec.ignoreSelection; - } - destroy() { - this.widget.type.destroy(this.dom); - super.destroy(); - } - get domAtom() { - return true; - } - get ignoreForSelection() { - return !!this.widget.type.spec.relaxedSide; - } - get side() { - return this.widget.type.side; - } -} -class CompositionViewDesc extends ViewDesc { - constructor(parent, dom, textDOM, text) { - super(parent, [], dom, null); - this.textDOM = textDOM; - this.text = text; - } - get size() { - return this.text.length; - } - localPosFromDOM(dom, offset) { - if (dom != this.textDOM) - return this.posAtStart + (offset ? this.size : 0); - return this.posAtStart + offset; - } - domFromPos(pos) { - return { node: this.textDOM, offset: pos }; - } - ignoreMutation(mut) { - return mut.type === "characterData" && mut.target.nodeValue == mut.oldValue; - } -} -class MarkViewDesc extends ViewDesc { - constructor(parent, mark, dom, contentDOM, spec) { - super(parent, [], dom, contentDOM); - this.mark = mark; - this.spec = spec; - } - static create(parent, mark, inline, view) { - let custom = view.nodeViews[mark.type.name]; - let spec = custom && custom(mark, view, inline); - if (!spec || !spec.dom) - spec = DOMSerializer.renderSpec(document, mark.type.spec.toDOM(mark, inline), null, mark.attrs); - return new MarkViewDesc(parent, mark, spec.dom, spec.contentDOM || spec.dom, spec); - } - parseRule() { - if (this.dirty & NODE_DIRTY || this.mark.type.spec.reparseInView) - return null; - return { mark: this.mark.type.name, attrs: this.mark.attrs, contentElement: this.contentDOM }; - } - matchesMark(mark) { - return this.dirty != NODE_DIRTY && this.mark.eq(mark); - } - markDirty(from2, to) { - super.markDirty(from2, to); - if (this.dirty != NOT_DIRTY) { - let parent = this.parent; - while (!parent.node) - parent = parent.parent; - if (parent.dirty < this.dirty) - parent.dirty = this.dirty; - this.dirty = NOT_DIRTY; - } - } - slice(from2, to, view) { - let copy2 = MarkViewDesc.create(this.parent, this.mark, true, view); - let nodes = this.children, size = this.size; - if (to < size) - nodes = replaceNodes(nodes, to, size, view); - if (from2 > 0) - nodes = replaceNodes(nodes, 0, from2, view); - for (let i = 0; i < nodes.length; i++) - nodes[i].parent = copy2; - copy2.children = nodes; - return copy2; - } - ignoreMutation(mutation) { - return this.spec.ignoreMutation ? this.spec.ignoreMutation(mutation) : super.ignoreMutation(mutation); - } - destroy() { - if (this.spec.destroy) - this.spec.destroy(); - super.destroy(); - } -} -class NodeViewDesc extends ViewDesc { - constructor(parent, node, outerDeco, innerDeco, dom, contentDOM, nodeDOM, view, pos) { - super(parent, [], dom, contentDOM); - this.node = node; - this.outerDeco = outerDeco; - this.innerDeco = innerDeco; - this.nodeDOM = nodeDOM; - } - // By default, a node is rendered using the `toDOM` method from the - // node type spec. But client code can use the `nodeViews` spec to - // supply a custom node view, which can influence various aspects of - // the way the node works. - // - // (Using subclassing for this was intentionally decided against, - // since it'd require exposing a whole slew of finicky - // implementation details to the user code that they probably will - // never need.) - static create(parent, node, outerDeco, innerDeco, view, pos) { - let custom = view.nodeViews[node.type.name], descObj; - let spec = custom && custom(node, view, () => { - if (!descObj) - return pos; - if (descObj.parent) - return descObj.parent.posBeforeChild(descObj); - }, outerDeco, innerDeco); - let dom = spec && spec.dom, contentDOM = spec && spec.contentDOM; - if (node.isText) { - if (!dom) - dom = document.createTextNode(node.text); - else if (dom.nodeType != 3) - throw new RangeError("Text must be rendered as a DOM text node"); - } else if (!dom) { - let spec2 = DOMSerializer.renderSpec(document, node.type.spec.toDOM(node), null, node.attrs); - ({ dom, contentDOM } = spec2); - } - if (!contentDOM && !node.isText && dom.nodeName != "BR") { - if (!dom.hasAttribute("contenteditable")) - dom.contentEditable = "false"; - if (node.type.spec.draggable) - dom.draggable = true; - } - let nodeDOM = dom; - dom = applyOuterDeco(dom, outerDeco, node); - if (spec) - return descObj = new CustomNodeViewDesc(parent, node, outerDeco, innerDeco, dom, contentDOM || null, nodeDOM, spec, view, pos + 1); - else if (node.isText) - return new TextViewDesc(parent, node, outerDeco, innerDeco, dom, nodeDOM, view); - else - return new NodeViewDesc(parent, node, outerDeco, innerDeco, dom, contentDOM || null, nodeDOM, view, pos + 1); - } - parseRule() { - if (this.node.type.spec.reparseInView) - return null; - let rule = { node: this.node.type.name, attrs: this.node.attrs }; - if (this.node.type.whitespace == "pre") - rule.preserveWhitespace = "full"; - if (!this.contentDOM) { - rule.getContent = () => this.node.content; - } else if (!this.contentLost) { - rule.contentElement = this.contentDOM; - } else { - for (let i = this.children.length - 1; i >= 0; i--) { - let child = this.children[i]; - if (this.dom.contains(child.dom.parentNode)) { - rule.contentElement = child.dom.parentNode; - break; - } - } - if (!rule.contentElement) - rule.getContent = () => Fragment.empty; - } - return rule; - } - matchesNode(node, outerDeco, innerDeco) { - return this.dirty == NOT_DIRTY && node.eq(this.node) && sameOuterDeco(outerDeco, this.outerDeco) && innerDeco.eq(this.innerDeco); - } - get size() { - return this.node.nodeSize; - } - get border() { - return this.node.isLeaf ? 0 : 1; - } - // Syncs `this.children` to match `this.node.content` and the local - // decorations, possibly introducing nesting for marks. Then, in a - // separate step, syncs the DOM inside `this.contentDOM` to - // `this.children`. - updateChildren(view, pos) { - let inline = this.node.inlineContent, off = pos; - let composition = view.composing ? this.localCompositionInfo(view, pos) : null; - let localComposition = composition && composition.pos > -1 ? composition : null; - let compositionInChild = composition && composition.pos < 0; - let updater = new ViewTreeUpdater(this, localComposition && localComposition.node, view); - iterDeco(this.node, this.innerDeco, (widget, i, insideNode) => { - if (widget.spec.marks) - updater.syncToMarks(widget.spec.marks, inline, view, i); - else if (widget.type.side >= 0 && !insideNode) - updater.syncToMarks(i == this.node.childCount ? Mark$1.none : this.node.child(i).marks, inline, view, i); - updater.placeWidget(widget, view, off); - }, (child, outerDeco, innerDeco, i) => { - updater.syncToMarks(child.marks, inline, view, i); - let compIndex; - if (updater.findNodeMatch(child, outerDeco, innerDeco, i)) ; - else if (compositionInChild && view.state.selection.from > off && view.state.selection.to < off + child.nodeSize && (compIndex = updater.findIndexWithChild(composition.node)) > -1 && updater.updateNodeAt(child, outerDeco, innerDeco, compIndex, view)) ; - else if (updater.updateNextNode(child, outerDeco, innerDeco, view, i, off)) ; - else { - updater.addNode(child, outerDeco, innerDeco, view, off); - } - off += child.nodeSize; - }); - updater.syncToMarks([], inline, view, 0); - if (this.node.isTextblock) - updater.addTextblockHacks(); - updater.destroyRest(); - if (updater.changed || this.dirty == CONTENT_DIRTY) { - if (localComposition) - this.protectLocalComposition(view, localComposition); - renderDescs(this.contentDOM, this.children, view); - if (ios) - iosHacks(this.dom); - } - } - localCompositionInfo(view, pos) { - let { from: from2, to } = view.state.selection; - if (!(view.state.selection instanceof TextSelection) || from2 < pos || to > pos + this.node.content.size) - return null; - let textNode = view.input.compositionNode; - if (!textNode || !this.dom.contains(textNode.parentNode)) - return null; - if (this.node.inlineContent) { - let text = textNode.nodeValue; - let textPos = findTextInFragment(this.node.content, text, from2 - pos, to - pos); - return textPos < 0 ? null : { node: textNode, pos: textPos, text }; - } else { - return { node: textNode, pos: -1, text: "" }; - } - } - protectLocalComposition(view, { node, pos, text }) { - if (this.getDesc(node)) - return; - let topNode = node; - for (; ; topNode = topNode.parentNode) { - if (topNode.parentNode == this.contentDOM) - break; - while (topNode.previousSibling) - topNode.parentNode.removeChild(topNode.previousSibling); - while (topNode.nextSibling) - topNode.parentNode.removeChild(topNode.nextSibling); - if (topNode.pmViewDesc) - topNode.pmViewDesc = void 0; - } - let desc = new CompositionViewDesc(this, topNode, node, text); - view.input.compositionNodes.push(desc); - this.children = replaceNodes(this.children, pos, pos + text.length, view, desc); - } - // If this desc must be updated to match the given node decoration, - // do so and return true. - update(node, outerDeco, innerDeco, view) { - if (this.dirty == NODE_DIRTY || !node.sameMarkup(this.node)) - return false; - this.updateInner(node, outerDeco, innerDeco, view); - return true; - } - updateInner(node, outerDeco, innerDeco, view) { - this.updateOuterDeco(outerDeco); - this.node = node; - this.innerDeco = innerDeco; - if (this.contentDOM) - this.updateChildren(view, this.posAtStart); - this.dirty = NOT_DIRTY; - } - updateOuterDeco(outerDeco) { - if (sameOuterDeco(outerDeco, this.outerDeco)) - return; - let needsWrap = this.nodeDOM.nodeType != 1; - let oldDOM = this.dom; - this.dom = patchOuterDeco(this.dom, this.nodeDOM, computeOuterDeco(this.outerDeco, this.node, needsWrap), computeOuterDeco(outerDeco, this.node, needsWrap)); - if (this.dom != oldDOM) { - oldDOM.pmViewDesc = void 0; - this.dom.pmViewDesc = this; - } - this.outerDeco = outerDeco; - } - // Mark this node as being the selected node. - selectNode() { - if (this.nodeDOM.nodeType == 1) { - this.nodeDOM.classList.add("ProseMirror-selectednode"); - if (this.contentDOM || !this.node.type.spec.draggable) - this.nodeDOM.draggable = true; - } - } - // Remove selected node marking from this node. - deselectNode() { - if (this.nodeDOM.nodeType == 1) { - this.nodeDOM.classList.remove("ProseMirror-selectednode"); - if (this.contentDOM || !this.node.type.spec.draggable) - this.nodeDOM.removeAttribute("draggable"); - } - } - get domAtom() { - return this.node.isAtom; - } -} -function docViewDesc(doc2, outerDeco, innerDeco, dom, view) { - applyOuterDeco(dom, outerDeco, doc2); - let docView = new NodeViewDesc(void 0, doc2, outerDeco, innerDeco, dom, dom, dom, view, 0); - if (docView.contentDOM) - docView.updateChildren(view, 0); - return docView; -} -class TextViewDesc extends NodeViewDesc { - constructor(parent, node, outerDeco, innerDeco, dom, nodeDOM, view) { - super(parent, node, outerDeco, innerDeco, dom, null, nodeDOM, view, 0); - } - parseRule() { - let skip = this.nodeDOM.parentNode; - while (skip && skip != this.dom && !skip.pmIsDeco) - skip = skip.parentNode; - return { skip: skip || true }; - } - update(node, outerDeco, innerDeco, view) { - if (this.dirty == NODE_DIRTY || this.dirty != NOT_DIRTY && !this.inParent() || !node.sameMarkup(this.node)) - return false; - this.updateOuterDeco(outerDeco); - if ((this.dirty != NOT_DIRTY || node.text != this.node.text) && node.text != this.nodeDOM.nodeValue) { - this.nodeDOM.nodeValue = node.text; - if (view.trackWrites == this.nodeDOM) - view.trackWrites = null; - } - this.node = node; - this.dirty = NOT_DIRTY; - return true; - } - inParent() { - let parentDOM = this.parent.contentDOM; - for (let n = this.nodeDOM; n; n = n.parentNode) - if (n == parentDOM) - return true; - return false; - } - domFromPos(pos) { - return { node: this.nodeDOM, offset: pos }; - } - localPosFromDOM(dom, offset, bias) { - if (dom == this.nodeDOM) - return this.posAtStart + Math.min(offset, this.node.text.length); - return super.localPosFromDOM(dom, offset, bias); - } - ignoreMutation(mutation) { - return mutation.type != "characterData" && mutation.type != "selection"; - } - slice(from2, to, view) { - let node = this.node.cut(from2, to), dom = document.createTextNode(node.text); - return new TextViewDesc(this.parent, node, this.outerDeco, this.innerDeco, dom, dom, view); - } - markDirty(from2, to) { - super.markDirty(from2, to); - if (this.dom != this.nodeDOM && (from2 == 0 || to == this.nodeDOM.nodeValue.length)) - this.dirty = NODE_DIRTY; - } - get domAtom() { - return false; - } - isText(text) { - return this.node.text == text; - } -} -class TrailingHackViewDesc extends ViewDesc { - parseRule() { - return { ignore: true }; - } - matchesHack(nodeName) { - return this.dirty == NOT_DIRTY && this.dom.nodeName == nodeName; - } - get domAtom() { - return true; - } - get ignoreForCoords() { - return this.dom.nodeName == "IMG"; - } -} -class CustomNodeViewDesc extends NodeViewDesc { - constructor(parent, node, outerDeco, innerDeco, dom, contentDOM, nodeDOM, spec, view, pos) { - super(parent, node, outerDeco, innerDeco, dom, contentDOM, nodeDOM, view, pos); - this.spec = spec; - } - // A custom `update` method gets to decide whether the update goes - // through. If it does, and there's a `contentDOM` node, our logic - // updates the children. - update(node, outerDeco, innerDeco, view) { - if (this.dirty == NODE_DIRTY) - return false; - if (this.spec.update && (this.node.type == node.type || this.spec.multiType)) { - let result = this.spec.update(node, outerDeco, innerDeco); - if (result) - this.updateInner(node, outerDeco, innerDeco, view); - return result; - } else if (!this.contentDOM && !node.isLeaf) { - return false; - } else { - return super.update(node, outerDeco, innerDeco, view); - } - } - selectNode() { - this.spec.selectNode ? this.spec.selectNode() : super.selectNode(); - } - deselectNode() { - this.spec.deselectNode ? this.spec.deselectNode() : super.deselectNode(); - } - setSelection(anchor, head, view, force) { - this.spec.setSelection ? this.spec.setSelection(anchor, head, view.root) : super.setSelection(anchor, head, view, force); - } - destroy() { - if (this.spec.destroy) - this.spec.destroy(); - super.destroy(); - } - stopEvent(event) { - return this.spec.stopEvent ? this.spec.stopEvent(event) : false; - } - ignoreMutation(mutation) { - return this.spec.ignoreMutation ? this.spec.ignoreMutation(mutation) : super.ignoreMutation(mutation); - } -} -function renderDescs(parentDOM, descs, view) { - let dom = parentDOM.firstChild, written = false; - for (let i = 0; i < descs.length; i++) { - let desc = descs[i], childDOM = desc.dom; - if (childDOM.parentNode == parentDOM) { - while (childDOM != dom) { - dom = rm(dom); - written = true; - } - dom = dom.nextSibling; - } else { - written = true; - parentDOM.insertBefore(childDOM, dom); - } - if (desc instanceof MarkViewDesc) { - let pos = dom ? dom.previousSibling : parentDOM.lastChild; - renderDescs(desc.contentDOM, desc.children, view); - dom = pos ? pos.nextSibling : parentDOM.firstChild; - } - } - while (dom) { - dom = rm(dom); - written = true; - } - if (written && view.trackWrites == parentDOM) - view.trackWrites = null; -} -const OuterDecoLevel = function(nodeName) { - if (nodeName) - this.nodeName = nodeName; -}; -OuterDecoLevel.prototype = /* @__PURE__ */ Object.create(null); -const noDeco = [new OuterDecoLevel()]; -function computeOuterDeco(outerDeco, node, needsWrap) { - if (outerDeco.length == 0) - return noDeco; - let top = needsWrap ? noDeco[0] : new OuterDecoLevel(), result = [top]; - for (let i = 0; i < outerDeco.length; i++) { - let attrs = outerDeco[i].type.attrs; - if (!attrs) - continue; - if (attrs.nodeName) - result.push(top = new OuterDecoLevel(attrs.nodeName)); - for (let name in attrs) { - let val = attrs[name]; - if (val == null) - continue; - if (needsWrap && result.length == 1) - result.push(top = new OuterDecoLevel(node.isInline ? "span" : "div")); - if (name == "class") - top.class = (top.class ? top.class + " " : "") + val; - else if (name == "style") - top.style = (top.style ? top.style + ";" : "") + val; - else if (name != "nodeName") - top[name] = val; - } - } - return result; -} -function patchOuterDeco(outerDOM, nodeDOM, prevComputed, curComputed) { - if (prevComputed == noDeco && curComputed == noDeco) - return nodeDOM; - let curDOM = nodeDOM; - for (let i = 0; i < curComputed.length; i++) { - let deco = curComputed[i], prev = prevComputed[i]; - if (i) { - let parent; - if (prev && prev.nodeName == deco.nodeName && curDOM != outerDOM && (parent = curDOM.parentNode) && parent.nodeName.toLowerCase() == deco.nodeName) { - curDOM = parent; - } else { - parent = document.createElement(deco.nodeName); - parent.pmIsDeco = true; - parent.appendChild(curDOM); - prev = noDeco[0]; - curDOM = parent; - } - } - patchAttributes(curDOM, prev || noDeco[0], deco); - } - return curDOM; -} -function patchAttributes(dom, prev, cur) { - for (let name in prev) - if (name != "class" && name != "style" && name != "nodeName" && !(name in cur)) - dom.removeAttribute(name); - for (let name in cur) - if (name != "class" && name != "style" && name != "nodeName" && cur[name] != prev[name]) - dom.setAttribute(name, cur[name]); - if (prev.class != cur.class) { - let prevList = prev.class ? prev.class.split(" ").filter(Boolean) : []; - let curList = cur.class ? cur.class.split(" ").filter(Boolean) : []; - for (let i = 0; i < prevList.length; i++) - if (curList.indexOf(prevList[i]) == -1) - dom.classList.remove(prevList[i]); - for (let i = 0; i < curList.length; i++) - if (prevList.indexOf(curList[i]) == -1) - dom.classList.add(curList[i]); - if (dom.classList.length == 0) - dom.removeAttribute("class"); - } - if (prev.style != cur.style) { - if (prev.style) { - let prop = /\s*([\w\-\xa1-\uffff]+)\s*:(?:"(?:\\.|[^"])*"|'(?:\\.|[^'])*'|\(.*?\)|[^;])*/g, m; - while (m = prop.exec(prev.style)) - dom.style.removeProperty(m[1]); - } - if (cur.style) - dom.style.cssText += cur.style; - } -} -function applyOuterDeco(dom, deco, node) { - return patchOuterDeco(dom, dom, noDeco, computeOuterDeco(deco, node, dom.nodeType != 1)); -} -function sameOuterDeco(a, b) { - if (a.length != b.length) - return false; - for (let i = 0; i < a.length; i++) - if (!a[i].type.eq(b[i].type)) - return false; - return true; -} -function rm(dom) { - let next = dom.nextSibling; - dom.parentNode.removeChild(dom); - return next; -} -class ViewTreeUpdater { - constructor(top, lock, view) { - this.lock = lock; - this.view = view; - this.index = 0; - this.stack = []; - this.changed = false; - this.top = top; - this.preMatch = preMatch(top.node.content, top); - } - // Destroy and remove the children between the given indices in - // `this.top`. - destroyBetween(start, end) { - if (start == end) - return; - for (let i = start; i < end; i++) - this.top.children[i].destroy(); - this.top.children.splice(start, end - start); - this.changed = true; - } - // Destroy all remaining children in `this.top`. - destroyRest() { - this.destroyBetween(this.index, this.top.children.length); - } - // Sync the current stack of mark descs with the given array of - // marks, reusing existing mark descs when possible. - syncToMarks(marks, inline, view, parentIndex) { - let keep = 0, depth = this.stack.length >> 1; - let maxKeep = Math.min(depth, marks.length); - while (keep < maxKeep && (keep == depth - 1 ? this.top : this.stack[keep + 1 << 1]).matchesMark(marks[keep]) && marks[keep].type.spec.spanning !== false) - keep++; - while (keep < depth) { - this.destroyRest(); - this.top.dirty = NOT_DIRTY; - this.index = this.stack.pop(); - this.top = this.stack.pop(); - depth--; - } - while (depth < marks.length) { - this.stack.push(this.top, this.index + 1); - let found2 = -1, scanTo = this.top.children.length; - if (parentIndex < this.preMatch.index) - scanTo = Math.min(this.index + 3, scanTo); - for (let i = this.index; i < scanTo; i++) { - let next = this.top.children[i]; - if (next.matchesMark(marks[depth]) && !this.isLocked(next.dom)) { - found2 = i; - break; - } - } - if (found2 > -1) { - if (found2 > this.index) { - this.changed = true; - this.destroyBetween(this.index, found2); - } - this.top = this.top.children[this.index]; - } else { - let markDesc = MarkViewDesc.create(this.top, marks[depth], inline, view); - this.top.children.splice(this.index, 0, markDesc); - this.top = markDesc; - this.changed = true; - } - this.index = 0; - depth++; - } - } - // Try to find a node desc matching the given data. Skip over it and - // return true when successful. - findNodeMatch(node, outerDeco, innerDeco, index) { - let found2 = -1, targetDesc; - if (index >= this.preMatch.index && (targetDesc = this.preMatch.matches[index - this.preMatch.index]).parent == this.top && targetDesc.matchesNode(node, outerDeco, innerDeco)) { - found2 = this.top.children.indexOf(targetDesc, this.index); - } else { - for (let i = this.index, e = Math.min(this.top.children.length, i + 5); i < e; i++) { - let child = this.top.children[i]; - if (child.matchesNode(node, outerDeco, innerDeco) && !this.preMatch.matched.has(child)) { - found2 = i; - break; - } - } - } - if (found2 < 0) - return false; - this.destroyBetween(this.index, found2); - this.index++; - return true; - } - updateNodeAt(node, outerDeco, innerDeco, index, view) { - let child = this.top.children[index]; - if (child.dirty == NODE_DIRTY && child.dom == child.contentDOM) - child.dirty = CONTENT_DIRTY; - if (!child.update(node, outerDeco, innerDeco, view)) - return false; - this.destroyBetween(this.index, index); - this.index++; - return true; - } - findIndexWithChild(domNode) { - for (; ; ) { - let parent = domNode.parentNode; - if (!parent) - return -1; - if (parent == this.top.contentDOM) { - let desc = domNode.pmViewDesc; - if (desc) - for (let i = this.index; i < this.top.children.length; i++) { - if (this.top.children[i] == desc) - return i; - } - return -1; - } - domNode = parent; - } - } - // Try to update the next node, if any, to the given data. Checks - // pre-matches to avoid overwriting nodes that could still be used. - updateNextNode(node, outerDeco, innerDeco, view, index, pos) { - for (let i = this.index; i < this.top.children.length; i++) { - let next = this.top.children[i]; - if (next instanceof NodeViewDesc) { - let preMatch2 = this.preMatch.matched.get(next); - if (preMatch2 != null && preMatch2 != index) - return false; - let nextDOM = next.dom, updated; - let locked = this.isLocked(nextDOM) && !(node.isText && next.node && next.node.isText && next.nodeDOM.nodeValue == node.text && next.dirty != NODE_DIRTY && sameOuterDeco(outerDeco, next.outerDeco)); - if (!locked && next.update(node, outerDeco, innerDeco, view)) { - this.destroyBetween(this.index, i); - if (next.dom != nextDOM) - this.changed = true; - this.index++; - return true; - } else if (!locked && (updated = this.recreateWrapper(next, node, outerDeco, innerDeco, view, pos))) { - this.destroyBetween(this.index, i); - this.top.children[this.index] = updated; - if (updated.contentDOM) { - updated.dirty = CONTENT_DIRTY; - updated.updateChildren(view, pos + 1); - updated.dirty = NOT_DIRTY; - } - this.changed = true; - this.index++; - return true; - } - break; - } - } - return false; - } - // When a node with content is replaced by a different node with - // identical content, move over its children. - recreateWrapper(next, node, outerDeco, innerDeco, view, pos) { - if (next.dirty || node.isAtom || !next.children.length || !next.node.content.eq(node.content) || !sameOuterDeco(outerDeco, next.outerDeco) || !innerDeco.eq(next.innerDeco)) - return null; - let wrapper = NodeViewDesc.create(this.top, node, outerDeco, innerDeco, view, pos); - if (wrapper.contentDOM) { - wrapper.children = next.children; - next.children = []; - for (let ch of wrapper.children) - ch.parent = wrapper; - } - next.destroy(); - return wrapper; - } - // Insert the node as a newly created node desc. - addNode(node, outerDeco, innerDeco, view, pos) { - let desc = NodeViewDesc.create(this.top, node, outerDeco, innerDeco, view, pos); - if (desc.contentDOM) - desc.updateChildren(view, pos + 1); - this.top.children.splice(this.index++, 0, desc); - this.changed = true; - } - placeWidget(widget, view, pos) { - let next = this.index < this.top.children.length ? this.top.children[this.index] : null; - if (next && next.matchesWidget(widget) && (widget == next.widget || !next.widget.type.toDOM.parentNode)) { - this.index++; - } else { - let desc = new WidgetViewDesc(this.top, widget, view, pos); - this.top.children.splice(this.index++, 0, desc); - this.changed = true; - } - } - // Make sure a textblock looks and behaves correctly in - // contentEditable. - addTextblockHacks() { - let lastChild = this.top.children[this.index - 1], parent = this.top; - while (lastChild instanceof MarkViewDesc) { - parent = lastChild; - lastChild = parent.children[parent.children.length - 1]; - } - if (!lastChild || // Empty textblock - !(lastChild instanceof TextViewDesc) || /\n$/.test(lastChild.node.text) || this.view.requiresGeckoHackNode && /\s$/.test(lastChild.node.text)) { - if ((safari || chrome) && lastChild && lastChild.dom.contentEditable == "false") - this.addHackNode("IMG", parent); - this.addHackNode("BR", this.top); - } - } - addHackNode(nodeName, parent) { - if (parent == this.top && this.index < parent.children.length && parent.children[this.index].matchesHack(nodeName)) { - this.index++; - } else { - let dom = document.createElement(nodeName); - if (nodeName == "IMG") { - dom.className = "ProseMirror-separator"; - dom.alt = ""; - } - if (nodeName == "BR") - dom.className = "ProseMirror-trailingBreak"; - let hack = new TrailingHackViewDesc(this.top, [], dom, null); - if (parent != this.top) - parent.children.push(hack); - else - parent.children.splice(this.index++, 0, hack); - this.changed = true; - } - } - isLocked(node) { - return this.lock && (node == this.lock || node.nodeType == 1 && node.contains(this.lock.parentNode)); - } -} -function preMatch(frag, parentDesc) { - let curDesc = parentDesc, descI = curDesc.children.length; - let fI = frag.childCount, matched = /* @__PURE__ */ new Map(), matches2 = []; - outer: while (fI > 0) { - let desc; - for (; ; ) { - if (descI) { - let next = curDesc.children[descI - 1]; - if (next instanceof MarkViewDesc) { - curDesc = next; - descI = next.children.length; - } else { - desc = next; - descI--; - break; - } - } else if (curDesc == parentDesc) { - break outer; - } else { - descI = curDesc.parent.children.indexOf(curDesc); - curDesc = curDesc.parent; - } - } - let node = desc.node; - if (!node) - continue; - if (node != frag.child(fI - 1)) - break; - --fI; - matched.set(desc, fI); - matches2.push(desc); - } - return { index: fI, matched, matches: matches2.reverse() }; -} -function compareSide(a, b) { - return a.type.side - b.type.side; -} -function iterDeco(parent, deco, onWidget, onNode) { - let locals = deco.locals(parent), offset = 0; - if (locals.length == 0) { - for (let i = 0; i < parent.childCount; i++) { - let child = parent.child(i); - onNode(child, locals, deco.forChild(offset, child), i); - offset += child.nodeSize; - } - return; - } - let decoIndex = 0, active = [], restNode = null; - for (let parentIndex = 0; ; ) { - let widget, widgets; - while (decoIndex < locals.length && locals[decoIndex].to == offset) { - let next = locals[decoIndex++]; - if (next.widget) { - if (!widget) - widget = next; - else - (widgets || (widgets = [widget])).push(next); - } - } - if (widget) { - if (widgets) { - widgets.sort(compareSide); - for (let i = 0; i < widgets.length; i++) - onWidget(widgets[i], parentIndex, !!restNode); - } else { - onWidget(widget, parentIndex, !!restNode); - } - } - let child, index; - if (restNode) { - index = -1; - child = restNode; - restNode = null; - } else if (parentIndex < parent.childCount) { - index = parentIndex; - child = parent.child(parentIndex++); - } else { - break; - } - for (let i = 0; i < active.length; i++) - if (active[i].to <= offset) - active.splice(i--, 1); - while (decoIndex < locals.length && locals[decoIndex].from <= offset && locals[decoIndex].to > offset) - active.push(locals[decoIndex++]); - let end = offset + child.nodeSize; - if (child.isText) { - let cutAt = end; - if (decoIndex < locals.length && locals[decoIndex].from < cutAt) - cutAt = locals[decoIndex].from; - for (let i = 0; i < active.length; i++) - if (active[i].to < cutAt) - cutAt = active[i].to; - if (cutAt < end) { - restNode = child.cut(cutAt - offset); - child = child.cut(0, cutAt - offset); - end = cutAt; - index = -1; - } - } else { - while (decoIndex < locals.length && locals[decoIndex].to < end) - decoIndex++; - } - let outerDeco = child.isInline && !child.isLeaf ? active.filter((d) => !d.inline) : active.slice(); - onNode(child, outerDeco, deco.forChild(offset, child), index); - offset = end; - } -} -function iosHacks(dom) { - if (dom.nodeName == "UL" || dom.nodeName == "OL") { - let oldCSS = dom.style.cssText; - dom.style.cssText = oldCSS + "; list-style: square !important"; - window.getComputedStyle(dom).listStyle; - dom.style.cssText = oldCSS; - } -} -function findTextInFragment(frag, text, from2, to) { - for (let i = 0, pos = 0; i < frag.childCount && pos <= to; ) { - let child = frag.child(i++), childStart = pos; - pos += child.nodeSize; - if (!child.isText) - continue; - let str = child.text; - while (i < frag.childCount) { - let next = frag.child(i++); - pos += next.nodeSize; - if (!next.isText) - break; - str += next.text; - } - if (pos >= from2) { - if (pos >= to && str.slice(to - text.length - childStart, to - childStart) == text) - return to - text.length; - let found2 = childStart < to ? str.lastIndexOf(text, to - childStart - 1) : -1; - if (found2 >= 0 && found2 + text.length + childStart >= from2) - return childStart + found2; - if (from2 == to && str.length >= to + text.length - childStart && str.slice(to - childStart, to - childStart + text.length) == text) - return to; - } - } - return -1; -} -function replaceNodes(nodes, from2, to, view, replacement) { - let result = []; - for (let i = 0, off = 0; i < nodes.length; i++) { - let child = nodes[i], start = off, end = off += child.size; - if (start >= to || end <= from2) { - result.push(child); - } else { - if (start < from2) - result.push(child.slice(0, from2 - start, view)); - if (replacement) { - result.push(replacement); - replacement = void 0; - } - if (end > to) - result.push(child.slice(to - start, child.size, view)); - } - } - return result; -} -function selectionFromDOM(view, origin = null) { - let domSel = view.domSelectionRange(), doc2 = view.state.doc; - if (!domSel.focusNode) - return null; - let nearestDesc = view.docView.nearestDesc(domSel.focusNode), inWidget = nearestDesc && nearestDesc.size == 0; - let head = view.docView.posFromDOM(domSel.focusNode, domSel.focusOffset, 1); - if (head < 0) - return null; - let $head = doc2.resolve(head), anchor, selection; - if (selectionCollapsed(domSel)) { - anchor = head; - while (nearestDesc && !nearestDesc.node) - nearestDesc = nearestDesc.parent; - let nearestDescNode = nearestDesc.node; - if (nearestDesc && nearestDescNode.isAtom && NodeSelection.isSelectable(nearestDescNode) && nearestDesc.parent && !(nearestDescNode.isInline && isOnEdge(domSel.focusNode, domSel.focusOffset, nearestDesc.dom))) { - let pos = nearestDesc.posBefore; - selection = new NodeSelection(head == pos ? $head : doc2.resolve(pos)); - } - } else { - if (domSel instanceof view.dom.ownerDocument.defaultView.Selection && domSel.rangeCount > 1) { - let min = head, max = head; - for (let i = 0; i < domSel.rangeCount; i++) { - let range = domSel.getRangeAt(i); - min = Math.min(min, view.docView.posFromDOM(range.startContainer, range.startOffset, 1)); - max = Math.max(max, view.docView.posFromDOM(range.endContainer, range.endOffset, -1)); - } - if (min < 0) - return null; - [anchor, head] = max == view.state.selection.anchor ? [max, min] : [min, max]; - $head = doc2.resolve(head); - } else { - anchor = view.docView.posFromDOM(domSel.anchorNode, domSel.anchorOffset, 1); - } - if (anchor < 0) - return null; - } - let $anchor = doc2.resolve(anchor); - if (!selection) { - let bias = origin == "pointer" || view.state.selection.head < $head.pos && !inWidget ? 1 : -1; - selection = selectionBetween(view, $anchor, $head, bias); - } - return selection; -} -function editorOwnsSelection(view) { - return view.editable ? view.hasFocus() : hasSelection(view) && document.activeElement && document.activeElement.contains(view.dom); -} -function selectionToDOM(view, force = false) { - let sel = view.state.selection; - syncNodeSelection(view, sel); - if (!editorOwnsSelection(view)) - return; - if (!force && view.input.mouseDown && view.input.mouseDown.allowDefault && chrome) { - let domSel = view.domSelectionRange(), curSel = view.domObserver.currentSelection; - if (domSel.anchorNode && curSel.anchorNode && isEquivalentPosition(domSel.anchorNode, domSel.anchorOffset, curSel.anchorNode, curSel.anchorOffset)) { - view.input.mouseDown.delayedSelectionSync = true; - view.domObserver.setCurSelection(); - return; - } - } - view.domObserver.disconnectSelection(); - if (view.cursorWrapper) { - selectCursorWrapper(view); - } else { - let { anchor, head } = sel, resetEditableFrom, resetEditableTo; - if (brokenSelectBetweenUneditable && !(sel instanceof TextSelection)) { - if (!sel.$from.parent.inlineContent) - resetEditableFrom = temporarilyEditableNear(view, sel.from); - if (!sel.empty && !sel.$from.parent.inlineContent) - resetEditableTo = temporarilyEditableNear(view, sel.to); - } - view.docView.setSelection(anchor, head, view, force); - if (brokenSelectBetweenUneditable) { - if (resetEditableFrom) - resetEditable(resetEditableFrom); - if (resetEditableTo) - resetEditable(resetEditableTo); - } - if (sel.visible) { - view.dom.classList.remove("ProseMirror-hideselection"); - } else { - view.dom.classList.add("ProseMirror-hideselection"); - if ("onselectionchange" in document) - removeClassOnSelectionChange(view); - } - } - view.domObserver.setCurSelection(); - view.domObserver.connectSelection(); -} -const brokenSelectBetweenUneditable = safari || chrome && chrome_version < 63; -function temporarilyEditableNear(view, pos) { - let { node, offset } = view.docView.domFromPos(pos, 0); - let after = offset < node.childNodes.length ? node.childNodes[offset] : null; - let before = offset ? node.childNodes[offset - 1] : null; - if (safari && after && after.contentEditable == "false") - return setEditable(after); - if ((!after || after.contentEditable == "false") && (!before || before.contentEditable == "false")) { - if (after) - return setEditable(after); - else if (before) - return setEditable(before); - } -} -function setEditable(element) { - element.contentEditable = "true"; - if (safari && element.draggable) { - element.draggable = false; - element.wasDraggable = true; - } - return element; -} -function resetEditable(element) { - element.contentEditable = "false"; - if (element.wasDraggable) { - element.draggable = true; - element.wasDraggable = null; - } -} -function removeClassOnSelectionChange(view) { - let doc2 = view.dom.ownerDocument; - doc2.removeEventListener("selectionchange", view.input.hideSelectionGuard); - let domSel = view.domSelectionRange(); - let node = domSel.anchorNode, offset = domSel.anchorOffset; - doc2.addEventListener("selectionchange", view.input.hideSelectionGuard = () => { - if (domSel.anchorNode != node || domSel.anchorOffset != offset) { - doc2.removeEventListener("selectionchange", view.input.hideSelectionGuard); - setTimeout(() => { - if (!editorOwnsSelection(view) || view.state.selection.visible) - view.dom.classList.remove("ProseMirror-hideselection"); - }, 20); - } - }); -} -function selectCursorWrapper(view) { - let domSel = view.domSelection(); - if (!domSel) - return; - let node = view.cursorWrapper.dom, img = node.nodeName == "IMG"; - if (img) - domSel.collapse(node.parentNode, domIndex(node) + 1); - else - domSel.collapse(node, 0); - if (!img && !view.state.selection.visible && ie$1 && ie_version <= 11) { - node.disabled = true; - node.disabled = false; - } -} -function syncNodeSelection(view, sel) { - if (sel instanceof NodeSelection) { - let desc = view.docView.descAt(sel.from); - if (desc != view.lastSelectedViewDesc) { - clearNodeSelection(view); - if (desc) - desc.selectNode(); - view.lastSelectedViewDesc = desc; - } - } else { - clearNodeSelection(view); - } -} -function clearNodeSelection(view) { - if (view.lastSelectedViewDesc) { - if (view.lastSelectedViewDesc.parent) - view.lastSelectedViewDesc.deselectNode(); - view.lastSelectedViewDesc = void 0; - } -} -function selectionBetween(view, $anchor, $head, bias) { - return view.someProp("createSelectionBetween", (f) => f(view, $anchor, $head)) || TextSelection.between($anchor, $head, bias); -} -function hasFocusAndSelection(view) { - if (view.editable && !view.hasFocus()) - return false; - return hasSelection(view); -} -function hasSelection(view) { - let sel = view.domSelectionRange(); - if (!sel.anchorNode) - return false; - try { - return view.dom.contains(sel.anchorNode.nodeType == 3 ? sel.anchorNode.parentNode : sel.anchorNode) && (view.editable || view.dom.contains(sel.focusNode.nodeType == 3 ? sel.focusNode.parentNode : sel.focusNode)); - } catch (_) { - return false; - } -} -function anchorInRightPlace(view) { - let anchorDOM = view.docView.domFromPos(view.state.selection.anchor, 0); - let domSel = view.domSelectionRange(); - return isEquivalentPosition(anchorDOM.node, anchorDOM.offset, domSel.anchorNode, domSel.anchorOffset); -} -function moveSelectionBlock(state, dir) { - let { $anchor, $head } = state.selection; - let $side = dir > 0 ? $anchor.max($head) : $anchor.min($head); - let $start = !$side.parent.inlineContent ? $side : $side.depth ? state.doc.resolve(dir > 0 ? $side.after() : $side.before()) : null; - return $start && Selection.findFrom($start, dir); -} -function apply(view, sel) { - view.dispatch(view.state.tr.setSelection(sel).scrollIntoView()); - return true; -} -function selectHorizontally(view, dir, mods) { - let sel = view.state.selection; - if (sel instanceof TextSelection) { - if (mods.indexOf("s") > -1) { - let { $head } = sel, node = $head.textOffset ? null : dir < 0 ? $head.nodeBefore : $head.nodeAfter; - if (!node || node.isText || !node.isLeaf) - return false; - let $newHead = view.state.doc.resolve($head.pos + node.nodeSize * (dir < 0 ? -1 : 1)); - return apply(view, new TextSelection(sel.$anchor, $newHead)); - } else if (!sel.empty) { - return false; - } else if (view.endOfTextblock(dir > 0 ? "forward" : "backward")) { - let next = moveSelectionBlock(view.state, dir); - if (next && next instanceof NodeSelection) - return apply(view, next); - return false; - } else if (!(mac$2 && mods.indexOf("m") > -1)) { - let $head = sel.$head, node = $head.textOffset ? null : dir < 0 ? $head.nodeBefore : $head.nodeAfter, desc; - if (!node || node.isText) - return false; - let nodePos = dir < 0 ? $head.pos - node.nodeSize : $head.pos; - if (!(node.isAtom || (desc = view.docView.descAt(nodePos)) && !desc.contentDOM)) - return false; - if (NodeSelection.isSelectable(node)) { - return apply(view, new NodeSelection(dir < 0 ? view.state.doc.resolve($head.pos - node.nodeSize) : $head)); - } else if (webkit) { - return apply(view, new TextSelection(view.state.doc.resolve(dir < 0 ? nodePos : nodePos + node.nodeSize))); - } else { - return false; - } - } - } else if (sel instanceof NodeSelection && sel.node.isInline) { - return apply(view, new TextSelection(dir > 0 ? sel.$to : sel.$from)); - } else { - let next = moveSelectionBlock(view.state, dir); - if (next) - return apply(view, next); - return false; - } -} -function nodeLen(node) { - return node.nodeType == 3 ? node.nodeValue.length : node.childNodes.length; -} -function isIgnorable(dom, dir) { - let desc = dom.pmViewDesc; - return desc && desc.size == 0 && (dir < 0 || dom.nextSibling || dom.nodeName != "BR"); -} -function skipIgnoredNodes(view, dir) { - return dir < 0 ? skipIgnoredNodesBefore(view) : skipIgnoredNodesAfter(view); -} -function skipIgnoredNodesBefore(view) { - let sel = view.domSelectionRange(); - let node = sel.focusNode, offset = sel.focusOffset; - if (!node) - return; - let moveNode, moveOffset, force = false; - if (gecko && node.nodeType == 1 && offset < nodeLen(node) && isIgnorable(node.childNodes[offset], -1)) - force = true; - for (; ; ) { - if (offset > 0) { - if (node.nodeType != 1) { - break; - } else { - let before = node.childNodes[offset - 1]; - if (isIgnorable(before, -1)) { - moveNode = node; - moveOffset = --offset; - } else if (before.nodeType == 3) { - node = before; - offset = node.nodeValue.length; - } else - break; - } - } else if (isBlockNode(node)) { - break; - } else { - let prev = node.previousSibling; - while (prev && isIgnorable(prev, -1)) { - moveNode = node.parentNode; - moveOffset = domIndex(prev); - prev = prev.previousSibling; - } - if (!prev) { - node = node.parentNode; - if (node == view.dom) - break; - offset = 0; - } else { - node = prev; - offset = nodeLen(node); - } - } - } - if (force) - setSelFocus(view, node, offset); - else if (moveNode) - setSelFocus(view, moveNode, moveOffset); -} -function skipIgnoredNodesAfter(view) { - let sel = view.domSelectionRange(); - let node = sel.focusNode, offset = sel.focusOffset; - if (!node) - return; - let len = nodeLen(node); - let moveNode, moveOffset; - for (; ; ) { - if (offset < len) { - if (node.nodeType != 1) - break; - let after = node.childNodes[offset]; - if (isIgnorable(after, 1)) { - moveNode = node; - moveOffset = ++offset; - } else - break; - } else if (isBlockNode(node)) { - break; - } else { - let next = node.nextSibling; - while (next && isIgnorable(next, 1)) { - moveNode = next.parentNode; - moveOffset = domIndex(next) + 1; - next = next.nextSibling; - } - if (!next) { - node = node.parentNode; - if (node == view.dom) - break; - offset = len = 0; - } else { - node = next; - offset = 0; - len = nodeLen(node); - } - } - } - if (moveNode) - setSelFocus(view, moveNode, moveOffset); -} -function isBlockNode(dom) { - let desc = dom.pmViewDesc; - return desc && desc.node && desc.node.isBlock; -} -function textNodeAfter(node, offset) { - while (node && offset == node.childNodes.length && !hasBlockDesc(node)) { - offset = domIndex(node) + 1; - node = node.parentNode; - } - while (node && offset < node.childNodes.length) { - let next = node.childNodes[offset]; - if (next.nodeType == 3) - return next; - if (next.nodeType == 1 && next.contentEditable == "false") - break; - node = next; - offset = 0; - } -} -function textNodeBefore(node, offset) { - while (node && !offset && !hasBlockDesc(node)) { - offset = domIndex(node); - node = node.parentNode; - } - while (node && offset) { - let next = node.childNodes[offset - 1]; - if (next.nodeType == 3) - return next; - if (next.nodeType == 1 && next.contentEditable == "false") - break; - node = next; - offset = node.childNodes.length; - } -} -function setSelFocus(view, node, offset) { - if (node.nodeType != 3) { - let before, after; - if (after = textNodeAfter(node, offset)) { - node = after; - offset = 0; - } else if (before = textNodeBefore(node, offset)) { - node = before; - offset = before.nodeValue.length; - } - } - let sel = view.domSelection(); - if (!sel) - return; - if (selectionCollapsed(sel)) { - let range = document.createRange(); - range.setEnd(node, offset); - range.setStart(node, offset); - sel.removeAllRanges(); - sel.addRange(range); - } else if (sel.extend) { - sel.extend(node, offset); - } - view.domObserver.setCurSelection(); - let { state } = view; - setTimeout(() => { - if (view.state == state) - selectionToDOM(view); - }, 50); -} -function findDirection(view, pos) { - let $pos = view.state.doc.resolve(pos); - if (!(chrome || windows$1) && $pos.parent.inlineContent) { - let coords = view.coordsAtPos(pos); - if (pos > $pos.start()) { - let before = view.coordsAtPos(pos - 1); - let mid = (before.top + before.bottom) / 2; - if (mid > coords.top && mid < coords.bottom && Math.abs(before.left - coords.left) > 1) - return before.left < coords.left ? "ltr" : "rtl"; - } - if (pos < $pos.end()) { - let after = view.coordsAtPos(pos + 1); - let mid = (after.top + after.bottom) / 2; - if (mid > coords.top && mid < coords.bottom && Math.abs(after.left - coords.left) > 1) - return after.left > coords.left ? "ltr" : "rtl"; - } - } - let computed = getComputedStyle(view.dom).direction; - return computed == "rtl" ? "rtl" : "ltr"; -} -function selectVertically(view, dir, mods) { - let sel = view.state.selection; - if (sel instanceof TextSelection && !sel.empty || mods.indexOf("s") > -1) - return false; - if (mac$2 && mods.indexOf("m") > -1) - return false; - let { $from, $to } = sel; - if (!$from.parent.inlineContent || view.endOfTextblock(dir < 0 ? "up" : "down")) { - let next = moveSelectionBlock(view.state, dir); - if (next && next instanceof NodeSelection) - return apply(view, next); - } - if (!$from.parent.inlineContent) { - let side = dir < 0 ? $from : $to; - let beyond = sel instanceof AllSelection ? Selection.near(side, dir) : Selection.findFrom(side, dir); - return beyond ? apply(view, beyond) : false; - } - return false; -} -function stopNativeHorizontalDelete(view, dir) { - if (!(view.state.selection instanceof TextSelection)) - return true; - let { $head, $anchor, empty: empty2 } = view.state.selection; - if (!$head.sameParent($anchor)) - return true; - if (!empty2) - return false; - if (view.endOfTextblock(dir > 0 ? "forward" : "backward")) - return true; - let nextNode = !$head.textOffset && (dir < 0 ? $head.nodeBefore : $head.nodeAfter); - if (nextNode && !nextNode.isText) { - let tr2 = view.state.tr; - if (dir < 0) - tr2.delete($head.pos - nextNode.nodeSize, $head.pos); - else - tr2.delete($head.pos, $head.pos + nextNode.nodeSize); - view.dispatch(tr2); - return true; - } - return false; -} -function switchEditable(view, node, state) { - view.domObserver.stop(); - node.contentEditable = state; - view.domObserver.start(); -} -function safariDownArrowBug(view) { - if (!safari || view.state.selection.$head.parentOffset > 0) - return false; - let { focusNode, focusOffset } = view.domSelectionRange(); - if (focusNode && focusNode.nodeType == 1 && focusOffset == 0 && focusNode.firstChild && focusNode.firstChild.contentEditable == "false") { - let child = focusNode.firstChild; - switchEditable(view, child, "true"); - setTimeout(() => switchEditable(view, child, "false"), 20); - } - return false; -} -function getMods(event) { - let result = ""; - if (event.ctrlKey) - result += "c"; - if (event.metaKey) - result += "m"; - if (event.altKey) - result += "a"; - if (event.shiftKey) - result += "s"; - return result; -} -function captureKeyDown(view, event) { - let code = event.keyCode, mods = getMods(event); - if (code == 8 || mac$2 && code == 72 && mods == "c") { - return stopNativeHorizontalDelete(view, -1) || skipIgnoredNodes(view, -1); - } else if (code == 46 && !event.shiftKey || mac$2 && code == 68 && mods == "c") { - return stopNativeHorizontalDelete(view, 1) || skipIgnoredNodes(view, 1); - } else if (code == 13 || code == 27) { - return true; - } else if (code == 37 || mac$2 && code == 66 && mods == "c") { - let dir = code == 37 ? findDirection(view, view.state.selection.from) == "ltr" ? -1 : 1 : -1; - return selectHorizontally(view, dir, mods) || skipIgnoredNodes(view, dir); - } else if (code == 39 || mac$2 && code == 70 && mods == "c") { - let dir = code == 39 ? findDirection(view, view.state.selection.from) == "ltr" ? 1 : -1 : 1; - return selectHorizontally(view, dir, mods) || skipIgnoredNodes(view, dir); - } else if (code == 38 || mac$2 && code == 80 && mods == "c") { - return selectVertically(view, -1, mods) || skipIgnoredNodes(view, -1); - } else if (code == 40 || mac$2 && code == 78 && mods == "c") { - return safariDownArrowBug(view) || selectVertically(view, 1, mods) || skipIgnoredNodes(view, 1); - } else if (mods == (mac$2 ? "m" : "c") && (code == 66 || code == 73 || code == 89 || code == 90)) { - return true; - } - return false; -} -function serializeForClipboard(view, slice2) { - view.someProp("transformCopied", (f) => { - slice2 = f(slice2, view); - }); - let context = [], { content, openStart, openEnd } = slice2; - while (openStart > 1 && openEnd > 1 && content.childCount == 1 && content.firstChild.childCount == 1) { - openStart--; - openEnd--; - let node = content.firstChild; - context.push(node.type.name, node.attrs != node.type.defaultAttrs ? node.attrs : null); - content = node.content; - } - let serializer = view.someProp("clipboardSerializer") || DOMSerializer.fromSchema(view.state.schema); - let doc2 = detachedDoc(), wrap2 = doc2.createElement("div"); - wrap2.appendChild(serializer.serializeFragment(content, { document: doc2 })); - let firstChild = wrap2.firstChild, needsWrap, wrappers = 0; - while (firstChild && firstChild.nodeType == 1 && (needsWrap = wrapMap[firstChild.nodeName.toLowerCase()])) { - for (let i = needsWrap.length - 1; i >= 0; i--) { - let wrapper = doc2.createElement(needsWrap[i]); - while (wrap2.firstChild) - wrapper.appendChild(wrap2.firstChild); - wrap2.appendChild(wrapper); - wrappers++; - } - firstChild = wrap2.firstChild; - } - if (firstChild && firstChild.nodeType == 1) - firstChild.setAttribute("data-pm-slice", `${openStart} ${openEnd}${wrappers ? ` -${wrappers}` : ""} ${JSON.stringify(context)}`); - let text = view.someProp("clipboardTextSerializer", (f) => f(slice2, view)) || slice2.content.textBetween(0, slice2.content.size, "\n\n"); - return { dom: wrap2, text, slice: slice2 }; -} -function parseFromClipboard(view, text, html, plainText, $context) { - let inCode = $context.parent.type.spec.code; - let dom, slice2; - if (!html && !text) - return null; - let asText = !!text && (plainText || inCode || !html); - if (asText) { - view.someProp("transformPastedText", (f) => { - text = f(text, inCode || plainText, view); - }); - if (inCode) { - slice2 = new Slice(Fragment.from(view.state.schema.text(text.replace(/\r\n?/g, "\n"))), 0, 0); - view.someProp("transformPasted", (f) => { - slice2 = f(slice2, view, true); - }); - return slice2; - } - let parsed = view.someProp("clipboardTextParser", (f) => f(text, $context, plainText, view)); - if (parsed) { - slice2 = parsed; - } else { - let marks = $context.marks(); - let { schema } = view.state, serializer = DOMSerializer.fromSchema(schema); - dom = document.createElement("div"); - text.split(/(?:\r\n?|\n)+/).forEach((block) => { - let p = dom.appendChild(document.createElement("p")); - if (block) - p.appendChild(serializer.serializeNode(schema.text(block, marks))); - }); - } - } else { - view.someProp("transformPastedHTML", (f) => { - html = f(html, view); - }); - dom = readHTML(html); - if (webkit) - restoreReplacedSpaces(dom); - } - let contextNode = dom && dom.querySelector("[data-pm-slice]"); - let sliceData = contextNode && /^(\d+) (\d+)(?: -(\d+))? (.*)/.exec(contextNode.getAttribute("data-pm-slice") || ""); - if (sliceData && sliceData[3]) - for (let i = +sliceData[3]; i > 0; i--) { - let child = dom.firstChild; - while (child && child.nodeType != 1) - child = child.nextSibling; - if (!child) - break; - dom = child; - } - if (!slice2) { - let parser = view.someProp("clipboardParser") || view.someProp("domParser") || DOMParser.fromSchema(view.state.schema); - slice2 = parser.parseSlice(dom, { - preserveWhitespace: !!(asText || sliceData), - context: $context, - ruleFromNode(dom2) { - if (dom2.nodeName == "BR" && !dom2.nextSibling && dom2.parentNode && !inlineParents.test(dom2.parentNode.nodeName)) - return { ignore: true }; - return null; - } - }); - } - if (sliceData) { - slice2 = addContext(closeSlice(slice2, +sliceData[1], +sliceData[2]), sliceData[4]); - } else { - slice2 = Slice.maxOpen(normalizeSiblings(slice2.content, $context), true); - if (slice2.openStart || slice2.openEnd) { - let openStart = 0, openEnd = 0; - for (let node = slice2.content.firstChild; openStart < slice2.openStart && !node.type.spec.isolating; openStart++, node = node.firstChild) { - } - for (let node = slice2.content.lastChild; openEnd < slice2.openEnd && !node.type.spec.isolating; openEnd++, node = node.lastChild) { - } - slice2 = closeSlice(slice2, openStart, openEnd); - } - } - view.someProp("transformPasted", (f) => { - slice2 = f(slice2, view, asText); - }); - return slice2; -} -const inlineParents = /^(a|abbr|acronym|b|cite|code|del|em|i|ins|kbd|label|output|q|ruby|s|samp|span|strong|sub|sup|time|u|tt|var)$/i; -function normalizeSiblings(fragment, $context) { - if (fragment.childCount < 2) - return fragment; - for (let d = $context.depth; d >= 0; d--) { - let parent = $context.node(d); - let match = parent.contentMatchAt($context.index(d)); - let lastWrap, result = []; - fragment.forEach((node) => { - if (!result) - return; - let wrap2 = match.findWrapping(node.type), inLast; - if (!wrap2) - return result = null; - if (inLast = result.length && lastWrap.length && addToSibling(wrap2, lastWrap, node, result[result.length - 1], 0)) { - result[result.length - 1] = inLast; - } else { - if (result.length) - result[result.length - 1] = closeRight(result[result.length - 1], lastWrap.length); - let wrapped = withWrappers(node, wrap2); - result.push(wrapped); - match = match.matchType(wrapped.type); - lastWrap = wrap2; - } - }); - if (result) - return Fragment.from(result); - } - return fragment; -} -function withWrappers(node, wrap2, from2 = 0) { - for (let i = wrap2.length - 1; i >= from2; i--) - node = wrap2[i].create(null, Fragment.from(node)); - return node; -} -function addToSibling(wrap2, lastWrap, node, sibling, depth) { - if (depth < wrap2.length && depth < lastWrap.length && wrap2[depth] == lastWrap[depth]) { - let inner = addToSibling(wrap2, lastWrap, node, sibling.lastChild, depth + 1); - if (inner) - return sibling.copy(sibling.content.replaceChild(sibling.childCount - 1, inner)); - let match = sibling.contentMatchAt(sibling.childCount); - if (match.matchType(depth == wrap2.length - 1 ? node.type : wrap2[depth + 1])) - return sibling.copy(sibling.content.append(Fragment.from(withWrappers(node, wrap2, depth + 1)))); - } -} -function closeRight(node, depth) { - if (depth == 0) - return node; - let fragment = node.content.replaceChild(node.childCount - 1, closeRight(node.lastChild, depth - 1)); - let fill = node.contentMatchAt(node.childCount).fillBefore(Fragment.empty, true); - return node.copy(fragment.append(fill)); -} -function closeRange(fragment, side, from2, to, depth, openEnd) { - let node = side < 0 ? fragment.firstChild : fragment.lastChild, inner = node.content; - if (fragment.childCount > 1) - openEnd = 0; - if (depth < to - 1) - inner = closeRange(inner, side, from2, to, depth + 1, openEnd); - if (depth >= from2) - inner = side < 0 ? node.contentMatchAt(0).fillBefore(inner, openEnd <= depth).append(inner) : inner.append(node.contentMatchAt(node.childCount).fillBefore(Fragment.empty, true)); - return fragment.replaceChild(side < 0 ? 0 : fragment.childCount - 1, node.copy(inner)); -} -function closeSlice(slice2, openStart, openEnd) { - if (openStart < slice2.openStart) - slice2 = new Slice(closeRange(slice2.content, -1, openStart, slice2.openStart, 0, slice2.openEnd), openStart, slice2.openEnd); - if (openEnd < slice2.openEnd) - slice2 = new Slice(closeRange(slice2.content, 1, openEnd, slice2.openEnd, 0, 0), slice2.openStart, openEnd); - return slice2; -} -const wrapMap = { - thead: ["table"], - tbody: ["table"], - tfoot: ["table"], - caption: ["table"], - colgroup: ["table"], - col: ["table", "colgroup"], - tr: ["table", "tbody"], - td: ["table", "tbody", "tr"], - th: ["table", "tbody", "tr"] -}; -let _detachedDoc = null; -function detachedDoc() { - return _detachedDoc || (_detachedDoc = document.implementation.createHTMLDocument("title")); -} -let _policy = null; -function maybeWrapTrusted(html) { - let trustedTypes = window.trustedTypes; - if (!trustedTypes) - return html; - if (!_policy) - _policy = trustedTypes.defaultPolicy || trustedTypes.createPolicy("ProseMirrorClipboard", { createHTML: (s) => s }); - return _policy.createHTML(html); -} -function readHTML(html) { - let metas = /^(\s*]*>)*/.exec(html); - if (metas) - html = html.slice(metas[0].length); - let elt = detachedDoc().createElement("div"); - let firstTag = /<([a-z][^>\s]+)/i.exec(html), wrap2; - if (wrap2 = firstTag && wrapMap[firstTag[1].toLowerCase()]) - html = wrap2.map((n) => "<" + n + ">").join("") + html + wrap2.map((n) => "").reverse().join(""); - elt.innerHTML = maybeWrapTrusted(html); - if (wrap2) - for (let i = 0; i < wrap2.length; i++) - elt = elt.querySelector(wrap2[i]) || elt; - return elt; -} -function restoreReplacedSpaces(dom) { - let nodes = dom.querySelectorAll(chrome ? "span:not([class]):not([style])" : "span.Apple-converted-space"); - for (let i = 0; i < nodes.length; i++) { - let node = nodes[i]; - if (node.childNodes.length == 1 && node.textContent == " " && node.parentNode) - node.parentNode.replaceChild(dom.ownerDocument.createTextNode(" "), node); - } -} -function addContext(slice2, context) { - if (!slice2.size) - return slice2; - let schema = slice2.content.firstChild.type.schema, array; - try { - array = JSON.parse(context); - } catch (e) { - return slice2; - } - let { content, openStart, openEnd } = slice2; - for (let i = array.length - 2; i >= 0; i -= 2) { - let type = schema.nodes[array[i]]; - if (!type || type.hasRequiredAttrs()) - break; - content = Fragment.from(type.create(array[i + 1], content)); - openStart++; - openEnd++; - } - return new Slice(content, openStart, openEnd); -} -const handlers = {}; -const editHandlers = {}; -const passiveHandlers = { touchstart: true, touchmove: true }; -class InputState { - constructor() { - this.shiftKey = false; - this.mouseDown = null; - this.lastKeyCode = null; - this.lastKeyCodeTime = 0; - this.lastClick = { time: 0, x: 0, y: 0, type: "", button: 0 }; - this.lastSelectionOrigin = null; - this.lastSelectionTime = 0; - this.lastIOSEnter = 0; - this.lastIOSEnterFallbackTimeout = -1; - this.lastFocus = 0; - this.lastTouch = 0; - this.lastChromeDelete = 0; - this.composing = false; - this.compositionNode = null; - this.composingTimeout = -1; - this.compositionNodes = []; - this.compositionEndedAt = -2e8; - this.compositionID = 1; - this.badSafariComposition = false; - this.compositionPendingChanges = 0; - this.domChangeCount = 0; - this.eventHandlers = /* @__PURE__ */ Object.create(null); - this.hideSelectionGuard = null; - } -} -function initInput(view) { - for (let event in handlers) { - let handler = handlers[event]; - view.dom.addEventListener(event, view.input.eventHandlers[event] = (event2) => { - if (eventBelongsToView(view, event2) && !runCustomHandler(view, event2) && (view.editable || !(event2.type in editHandlers))) - handler(view, event2); - }, passiveHandlers[event] ? { passive: true } : void 0); - } - if (safari) - view.dom.addEventListener("input", () => null); - ensureListeners(view); -} -function setSelectionOrigin(view, origin) { - view.input.lastSelectionOrigin = origin; - view.input.lastSelectionTime = Date.now(); -} -function destroyInput(view) { - view.domObserver.stop(); - for (let type in view.input.eventHandlers) - view.dom.removeEventListener(type, view.input.eventHandlers[type]); - clearTimeout(view.input.composingTimeout); - clearTimeout(view.input.lastIOSEnterFallbackTimeout); -} -function ensureListeners(view) { - view.someProp("handleDOMEvents", (currentHandlers) => { - for (let type in currentHandlers) - if (!view.input.eventHandlers[type]) - view.dom.addEventListener(type, view.input.eventHandlers[type] = (event) => runCustomHandler(view, event)); - }); -} -function runCustomHandler(view, event) { - return view.someProp("handleDOMEvents", (handlers2) => { - let handler = handlers2[event.type]; - return handler ? handler(view, event) || event.defaultPrevented : false; - }); -} -function eventBelongsToView(view, event) { - if (!event.bubbles) - return true; - if (event.defaultPrevented) - return false; - for (let node = event.target; node != view.dom; node = node.parentNode) - if (!node || node.nodeType == 11 || node.pmViewDesc && node.pmViewDesc.stopEvent(event)) - return false; - return true; -} -function dispatchEvent(view, event) { - if (!runCustomHandler(view, event) && handlers[event.type] && (view.editable || !(event.type in editHandlers))) - handlers[event.type](view, event); -} -editHandlers.keydown = (view, _event) => { - let event = _event; - view.input.shiftKey = event.keyCode == 16 || event.shiftKey; - if (inOrNearComposition(view, event)) - return; - view.input.lastKeyCode = event.keyCode; - view.input.lastKeyCodeTime = Date.now(); - if (android && chrome && event.keyCode == 13) - return; - if (event.keyCode != 229) - view.domObserver.forceFlush(); - if (ios && event.keyCode == 13 && !event.ctrlKey && !event.altKey && !event.metaKey) { - let now = Date.now(); - view.input.lastIOSEnter = now; - view.input.lastIOSEnterFallbackTimeout = setTimeout(() => { - if (view.input.lastIOSEnter == now) { - view.someProp("handleKeyDown", (f) => f(view, keyEvent(13, "Enter"))); - view.input.lastIOSEnter = 0; - } - }, 200); - } else if (view.someProp("handleKeyDown", (f) => f(view, event)) || captureKeyDown(view, event)) { - event.preventDefault(); - } else { - setSelectionOrigin(view, "key"); - } -}; -editHandlers.keyup = (view, event) => { - if (event.keyCode == 16) - view.input.shiftKey = false; -}; -editHandlers.keypress = (view, _event) => { - let event = _event; - if (inOrNearComposition(view, event) || !event.charCode || event.ctrlKey && !event.altKey || mac$2 && event.metaKey) - return; - if (view.someProp("handleKeyPress", (f) => f(view, event))) { - event.preventDefault(); - return; - } - let sel = view.state.selection; - if (!(sel instanceof TextSelection) || !sel.$from.sameParent(sel.$to)) { - let text = String.fromCharCode(event.charCode); - let deflt = () => view.state.tr.insertText(text).scrollIntoView(); - if (!/[\r\n]/.test(text) && !view.someProp("handleTextInput", (f) => f(view, sel.$from.pos, sel.$to.pos, text, deflt))) - view.dispatch(deflt()); - event.preventDefault(); - } -}; -function eventCoords(event) { - return { left: event.clientX, top: event.clientY }; -} -function isNear(event, click) { - let dx = click.x - event.clientX, dy = click.y - event.clientY; - return dx * dx + dy * dy < 100; -} -function runHandlerOnContext(view, propName, pos, inside, event) { - if (inside == -1) - return false; - let $pos = view.state.doc.resolve(inside); - for (let i = $pos.depth + 1; i > 0; i--) { - if (view.someProp(propName, (f) => i > $pos.depth ? f(view, pos, $pos.nodeAfter, $pos.before(i), event, true) : f(view, pos, $pos.node(i), $pos.before(i), event, false))) - return true; - } - return false; -} -function updateSelection(view, selection, origin) { - if (!view.focused) - view.focus(); - if (view.state.selection.eq(selection)) - return; - let tr2 = view.state.tr.setSelection(selection); - tr2.setMeta("pointer", true); - view.dispatch(tr2); -} -function selectClickedLeaf(view, inside) { - if (inside == -1) - return false; - let $pos = view.state.doc.resolve(inside), node = $pos.nodeAfter; - if (node && node.isAtom && NodeSelection.isSelectable(node)) { - updateSelection(view, new NodeSelection($pos)); - return true; - } - return false; -} -function selectClickedNode(view, inside) { - if (inside == -1) - return false; - let sel = view.state.selection, selectedNode, selectAt; - if (sel instanceof NodeSelection) - selectedNode = sel.node; - let $pos = view.state.doc.resolve(inside); - for (let i = $pos.depth + 1; i > 0; i--) { - let node = i > $pos.depth ? $pos.nodeAfter : $pos.node(i); - if (NodeSelection.isSelectable(node)) { - if (selectedNode && sel.$from.depth > 0 && i >= sel.$from.depth && $pos.before(sel.$from.depth + 1) == sel.$from.pos) - selectAt = $pos.before(sel.$from.depth); - else - selectAt = $pos.before(i); - break; - } - } - if (selectAt != null) { - updateSelection(view, NodeSelection.create(view.state.doc, selectAt)); - return true; - } else { - return false; - } -} -function handleSingleClick(view, pos, inside, event, selectNode) { - return runHandlerOnContext(view, "handleClickOn", pos, inside, event) || view.someProp("handleClick", (f) => f(view, pos, event)) || (selectNode ? selectClickedNode(view, inside) : selectClickedLeaf(view, inside)); -} -function handleDoubleClick(view, pos, inside, event) { - return runHandlerOnContext(view, "handleDoubleClickOn", pos, inside, event) || view.someProp("handleDoubleClick", (f) => f(view, pos, event)); -} -function handleTripleClick(view, pos, inside, event) { - return runHandlerOnContext(view, "handleTripleClickOn", pos, inside, event) || view.someProp("handleTripleClick", (f) => f(view, pos, event)) || defaultTripleClick(view, inside, event); -} -function defaultTripleClick(view, inside, event) { - if (event.button != 0) - return false; - let doc2 = view.state.doc; - if (inside == -1) { - if (doc2.inlineContent) { - updateSelection(view, TextSelection.create(doc2, 0, doc2.content.size)); - return true; - } - return false; - } - let $pos = doc2.resolve(inside); - for (let i = $pos.depth + 1; i > 0; i--) { - let node = i > $pos.depth ? $pos.nodeAfter : $pos.node(i); - let nodePos = $pos.before(i); - if (node.inlineContent) - updateSelection(view, TextSelection.create(doc2, nodePos + 1, nodePos + 1 + node.content.size)); - else if (NodeSelection.isSelectable(node)) - updateSelection(view, NodeSelection.create(doc2, nodePos)); - else - continue; - return true; - } -} -function forceDOMFlush(view) { - return endComposition(view); -} -const selectNodeModifier = mac$2 ? "metaKey" : "ctrlKey"; -handlers.mousedown = (view, _event) => { - let event = _event; - view.input.shiftKey = event.shiftKey; - let flushed = forceDOMFlush(view); - let now = Date.now(), type = "singleClick"; - if (now - view.input.lastClick.time < 500 && isNear(event, view.input.lastClick) && !event[selectNodeModifier] && view.input.lastClick.button == event.button) { - if (view.input.lastClick.type == "singleClick") - type = "doubleClick"; - else if (view.input.lastClick.type == "doubleClick") - type = "tripleClick"; - } - view.input.lastClick = { time: now, x: event.clientX, y: event.clientY, type, button: event.button }; - let pos = view.posAtCoords(eventCoords(event)); - if (!pos) - return; - if (type == "singleClick") { - if (view.input.mouseDown) - view.input.mouseDown.done(); - view.input.mouseDown = new MouseDown(view, pos, event, !!flushed); - } else if ((type == "doubleClick" ? handleDoubleClick : handleTripleClick)(view, pos.pos, pos.inside, event)) { - event.preventDefault(); - } else { - setSelectionOrigin(view, "pointer"); - } -}; -class MouseDown { - constructor(view, pos, event, flushed) { - this.view = view; - this.pos = pos; - this.event = event; - this.flushed = flushed; - this.delayedSelectionSync = false; - this.mightDrag = null; - this.startDoc = view.state.doc; - this.selectNode = !!event[selectNodeModifier]; - this.allowDefault = event.shiftKey; - let targetNode, targetPos; - if (pos.inside > -1) { - targetNode = view.state.doc.nodeAt(pos.inside); - targetPos = pos.inside; - } else { - let $pos = view.state.doc.resolve(pos.pos); - targetNode = $pos.parent; - targetPos = $pos.depth ? $pos.before() : 0; - } - const target = flushed ? null : event.target; - const targetDesc = target ? view.docView.nearestDesc(target, true) : null; - this.target = targetDesc && targetDesc.nodeDOM.nodeType == 1 ? targetDesc.nodeDOM : null; - let { selection } = view.state; - if (event.button == 0 && (targetNode.type.spec.draggable && targetNode.type.spec.selectable !== false || selection instanceof NodeSelection && selection.from <= targetPos && selection.to > targetPos)) - this.mightDrag = { - node: targetNode, - pos: targetPos, - addAttr: !!(this.target && !this.target.draggable), - setUneditable: !!(this.target && gecko && !this.target.hasAttribute("contentEditable")) - }; - if (this.target && this.mightDrag && (this.mightDrag.addAttr || this.mightDrag.setUneditable)) { - this.view.domObserver.stop(); - if (this.mightDrag.addAttr) - this.target.draggable = true; - if (this.mightDrag.setUneditable) - setTimeout(() => { - if (this.view.input.mouseDown == this) - this.target.setAttribute("contentEditable", "false"); - }, 20); - this.view.domObserver.start(); - } - view.root.addEventListener("mouseup", this.up = this.up.bind(this)); - view.root.addEventListener("mousemove", this.move = this.move.bind(this)); - setSelectionOrigin(view, "pointer"); - } - done() { - this.view.root.removeEventListener("mouseup", this.up); - this.view.root.removeEventListener("mousemove", this.move); - if (this.mightDrag && this.target) { - this.view.domObserver.stop(); - if (this.mightDrag.addAttr) - this.target.removeAttribute("draggable"); - if (this.mightDrag.setUneditable) - this.target.removeAttribute("contentEditable"); - this.view.domObserver.start(); - } - if (this.delayedSelectionSync) - setTimeout(() => selectionToDOM(this.view)); - this.view.input.mouseDown = null; - } - up(event) { - this.done(); - if (!this.view.dom.contains(event.target)) - return; - let pos = this.pos; - if (this.view.state.doc != this.startDoc) - pos = this.view.posAtCoords(eventCoords(event)); - this.updateAllowDefault(event); - if (this.allowDefault || !pos) { - setSelectionOrigin(this.view, "pointer"); - } else if (handleSingleClick(this.view, pos.pos, pos.inside, event, this.selectNode)) { - event.preventDefault(); - } else if (event.button == 0 && (this.flushed || // Safari ignores clicks on draggable elements - safari && this.mightDrag && !this.mightDrag.node.isAtom || // Chrome will sometimes treat a node selection as a - // cursor, but still report that the node is selected - // when asked through getSelection. You'll then get a - // situation where clicking at the point where that - // (hidden) cursor is doesn't change the selection, and - // thus doesn't get a reaction from ProseMirror. This - // works around that. - chrome && !this.view.state.selection.visible && Math.min(Math.abs(pos.pos - this.view.state.selection.from), Math.abs(pos.pos - this.view.state.selection.to)) <= 2)) { - updateSelection(this.view, Selection.near(this.view.state.doc.resolve(pos.pos))); - event.preventDefault(); - } else { - setSelectionOrigin(this.view, "pointer"); - } - } - move(event) { - this.updateAllowDefault(event); - setSelectionOrigin(this.view, "pointer"); - if (event.buttons == 0) - this.done(); - } - updateAllowDefault(event) { - if (!this.allowDefault && (Math.abs(this.event.x - event.clientX) > 4 || Math.abs(this.event.y - event.clientY) > 4)) - this.allowDefault = true; - } -} -handlers.touchstart = (view) => { - view.input.lastTouch = Date.now(); - forceDOMFlush(view); - setSelectionOrigin(view, "pointer"); -}; -handlers.touchmove = (view) => { - view.input.lastTouch = Date.now(); - setSelectionOrigin(view, "pointer"); -}; -handlers.contextmenu = (view) => forceDOMFlush(view); -function inOrNearComposition(view, event) { - if (view.composing) - return true; - if (safari && Math.abs(event.timeStamp - view.input.compositionEndedAt) < 500) { - view.input.compositionEndedAt = -2e8; - return true; - } - return false; -} -const timeoutComposition = android ? 5e3 : -1; -editHandlers.compositionstart = editHandlers.compositionupdate = (view) => { - if (!view.composing) { - view.domObserver.flush(); - let { state } = view, $pos = state.selection.$to; - if (state.selection instanceof TextSelection && (state.storedMarks || !$pos.textOffset && $pos.parentOffset && $pos.nodeBefore.marks.some((m) => m.type.spec.inclusive === false) || chrome && windows$1 && selectionBeforeUneditable(view))) { - view.markCursor = view.state.storedMarks || $pos.marks(); - endComposition(view, true); - view.markCursor = null; - } else { - endComposition(view, !state.selection.empty); - if (gecko && state.selection.empty && $pos.parentOffset && !$pos.textOffset && $pos.nodeBefore.marks.length) { - let sel = view.domSelectionRange(); - for (let node = sel.focusNode, offset = sel.focusOffset; node && node.nodeType == 1 && offset != 0; ) { - let before = offset < 0 ? node.lastChild : node.childNodes[offset - 1]; - if (!before) - break; - if (before.nodeType == 3) { - let sel2 = view.domSelection(); - if (sel2) - sel2.collapse(before, before.nodeValue.length); - break; - } else { - node = before; - offset = -1; - } - } - } - } - view.input.composing = true; - } - scheduleComposeEnd(view, timeoutComposition); -}; -function selectionBeforeUneditable(view) { - let { focusNode, focusOffset } = view.domSelectionRange(); - if (!focusNode || focusNode.nodeType != 1 || focusOffset >= focusNode.childNodes.length) - return false; - let next = focusNode.childNodes[focusOffset]; - return next.nodeType == 1 && next.contentEditable == "false"; -} -editHandlers.compositionend = (view, event) => { - if (view.composing) { - view.input.composing = false; - view.input.compositionEndedAt = event.timeStamp; - view.input.compositionPendingChanges = view.domObserver.pendingRecords().length ? view.input.compositionID : 0; - view.input.compositionNode = null; - if (view.input.badSafariComposition) - view.domObserver.forceFlush(); - else if (view.input.compositionPendingChanges) - Promise.resolve().then(() => view.domObserver.flush()); - view.input.compositionID++; - scheduleComposeEnd(view, 20); - } -}; -function scheduleComposeEnd(view, delay) { - clearTimeout(view.input.composingTimeout); - if (delay > -1) - view.input.composingTimeout = setTimeout(() => endComposition(view), delay); -} -function clearComposition(view) { - if (view.composing) { - view.input.composing = false; - view.input.compositionEndedAt = timestampFromCustomEvent(); - } - while (view.input.compositionNodes.length > 0) - view.input.compositionNodes.pop().markParentsDirty(); -} -function findCompositionNode(view) { - let sel = view.domSelectionRange(); - if (!sel.focusNode) - return null; - let textBefore = textNodeBefore$1(sel.focusNode, sel.focusOffset); - let textAfter = textNodeAfter$1(sel.focusNode, sel.focusOffset); - if (textBefore && textAfter && textBefore != textAfter) { - let descAfter = textAfter.pmViewDesc, lastChanged = view.domObserver.lastChangedTextNode; - if (textBefore == lastChanged || textAfter == lastChanged) - return lastChanged; - if (!descAfter || !descAfter.isText(textAfter.nodeValue)) { - return textAfter; - } else if (view.input.compositionNode == textAfter) { - let descBefore = textBefore.pmViewDesc; - if (!(!descBefore || !descBefore.isText(textBefore.nodeValue))) - return textAfter; - } - } - return textBefore || textAfter; -} -function timestampFromCustomEvent() { - let event = document.createEvent("Event"); - event.initEvent("event", true, true); - return event.timeStamp; -} -function endComposition(view, restarting = false) { - if (android && view.domObserver.flushingSoon >= 0) - return; - view.domObserver.forceFlush(); - clearComposition(view); - if (restarting || view.docView && view.docView.dirty) { - let sel = selectionFromDOM(view), cur = view.state.selection; - if (sel && !sel.eq(cur)) - view.dispatch(view.state.tr.setSelection(sel)); - else if ((view.markCursor || restarting) && !cur.$from.node(cur.$from.sharedDepth(cur.to)).inlineContent) - view.dispatch(view.state.tr.deleteSelection()); - else - view.updateState(view.state); - return true; - } - return false; -} -function captureCopy(view, dom) { - if (!view.dom.parentNode) - return; - let wrap2 = view.dom.parentNode.appendChild(document.createElement("div")); - wrap2.appendChild(dom); - wrap2.style.cssText = "position: fixed; left: -10000px; top: 10px"; - let sel = getSelection(), range = document.createRange(); - range.selectNodeContents(dom); - view.dom.blur(); - sel.removeAllRanges(); - sel.addRange(range); - setTimeout(() => { - if (wrap2.parentNode) - wrap2.parentNode.removeChild(wrap2); - view.focus(); - }, 50); -} -const brokenClipboardAPI = ie$1 && ie_version < 15 || ios && webkit_version < 604; -handlers.copy = editHandlers.cut = (view, _event) => { - let event = _event; - let sel = view.state.selection, cut2 = event.type == "cut"; - if (sel.empty) - return; - let data = brokenClipboardAPI ? null : event.clipboardData; - let slice2 = sel.content(), { dom, text } = serializeForClipboard(view, slice2); - if (data) { - event.preventDefault(); - data.clearData(); - data.setData("text/html", dom.innerHTML); - data.setData("text/plain", text); - } else { - captureCopy(view, dom); - } - if (cut2) - view.dispatch(view.state.tr.deleteSelection().scrollIntoView().setMeta("uiEvent", "cut")); -}; -function sliceSingleNode(slice2) { - return slice2.openStart == 0 && slice2.openEnd == 0 && slice2.content.childCount == 1 ? slice2.content.firstChild : null; -} -function capturePaste(view, event) { - if (!view.dom.parentNode) - return; - let plainText = view.input.shiftKey || view.state.selection.$from.parent.type.spec.code; - let target = view.dom.parentNode.appendChild(document.createElement(plainText ? "textarea" : "div")); - if (!plainText) - target.contentEditable = "true"; - target.style.cssText = "position: fixed; left: -10000px; top: 10px"; - target.focus(); - let plain = view.input.shiftKey && view.input.lastKeyCode != 45; - setTimeout(() => { - view.focus(); - if (target.parentNode) - target.parentNode.removeChild(target); - if (plainText) - doPaste(view, target.value, null, plain, event); - else - doPaste(view, target.textContent, target.innerHTML, plain, event); - }, 50); -} -function doPaste(view, text, html, preferPlain, event) { - let slice2 = parseFromClipboard(view, text, html, preferPlain, view.state.selection.$from); - if (view.someProp("handlePaste", (f) => f(view, event, slice2 || Slice.empty))) - return true; - if (!slice2) - return false; - let singleNode = sliceSingleNode(slice2); - let tr2 = singleNode ? view.state.tr.replaceSelectionWith(singleNode, preferPlain) : view.state.tr.replaceSelection(slice2); - view.dispatch(tr2.scrollIntoView().setMeta("paste", true).setMeta("uiEvent", "paste")); - return true; -} -function getText$1(clipboardData) { - let text = clipboardData.getData("text/plain") || clipboardData.getData("Text"); - if (text) - return text; - let uris = clipboardData.getData("text/uri-list"); - return uris ? uris.replace(/\r?\n/g, " ") : ""; -} -editHandlers.paste = (view, _event) => { - let event = _event; - if (view.composing && !android) - return; - let data = brokenClipboardAPI ? null : event.clipboardData; - let plain = view.input.shiftKey && view.input.lastKeyCode != 45; - if (data && doPaste(view, getText$1(data), data.getData("text/html"), plain, event)) - event.preventDefault(); - else - capturePaste(view, event); -}; -class Dragging { - constructor(slice2, move, node) { - this.slice = slice2; - this.move = move; - this.node = node; - } -} -const dragCopyModifier = mac$2 ? "altKey" : "ctrlKey"; -function dragMoves(view, event) { - let copy2; - view.someProp("dragCopies", (test) => { - copy2 = copy2 || test(event); - }); - return copy2 != null ? !copy2 : !event[dragCopyModifier]; -} -handlers.dragstart = (view, _event) => { - let event = _event; - let mouseDown = view.input.mouseDown; - if (mouseDown) - mouseDown.done(); - if (!event.dataTransfer) - return; - let sel = view.state.selection; - let pos = sel.empty ? null : view.posAtCoords(eventCoords(event)); - let node; - if (pos && pos.pos >= sel.from && pos.pos <= (sel instanceof NodeSelection ? sel.to - 1 : sel.to)) ; - else if (mouseDown && mouseDown.mightDrag) { - node = NodeSelection.create(view.state.doc, mouseDown.mightDrag.pos); - } else if (event.target && event.target.nodeType == 1) { - let desc = view.docView.nearestDesc(event.target, true); - if (desc && desc.node.type.spec.draggable && desc != view.docView) - node = NodeSelection.create(view.state.doc, desc.posBefore); - } - let draggedSlice = (node || view.state.selection).content(); - let { dom, text, slice: slice2 } = serializeForClipboard(view, draggedSlice); - if (!event.dataTransfer.files.length || !chrome || chrome_version > 120) - event.dataTransfer.clearData(); - event.dataTransfer.setData(brokenClipboardAPI ? "Text" : "text/html", dom.innerHTML); - event.dataTransfer.effectAllowed = "copyMove"; - if (!brokenClipboardAPI) - event.dataTransfer.setData("text/plain", text); - view.dragging = new Dragging(slice2, dragMoves(view, event), node); -}; -handlers.dragend = (view) => { - let dragging = view.dragging; - window.setTimeout(() => { - if (view.dragging == dragging) - view.dragging = null; - }, 50); -}; -editHandlers.dragover = editHandlers.dragenter = (_, e) => e.preventDefault(); -editHandlers.drop = (view, event) => { - try { - handleDrop(view, event, view.dragging); - } finally { - view.dragging = null; - } -}; -function handleDrop(view, event, dragging) { - if (!event.dataTransfer) - return; - let eventPos = view.posAtCoords(eventCoords(event)); - if (!eventPos) - return; - let $mouse = view.state.doc.resolve(eventPos.pos); - let slice2 = dragging && dragging.slice; - if (slice2) { - view.someProp("transformPasted", (f) => { - slice2 = f(slice2, view, false); - }); - } else { - slice2 = parseFromClipboard(view, getText$1(event.dataTransfer), brokenClipboardAPI ? null : event.dataTransfer.getData("text/html"), false, $mouse); - } - let move = !!(dragging && dragMoves(view, event)); - if (view.someProp("handleDrop", (f) => f(view, event, slice2 || Slice.empty, move))) { - event.preventDefault(); - return; - } - if (!slice2) - return; - event.preventDefault(); - let insertPos = slice2 ? dropPoint(view.state.doc, $mouse.pos, slice2) : $mouse.pos; - if (insertPos == null) - insertPos = $mouse.pos; - let tr2 = view.state.tr; - if (move) { - let { node } = dragging; - if (node) - node.replace(tr2); - else - tr2.deleteSelection(); - } - let pos = tr2.mapping.map(insertPos); - let isNode = slice2.openStart == 0 && slice2.openEnd == 0 && slice2.content.childCount == 1; - let beforeInsert = tr2.doc; - if (isNode) - tr2.replaceRangeWith(pos, pos, slice2.content.firstChild); - else - tr2.replaceRange(pos, pos, slice2); - if (tr2.doc.eq(beforeInsert)) - return; - let $pos = tr2.doc.resolve(pos); - if (isNode && NodeSelection.isSelectable(slice2.content.firstChild) && $pos.nodeAfter && $pos.nodeAfter.sameMarkup(slice2.content.firstChild)) { - tr2.setSelection(new NodeSelection($pos)); - } else { - let end = tr2.mapping.map(insertPos); - tr2.mapping.maps[tr2.mapping.maps.length - 1].forEach((_from, _to, _newFrom, newTo) => end = newTo); - tr2.setSelection(selectionBetween(view, $pos, tr2.doc.resolve(end))); - } - view.focus(); - view.dispatch(tr2.setMeta("uiEvent", "drop")); -} -handlers.focus = (view) => { - view.input.lastFocus = Date.now(); - if (!view.focused) { - view.domObserver.stop(); - view.dom.classList.add("ProseMirror-focused"); - view.domObserver.start(); - view.focused = true; - setTimeout(() => { - if (view.docView && view.hasFocus() && !view.domObserver.currentSelection.eq(view.domSelectionRange())) - selectionToDOM(view); - }, 20); - } -}; -handlers.blur = (view, _event) => { - let event = _event; - if (view.focused) { - view.domObserver.stop(); - view.dom.classList.remove("ProseMirror-focused"); - view.domObserver.start(); - if (event.relatedTarget && view.dom.contains(event.relatedTarget)) - view.domObserver.currentSelection.clear(); - view.focused = false; - } -}; -handlers.beforeinput = (view, _event) => { - let event = _event; - if (chrome && android && event.inputType == "deleteContentBackward") { - view.domObserver.flushSoon(); - let { domChangeCount } = view.input; - setTimeout(() => { - if (view.input.domChangeCount != domChangeCount) - return; - view.dom.blur(); - view.focus(); - if (view.someProp("handleKeyDown", (f) => f(view, keyEvent(8, "Backspace")))) - return; - let { $cursor } = view.state.selection; - if ($cursor && $cursor.pos > 0) - view.dispatch(view.state.tr.delete($cursor.pos - 1, $cursor.pos).scrollIntoView()); - }, 50); - } -}; -for (let prop in editHandlers) - handlers[prop] = editHandlers[prop]; -function compareObjs(a, b) { - if (a == b) - return true; - for (let p in a) - if (a[p] !== b[p]) - return false; - for (let p in b) - if (!(p in a)) - return false; - return true; -} -class WidgetType { - constructor(toDOM, spec) { - this.toDOM = toDOM; - this.spec = spec || noSpec; - this.side = this.spec.side || 0; - } - map(mapping, span, offset, oldOffset) { - let { pos, deleted } = mapping.mapResult(span.from + oldOffset, this.side < 0 ? -1 : 1); - return deleted ? null : new Decoration(pos - offset, pos - offset, this); - } - valid() { - return true; - } - eq(other) { - return this == other || other instanceof WidgetType && (this.spec.key && this.spec.key == other.spec.key || this.toDOM == other.toDOM && compareObjs(this.spec, other.spec)); - } - destroy(node) { - if (this.spec.destroy) - this.spec.destroy(node); - } -} -class InlineType { - constructor(attrs, spec) { - this.attrs = attrs; - this.spec = spec || noSpec; - } - map(mapping, span, offset, oldOffset) { - let from2 = mapping.map(span.from + oldOffset, this.spec.inclusiveStart ? -1 : 1) - offset; - let to = mapping.map(span.to + oldOffset, this.spec.inclusiveEnd ? 1 : -1) - offset; - return from2 >= to ? null : new Decoration(from2, to, this); - } - valid(_, span) { - return span.from < span.to; - } - eq(other) { - return this == other || other instanceof InlineType && compareObjs(this.attrs, other.attrs) && compareObjs(this.spec, other.spec); - } - static is(span) { - return span.type instanceof InlineType; - } - destroy() { - } -} -class NodeType2 { - constructor(attrs, spec) { - this.attrs = attrs; - this.spec = spec || noSpec; - } - map(mapping, span, offset, oldOffset) { - let from2 = mapping.mapResult(span.from + oldOffset, 1); - if (from2.deleted) - return null; - let to = mapping.mapResult(span.to + oldOffset, -1); - if (to.deleted || to.pos <= from2.pos) - return null; - return new Decoration(from2.pos - offset, to.pos - offset, this); - } - valid(node, span) { - let { index, offset } = node.content.findIndex(span.from), child; - return offset == span.from && !(child = node.child(index)).isText && offset + child.nodeSize == span.to; - } - eq(other) { - return this == other || other instanceof NodeType2 && compareObjs(this.attrs, other.attrs) && compareObjs(this.spec, other.spec); - } - destroy() { - } -} -class Decoration { - /** - @internal - */ - constructor(from2, to, type) { - this.from = from2; - this.to = to; - this.type = type; - } - /** - @internal - */ - copy(from2, to) { - return new Decoration(from2, to, this.type); - } - /** - @internal - */ - eq(other, offset = 0) { - return this.type.eq(other.type) && this.from + offset == other.from && this.to + offset == other.to; - } - /** - @internal - */ - map(mapping, offset, oldOffset) { - return this.type.map(mapping, this, offset, oldOffset); - } - /** - Creates a widget decoration, which is a DOM node that's shown in - the document at the given position. It is recommended that you - delay rendering the widget by passing a function that will be - called when the widget is actually drawn in a view, but you can - also directly pass a DOM node. `getPos` can be used to find the - widget's current document position. - */ - static widget(pos, toDOM, spec) { - return new Decoration(pos, pos, new WidgetType(toDOM, spec)); - } - /** - Creates an inline decoration, which adds the given attributes to - each inline node between `from` and `to`. - */ - static inline(from2, to, attrs, spec) { - return new Decoration(from2, to, new InlineType(attrs, spec)); - } - /** - Creates a node decoration. `from` and `to` should point precisely - before and after a node in the document. That node, and only that - node, will receive the given attributes. - */ - static node(from2, to, attrs, spec) { - return new Decoration(from2, to, new NodeType2(attrs, spec)); - } - /** - The spec provided when creating this decoration. Can be useful - if you've stored extra information in that object. - */ - get spec() { - return this.type.spec; - } - /** - @internal - */ - get inline() { - return this.type instanceof InlineType; - } - /** - @internal - */ - get widget() { - return this.type instanceof WidgetType; - } -} -const none = [], noSpec = {}; -class DecorationSet { - /** - @internal - */ - constructor(local, children) { - this.local = local.length ? local : none; - this.children = children.length ? children : none; - } - /** - Create a set of decorations, using the structure of the given - document. This will consume (modify) the `decorations` array, so - you must make a copy if you want need to preserve that. - */ - static create(doc2, decorations) { - return decorations.length ? buildTree(decorations, doc2, 0, noSpec) : empty; - } - /** - Find all decorations in this set which touch the given range - (including decorations that start or end directly at the - boundaries) and match the given predicate on their spec. When - `start` and `end` are omitted, all decorations in the set are - considered. When `predicate` isn't given, all decorations are - assumed to match. - */ - find(start, end, predicate) { - let result = []; - this.findInner(start == null ? 0 : start, end == null ? 1e9 : end, result, 0, predicate); - return result; - } - findInner(start, end, result, offset, predicate) { - for (let i = 0; i < this.local.length; i++) { - let span = this.local[i]; - if (span.from <= end && span.to >= start && (!predicate || predicate(span.spec))) - result.push(span.copy(span.from + offset, span.to + offset)); - } - for (let i = 0; i < this.children.length; i += 3) { - if (this.children[i] < end && this.children[i + 1] > start) { - let childOff = this.children[i] + 1; - this.children[i + 2].findInner(start - childOff, end - childOff, result, offset + childOff, predicate); - } - } - } - /** - Map the set of decorations in response to a change in the - document. - */ - map(mapping, doc2, options) { - if (this == empty || mapping.maps.length == 0) - return this; - return this.mapInner(mapping, doc2, 0, 0, options || noSpec); - } - /** - @internal - */ - mapInner(mapping, node, offset, oldOffset, options) { - let newLocal; - for (let i = 0; i < this.local.length; i++) { - let mapped = this.local[i].map(mapping, offset, oldOffset); - if (mapped && mapped.type.valid(node, mapped)) - (newLocal || (newLocal = [])).push(mapped); - else if (options.onRemove) - options.onRemove(this.local[i].spec); - } - if (this.children.length) - return mapChildren(this.children, newLocal || [], mapping, node, offset, oldOffset, options); - else - return newLocal ? new DecorationSet(newLocal.sort(byPos), none) : empty; - } - /** - Add the given array of decorations to the ones in the set, - producing a new set. Consumes the `decorations` array. Needs - access to the current document to create the appropriate tree - structure. - */ - add(doc2, decorations) { - if (!decorations.length) - return this; - if (this == empty) - return DecorationSet.create(doc2, decorations); - return this.addInner(doc2, decorations, 0); - } - addInner(doc2, decorations, offset) { - let children, childIndex = 0; - doc2.forEach((childNode, childOffset) => { - let baseOffset = childOffset + offset, found2; - if (!(found2 = takeSpansForNode(decorations, childNode, baseOffset))) - return; - if (!children) - children = this.children.slice(); - while (childIndex < children.length && children[childIndex] < childOffset) - childIndex += 3; - if (children[childIndex] == childOffset) - children[childIndex + 2] = children[childIndex + 2].addInner(childNode, found2, baseOffset + 1); - else - children.splice(childIndex, 0, childOffset, childOffset + childNode.nodeSize, buildTree(found2, childNode, baseOffset + 1, noSpec)); - childIndex += 3; - }); - let local = moveSpans(childIndex ? withoutNulls(decorations) : decorations, -offset); - for (let i = 0; i < local.length; i++) - if (!local[i].type.valid(doc2, local[i])) - local.splice(i--, 1); - return new DecorationSet(local.length ? this.local.concat(local).sort(byPos) : this.local, children || this.children); - } - /** - Create a new set that contains the decorations in this set, minus - the ones in the given array. - */ - remove(decorations) { - if (decorations.length == 0 || this == empty) - return this; - return this.removeInner(decorations, 0); - } - removeInner(decorations, offset) { - let children = this.children, local = this.local; - for (let i = 0; i < children.length; i += 3) { - let found2; - let from2 = children[i] + offset, to = children[i + 1] + offset; - for (let j = 0, span; j < decorations.length; j++) - if (span = decorations[j]) { - if (span.from > from2 && span.to < to) { - decorations[j] = null; - (found2 || (found2 = [])).push(span); - } - } - if (!found2) - continue; - if (children == this.children) - children = this.children.slice(); - let removed = children[i + 2].removeInner(found2, from2 + 1); - if (removed != empty) { - children[i + 2] = removed; - } else { - children.splice(i, 3); - i -= 3; - } - } - if (local.length) { - for (let i = 0, span; i < decorations.length; i++) - if (span = decorations[i]) { - for (let j = 0; j < local.length; j++) - if (local[j].eq(span, offset)) { - if (local == this.local) - local = this.local.slice(); - local.splice(j--, 1); - } - } - } - if (children == this.children && local == this.local) - return this; - return local.length || children.length ? new DecorationSet(local, children) : empty; - } - forChild(offset, node) { - if (this == empty) - return this; - if (node.isLeaf) - return DecorationSet.empty; - let child, local; - for (let i = 0; i < this.children.length; i += 3) - if (this.children[i] >= offset) { - if (this.children[i] == offset) - child = this.children[i + 2]; - break; - } - let start = offset + 1, end = start + node.content.size; - for (let i = 0; i < this.local.length; i++) { - let dec = this.local[i]; - if (dec.from < end && dec.to > start && dec.type instanceof InlineType) { - let from2 = Math.max(start, dec.from) - start, to = Math.min(end, dec.to) - start; - if (from2 < to) - (local || (local = [])).push(dec.copy(from2, to)); - } - } - if (local) { - let localSet = new DecorationSet(local.sort(byPos), none); - return child ? new DecorationGroup([localSet, child]) : localSet; - } - return child || empty; - } - /** - @internal - */ - eq(other) { - if (this == other) - return true; - if (!(other instanceof DecorationSet) || this.local.length != other.local.length || this.children.length != other.children.length) - return false; - for (let i = 0; i < this.local.length; i++) - if (!this.local[i].eq(other.local[i])) - return false; - for (let i = 0; i < this.children.length; i += 3) - if (this.children[i] != other.children[i] || this.children[i + 1] != other.children[i + 1] || !this.children[i + 2].eq(other.children[i + 2])) - return false; - return true; - } - /** - @internal - */ - locals(node) { - return removeOverlap(this.localsInner(node)); - } - /** - @internal - */ - localsInner(node) { - if (this == empty) - return none; - if (node.inlineContent || !this.local.some(InlineType.is)) - return this.local; - let result = []; - for (let i = 0; i < this.local.length; i++) { - if (!(this.local[i].type instanceof InlineType)) - result.push(this.local[i]); - } - return result; - } - forEachSet(f) { - f(this); - } -} -DecorationSet.empty = new DecorationSet([], []); -DecorationSet.removeOverlap = removeOverlap; -const empty = DecorationSet.empty; -class DecorationGroup { - constructor(members) { - this.members = members; - } - map(mapping, doc2) { - const mappedDecos = this.members.map((member) => member.map(mapping, doc2, noSpec)); - return DecorationGroup.from(mappedDecos); - } - forChild(offset, child) { - if (child.isLeaf) - return DecorationSet.empty; - let found2 = []; - for (let i = 0; i < this.members.length; i++) { - let result = this.members[i].forChild(offset, child); - if (result == empty) - continue; - if (result instanceof DecorationGroup) - found2 = found2.concat(result.members); - else - found2.push(result); - } - return DecorationGroup.from(found2); - } - eq(other) { - if (!(other instanceof DecorationGroup) || other.members.length != this.members.length) - return false; - for (let i = 0; i < this.members.length; i++) - if (!this.members[i].eq(other.members[i])) - return false; - return true; - } - locals(node) { - let result, sorted = true; - for (let i = 0; i < this.members.length; i++) { - let locals = this.members[i].localsInner(node); - if (!locals.length) - continue; - if (!result) { - result = locals; - } else { - if (sorted) { - result = result.slice(); - sorted = false; - } - for (let j = 0; j < locals.length; j++) - result.push(locals[j]); - } - } - return result ? removeOverlap(sorted ? result : result.sort(byPos)) : none; - } - // Create a group for the given array of decoration sets, or return - // a single set when possible. - static from(members) { - switch (members.length) { - case 0: - return empty; - case 1: - return members[0]; - default: - return new DecorationGroup(members.every((m) => m instanceof DecorationSet) ? members : members.reduce((r, m) => r.concat(m instanceof DecorationSet ? m : m.members), [])); - } - } - forEachSet(f) { - for (let i = 0; i < this.members.length; i++) - this.members[i].forEachSet(f); - } -} -function mapChildren(oldChildren, newLocal, mapping, node, offset, oldOffset, options) { - let children = oldChildren.slice(); - for (let i = 0, baseOffset = oldOffset; i < mapping.maps.length; i++) { - let moved = 0; - mapping.maps[i].forEach((oldStart, oldEnd, newStart, newEnd) => { - let dSize = newEnd - newStart - (oldEnd - oldStart); - for (let i2 = 0; i2 < children.length; i2 += 3) { - let end = children[i2 + 1]; - if (end < 0 || oldStart > end + baseOffset - moved) - continue; - let start = children[i2] + baseOffset - moved; - if (oldEnd >= start) { - children[i2 + 1] = oldStart <= start ? -2 : -1; - } else if (oldStart >= baseOffset && dSize) { - children[i2] += dSize; - children[i2 + 1] += dSize; - } - } - moved += dSize; - }); - baseOffset = mapping.maps[i].map(baseOffset, -1); - } - let mustRebuild = false; - for (let i = 0; i < children.length; i += 3) - if (children[i + 1] < 0) { - if (children[i + 1] == -2) { - mustRebuild = true; - children[i + 1] = -1; - continue; - } - let from2 = mapping.map(oldChildren[i] + oldOffset), fromLocal = from2 - offset; - if (fromLocal < 0 || fromLocal >= node.content.size) { - mustRebuild = true; - continue; - } - let to = mapping.map(oldChildren[i + 1] + oldOffset, -1), toLocal = to - offset; - let { index, offset: childOffset } = node.content.findIndex(fromLocal); - let childNode = node.maybeChild(index); - if (childNode && childOffset == fromLocal && childOffset + childNode.nodeSize == toLocal) { - let mapped = children[i + 2].mapInner(mapping, childNode, from2 + 1, oldChildren[i] + oldOffset + 1, options); - if (mapped != empty) { - children[i] = fromLocal; - children[i + 1] = toLocal; - children[i + 2] = mapped; - } else { - children[i + 1] = -2; - mustRebuild = true; - } - } else { - mustRebuild = true; - } - } - if (mustRebuild) { - let decorations = mapAndGatherRemainingDecorations(children, oldChildren, newLocal, mapping, offset, oldOffset, options); - let built = buildTree(decorations, node, 0, options); - newLocal = built.local; - for (let i = 0; i < children.length; i += 3) - if (children[i + 1] < 0) { - children.splice(i, 3); - i -= 3; - } - for (let i = 0, j = 0; i < built.children.length; i += 3) { - let from2 = built.children[i]; - while (j < children.length && children[j] < from2) - j += 3; - children.splice(j, 0, built.children[i], built.children[i + 1], built.children[i + 2]); - } - } - return new DecorationSet(newLocal.sort(byPos), children); -} -function moveSpans(spans, offset) { - if (!offset || !spans.length) - return spans; - let result = []; - for (let i = 0; i < spans.length; i++) { - let span = spans[i]; - result.push(new Decoration(span.from + offset, span.to + offset, span.type)); - } - return result; -} -function mapAndGatherRemainingDecorations(children, oldChildren, decorations, mapping, offset, oldOffset, options) { - function gather(set, oldOffset2) { - for (let i = 0; i < set.local.length; i++) { - let mapped = set.local[i].map(mapping, offset, oldOffset2); - if (mapped) - decorations.push(mapped); - else if (options.onRemove) - options.onRemove(set.local[i].spec); - } - for (let i = 0; i < set.children.length; i += 3) - gather(set.children[i + 2], set.children[i] + oldOffset2 + 1); - } - for (let i = 0; i < children.length; i += 3) - if (children[i + 1] == -1) - gather(children[i + 2], oldChildren[i] + oldOffset + 1); - return decorations; -} -function takeSpansForNode(spans, node, offset) { - if (node.isLeaf) - return null; - let end = offset + node.nodeSize, found2 = null; - for (let i = 0, span; i < spans.length; i++) { - if ((span = spans[i]) && span.from > offset && span.to < end) { - (found2 || (found2 = [])).push(span); - spans[i] = null; - } - } - return found2; -} -function withoutNulls(array) { - let result = []; - for (let i = 0; i < array.length; i++) - if (array[i] != null) - result.push(array[i]); - return result; -} -function buildTree(spans, node, offset, options) { - let children = [], hasNulls = false; - node.forEach((childNode, localStart) => { - let found2 = takeSpansForNode(spans, childNode, localStart + offset); - if (found2) { - hasNulls = true; - let subtree = buildTree(found2, childNode, offset + localStart + 1, options); - if (subtree != empty) - children.push(localStart, localStart + childNode.nodeSize, subtree); - } - }); - let locals = moveSpans(hasNulls ? withoutNulls(spans) : spans, -offset).sort(byPos); - for (let i = 0; i < locals.length; i++) - if (!locals[i].type.valid(node, locals[i])) { - if (options.onRemove) - options.onRemove(locals[i].spec); - locals.splice(i--, 1); - } - return locals.length || children.length ? new DecorationSet(locals, children) : empty; -} -function byPos(a, b) { - return a.from - b.from || a.to - b.to; -} -function removeOverlap(spans) { - let working = spans; - for (let i = 0; i < working.length - 1; i++) { - let span = working[i]; - if (span.from != span.to) - for (let j = i + 1; j < working.length; j++) { - let next = working[j]; - if (next.from == span.from) { - if (next.to != span.to) { - if (working == spans) - working = spans.slice(); - working[j] = next.copy(next.from, span.to); - insertAhead(working, j + 1, next.copy(span.to, next.to)); - } - continue; - } else { - if (next.from < span.to) { - if (working == spans) - working = spans.slice(); - working[i] = span.copy(span.from, next.from); - insertAhead(working, j, span.copy(next.from, span.to)); - } - break; - } - } - } - return working; -} -function insertAhead(array, i, deco) { - while (i < array.length && byPos(deco, array[i]) > 0) - i++; - array.splice(i, 0, deco); -} -function viewDecorations(view) { - let found2 = []; - view.someProp("decorations", (f) => { - let result = f(view.state); - if (result && result != empty) - found2.push(result); - }); - if (view.cursorWrapper) - found2.push(DecorationSet.create(view.state.doc, [view.cursorWrapper.deco])); - return DecorationGroup.from(found2); -} -const observeOptions = { - childList: true, - characterData: true, - characterDataOldValue: true, - attributes: true, - attributeOldValue: true, - subtree: true -}; -const useCharData = ie$1 && ie_version <= 11; -class SelectionState { - constructor() { - this.anchorNode = null; - this.anchorOffset = 0; - this.focusNode = null; - this.focusOffset = 0; - } - set(sel) { - this.anchorNode = sel.anchorNode; - this.anchorOffset = sel.anchorOffset; - this.focusNode = sel.focusNode; - this.focusOffset = sel.focusOffset; - } - clear() { - this.anchorNode = this.focusNode = null; - } - eq(sel) { - return sel.anchorNode == this.anchorNode && sel.anchorOffset == this.anchorOffset && sel.focusNode == this.focusNode && sel.focusOffset == this.focusOffset; - } -} -class DOMObserver { - constructor(view, handleDOMChange) { - this.view = view; - this.handleDOMChange = handleDOMChange; - this.queue = []; - this.flushingSoon = -1; - this.observer = null; - this.currentSelection = new SelectionState(); - this.onCharData = null; - this.suppressingSelectionUpdates = false; - this.lastChangedTextNode = null; - this.observer = window.MutationObserver && new window.MutationObserver((mutations) => { - for (let i = 0; i < mutations.length; i++) - this.queue.push(mutations[i]); - if (ie$1 && ie_version <= 11 && mutations.some((m) => m.type == "childList" && m.removedNodes.length || m.type == "characterData" && m.oldValue.length > m.target.nodeValue.length)) { - this.flushSoon(); - } else if (safari && view.composing && mutations.some((m) => m.type == "childList" && m.target.nodeName == "TR")) { - view.input.badSafariComposition = true; - this.flushSoon(); - } else { - this.flush(); - } - }); - if (useCharData) { - this.onCharData = (e) => { - this.queue.push({ target: e.target, type: "characterData", oldValue: e.prevValue }); - this.flushSoon(); - }; - } - this.onSelectionChange = this.onSelectionChange.bind(this); - } - flushSoon() { - if (this.flushingSoon < 0) - this.flushingSoon = window.setTimeout(() => { - this.flushingSoon = -1; - this.flush(); - }, 20); - } - forceFlush() { - if (this.flushingSoon > -1) { - window.clearTimeout(this.flushingSoon); - this.flushingSoon = -1; - this.flush(); - } - } - start() { - if (this.observer) { - this.observer.takeRecords(); - this.observer.observe(this.view.dom, observeOptions); - } - if (this.onCharData) - this.view.dom.addEventListener("DOMCharacterDataModified", this.onCharData); - this.connectSelection(); - } - stop() { - if (this.observer) { - let take = this.observer.takeRecords(); - if (take.length) { - for (let i = 0; i < take.length; i++) - this.queue.push(take[i]); - window.setTimeout(() => this.flush(), 20); - } - this.observer.disconnect(); - } - if (this.onCharData) - this.view.dom.removeEventListener("DOMCharacterDataModified", this.onCharData); - this.disconnectSelection(); - } - connectSelection() { - this.view.dom.ownerDocument.addEventListener("selectionchange", this.onSelectionChange); - } - disconnectSelection() { - this.view.dom.ownerDocument.removeEventListener("selectionchange", this.onSelectionChange); - } - suppressSelectionUpdates() { - this.suppressingSelectionUpdates = true; - setTimeout(() => this.suppressingSelectionUpdates = false, 50); - } - onSelectionChange() { - if (!hasFocusAndSelection(this.view)) - return; - if (this.suppressingSelectionUpdates) - return selectionToDOM(this.view); - if (ie$1 && ie_version <= 11 && !this.view.state.selection.empty) { - let sel = this.view.domSelectionRange(); - if (sel.focusNode && isEquivalentPosition(sel.focusNode, sel.focusOffset, sel.anchorNode, sel.anchorOffset)) - return this.flushSoon(); - } - this.flush(); - } - setCurSelection() { - this.currentSelection.set(this.view.domSelectionRange()); - } - ignoreSelectionChange(sel) { - if (!sel.focusNode) - return true; - let ancestors = /* @__PURE__ */ new Set(), container; - for (let scan = sel.focusNode; scan; scan = parentNode(scan)) - ancestors.add(scan); - for (let scan = sel.anchorNode; scan; scan = parentNode(scan)) - if (ancestors.has(scan)) { - container = scan; - break; - } - let desc = container && this.view.docView.nearestDesc(container); - if (desc && desc.ignoreMutation({ - type: "selection", - target: container.nodeType == 3 ? container.parentNode : container - })) { - this.setCurSelection(); - return true; - } - } - pendingRecords() { - if (this.observer) - for (let mut of this.observer.takeRecords()) - this.queue.push(mut); - return this.queue; - } - flush() { - let { view } = this; - if (!view.docView || this.flushingSoon > -1) - return; - let mutations = this.pendingRecords(); - if (mutations.length) - this.queue = []; - let sel = view.domSelectionRange(); - let newSel = !this.suppressingSelectionUpdates && !this.currentSelection.eq(sel) && hasFocusAndSelection(view) && !this.ignoreSelectionChange(sel); - let from2 = -1, to = -1, typeOver = false, added = []; - if (view.editable) { - for (let i = 0; i < mutations.length; i++) { - let result = this.registerMutation(mutations[i], added); - if (result) { - from2 = from2 < 0 ? result.from : Math.min(result.from, from2); - to = to < 0 ? result.to : Math.max(result.to, to); - if (result.typeOver) - typeOver = true; - } - } - } - if (added.some((n) => n.nodeName == "BR") && (view.input.lastKeyCode == 8 || view.input.lastKeyCode == 46)) { - for (let node of added) - if (node.nodeName == "BR" && node.parentNode) { - let after = node.nextSibling; - while (after && after.nodeType == 1) { - if (after.contentEditable == "false") { - node.parentNode.removeChild(node); - break; - } - after = after.firstChild; - } - } - } else if (gecko && added.length) { - let brs = added.filter((n) => n.nodeName == "BR"); - if (brs.length == 2) { - let [a, b] = brs; - if (a.parentNode && a.parentNode.parentNode == b.parentNode) - b.remove(); - else - a.remove(); - } else { - let { focusNode } = this.currentSelection; - for (let br of brs) { - let parent = br.parentNode; - if (parent && parent.nodeName == "LI" && (!focusNode || blockParent(view, focusNode) != parent)) - br.remove(); - } - } - } - let readSel = null; - if (from2 < 0 && newSel && view.input.lastFocus > Date.now() - 200 && Math.max(view.input.lastTouch, view.input.lastClick.time) < Date.now() - 300 && selectionCollapsed(sel) && (readSel = selectionFromDOM(view)) && readSel.eq(Selection.near(view.state.doc.resolve(0), 1))) { - view.input.lastFocus = 0; - selectionToDOM(view); - this.currentSelection.set(sel); - view.scrollToSelection(); - } else if (from2 > -1 || newSel) { - if (from2 > -1) { - view.docView.markDirty(from2, to); - checkCSS(view); - } - if (view.input.badSafariComposition) { - view.input.badSafariComposition = false; - fixUpBadSafariComposition(view, added); - } - this.handleDOMChange(from2, to, typeOver, added); - if (view.docView && view.docView.dirty) - view.updateState(view.state); - else if (!this.currentSelection.eq(sel)) - selectionToDOM(view); - this.currentSelection.set(sel); - } - } - registerMutation(mut, added) { - if (added.indexOf(mut.target) > -1) - return null; - let desc = this.view.docView.nearestDesc(mut.target); - if (mut.type == "attributes" && (desc == this.view.docView || mut.attributeName == "contenteditable" || // Firefox sometimes fires spurious events for null/empty styles - mut.attributeName == "style" && !mut.oldValue && !mut.target.getAttribute("style"))) - return null; - if (!desc || desc.ignoreMutation(mut)) - return null; - if (mut.type == "childList") { - for (let i = 0; i < mut.addedNodes.length; i++) { - let node = mut.addedNodes[i]; - added.push(node); - if (node.nodeType == 3) - this.lastChangedTextNode = node; - } - if (desc.contentDOM && desc.contentDOM != desc.dom && !desc.contentDOM.contains(mut.target)) - return { from: desc.posBefore, to: desc.posAfter }; - let prev = mut.previousSibling, next = mut.nextSibling; - if (ie$1 && ie_version <= 11 && mut.addedNodes.length) { - for (let i = 0; i < mut.addedNodes.length; i++) { - let { previousSibling, nextSibling } = mut.addedNodes[i]; - if (!previousSibling || Array.prototype.indexOf.call(mut.addedNodes, previousSibling) < 0) - prev = previousSibling; - if (!nextSibling || Array.prototype.indexOf.call(mut.addedNodes, nextSibling) < 0) - next = nextSibling; - } - } - let fromOffset = prev && prev.parentNode == mut.target ? domIndex(prev) + 1 : 0; - let from2 = desc.localPosFromDOM(mut.target, fromOffset, -1); - let toOffset = next && next.parentNode == mut.target ? domIndex(next) : mut.target.childNodes.length; - let to = desc.localPosFromDOM(mut.target, toOffset, 1); - return { from: from2, to }; - } else if (mut.type == "attributes") { - return { from: desc.posAtStart - desc.border, to: desc.posAtEnd + desc.border }; - } else { - this.lastChangedTextNode = mut.target; - return { - from: desc.posAtStart, - to: desc.posAtEnd, - // An event was generated for a text change that didn't change - // any text. Mark the dom change to fall back to assuming the - // selection was typed over with an identical value if it can't - // find another change. - typeOver: mut.target.nodeValue == mut.oldValue - }; - } - } -} -let cssChecked = /* @__PURE__ */ new WeakMap(); -let cssCheckWarned = false; -function checkCSS(view) { - if (cssChecked.has(view)) - return; - cssChecked.set(view, null); - if (["normal", "nowrap", "pre-line"].indexOf(getComputedStyle(view.dom).whiteSpace) !== -1) { - view.requiresGeckoHackNode = gecko; - if (cssCheckWarned) - return; - console["warn"]("ProseMirror expects the CSS white-space property to be set, preferably to 'pre-wrap'. It is recommended to load style/prosemirror.css from the prosemirror-view package."); - cssCheckWarned = true; - } -} -function rangeToSelectionRange(view, range) { - let anchorNode = range.startContainer, anchorOffset = range.startOffset; - let focusNode = range.endContainer, focusOffset = range.endOffset; - let currentAnchor = view.domAtPos(view.state.selection.anchor); - if (isEquivalentPosition(currentAnchor.node, currentAnchor.offset, focusNode, focusOffset)) - [anchorNode, anchorOffset, focusNode, focusOffset] = [focusNode, focusOffset, anchorNode, anchorOffset]; - return { anchorNode, anchorOffset, focusNode, focusOffset }; -} -function safariShadowSelectionRange(view, selection) { - if (selection.getComposedRanges) { - let range = selection.getComposedRanges(view.root)[0]; - if (range) - return rangeToSelectionRange(view, range); - } - let found2; - function read(event) { - event.preventDefault(); - event.stopImmediatePropagation(); - found2 = event.getTargetRanges()[0]; - } - view.dom.addEventListener("beforeinput", read, true); - document.execCommand("indent"); - view.dom.removeEventListener("beforeinput", read, true); - return found2 ? rangeToSelectionRange(view, found2) : null; -} -function blockParent(view, node) { - for (let p = node.parentNode; p && p != view.dom; p = p.parentNode) { - let desc = view.docView.nearestDesc(p, true); - if (desc && desc.node.isBlock) - return p; - } - return null; -} -function fixUpBadSafariComposition(view, addedNodes) { - var _a; - let { focusNode, focusOffset } = view.domSelectionRange(); - for (let node of addedNodes) { - if (((_a = node.parentNode) === null || _a === void 0 ? void 0 : _a.nodeName) == "TR") { - let nextCell = node.nextSibling; - while (nextCell && (nextCell.nodeName != "TD" && nextCell.nodeName != "TH")) - nextCell = nextCell.nextSibling; - if (nextCell) { - let parent = nextCell; - for (; ; ) { - let first2 = parent.firstChild; - if (!first2 || first2.nodeType != 1 || first2.contentEditable == "false" || /^(BR|IMG)$/.test(first2.nodeName)) - break; - parent = first2; - } - parent.insertBefore(node, parent.firstChild); - if (focusNode == node) - view.domSelection().collapse(node, focusOffset); - } else { - node.parentNode.removeChild(node); - } - } - } -} -function parseBetween(view, from_, to_) { - let { node: parent, fromOffset, toOffset, from: from2, to } = view.docView.parseRange(from_, to_); - let domSel = view.domSelectionRange(); - let find2; - let anchor = domSel.anchorNode; - if (anchor && view.dom.contains(anchor.nodeType == 1 ? anchor : anchor.parentNode)) { - find2 = [{ node: anchor, offset: domSel.anchorOffset }]; - if (!selectionCollapsed(domSel)) - find2.push({ node: domSel.focusNode, offset: domSel.focusOffset }); - } - if (chrome && view.input.lastKeyCode === 8) { - for (let off = toOffset; off > fromOffset; off--) { - let node = parent.childNodes[off - 1], desc = node.pmViewDesc; - if (node.nodeName == "BR" && !desc) { - toOffset = off; - break; - } - if (!desc || desc.size) - break; - } - } - let startDoc = view.state.doc; - let parser = view.someProp("domParser") || DOMParser.fromSchema(view.state.schema); - let $from = startDoc.resolve(from2); - let sel = null, doc2 = parser.parse(parent, { - topNode: $from.parent, - topMatch: $from.parent.contentMatchAt($from.index()), - topOpen: true, - from: fromOffset, - to: toOffset, - preserveWhitespace: $from.parent.type.whitespace == "pre" ? "full" : true, - findPositions: find2, - ruleFromNode, - context: $from - }); - if (find2 && find2[0].pos != null) { - let anchor2 = find2[0].pos, head = find2[1] && find2[1].pos; - if (head == null) - head = anchor2; - sel = { anchor: anchor2 + from2, head: head + from2 }; - } - return { doc: doc2, sel, from: from2, to }; -} -function ruleFromNode(dom) { - let desc = dom.pmViewDesc; - if (desc) { - return desc.parseRule(); - } else if (dom.nodeName == "BR" && dom.parentNode) { - if (safari && /^(ul|ol)$/i.test(dom.parentNode.nodeName)) { - let skip = document.createElement("div"); - skip.appendChild(document.createElement("li")); - return { skip }; - } else if (dom.parentNode.lastChild == dom || safari && /^(tr|table)$/i.test(dom.parentNode.nodeName)) { - return { ignore: true }; - } - } else if (dom.nodeName == "IMG" && dom.getAttribute("mark-placeholder")) { - return { ignore: true }; - } - return null; -} -const isInline = /^(a|abbr|acronym|b|bd[io]|big|br|button|cite|code|data(list)?|del|dfn|em|i|img|ins|kbd|label|map|mark|meter|output|q|ruby|s|samp|small|span|strong|su[bp]|time|u|tt|var)$/i; -function readDOMChange(view, from2, to, typeOver, addedNodes) { - let compositionID = view.input.compositionPendingChanges || (view.composing ? view.input.compositionID : 0); - view.input.compositionPendingChanges = 0; - if (from2 < 0) { - let origin = view.input.lastSelectionTime > Date.now() - 50 ? view.input.lastSelectionOrigin : null; - let newSel = selectionFromDOM(view, origin); - if (newSel && !view.state.selection.eq(newSel)) { - if (chrome && android && view.input.lastKeyCode === 13 && Date.now() - 100 < view.input.lastKeyCodeTime && view.someProp("handleKeyDown", (f) => f(view, keyEvent(13, "Enter")))) - return; - let tr2 = view.state.tr.setSelection(newSel); - if (origin == "pointer") - tr2.setMeta("pointer", true); - else if (origin == "key") - tr2.scrollIntoView(); - if (compositionID) - tr2.setMeta("composition", compositionID); - view.dispatch(tr2); - } - return; - } - let $before = view.state.doc.resolve(from2); - let shared = $before.sharedDepth(to); - from2 = $before.before(shared + 1); - to = view.state.doc.resolve(to).after(shared + 1); - let sel = view.state.selection; - let parse = parseBetween(view, from2, to); - let doc2 = view.state.doc, compare = doc2.slice(parse.from, parse.to); - let preferredPos, preferredSide; - if (view.input.lastKeyCode === 8 && Date.now() - 100 < view.input.lastKeyCodeTime) { - preferredPos = view.state.selection.to; - preferredSide = "end"; - } else { - preferredPos = view.state.selection.from; - preferredSide = "start"; - } - view.input.lastKeyCode = null; - let change = findDiff(compare.content, parse.doc.content, parse.from, preferredPos, preferredSide); - if (change) - view.input.domChangeCount++; - if ((ios && view.input.lastIOSEnter > Date.now() - 225 || android) && addedNodes.some((n) => n.nodeType == 1 && !isInline.test(n.nodeName)) && (!change || change.endA >= change.endB) && view.someProp("handleKeyDown", (f) => f(view, keyEvent(13, "Enter")))) { - view.input.lastIOSEnter = 0; - return; - } - if (!change) { - if (typeOver && sel instanceof TextSelection && !sel.empty && sel.$head.sameParent(sel.$anchor) && !view.composing && !(parse.sel && parse.sel.anchor != parse.sel.head)) { - change = { start: sel.from, endA: sel.to, endB: sel.to }; - } else { - if (parse.sel) { - let sel2 = resolveSelection(view, view.state.doc, parse.sel); - if (sel2 && !sel2.eq(view.state.selection)) { - let tr2 = view.state.tr.setSelection(sel2); - if (compositionID) - tr2.setMeta("composition", compositionID); - view.dispatch(tr2); - } - } - return; - } - } - if (view.state.selection.from < view.state.selection.to && change.start == change.endB && view.state.selection instanceof TextSelection) { - if (change.start > view.state.selection.from && change.start <= view.state.selection.from + 2 && view.state.selection.from >= parse.from) { - change.start = view.state.selection.from; - } else if (change.endA < view.state.selection.to && change.endA >= view.state.selection.to - 2 && view.state.selection.to <= parse.to) { - change.endB += view.state.selection.to - change.endA; - change.endA = view.state.selection.to; - } - } - if (ie$1 && ie_version <= 11 && change.endB == change.start + 1 && change.endA == change.start && change.start > parse.from && parse.doc.textBetween(change.start - parse.from - 1, change.start - parse.from + 1) == "  ") { - change.start--; - change.endA--; - change.endB--; - } - let $from = parse.doc.resolveNoCache(change.start - parse.from); - let $to = parse.doc.resolveNoCache(change.endB - parse.from); - let $fromA = doc2.resolve(change.start); - let inlineChange = $from.sameParent($to) && $from.parent.inlineContent && $fromA.end() >= change.endA; - if ((ios && view.input.lastIOSEnter > Date.now() - 225 && (!inlineChange || addedNodes.some((n) => n.nodeName == "DIV" || n.nodeName == "P")) || !inlineChange && $from.pos < parse.doc.content.size && (!$from.sameParent($to) || !$from.parent.inlineContent) && $from.pos < $to.pos && !/\S/.test(parse.doc.textBetween($from.pos, $to.pos, "", ""))) && view.someProp("handleKeyDown", (f) => f(view, keyEvent(13, "Enter")))) { - view.input.lastIOSEnter = 0; - return; - } - if (view.state.selection.anchor > change.start && looksLikeBackspace(doc2, change.start, change.endA, $from, $to) && view.someProp("handleKeyDown", (f) => f(view, keyEvent(8, "Backspace")))) { - if (android && chrome) - view.domObserver.suppressSelectionUpdates(); - return; - } - if (chrome && change.endB == change.start) - view.input.lastChromeDelete = Date.now(); - if (android && !inlineChange && $from.start() != $to.start() && $to.parentOffset == 0 && $from.depth == $to.depth && parse.sel && parse.sel.anchor == parse.sel.head && parse.sel.head == change.endA) { - change.endB -= 2; - $to = parse.doc.resolveNoCache(change.endB - parse.from); - setTimeout(() => { - view.someProp("handleKeyDown", function(f) { - return f(view, keyEvent(13, "Enter")); - }); - }, 20); - } - let chFrom = change.start, chTo = change.endA; - let mkTr = (base2) => { - let tr2 = base2 || view.state.tr.replace(chFrom, chTo, parse.doc.slice(change.start - parse.from, change.endB - parse.from)); - if (parse.sel) { - let sel2 = resolveSelection(view, tr2.doc, parse.sel); - if (sel2 && !(chrome && view.composing && sel2.empty && (change.start != change.endB || view.input.lastChromeDelete < Date.now() - 100) && (sel2.head == chFrom || sel2.head == tr2.mapping.map(chTo) - 1) || ie$1 && sel2.empty && sel2.head == chFrom)) - tr2.setSelection(sel2); - } - if (compositionID) - tr2.setMeta("composition", compositionID); - return tr2.scrollIntoView(); - }; - let markChange; - if (inlineChange) { - if ($from.pos == $to.pos) { - if (ie$1 && ie_version <= 11 && $from.parentOffset == 0) { - view.domObserver.suppressSelectionUpdates(); - setTimeout(() => selectionToDOM(view), 20); - } - let tr2 = mkTr(view.state.tr.delete(chFrom, chTo)); - let marks = doc2.resolve(change.start).marksAcross(doc2.resolve(change.endA)); - if (marks) - tr2.ensureMarks(marks); - view.dispatch(tr2); - } else if ( - // Adding or removing a mark - change.endA == change.endB && (markChange = isMarkChange($from.parent.content.cut($from.parentOffset, $to.parentOffset), $fromA.parent.content.cut($fromA.parentOffset, change.endA - $fromA.start()))) - ) { - let tr2 = mkTr(view.state.tr); - if (markChange.type == "add") - tr2.addMark(chFrom, chTo, markChange.mark); - else - tr2.removeMark(chFrom, chTo, markChange.mark); - view.dispatch(tr2); - } else if ($from.parent.child($from.index()).isText && $from.index() == $to.index() - ($to.textOffset ? 0 : 1)) { - let text = $from.parent.textBetween($from.parentOffset, $to.parentOffset); - let deflt = () => mkTr(view.state.tr.insertText(text, chFrom, chTo)); - if (!view.someProp("handleTextInput", (f) => f(view, chFrom, chTo, text, deflt))) - view.dispatch(deflt()); - } else { - view.dispatch(mkTr()); - } - } else { - view.dispatch(mkTr()); - } -} -function resolveSelection(view, doc2, parsedSel) { - if (Math.max(parsedSel.anchor, parsedSel.head) > doc2.content.size) - return null; - return selectionBetween(view, doc2.resolve(parsedSel.anchor), doc2.resolve(parsedSel.head)); -} -function isMarkChange(cur, prev) { - let curMarks = cur.firstChild.marks, prevMarks = prev.firstChild.marks; - let added = curMarks, removed = prevMarks, type, mark, update; - for (let i = 0; i < prevMarks.length; i++) - added = prevMarks[i].removeFromSet(added); - for (let i = 0; i < curMarks.length; i++) - removed = curMarks[i].removeFromSet(removed); - if (added.length == 1 && removed.length == 0) { - mark = added[0]; - type = "add"; - update = (node) => node.mark(mark.addToSet(node.marks)); - } else if (added.length == 0 && removed.length == 1) { - mark = removed[0]; - type = "remove"; - update = (node) => node.mark(mark.removeFromSet(node.marks)); - } else { - return null; - } - let updated = []; - for (let i = 0; i < prev.childCount; i++) - updated.push(update(prev.child(i))); - if (Fragment.from(updated).eq(cur)) - return { mark, type }; -} -function looksLikeBackspace(old, start, end, $newStart, $newEnd) { - if ( - // The content must have shrunk - end - start <= $newEnd.pos - $newStart.pos || // newEnd must point directly at or after the end of the block that newStart points into - skipClosingAndOpening($newStart, true, false) < $newEnd.pos - ) - return false; - let $start = old.resolve(start); - if (!$newStart.parent.isTextblock) { - let after = $start.nodeAfter; - return after != null && end == start + after.nodeSize; - } - if ($start.parentOffset < $start.parent.content.size || !$start.parent.isTextblock) - return false; - let $next = old.resolve(skipClosingAndOpening($start, true, true)); - if (!$next.parent.isTextblock || $next.pos > end || skipClosingAndOpening($next, true, false) < end) - return false; - return $newStart.parent.content.cut($newStart.parentOffset).eq($next.parent.content); -} -function skipClosingAndOpening($pos, fromEnd, mayOpen) { - let depth = $pos.depth, end = fromEnd ? $pos.end() : $pos.pos; - while (depth > 0 && (fromEnd || $pos.indexAfter(depth) == $pos.node(depth).childCount)) { - depth--; - end++; - fromEnd = false; - } - if (mayOpen) { - let next = $pos.node(depth).maybeChild($pos.indexAfter(depth)); - while (next && !next.isLeaf) { - next = next.firstChild; - end++; - } - } - return end; -} -function findDiff(a, b, pos, preferredPos, preferredSide) { - let start = a.findDiffStart(b, pos); - if (start == null) - return null; - let { a: endA, b: endB } = a.findDiffEnd(b, pos + a.size, pos + b.size); - if (preferredSide == "end") { - let adjust = Math.max(0, start - Math.min(endA, endB)); - preferredPos -= endA + adjust - start; - } - if (endA < start && a.size < b.size) { - let move = preferredPos <= start && preferredPos >= endA ? start - preferredPos : 0; - start -= move; - if (start && start < b.size && isSurrogatePair(b.textBetween(start - 1, start + 1))) - start += move ? 1 : -1; - endB = start + (endB - endA); - endA = start; - } else if (endB < start) { - let move = preferredPos <= start && preferredPos >= endB ? start - preferredPos : 0; - start -= move; - if (start && start < a.size && isSurrogatePair(a.textBetween(start - 1, start + 1))) - start += move ? 1 : -1; - endA = start + (endA - endB); - endB = start; - } - return { start, endA, endB }; -} -function isSurrogatePair(str) { - if (str.length != 2) - return false; - let a = str.charCodeAt(0), b = str.charCodeAt(1); - return a >= 56320 && a <= 57343 && b >= 55296 && b <= 56319; -} -class EditorView { - /** - Create a view. `place` may be a DOM node that the editor should - be appended to, a function that will place it into the document, - or an object whose `mount` property holds the node to use as the - document container. If it is `null`, the editor will not be - added to the document. - */ - constructor(place, props) { - this._root = null; - this.focused = false; - this.trackWrites = null; - this.mounted = false; - this.markCursor = null; - this.cursorWrapper = null; - this.lastSelectedViewDesc = void 0; - this.input = new InputState(); - this.prevDirectPlugins = []; - this.pluginViews = []; - this.requiresGeckoHackNode = false; - this.dragging = null; - this._props = props; - this.state = props.state; - this.directPlugins = props.plugins || []; - this.directPlugins.forEach(checkStateComponent); - this.dispatch = this.dispatch.bind(this); - this.dom = place && place.mount || document.createElement("div"); - if (place) { - if (place.appendChild) - place.appendChild(this.dom); - else if (typeof place == "function") - place(this.dom); - else if (place.mount) - this.mounted = true; - } - this.editable = getEditable(this); - updateCursorWrapper(this); - this.nodeViews = buildNodeViews(this); - this.docView = docViewDesc(this.state.doc, computeDocDeco(this), viewDecorations(this), this.dom, this); - this.domObserver = new DOMObserver(this, (from2, to, typeOver, added) => readDOMChange(this, from2, to, typeOver, added)); - this.domObserver.start(); - initInput(this); - this.updatePluginViews(); - } - /** - Holds `true` when a - [composition](https://w3c.github.io/uievents/#events-compositionevents) - is active. - */ - get composing() { - return this.input.composing; - } - /** - The view's current [props](https://prosemirror.net/docs/ref/#view.EditorProps). - */ - get props() { - if (this._props.state != this.state) { - let prev = this._props; - this._props = {}; - for (let name in prev) - this._props[name] = prev[name]; - this._props.state = this.state; - } - return this._props; - } - /** - Update the view's props. Will immediately cause an update to - the DOM. - */ - update(props) { - if (props.handleDOMEvents != this._props.handleDOMEvents) - ensureListeners(this); - let prevProps = this._props; - this._props = props; - if (props.plugins) { - props.plugins.forEach(checkStateComponent); - this.directPlugins = props.plugins; - } - this.updateStateInner(props.state, prevProps); - } - /** - Update the view by updating existing props object with the object - given as argument. Equivalent to `view.update(Object.assign({}, - view.props, props))`. - */ - setProps(props) { - let updated = {}; - for (let name in this._props) - updated[name] = this._props[name]; - updated.state = this.state; - for (let name in props) - updated[name] = props[name]; - this.update(updated); - } - /** - Update the editor's `state` prop, without touching any of the - other props. - */ - updateState(state) { - this.updateStateInner(state, this._props); - } - updateStateInner(state, prevProps) { - var _a; - let prev = this.state, redraw = false, updateSel = false; - if (state.storedMarks && this.composing) { - clearComposition(this); - updateSel = true; - } - this.state = state; - let pluginsChanged = prev.plugins != state.plugins || this._props.plugins != prevProps.plugins; - if (pluginsChanged || this._props.plugins != prevProps.plugins || this._props.nodeViews != prevProps.nodeViews) { - let nodeViews = buildNodeViews(this); - if (changedNodeViews(nodeViews, this.nodeViews)) { - this.nodeViews = nodeViews; - redraw = true; - } - } - if (pluginsChanged || prevProps.handleDOMEvents != this._props.handleDOMEvents) { - ensureListeners(this); - } - this.editable = getEditable(this); - updateCursorWrapper(this); - let innerDeco = viewDecorations(this), outerDeco = computeDocDeco(this); - let scroll = prev.plugins != state.plugins && !prev.doc.eq(state.doc) ? "reset" : state.scrollToSelection > prev.scrollToSelection ? "to selection" : "preserve"; - let updateDoc = redraw || !this.docView.matchesNode(state.doc, outerDeco, innerDeco); - if (updateDoc || !state.selection.eq(prev.selection)) - updateSel = true; - let oldScrollPos = scroll == "preserve" && updateSel && this.dom.style.overflowAnchor == null && storeScrollPos(this); - if (updateSel) { - this.domObserver.stop(); - let forceSelUpdate = updateDoc && (ie$1 || chrome) && !this.composing && !prev.selection.empty && !state.selection.empty && selectionContextChanged(prev.selection, state.selection); - if (updateDoc) { - let chromeKludge = chrome ? this.trackWrites = this.domSelectionRange().focusNode : null; - if (this.composing) - this.input.compositionNode = findCompositionNode(this); - if (redraw || !this.docView.update(state.doc, outerDeco, innerDeco, this)) { - this.docView.updateOuterDeco(outerDeco); - this.docView.destroy(); - this.docView = docViewDesc(state.doc, outerDeco, innerDeco, this.dom, this); - } - if (chromeKludge && (!this.trackWrites || !this.dom.contains(this.trackWrites))) - forceSelUpdate = true; - } - if (forceSelUpdate || !(this.input.mouseDown && this.domObserver.currentSelection.eq(this.domSelectionRange()) && anchorInRightPlace(this))) { - selectionToDOM(this, forceSelUpdate); - } else { - syncNodeSelection(this, state.selection); - this.domObserver.setCurSelection(); - } - this.domObserver.start(); - } - this.updatePluginViews(prev); - if (((_a = this.dragging) === null || _a === void 0 ? void 0 : _a.node) && !prev.doc.eq(state.doc)) - this.updateDraggedNode(this.dragging, prev); - if (scroll == "reset") { - this.dom.scrollTop = 0; - } else if (scroll == "to selection") { - this.scrollToSelection(); - } else if (oldScrollPos) { - resetScrollPos(oldScrollPos); - } - } - /** - @internal - */ - scrollToSelection() { - let startDOM = this.domSelectionRange().focusNode; - if (!startDOM || !this.dom.contains(startDOM.nodeType == 1 ? startDOM : startDOM.parentNode)) ; - else if (this.someProp("handleScrollToSelection", (f) => f(this))) ; - else if (this.state.selection instanceof NodeSelection) { - let target = this.docView.domAfterPos(this.state.selection.from); - if (target.nodeType == 1) - scrollRectIntoView(this, target.getBoundingClientRect(), startDOM); - } else { - scrollRectIntoView(this, this.coordsAtPos(this.state.selection.head, 1), startDOM); - } - } - destroyPluginViews() { - let view; - while (view = this.pluginViews.pop()) - if (view.destroy) - view.destroy(); - } - updatePluginViews(prevState) { - if (!prevState || prevState.plugins != this.state.plugins || this.directPlugins != this.prevDirectPlugins) { - this.prevDirectPlugins = this.directPlugins; - this.destroyPluginViews(); - for (let i = 0; i < this.directPlugins.length; i++) { - let plugin = this.directPlugins[i]; - if (plugin.spec.view) - this.pluginViews.push(plugin.spec.view(this)); - } - for (let i = 0; i < this.state.plugins.length; i++) { - let plugin = this.state.plugins[i]; - if (plugin.spec.view) - this.pluginViews.push(plugin.spec.view(this)); - } - } else { - for (let i = 0; i < this.pluginViews.length; i++) { - let pluginView = this.pluginViews[i]; - if (pluginView.update) - pluginView.update(this, prevState); - } - } - } - updateDraggedNode(dragging, prev) { - let sel = dragging.node, found2 = -1; - if (sel.from < this.state.doc.content.size && this.state.doc.nodeAt(sel.from) == sel.node) { - found2 = sel.from; - } else { - let movedPos = sel.from + (this.state.doc.content.size - prev.doc.content.size); - let moved = movedPos > 0 && movedPos < this.state.doc.content.size && this.state.doc.nodeAt(movedPos); - if (moved == sel.node) - found2 = movedPos; - } - this.dragging = new Dragging(dragging.slice, dragging.move, found2 < 0 ? void 0 : NodeSelection.create(this.state.doc, found2)); - } - someProp(propName, f) { - let prop = this._props && this._props[propName], value; - if (prop != null && (value = f ? f(prop) : prop)) - return value; - for (let i = 0; i < this.directPlugins.length; i++) { - let prop2 = this.directPlugins[i].props[propName]; - if (prop2 != null && (value = f ? f(prop2) : prop2)) - return value; - } - let plugins = this.state.plugins; - if (plugins) - for (let i = 0; i < plugins.length; i++) { - let prop2 = plugins[i].props[propName]; - if (prop2 != null && (value = f ? f(prop2) : prop2)) - return value; - } - } - /** - Query whether the view has focus. - */ - hasFocus() { - if (ie$1) { - let node = this.root.activeElement; - if (node == this.dom) - return true; - if (!node || !this.dom.contains(node)) - return false; - while (node && this.dom != node && this.dom.contains(node)) { - if (node.contentEditable == "false") - return false; - node = node.parentElement; - } - return true; - } - return this.root.activeElement == this.dom; - } - /** - Focus the editor. - */ - focus() { - this.domObserver.stop(); - if (this.editable) - focusPreventScroll(this.dom); - selectionToDOM(this); - this.domObserver.start(); - } - /** - Get the document root in which the editor exists. This will - usually be the top-level `document`, but might be a [shadow - DOM](https://developer.mozilla.org/en-US/docs/Web/Web_Components/Shadow_DOM) - root if the editor is inside one. - */ - get root() { - let cached = this._root; - if (cached == null) - for (let search = this.dom.parentNode; search; search = search.parentNode) { - if (search.nodeType == 9 || search.nodeType == 11 && search.host) { - if (!search.getSelection) - Object.getPrototypeOf(search).getSelection = () => search.ownerDocument.getSelection(); - return this._root = search; - } - } - return cached || document; - } - /** - When an existing editor view is moved to a new document or - shadow tree, call this to make it recompute its root. - */ - updateRoot() { - this._root = null; - } - /** - Given a pair of viewport coordinates, return the document - position that corresponds to them. May return null if the given - coordinates aren't inside of the editor. When an object is - returned, its `pos` property is the position nearest to the - coordinates, and its `inside` property holds the position of the - inner node that the position falls inside of, or -1 if it is at - the top level, not in any node. - */ - posAtCoords(coords) { - return posAtCoords(this, coords); - } - /** - Returns the viewport rectangle at a given document position. - `left` and `right` will be the same number, as this returns a - flat cursor-ish rectangle. If the position is between two things - that aren't directly adjacent, `side` determines which element - is used. When < 0, the element before the position is used, - otherwise the element after. - */ - coordsAtPos(pos, side = 1) { - return coordsAtPos(this, pos, side); - } - /** - Find the DOM position that corresponds to the given document - position. When `side` is negative, find the position as close as - possible to the content before the position. When positive, - prefer positions close to the content after the position. When - zero, prefer as shallow a position as possible. - - Note that you should **not** mutate the editor's internal DOM, - only inspect it (and even that is usually not necessary). - */ - domAtPos(pos, side = 0) { - return this.docView.domFromPos(pos, side); - } - /** - Find the DOM node that represents the document node after the - given position. May return `null` when the position doesn't point - in front of a node or if the node is inside an opaque node view. - - This is intended to be able to call things like - `getBoundingClientRect` on that DOM node. Do **not** mutate the - editor DOM directly, or add styling this way, since that will be - immediately overriden by the editor as it redraws the node. - */ - nodeDOM(pos) { - let desc = this.docView.descAt(pos); - return desc ? desc.nodeDOM : null; - } - /** - Find the document position that corresponds to a given DOM - position. (Whenever possible, it is preferable to inspect the - document structure directly, rather than poking around in the - DOM, but sometimes—for example when interpreting an event - target—you don't have a choice.) - - The `bias` parameter can be used to influence which side of a DOM - node to use when the position is inside a leaf node. - */ - posAtDOM(node, offset, bias = -1) { - let pos = this.docView.posFromDOM(node, offset, bias); - if (pos == null) - throw new RangeError("DOM position not inside the editor"); - return pos; - } - /** - Find out whether the selection is at the end of a textblock when - moving in a given direction. When, for example, given `"left"`, - it will return true if moving left from the current cursor - position would leave that position's parent textblock. Will apply - to the view's current state by default, but it is possible to - pass a different state. - */ - endOfTextblock(dir, state) { - return endOfTextblock(this, state || this.state, dir); - } - /** - Run the editor's paste logic with the given HTML string. The - `event`, if given, will be passed to the - [`handlePaste`](https://prosemirror.net/docs/ref/#view.EditorProps.handlePaste) hook. - */ - pasteHTML(html, event) { - return doPaste(this, "", html, false, event || new ClipboardEvent("paste")); - } - /** - Run the editor's paste logic with the given plain-text input. - */ - pasteText(text, event) { - return doPaste(this, text, null, true, event || new ClipboardEvent("paste")); - } - /** - Serialize the given slice as it would be if it was copied from - this editor. Returns a DOM element that contains a - representation of the slice as its children, a textual - representation, and the transformed slice (which can be - different from the given input due to hooks like - [`transformCopied`](https://prosemirror.net/docs/ref/#view.EditorProps.transformCopied)). - */ - serializeForClipboard(slice2) { - return serializeForClipboard(this, slice2); - } - /** - Removes the editor from the DOM and destroys all [node - views](https://prosemirror.net/docs/ref/#view.NodeView). - */ - destroy() { - if (!this.docView) - return; - destroyInput(this); - this.destroyPluginViews(); - if (this.mounted) { - this.docView.update(this.state.doc, [], viewDecorations(this), this); - this.dom.textContent = ""; - } else if (this.dom.parentNode) { - this.dom.parentNode.removeChild(this.dom); - } - this.docView.destroy(); - this.docView = null; - clearReusedRange(); - } - /** - This is true when the view has been - [destroyed](https://prosemirror.net/docs/ref/#view.EditorView.destroy) (and thus should not be - used anymore). - */ - get isDestroyed() { - return this.docView == null; - } - /** - Used for testing. - */ - dispatchEvent(event) { - return dispatchEvent(this, event); - } - /** - @internal - */ - domSelectionRange() { - let sel = this.domSelection(); - if (!sel) - return { focusNode: null, focusOffset: 0, anchorNode: null, anchorOffset: 0 }; - return safari && this.root.nodeType === 11 && deepActiveElement(this.dom.ownerDocument) == this.dom && safariShadowSelectionRange(this, sel) || sel; - } - /** - @internal - */ - domSelection() { - return this.root.getSelection(); - } -} -EditorView.prototype.dispatch = function(tr2) { - let dispatchTransaction = this._props.dispatchTransaction; - if (dispatchTransaction) - dispatchTransaction.call(this, tr2); - else - this.updateState(this.state.apply(tr2)); -}; -function computeDocDeco(view) { - let attrs = /* @__PURE__ */ Object.create(null); - attrs.class = "ProseMirror"; - attrs.contenteditable = String(view.editable); - view.someProp("attributes", (value) => { - if (typeof value == "function") - value = value(view.state); - if (value) - for (let attr in value) { - if (attr == "class") - attrs.class += " " + value[attr]; - else if (attr == "style") - attrs.style = (attrs.style ? attrs.style + ";" : "") + value[attr]; - else if (!attrs[attr] && attr != "contenteditable" && attr != "nodeName") - attrs[attr] = String(value[attr]); - } - }); - if (!attrs.translate) - attrs.translate = "no"; - return [Decoration.node(0, view.state.doc.content.size, attrs)]; -} -function updateCursorWrapper(view) { - if (view.markCursor) { - let dom = document.createElement("img"); - dom.className = "ProseMirror-separator"; - dom.setAttribute("mark-placeholder", "true"); - dom.setAttribute("alt", ""); - view.cursorWrapper = { dom, deco: Decoration.widget(view.state.selection.from, dom, { raw: true, marks: view.markCursor }) }; - } else { - view.cursorWrapper = null; - } -} -function getEditable(view) { - return !view.someProp("editable", (value) => value(view.state) === false); -} -function selectionContextChanged(sel1, sel2) { - let depth = Math.min(sel1.$anchor.sharedDepth(sel1.head), sel2.$anchor.sharedDepth(sel2.head)); - return sel1.$anchor.start(depth) != sel2.$anchor.start(depth); -} -function buildNodeViews(view) { - let result = /* @__PURE__ */ Object.create(null); - function add(obj) { - for (let prop in obj) - if (!Object.prototype.hasOwnProperty.call(result, prop)) - result[prop] = obj[prop]; - } - view.someProp("nodeViews", add); - view.someProp("markViews", add); - return result; -} -function changedNodeViews(a, b) { - let nA = 0, nB = 0; - for (let prop in a) { - if (a[prop] != b[prop]) - return true; - nA++; - } - for (let _ in b) - nB++; - return nA != nB; -} -function checkStateComponent(plugin) { - if (plugin.spec.state || plugin.spec.filterTransaction || plugin.spec.appendTransaction) - throw new RangeError("Plugins passed directly to the view must not have a state component"); -} -var base = { - 8: "Backspace", - 9: "Tab", - 10: "Enter", - 12: "NumLock", - 13: "Enter", - 16: "Shift", - 17: "Control", - 18: "Alt", - 20: "CapsLock", - 27: "Escape", - 32: " ", - 33: "PageUp", - 34: "PageDown", - 35: "End", - 36: "Home", - 37: "ArrowLeft", - 38: "ArrowUp", - 39: "ArrowRight", - 40: "ArrowDown", - 44: "PrintScreen", - 45: "Insert", - 46: "Delete", - 59: ";", - 61: "=", - 91: "Meta", - 92: "Meta", - 106: "*", - 107: "+", - 108: ",", - 109: "-", - 110: ".", - 111: "/", - 144: "NumLock", - 145: "ScrollLock", - 160: "Shift", - 161: "Shift", - 162: "Control", - 163: "Control", - 164: "Alt", - 165: "Alt", - 173: "-", - 186: ";", - 187: "=", - 188: ",", - 189: "-", - 190: ".", - 191: "/", - 192: "`", - 219: "[", - 220: "\\", - 221: "]", - 222: "'" -}; -var shift = { - 48: ")", - 49: "!", - 50: "@", - 51: "#", - 52: "$", - 53: "%", - 54: "^", - 55: "&", - 56: "*", - 57: "(", - 59: ":", - 61: "+", - 173: "_", - 186: ":", - 187: "+", - 188: "<", - 189: "_", - 190: ">", - 191: "?", - 192: "~", - 219: "{", - 220: "|", - 221: "}", - 222: '"' -}; -var mac$1 = typeof navigator != "undefined" && /Mac/.test(navigator.platform); -var ie = typeof navigator != "undefined" && /MSIE \d|Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(navigator.userAgent); -for (var i = 0; i < 10; i++) base[48 + i] = base[96 + i] = String(i); -for (var i = 1; i <= 24; i++) base[i + 111] = "F" + i; -for (var i = 65; i <= 90; i++) { - base[i] = String.fromCharCode(i + 32); - shift[i] = String.fromCharCode(i); -} -for (var code in base) if (!shift.hasOwnProperty(code)) shift[code] = base[code]; -function keyName(event) { - var ignoreKey = mac$1 && event.metaKey && event.shiftKey && !event.ctrlKey && !event.altKey || ie && event.shiftKey && event.key && event.key.length == 1 || event.key == "Unidentified"; - var name = !ignoreKey && event.key || (event.shiftKey ? shift : base)[event.keyCode] || event.key || "Unidentified"; - if (name == "Esc") name = "Escape"; - if (name == "Del") name = "Delete"; - if (name == "Left") name = "ArrowLeft"; - if (name == "Up") name = "ArrowUp"; - if (name == "Right") name = "ArrowRight"; - if (name == "Down") name = "ArrowDown"; - return name; -} -const mac = typeof navigator != "undefined" && /Mac|iP(hone|[oa]d)/.test(navigator.platform); -const windows = typeof navigator != "undefined" && /Win/.test(navigator.platform); -function normalizeKeyName$1(name) { - let parts = name.split(/-(?!$)/), result = parts[parts.length - 1]; - if (result == "Space") - result = " "; - let alt, ctrl, shift2, meta; - for (let i = 0; i < parts.length - 1; i++) { - let mod = parts[i]; - if (/^(cmd|meta|m)$/i.test(mod)) - meta = true; - else if (/^a(lt)?$/i.test(mod)) - alt = true; - else if (/^(c|ctrl|control)$/i.test(mod)) - ctrl = true; - else if (/^s(hift)?$/i.test(mod)) - shift2 = true; - else if (/^mod$/i.test(mod)) { - if (mac) - meta = true; - else - ctrl = true; - } else - throw new Error("Unrecognized modifier name: " + mod); - } - if (alt) - result = "Alt-" + result; - if (ctrl) - result = "Ctrl-" + result; - if (meta) - result = "Meta-" + result; - if (shift2) - result = "Shift-" + result; - return result; -} -function normalize(map2) { - let copy2 = /* @__PURE__ */ Object.create(null); - for (let prop in map2) - copy2[normalizeKeyName$1(prop)] = map2[prop]; - return copy2; -} -function modifiers(name, event, shift2 = true) { - if (event.altKey) - name = "Alt-" + name; - if (event.ctrlKey) - name = "Ctrl-" + name; - if (event.metaKey) - name = "Meta-" + name; - if (shift2 && event.shiftKey) - name = "Shift-" + name; - return name; -} -function keymap(bindings) { - return new Plugin({ props: { handleKeyDown: keydownHandler(bindings) } }); -} -function keydownHandler(bindings) { - let map2 = normalize(bindings); - return function(view, event) { - let name = keyName(event), baseName, direct = map2[modifiers(name, event)]; - if (direct && direct(view.state, view.dispatch, view)) - return true; - if (name.length == 1 && name != " ") { - if (event.shiftKey) { - let noShift = map2[modifiers(name, event, false)]; - if (noShift && noShift(view.state, view.dispatch, view)) - return true; - } - if ((event.altKey || event.metaKey || event.ctrlKey) && // Ctrl-Alt may be used for AltGr on Windows - !(windows && event.ctrlKey && event.altKey) && (baseName = base[event.keyCode]) && baseName != name) { - let fromCode = map2[modifiers(baseName, event)]; - if (fromCode && fromCode(view.state, view.dispatch, view)) - return true; - } - } - return false; - }; -} -var __defProp$1 = Object.defineProperty; -var __export$1 = (target, all) => { - for (var name in all) - __defProp$1(target, name, { get: all[name], enumerable: true }); -}; -function createChainableState(config) { - const { state, transaction } = config; - let { selection } = transaction; - let { doc: doc2 } = transaction; - let { storedMarks } = transaction; - return { - ...state, - apply: state.apply.bind(state), - applyTransaction: state.applyTransaction.bind(state), - plugins: state.plugins, - schema: state.schema, - reconfigure: state.reconfigure.bind(state), - toJSON: state.toJSON.bind(state), - get storedMarks() { - return storedMarks; - }, - get selection() { - return selection; - }, - get doc() { - return doc2; - }, - get tr() { - selection = transaction.selection; - doc2 = transaction.doc; - storedMarks = transaction.storedMarks; - return transaction; - } - }; -} -var CommandManager = class { - constructor(props) { - this.editor = props.editor; - this.rawCommands = this.editor.extensionManager.commands; - this.customState = props.state; - } - get hasCustomState() { - return !!this.customState; - } - get state() { - return this.customState || this.editor.state; - } - get commands() { - const { rawCommands, editor, state } = this; - const { view } = editor; - const { tr: tr2 } = state; - const props = this.buildProps(tr2); - return Object.fromEntries( - Object.entries(rawCommands).map(([name, command2]) => { - const method = (...args) => { - const callback = command2(...args)(props); - if (!tr2.getMeta("preventDispatch") && !this.hasCustomState) { - view.dispatch(tr2); - } - return callback; - }; - return [name, method]; - }) - ); - } - get chain() { - return () => this.createChain(); - } - get can() { - return () => this.createCan(); - } - createChain(startTr, shouldDispatch = true) { - const { rawCommands, editor, state } = this; - const { view } = editor; - const callbacks = []; - const hasStartTransaction = !!startTr; - const tr2 = startTr || state.tr; - const run3 = () => { - if (!hasStartTransaction && shouldDispatch && !tr2.getMeta("preventDispatch") && !this.hasCustomState) { - view.dispatch(tr2); - } - return callbacks.every((callback) => callback === true); - }; - const chain = { - ...Object.fromEntries( - Object.entries(rawCommands).map(([name, command2]) => { - const chainedCommand = (...args) => { - const props = this.buildProps(tr2, shouldDispatch); - const callback = command2(...args)(props); - callbacks.push(callback); - return chain; - }; - return [name, chainedCommand]; - }) - ), - run: run3 - }; - return chain; - } - createCan(startTr) { - const { rawCommands, state } = this; - const dispatch = false; - const tr2 = startTr || state.tr; - const props = this.buildProps(tr2, dispatch); - const formattedCommands = Object.fromEntries( - Object.entries(rawCommands).map(([name, command2]) => { - return [name, (...args) => command2(...args)({ ...props, dispatch: void 0 })]; - }) - ); - return { - ...formattedCommands, - chain: () => this.createChain(tr2, dispatch) - }; - } - buildProps(tr2, shouldDispatch = true) { - const { rawCommands, editor, state } = this; - const { view } = editor; - const props = { - tr: tr2, - editor, - view, - state: createChainableState({ - state, - transaction: tr2 - }), - dispatch: shouldDispatch ? () => void 0 : void 0, - chain: () => this.createChain(tr2, shouldDispatch), - can: () => this.createCan(tr2), - get commands() { - return Object.fromEntries( - Object.entries(rawCommands).map(([name, command2]) => { - return [name, (...args) => command2(...args)(props)]; - }) - ); - } - }; - return props; - } -}; -var commands_exports = {}; -__export$1(commands_exports, { - blur: () => blur, - clearContent: () => clearContent, - clearNodes: () => clearNodes, - command: () => command, - createParagraphNear: () => createParagraphNear, - cut: () => cut, - deleteCurrentNode: () => deleteCurrentNode, - deleteNode: () => deleteNode, - deleteRange: () => deleteRange, - deleteSelection: () => deleteSelection, - enter: () => enter, - exitCode: () => exitCode, - extendMarkRange: () => extendMarkRange, - first: () => first, - focus: () => focus, - forEach: () => forEach, - insertContent: () => insertContent, - insertContentAt: () => insertContentAt, - joinBackward: () => joinBackward, - joinDown: () => joinDown, - joinForward: () => joinForward, - joinItemBackward: () => joinItemBackward, - joinItemForward: () => joinItemForward, - joinTextblockBackward: () => joinTextblockBackward, - joinTextblockForward: () => joinTextblockForward, - joinUp: () => joinUp, - keyboardShortcut: () => keyboardShortcut, - lift: () => lift, - liftEmptyBlock: () => liftEmptyBlock, - liftListItem: () => liftListItem, - newlineInCode: () => newlineInCode, - resetAttributes: () => resetAttributes, - scrollIntoView: () => scrollIntoView, - selectAll: () => selectAll, - selectNodeBackward: () => selectNodeBackward, - selectNodeForward: () => selectNodeForward, - selectParentNode: () => selectParentNode, - selectTextblockEnd: () => selectTextblockEnd, - selectTextblockStart: () => selectTextblockStart, - setContent: () => setContent, - setMark: () => setMark, - setMeta: () => setMeta, - setNode: () => setNode, - setNodeSelection: () => setNodeSelection, - setTextDirection: () => setTextDirection, - setTextSelection: () => setTextSelection, - sinkListItem: () => sinkListItem, - splitBlock: () => splitBlock, - splitListItem: () => splitListItem, - toggleList: () => toggleList, - toggleMark: () => toggleMark, - toggleNode: () => toggleNode, - toggleWrap: () => toggleWrap, - undoInputRule: () => undoInputRule, - unsetAllMarks: () => unsetAllMarks, - unsetMark: () => unsetMark, - unsetTextDirection: () => unsetTextDirection, - updateAttributes: () => updateAttributes, - wrapIn: () => wrapIn, - wrapInList: () => wrapInList -}); -var blur = () => ({ editor, view }) => { - requestAnimationFrame(() => { - var _a; - if (!editor.isDestroyed) { - view.dom.blur(); - (_a = window == null ? void 0 : window.getSelection()) == null ? void 0 : _a.removeAllRanges(); - } - }); - return true; -}; -var clearContent = (emitUpdate = true) => ({ commands }) => { - return commands.setContent("", { emitUpdate }); -}; -var clearNodes = () => ({ state, tr: tr2, dispatch }) => { - const { selection } = tr2; - const { ranges } = selection; - if (!dispatch) { - return true; - } - ranges.forEach(({ $from, $to }) => { - state.doc.nodesBetween($from.pos, $to.pos, (node, pos) => { - if (node.type.isText) { - return; - } - const { doc: doc2, mapping } = tr2; - const $mappedFrom = doc2.resolve(mapping.map(pos)); - const $mappedTo = doc2.resolve(mapping.map(pos + node.nodeSize)); - const nodeRange = $mappedFrom.blockRange($mappedTo); - if (!nodeRange) { - return; - } - const targetLiftDepth = liftTarget(nodeRange); - if (node.type.isTextblock) { - const { defaultType } = $mappedFrom.parent.contentMatchAt($mappedFrom.index()); - tr2.setNodeMarkup(nodeRange.start, defaultType); - } - if (targetLiftDepth || targetLiftDepth === 0) { - tr2.lift(nodeRange, targetLiftDepth); - } - }); - }); - return true; -}; -var command = (fn) => (props) => { - return fn(props); -}; -var createParagraphNear = () => ({ state, dispatch }) => { - return createParagraphNear$1(state, dispatch); -}; -var cut = (originRange, targetPos) => ({ editor, tr: tr2 }) => { - const { state } = editor; - const contentSlice = state.doc.slice(originRange.from, originRange.to); - tr2.deleteRange(originRange.from, originRange.to); - const newPos = tr2.mapping.map(targetPos); - tr2.insert(newPos, contentSlice.content); - tr2.setSelection(new TextSelection(tr2.doc.resolve(Math.max(newPos - 1, 0)))); - return true; -}; -var deleteCurrentNode = () => ({ tr: tr2, dispatch }) => { - const { selection } = tr2; - const currentNode = selection.$anchor.node(); - if (currentNode.content.size > 0) { - return false; - } - const $pos = tr2.selection.$anchor; - for (let depth = $pos.depth; depth > 0; depth -= 1) { - const node = $pos.node(depth); - if (node.type === currentNode.type) { - if (dispatch) { - const from2 = $pos.before(depth); - const to = $pos.after(depth); - tr2.delete(from2, to).scrollIntoView(); - } - return true; - } - } - return false; -}; -function getNodeType(nameOrType, schema) { - if (typeof nameOrType === "string") { - if (!schema.nodes[nameOrType]) { - throw Error(`There is no node type named '${nameOrType}'. Maybe you forgot to add the extension?`); - } - return schema.nodes[nameOrType]; - } - return nameOrType; -} -var deleteNode = (typeOrName) => ({ tr: tr2, state, dispatch }) => { - const type = getNodeType(typeOrName, state.schema); - const $pos = tr2.selection.$anchor; - for (let depth = $pos.depth; depth > 0; depth -= 1) { - const node = $pos.node(depth); - if (node.type === type) { - if (dispatch) { - const from2 = $pos.before(depth); - const to = $pos.after(depth); - tr2.delete(from2, to).scrollIntoView(); - } - return true; - } - } - return false; -}; -var deleteRange = (range) => ({ tr: tr2, dispatch }) => { - const { from: from2, to } = range; - if (dispatch) { - tr2.delete(from2, to); - } - return true; -}; -var deleteSelection = () => ({ state, dispatch }) => { - return deleteSelection$1(state, dispatch); -}; -var enter = () => ({ commands }) => { - return commands.keyboardShortcut("Enter"); -}; -var exitCode = () => ({ state, dispatch }) => { - return exitCode$1(state, dispatch); -}; -function isRegExp(value) { - return Object.prototype.toString.call(value) === "[object RegExp]"; -} -function objectIncludes(object1, object2, options = { strict: true }) { - const keys2 = Object.keys(object2); - if (!keys2.length) { - return true; - } - return keys2.every((key) => { - if (options.strict) { - return object2[key] === object1[key]; - } - if (isRegExp(object2[key])) { - return object2[key].test(object1[key]); - } - return object2[key] === object1[key]; - }); -} -function findMarkInSet(marks, type, attributes = {}) { - return marks.find((item) => { - return item.type === type && objectIncludes( - // Only check equality for the attributes that are provided - Object.fromEntries(Object.keys(attributes).map((k) => [k, item.attrs[k]])), - attributes - ); - }); -} -function isMarkInSet(marks, type, attributes = {}) { - return !!findMarkInSet(marks, type, attributes); -} -function getMarkRange($pos, type, attributes) { - if (!$pos || !type) { - return; - } - let start = $pos.parent.childAfter($pos.parentOffset); - if (!start.node || !start.node.marks.some((mark2) => mark2.type === type)) { - start = $pos.parent.childBefore($pos.parentOffset); - } - if (!start.node || !start.node.marks.some((mark2) => mark2.type === type)) { - return; - } - if (!attributes) { - const firstMark = start.node.marks.find((mark2) => mark2.type === type); - if (firstMark) { - attributes = firstMark.attrs; - } - } - const mark = findMarkInSet([...start.node.marks], type, attributes); - if (!mark) { - return; - } - let startIndex = start.index; - let startPos = $pos.start() + start.offset; - let endIndex = startIndex + 1; - let endPos = startPos + start.node.nodeSize; - while (startIndex > 0 && isMarkInSet([...$pos.parent.child(startIndex - 1).marks], type, attributes)) { - startIndex -= 1; - startPos -= $pos.parent.child(startIndex).nodeSize; - } - while (endIndex < $pos.parent.childCount && isMarkInSet([...$pos.parent.child(endIndex).marks], type, attributes)) { - endPos += $pos.parent.child(endIndex).nodeSize; - endIndex += 1; - } - return { - from: startPos, - to: endPos - }; -} -function getMarkType(nameOrType, schema) { - if (typeof nameOrType === "string") { - if (!schema.marks[nameOrType]) { - throw Error(`There is no mark type named '${nameOrType}'. Maybe you forgot to add the extension?`); - } - return schema.marks[nameOrType]; - } - return nameOrType; -} -var extendMarkRange = (typeOrName, attributes) => ({ tr: tr2, state, dispatch }) => { - const type = getMarkType(typeOrName, state.schema); - const { doc: doc2, selection } = tr2; - const { $from, from: from2, to } = selection; - if (dispatch) { - const range = getMarkRange($from, type, attributes); - if (range && range.from <= from2 && range.to >= to) { - const newSelection = TextSelection.create(doc2, range.from, range.to); - tr2.setSelection(newSelection); - } - } - return true; -}; -var first = (commands) => (props) => { - const items = typeof commands === "function" ? commands(props) : commands; - for (let i = 0; i < items.length; i += 1) { - if (items[i](props)) { - return true; - } - } - return false; -}; -function isTextSelection(value) { - return value instanceof TextSelection; -} -function minMax(value = 0, min = 0, max = 0) { - return Math.min(Math.max(value, min), max); -} -function resolveFocusPosition(doc2, position = null) { - if (!position) { - return null; - } - const selectionAtStart = Selection.atStart(doc2); - const selectionAtEnd = Selection.atEnd(doc2); - if (position === "start" || position === true) { - return selectionAtStart; - } - if (position === "end") { - return selectionAtEnd; - } - const minPos = selectionAtStart.from; - const maxPos = selectionAtEnd.to; - if (position === "all") { - return TextSelection.create(doc2, minMax(0, minPos, maxPos), minMax(doc2.content.size, minPos, maxPos)); - } - return TextSelection.create(doc2, minMax(position, minPos, maxPos), minMax(position, minPos, maxPos)); -} -function isAndroid() { - return navigator.platform === "Android" || /android/i.test(navigator.userAgent); -} -function isiOS() { - return ["iPad Simulator", "iPhone Simulator", "iPod Simulator", "iPad", "iPhone", "iPod"].includes(navigator.platform) || // iPad on iOS 13 detection - navigator.userAgent.includes("Mac") && "ontouchend" in document; -} -function isSafari() { - return typeof navigator !== "undefined" ? /^((?!chrome|android).)*safari/i.test(navigator.userAgent) : false; -} -var focus = (position = null, options = {}) => ({ editor, view, tr: tr2, dispatch }) => { - options = { - scrollIntoView: true, - ...options - }; - const delayedFocus = () => { - if (isiOS() || isAndroid()) { - view.dom.focus(); - } - if (isSafari() && !isiOS() && !isAndroid()) { - view.dom.focus({ preventScroll: true }); - } - requestAnimationFrame(() => { - if (!editor.isDestroyed) { - view.focus(); - if (options == null ? void 0 : options.scrollIntoView) { - editor.commands.scrollIntoView(); - } - } - }); - }; - try { - if (view.hasFocus() && position === null || position === false) { - return true; - } - } catch { - return false; - } - if (dispatch && position === null && !isTextSelection(editor.state.selection)) { - delayedFocus(); - return true; - } - const selection = resolveFocusPosition(tr2.doc, position) || editor.state.selection; - const isSameSelection = editor.state.selection.eq(selection); - if (dispatch) { - if (!isSameSelection) { - tr2.setSelection(selection); - } - if (isSameSelection && tr2.storedMarks) { - tr2.setStoredMarks(tr2.storedMarks); - } - delayedFocus(); - } - return true; -}; -var forEach = (items, fn) => (props) => { - return items.every((item, index) => fn(item, { ...props, index })); -}; -var insertContent = (value, options) => ({ tr: tr2, commands }) => { - return commands.insertContentAt({ from: tr2.selection.from, to: tr2.selection.to }, value, options); -}; -var removeWhitespaces = (node) => { - const children = node.childNodes; - for (let i = children.length - 1; i >= 0; i -= 1) { - const child = children[i]; - if (child.nodeType === 3 && child.nodeValue && /^(\n\s\s|\n)$/.test(child.nodeValue)) { - node.removeChild(child); - } else if (child.nodeType === 1) { - removeWhitespaces(child); - } - } - return node; -}; -function elementFromString(value) { - if (typeof window === "undefined") { - throw new Error("[tiptap error]: there is no window object available, so this function cannot be used"); - } - const wrappedValue = `${value}`; - const html = new window.DOMParser().parseFromString(wrappedValue, "text/html").body; - return removeWhitespaces(html); -} -function createNodeFromContent(content, schema, options) { - if (content instanceof Node || content instanceof Fragment) { - return content; - } - options = { - slice: true, - parseOptions: {}, - ...options - }; - const isJSONContent = typeof content === "object" && content !== null; - const isTextContent = typeof content === "string"; - if (isJSONContent) { - try { - const isArrayContent = Array.isArray(content) && content.length > 0; - if (isArrayContent) { - return Fragment.fromArray(content.map((item) => schema.nodeFromJSON(item))); - } - const node = schema.nodeFromJSON(content); - if (options.errorOnInvalidContent) { - node.check(); - } - return node; - } catch (error) { - if (options.errorOnInvalidContent) { - throw new Error("[tiptap error]: Invalid JSON content", { cause: error }); - } - console.warn("[tiptap warn]: Invalid content.", "Passed value:", content, "Error:", error); - return createNodeFromContent("", schema, options); - } - } - if (isTextContent) { - if (options.errorOnInvalidContent) { - let hasInvalidContent = false; - let invalidContent = ""; - const contentCheckSchema = new Schema({ - topNode: schema.spec.topNode, - marks: schema.spec.marks, - // Prosemirror's schemas are executed such that: the last to execute, matches last - // This means that we can add a catch-all node at the end of the schema to catch any content that we don't know how to handle - nodes: schema.spec.nodes.append({ - __tiptap__private__unknown__catch__all__node: { - content: "inline*", - group: "block", - parseDOM: [ - { - tag: "*", - getAttrs: (e) => { - hasInvalidContent = true; - invalidContent = typeof e === "string" ? e : e.outerHTML; - return null; - } - } - ] - } - }) - }); - if (options.slice) { - DOMParser.fromSchema(contentCheckSchema).parseSlice(elementFromString(content), options.parseOptions); - } else { - DOMParser.fromSchema(contentCheckSchema).parse(elementFromString(content), options.parseOptions); - } - if (options.errorOnInvalidContent && hasInvalidContent) { - throw new Error("[tiptap error]: Invalid HTML content", { - cause: new Error(`Invalid element found: ${invalidContent}`) - }); - } - } - const parser = DOMParser.fromSchema(schema); - if (options.slice) { - return parser.parseSlice(elementFromString(content), options.parseOptions).content; - } - return parser.parse(elementFromString(content), options.parseOptions); - } - return createNodeFromContent("", schema, options); -} -function selectionToInsertionEnd(tr2, startLen, bias) { - const last = tr2.steps.length - 1; - if (last < startLen) { - return; - } - const step = tr2.steps[last]; - if (!(step instanceof ReplaceStep || step instanceof ReplaceAroundStep)) { - return; - } - const map2 = tr2.mapping.maps[last]; - let end = 0; - map2.forEach((_from, _to, _newFrom, newTo) => { - if (end === 0) { - end = newTo; - } - }); - tr2.setSelection(Selection.near(tr2.doc.resolve(end), bias)); -} -var isFragment = (nodeOrFragment) => { - return !("type" in nodeOrFragment); -}; -var insertContentAt = (position, value, options) => ({ tr: tr2, dispatch, editor }) => { - var _a; - if (dispatch) { - options = { - parseOptions: editor.options.parseOptions, - updateSelection: true, - applyInputRules: false, - applyPasteRules: false, - ...options - }; - let content; - const emitContentError = (error) => { - editor.emit("contentError", { - editor, - error, - disableCollaboration: () => { - if ("collaboration" in editor.storage && typeof editor.storage.collaboration === "object" && editor.storage.collaboration) { - editor.storage.collaboration.isDisabled = true; - } - } - }); - }; - const parseOptions = { - preserveWhitespace: "full", - ...options.parseOptions - }; - if (!options.errorOnInvalidContent && !editor.options.enableContentCheck && editor.options.emitContentError) { - try { - createNodeFromContent(value, editor.schema, { - parseOptions, - errorOnInvalidContent: true - }); - } catch (e) { - emitContentError(e); - } - } - try { - content = createNodeFromContent(value, editor.schema, { - parseOptions, - errorOnInvalidContent: (_a = options.errorOnInvalidContent) != null ? _a : editor.options.enableContentCheck - }); - } catch (e) { - emitContentError(e); - return false; - } - let { from: from2, to } = typeof position === "number" ? { from: position, to: position } : { from: position.from, to: position.to }; - let isOnlyTextContent = true; - let isOnlyBlockContent = true; - const nodes = isFragment(content) ? content : [content]; - nodes.forEach((node) => { - node.check(); - isOnlyTextContent = isOnlyTextContent ? node.isText && node.marks.length === 0 : false; - isOnlyBlockContent = isOnlyBlockContent ? node.isBlock : false; - }); - if (from2 === to && isOnlyBlockContent) { - const { parent } = tr2.doc.resolve(from2); - const isEmptyTextBlock = parent.isTextblock && !parent.type.spec.code && !parent.childCount; - if (isEmptyTextBlock) { - from2 -= 1; - to += 1; - } - } - let newContent; - if (isOnlyTextContent) { - if (Array.isArray(value)) { - newContent = value.map((v) => v.text || "").join(""); - } else if (value instanceof Fragment) { - let text = ""; - value.forEach((node) => { - if (node.text) { - text += node.text; - } - }); - newContent = text; - } else if (typeof value === "object" && !!value && !!value.text) { - newContent = value.text; - } else { - newContent = value; - } - tr2.insertText(newContent, from2, to); - } else { - newContent = content; - const $from = tr2.doc.resolve(from2); - const $fromNode = $from.node(); - const fromSelectionAtStart = $from.parentOffset === 0; - const isTextSelection2 = $fromNode.isText || $fromNode.isTextblock; - const hasContent = $fromNode.content.size > 0; - if (fromSelectionAtStart && isTextSelection2 && hasContent) { - from2 = Math.max(0, from2 - 1); - } - tr2.replaceWith(from2, to, newContent); - } - if (options.updateSelection) { - selectionToInsertionEnd(tr2, tr2.steps.length - 1, -1); - } - if (options.applyInputRules) { - tr2.setMeta("applyInputRules", { from: from2, text: newContent }); - } - if (options.applyPasteRules) { - tr2.setMeta("applyPasteRules", { from: from2, text: newContent }); - } - } - return true; -}; -var joinUp = () => ({ state, dispatch }) => { - return joinUp$1(state, dispatch); -}; -var joinDown = () => ({ state, dispatch }) => { - return joinDown$1(state, dispatch); -}; -var joinBackward = () => ({ state, dispatch }) => { - return joinBackward$1(state, dispatch); -}; -var joinForward = () => ({ state, dispatch }) => { - return joinForward$1(state, dispatch); -}; -var joinItemBackward = () => ({ state, dispatch, tr: tr2 }) => { - try { - const point = joinPoint(state.doc, state.selection.$from.pos, -1); - if (point === null || point === void 0) { - return false; - } - tr2.join(point, 2); - if (dispatch) { - dispatch(tr2); - } - return true; - } catch { - return false; - } -}; -var joinItemForward = () => ({ state, dispatch, tr: tr2 }) => { - try { - const point = joinPoint(state.doc, state.selection.$from.pos, 1); - if (point === null || point === void 0) { - return false; - } - tr2.join(point, 2); - if (dispatch) { - dispatch(tr2); - } - return true; - } catch { - return false; - } -}; -var joinTextblockBackward = () => ({ state, dispatch }) => { - return joinTextblockBackward$1(state, dispatch); -}; -var joinTextblockForward = () => ({ state, dispatch }) => { - return joinTextblockForward$1(state, dispatch); -}; -function isMacOS() { - return typeof navigator !== "undefined" ? /Mac/.test(navigator.platform) : false; -} -function normalizeKeyName(name) { - const parts = name.split(/-(?!$)/); - let result = parts[parts.length - 1]; - if (result === "Space") { - result = " "; - } - let alt; - let ctrl; - let shift2; - let meta; - for (let i = 0; i < parts.length - 1; i += 1) { - const mod = parts[i]; - if (/^(cmd|meta|m)$/i.test(mod)) { - meta = true; - } else if (/^a(lt)?$/i.test(mod)) { - alt = true; - } else if (/^(c|ctrl|control)$/i.test(mod)) { - ctrl = true; - } else if (/^s(hift)?$/i.test(mod)) { - shift2 = true; - } else if (/^mod$/i.test(mod)) { - if (isiOS() || isMacOS()) { - meta = true; - } else { - ctrl = true; - } - } else { - throw new Error(`Unrecognized modifier name: ${mod}`); - } - } - if (alt) { - result = `Alt-${result}`; - } - if (ctrl) { - result = `Ctrl-${result}`; - } - if (meta) { - result = `Meta-${result}`; - } - if (shift2) { - result = `Shift-${result}`; - } - return result; -} -var keyboardShortcut = (name) => ({ editor, view, tr: tr2, dispatch }) => { - const keys2 = normalizeKeyName(name).split(/-(?!$)/); - const key = keys2.find((item) => !["Alt", "Ctrl", "Meta", "Shift"].includes(item)); - const event = new KeyboardEvent("keydown", { - key: key === "Space" ? " " : key, - altKey: keys2.includes("Alt"), - ctrlKey: keys2.includes("Ctrl"), - metaKey: keys2.includes("Meta"), - shiftKey: keys2.includes("Shift"), - bubbles: true, - cancelable: true - }); - const capturedTransaction = editor.captureTransaction(() => { - view.someProp("handleKeyDown", (f) => f(view, event)); - }); - capturedTransaction == null ? void 0 : capturedTransaction.steps.forEach((step) => { - const newStep = step.map(tr2.mapping); - if (newStep && dispatch) { - tr2.maybeStep(newStep); - } - }); - return true; -}; -function isNodeActive(state, typeOrName, attributes = {}) { - const { from: from2, to, empty: empty2 } = state.selection; - const type = typeOrName ? getNodeType(typeOrName, state.schema) : null; - const nodeRanges = []; - state.doc.nodesBetween(from2, to, (node, pos) => { - if (node.isText) { - return; - } - const relativeFrom = Math.max(from2, pos); - const relativeTo = Math.min(to, pos + node.nodeSize); - nodeRanges.push({ - node, - from: relativeFrom, - to: relativeTo - }); - }); - const selectionRange = to - from2; - const matchedNodeRanges = nodeRanges.filter((nodeRange) => { - if (!type) { - return true; - } - return type.name === nodeRange.node.type.name; - }).filter((nodeRange) => objectIncludes(nodeRange.node.attrs, attributes, { strict: false })); - if (empty2) { - return !!matchedNodeRanges.length; - } - const range = matchedNodeRanges.reduce((sum, nodeRange) => sum + nodeRange.to - nodeRange.from, 0); - return range >= selectionRange; -} -var lift = (typeOrName, attributes = {}) => ({ state, dispatch }) => { - const type = getNodeType(typeOrName, state.schema); - const isActive2 = isNodeActive(state, type, attributes); - if (!isActive2) { - return false; - } - return lift$1(state, dispatch); -}; -var liftEmptyBlock = () => ({ state, dispatch }) => { - return liftEmptyBlock$1(state, dispatch); -}; -var liftListItem = (typeOrName) => ({ state, dispatch }) => { - const type = getNodeType(typeOrName, state.schema); - return liftListItem$1(type)(state, dispatch); -}; -var newlineInCode = () => ({ state, dispatch }) => { - return newlineInCode$1(state, dispatch); -}; -function getSchemaTypeNameByName(name, schema) { - if (schema.nodes[name]) { - return "node"; - } - if (schema.marks[name]) { - return "mark"; - } - return null; -} -function deleteProps(obj, propOrProps) { - const props = typeof propOrProps === "string" ? [propOrProps] : propOrProps; - return Object.keys(obj).reduce((newObj, prop) => { - if (!props.includes(prop)) { - newObj[prop] = obj[prop]; - } - return newObj; - }, {}); -} -var resetAttributes = (typeOrName, attributes) => ({ tr: tr2, state, dispatch }) => { - let nodeType = null; - let markType = null; - const schemaType = getSchemaTypeNameByName( - typeof typeOrName === "string" ? typeOrName : typeOrName.name, - state.schema - ); - if (!schemaType) { - return false; - } - if (schemaType === "node") { - nodeType = getNodeType(typeOrName, state.schema); - } - if (schemaType === "mark") { - markType = getMarkType(typeOrName, state.schema); - } - let canReset = false; - tr2.selection.ranges.forEach((range) => { - state.doc.nodesBetween(range.$from.pos, range.$to.pos, (node, pos) => { - if (nodeType && nodeType === node.type) { - canReset = true; - if (dispatch) { - tr2.setNodeMarkup(pos, void 0, deleteProps(node.attrs, attributes)); - } - } - if (markType && node.marks.length) { - node.marks.forEach((mark) => { - if (markType === mark.type) { - canReset = true; - if (dispatch) { - tr2.addMark(pos, pos + node.nodeSize, markType.create(deleteProps(mark.attrs, attributes))); - } - } - }); - } - }); - }); - return canReset; -}; -var scrollIntoView = () => ({ tr: tr2, dispatch }) => { - if (dispatch) { - tr2.scrollIntoView(); - } - return true; -}; -var selectAll = () => ({ tr: tr2, dispatch }) => { - if (dispatch) { - const selection = new AllSelection(tr2.doc); - tr2.setSelection(selection); - } - return true; -}; -var selectNodeBackward = () => ({ state, dispatch }) => { - return selectNodeBackward$1(state, dispatch); -}; -var selectNodeForward = () => ({ state, dispatch }) => { - return selectNodeForward$1(state, dispatch); -}; -var selectParentNode = () => ({ state, dispatch }) => { - return selectParentNode$1(state, dispatch); -}; -var selectTextblockEnd = () => ({ state, dispatch }) => { - return selectTextblockEnd$1(state, dispatch); -}; -var selectTextblockStart = () => ({ state, dispatch }) => { - return selectTextblockStart$1(state, dispatch); -}; -function createDocument(content, schema, parseOptions = {}, options = {}) { - return createNodeFromContent(content, schema, { - slice: false, - parseOptions, - errorOnInvalidContent: options.errorOnInvalidContent - }); -} -var setContent = (content, { errorOnInvalidContent, emitUpdate = true, parseOptions = {} } = {}) => ({ editor, tr: tr2, dispatch, commands }) => { - const { doc: doc2 } = tr2; - if (parseOptions.preserveWhitespace !== "full") { - const document2 = createDocument(content, editor.schema, parseOptions, { - errorOnInvalidContent: errorOnInvalidContent != null ? errorOnInvalidContent : editor.options.enableContentCheck - }); - if (dispatch) { - tr2.replaceWith(0, doc2.content.size, document2).setMeta("preventUpdate", !emitUpdate); - } - return true; - } - if (dispatch) { - tr2.setMeta("preventUpdate", !emitUpdate); - } - return commands.insertContentAt({ from: 0, to: doc2.content.size }, content, { - parseOptions, - errorOnInvalidContent: errorOnInvalidContent != null ? errorOnInvalidContent : editor.options.enableContentCheck - }); -}; -function getMarkAttributes(state, typeOrName) { - const type = getMarkType(typeOrName, state.schema); - const { from: from2, to, empty: empty2 } = state.selection; - const marks = []; - if (empty2) { - if (state.storedMarks) { - marks.push(...state.storedMarks); - } - marks.push(...state.selection.$head.marks()); - } else { - state.doc.nodesBetween(from2, to, (node) => { - marks.push(...node.marks); - }); - } - const mark = marks.find((markItem) => markItem.type.name === type.name); - if (!mark) { - return {}; - } - return { ...mark.attrs }; -} -function combineTransactionSteps(oldDoc, transactions) { - const transform = new Transform(oldDoc); - transactions.forEach((transaction) => { - transaction.steps.forEach((step) => { - transform.step(step); - }); - }); - return transform; -} -function defaultBlockAt(match) { - for (let i = 0; i < match.edgeCount; i += 1) { - const { type } = match.edge(i); - if (type.isTextblock && !type.hasRequiredAttrs()) { - return type; - } - } - return null; -} -function findChildrenInRange(node, range, predicate) { - const nodesWithPos = []; - node.nodesBetween(range.from, range.to, (child, pos) => { - if (predicate(child)) { - nodesWithPos.push({ - node: child, - pos - }); - } - }); - return nodesWithPos; -} -function findParentNodeClosestToPos($pos, predicate) { - for (let i = $pos.depth; i > 0; i -= 1) { - const node = $pos.node(i); - if (predicate(node)) { - return { - pos: i > 0 ? $pos.before(i) : 0, - start: $pos.start(i), - depth: i, - node - }; - } - } -} -function findParentNode(predicate) { - return (selection) => findParentNodeClosestToPos(selection.$from, predicate); -} -function getExtensionField(extension, field, context) { - if (extension.config[field] === void 0 && extension.parent) { - return getExtensionField(extension.parent, field, context); - } - if (typeof extension.config[field] === "function") { - const value = extension.config[field].bind({ - ...context, - parent: extension.parent ? getExtensionField(extension.parent, field, context) : null - }); - return value; - } - return extension.config[field]; -} -function flattenExtensions(extensions) { - return extensions.map((extension) => { - const context = { - name: extension.name, - options: extension.options, - storage: extension.storage - }; - const addExtensions = getExtensionField(extension, "addExtensions", context); - if (addExtensions) { - return [extension, ...flattenExtensions(addExtensions())]; - } - return extension; - }).flat(10); -} -function getHTMLFromFragment(fragment, schema) { - const documentFragment = DOMSerializer.fromSchema(schema).serializeFragment(fragment); - const temporaryDocument = document.implementation.createHTMLDocument(); - const container = temporaryDocument.createElement("div"); - container.appendChild(documentFragment); - return container.innerHTML; -} -function isFunction(value) { - return typeof value === "function"; -} -function callOrReturn(value, context = void 0, ...props) { - if (isFunction(value)) { - if (context) { - return value.bind(context)(...props); - } - return value(...props); - } - return value; -} -function isEmptyObject(value = {}) { - return Object.keys(value).length === 0 && value.constructor === Object; -} -function splitExtensions(extensions) { - const baseExtensions = extensions.filter((extension) => extension.type === "extension"); - const nodeExtensions = extensions.filter((extension) => extension.type === "node"); - const markExtensions = extensions.filter((extension) => extension.type === "mark"); - return { - baseExtensions, - nodeExtensions, - markExtensions - }; -} -function getAttributesFromExtensions(extensions) { - const extensionAttributes = []; - const { nodeExtensions, markExtensions } = splitExtensions(extensions); - const nodeAndMarkExtensions = [...nodeExtensions, ...markExtensions]; - const defaultAttribute = { - default: null, - validate: void 0, - rendered: true, - renderHTML: null, - parseHTML: null, - keepOnSplit: true, - isRequired: false - }; - const nodeExtensionTypes = nodeExtensions.filter((ext) => ext.name !== "text").map((ext) => ext.name); - const markExtensionTypes = markExtensions.map((ext) => ext.name); - const allExtensionTypes = [...nodeExtensionTypes, ...markExtensionTypes]; - extensions.forEach((extension) => { - const context = { - name: extension.name, - options: extension.options, - storage: extension.storage, - extensions: nodeAndMarkExtensions - }; - const addGlobalAttributes = getExtensionField( - extension, - "addGlobalAttributes", - context - ); - if (!addGlobalAttributes) { - return; - } - const globalAttributes = addGlobalAttributes(); - globalAttributes.forEach((globalAttribute) => { - let resolvedTypes; - if (Array.isArray(globalAttribute.types)) { - resolvedTypes = globalAttribute.types; - } else if (globalAttribute.types === "*") { - resolvedTypes = allExtensionTypes; - } else if (globalAttribute.types === "nodes") { - resolvedTypes = nodeExtensionTypes; - } else if (globalAttribute.types === "marks") { - resolvedTypes = markExtensionTypes; - } else { - resolvedTypes = []; - } - resolvedTypes.forEach((type) => { - Object.entries(globalAttribute.attributes).forEach(([name, attribute]) => { - extensionAttributes.push({ - type, - name, - attribute: { - ...defaultAttribute, - ...attribute - } - }); - }); - }); - }); - }); - nodeAndMarkExtensions.forEach((extension) => { - const context = { - name: extension.name, - options: extension.options, - storage: extension.storage - }; - const addAttributes = getExtensionField( - extension, - "addAttributes", - context - ); - if (!addAttributes) { - return; - } - const attributes = addAttributes(); - Object.entries(attributes).forEach(([name, attribute]) => { - const mergedAttr = { - ...defaultAttribute, - ...attribute - }; - if (typeof (mergedAttr == null ? void 0 : mergedAttr.default) === "function") { - mergedAttr.default = mergedAttr.default(); - } - if ((mergedAttr == null ? void 0 : mergedAttr.isRequired) && (mergedAttr == null ? void 0 : mergedAttr.default) === void 0) { - delete mergedAttr.default; - } - extensionAttributes.push({ - type: extension.name, - name, - attribute: mergedAttr - }); - }); - }); - return extensionAttributes; -} -function splitStyleDeclarations(styles) { - const result = []; - let current = ""; - let inSingleQuote = false; - let inDoubleQuote = false; - let parenDepth = 0; - const length = styles.length; - for (let i = 0; i < length; i += 1) { - const char = styles[i]; - if (char === "'" && !inDoubleQuote) { - inSingleQuote = !inSingleQuote; - current += char; - continue; - } - if (char === '"' && !inSingleQuote) { - inDoubleQuote = !inDoubleQuote; - current += char; - continue; - } - if (!inSingleQuote && !inDoubleQuote) { - if (char === "(") { - parenDepth += 1; - current += char; - continue; - } - if (char === ")" && parenDepth > 0) { - parenDepth -= 1; - current += char; - continue; - } - if (char === ";" && parenDepth === 0) { - result.push(current); - current = ""; - continue; - } - } - current += char; - } - if (current) { - result.push(current); - } - return result; -} -function parseStyleEntries(styles) { - const pairs = []; - const declarations = splitStyleDeclarations(styles || ""); - const numDeclarations = declarations.length; - for (let i = 0; i < numDeclarations; i += 1) { - const declaration = declarations[i]; - const firstColonIndex = declaration.indexOf(":"); - if (firstColonIndex === -1) { - continue; - } - const property = declaration.slice(0, firstColonIndex).trim(); - const value = declaration.slice(firstColonIndex + 1).trim(); - if (property && value) { - pairs.push([property, value]); - } - } - return pairs; -} -function mergeAttributes(...objects) { - return objects.filter((item) => !!item).reduce((items, item) => { - const mergedAttributes = { ...items }; - Object.entries(item).forEach(([key, value]) => { - const exists = mergedAttributes[key]; - if (!exists) { - mergedAttributes[key] = value; - return; - } - if (key === "class") { - const valueClasses = value ? String(value).split(" ") : []; - const existingClasses = mergedAttributes[key] ? mergedAttributes[key].split(" ") : []; - const insertClasses = valueClasses.filter((valueClass) => !existingClasses.includes(valueClass)); - mergedAttributes[key] = [...existingClasses, ...insertClasses].join(" "); - } else if (key === "style") { - const styleMap = new Map([...parseStyleEntries(mergedAttributes[key]), ...parseStyleEntries(value)]); - mergedAttributes[key] = Array.from(styleMap.entries()).map(([property, val]) => `${property}: ${val}`).join("; "); - } else { - mergedAttributes[key] = value; - } - }); - return mergedAttributes; - }, {}); -} -function getRenderedAttributes(nodeOrMark, extensionAttributes) { - return extensionAttributes.filter((attribute) => attribute.type === nodeOrMark.type.name).filter((item) => item.attribute.rendered).map((item) => { - if (!item.attribute.renderHTML) { - return { - [item.name]: nodeOrMark.attrs[item.name] - }; - } - return item.attribute.renderHTML(nodeOrMark.attrs) || {}; - }).reduce((attributes, attribute) => mergeAttributes(attributes, attribute), {}); -} -function fromString(value) { - if (typeof value !== "string") { - return value; - } - if (value.match(/^[+-]?(?:\d*\.)?\d+$/)) { - return Number(value); - } - if (value === "true") { - return true; - } - if (value === "false") { - return false; - } - return value; -} -function injectExtensionAttributesToParseRule(parseRule, extensionAttributes) { - if ("style" in parseRule) { - return parseRule; - } - return { - ...parseRule, - getAttrs: (node) => { - const oldAttributes = parseRule.getAttrs ? parseRule.getAttrs(node) : parseRule.attrs; - if (oldAttributes === false) { - return false; - } - const newAttributes = extensionAttributes.reduce((items, item) => { - const value = item.attribute.parseHTML ? item.attribute.parseHTML(node) : fromString(node.getAttribute(item.name)); - if (value === null || value === void 0) { - return items; - } - return { - ...items, - [item.name]: value - }; - }, {}); - return { ...oldAttributes, ...newAttributes }; - } - }; -} -function cleanUpSchemaItem(data) { - return Object.fromEntries( - // @ts-ignore - Object.entries(data).filter(([key, value]) => { - if (key === "attrs" && isEmptyObject(value)) { - return false; - } - return value !== null && value !== void 0; - }) - ); -} -function buildAttributeSpec(extensionAttribute) { - var _a, _b; - const spec = {}; - if (!((_a = extensionAttribute == null ? void 0 : extensionAttribute.attribute) == null ? void 0 : _a.isRequired) && "default" in ((extensionAttribute == null ? void 0 : extensionAttribute.attribute) || {})) { - spec.default = extensionAttribute.attribute.default; - } - if (((_b = extensionAttribute == null ? void 0 : extensionAttribute.attribute) == null ? void 0 : _b.validate) !== void 0) { - spec.validate = extensionAttribute.attribute.validate; - } - return [extensionAttribute.name, spec]; -} -function getSchemaByResolvedExtensions(extensions, editor) { - var _a; - const allAttributes = getAttributesFromExtensions(extensions); - const { nodeExtensions, markExtensions } = splitExtensions(extensions); - const topNode = (_a = nodeExtensions.find((extension) => getExtensionField(extension, "topNode"))) == null ? void 0 : _a.name; - const nodes = Object.fromEntries( - nodeExtensions.map((extension) => { - const extensionAttributes = allAttributes.filter((attribute) => attribute.type === extension.name); - const context = { - name: extension.name, - options: extension.options, - storage: extension.storage, - editor - }; - const extraNodeFields = extensions.reduce((fields, e) => { - const extendNodeSchema = getExtensionField(e, "extendNodeSchema", context); - return { - ...fields, - ...extendNodeSchema ? extendNodeSchema(extension) : {} - }; - }, {}); - const schema = cleanUpSchemaItem({ - ...extraNodeFields, - content: callOrReturn(getExtensionField(extension, "content", context)), - marks: callOrReturn(getExtensionField(extension, "marks", context)), - group: callOrReturn(getExtensionField(extension, "group", context)), - inline: callOrReturn(getExtensionField(extension, "inline", context)), - atom: callOrReturn(getExtensionField(extension, "atom", context)), - selectable: callOrReturn(getExtensionField(extension, "selectable", context)), - draggable: callOrReturn(getExtensionField(extension, "draggable", context)), - code: callOrReturn(getExtensionField(extension, "code", context)), - whitespace: callOrReturn(getExtensionField(extension, "whitespace", context)), - linebreakReplacement: callOrReturn( - getExtensionField(extension, "linebreakReplacement", context) - ), - defining: callOrReturn(getExtensionField(extension, "defining", context)), - isolating: callOrReturn(getExtensionField(extension, "isolating", context)), - attrs: Object.fromEntries(extensionAttributes.map(buildAttributeSpec)) - }); - const parseHTML = callOrReturn(getExtensionField(extension, "parseHTML", context)); - if (parseHTML) { - schema.parseDOM = parseHTML.map( - (parseRule) => injectExtensionAttributesToParseRule(parseRule, extensionAttributes) - ); - } - const renderHTML = getExtensionField(extension, "renderHTML", context); - if (renderHTML) { - schema.toDOM = (node) => renderHTML({ - node, - HTMLAttributes: getRenderedAttributes(node, extensionAttributes) - }); - } - const renderText = getExtensionField(extension, "renderText", context); - if (renderText) { - schema.toText = renderText; - } - return [extension.name, schema]; - }) - ); - const marks = Object.fromEntries( - markExtensions.map((extension) => { - const extensionAttributes = allAttributes.filter((attribute) => attribute.type === extension.name); - const context = { - name: extension.name, - options: extension.options, - storage: extension.storage, - editor - }; - const extraMarkFields = extensions.reduce((fields, e) => { - const extendMarkSchema = getExtensionField(e, "extendMarkSchema", context); - return { - ...fields, - ...extendMarkSchema ? extendMarkSchema(extension) : {} - }; - }, {}); - const schema = cleanUpSchemaItem({ - ...extraMarkFields, - inclusive: callOrReturn(getExtensionField(extension, "inclusive", context)), - excludes: callOrReturn(getExtensionField(extension, "excludes", context)), - group: callOrReturn(getExtensionField(extension, "group", context)), - spanning: callOrReturn(getExtensionField(extension, "spanning", context)), - code: callOrReturn(getExtensionField(extension, "code", context)), - attrs: Object.fromEntries(extensionAttributes.map(buildAttributeSpec)) - }); - const parseHTML = callOrReturn(getExtensionField(extension, "parseHTML", context)); - if (parseHTML) { - schema.parseDOM = parseHTML.map( - (parseRule) => injectExtensionAttributesToParseRule(parseRule, extensionAttributes) - ); - } - const renderHTML = getExtensionField(extension, "renderHTML", context); - if (renderHTML) { - schema.toDOM = (mark) => renderHTML({ - mark, - HTMLAttributes: getRenderedAttributes(mark, extensionAttributes) - }); - } - return [extension.name, schema]; - }) - ); - return new Schema({ - topNode, - nodes, - marks - }); -} -function findDuplicates(items) { - const filtered = items.filter((el, index) => items.indexOf(el) !== index); - return Array.from(new Set(filtered)); -} -function sortExtensions(extensions) { - const defaultPriority = 100; - return extensions.sort((a, b) => { - const priorityA = getExtensionField(a, "priority") || defaultPriority; - const priorityB = getExtensionField(b, "priority") || defaultPriority; - if (priorityA > priorityB) { - return -1; - } - if (priorityA < priorityB) { - return 1; - } - return 0; - }); -} -function resolveExtensions(extensions) { - const resolvedExtensions = sortExtensions(flattenExtensions(extensions)); - const duplicatedNames = findDuplicates(resolvedExtensions.map((extension) => extension.name)); - if (duplicatedNames.length) { - console.warn( - `[tiptap warn]: Duplicate extension names found: [${duplicatedNames.map((item) => `'${item}'`).join(", ")}]. This can lead to issues.` - ); - } - return resolvedExtensions; -} -function getTextBetween(startNode, range, options) { - const { from: from2, to } = range; - const { blockSeparator = "\n\n", textSerializers = {} } = options || {}; - let text = ""; - startNode.nodesBetween(from2, to, (node, pos, parent, index) => { - var _a; - if (node.isBlock && pos > from2) { - text += blockSeparator; - } - const textSerializer = textSerializers == null ? void 0 : textSerializers[node.type.name]; - if (textSerializer) { - if (parent) { - text += textSerializer({ - node, - pos, - parent, - index, - range - }); - } - return false; - } - if (node.isText) { - text += (_a = node == null ? void 0 : node.text) == null ? void 0 : _a.slice(Math.max(from2, pos) - pos, to - pos); - } - }); - return text; -} -function getText(node, options) { - const range = { - from: 0, - to: node.content.size - }; - return getTextBetween(node, range, options); -} -function getTextSerializersFromSchema(schema) { - return Object.fromEntries( - Object.entries(schema.nodes).filter(([, node]) => node.spec.toText).map(([name, node]) => [name, node.spec.toText]) - ); -} -function getNodeAttributes(state, typeOrName) { - const type = getNodeType(typeOrName, state.schema); - const { from: from2, to } = state.selection; - const nodes = []; - state.doc.nodesBetween(from2, to, (node2) => { - nodes.push(node2); - }); - const node = nodes.reverse().find((nodeItem) => nodeItem.type.name === type.name); - if (!node) { - return {}; - } - return { ...node.attrs }; -} -function getAttributes(state, typeOrName) { - const schemaType = getSchemaTypeNameByName( - typeof typeOrName === "string" ? typeOrName : typeOrName.name, - state.schema - ); - if (schemaType === "node") { - return getNodeAttributes(state, typeOrName); - } - if (schemaType === "mark") { - return getMarkAttributes(state, typeOrName); - } - return {}; -} -function removeDuplicates(array, by = JSON.stringify) { - const seen = {}; - return array.filter((item) => { - const key = by(item); - return Object.prototype.hasOwnProperty.call(seen, key) ? false : seen[key] = true; - }); -} -function simplifyChangedRanges(changes) { - const uniqueChanges = removeDuplicates(changes); - return uniqueChanges.length === 1 ? uniqueChanges : uniqueChanges.filter((change, index) => { - const rest = uniqueChanges.filter((_, i) => i !== index); - return !rest.some((otherChange) => { - return change.oldRange.from >= otherChange.oldRange.from && change.oldRange.to <= otherChange.oldRange.to && change.newRange.from >= otherChange.newRange.from && change.newRange.to <= otherChange.newRange.to; - }); - }); -} -function getChangedRanges(transform) { - const { mapping, steps } = transform; - const changes = []; - mapping.maps.forEach((stepMap, index) => { - const ranges = []; - if (!stepMap.ranges.length) { - const { from: from2, to } = steps[index]; - if (from2 === void 0 || to === void 0) { - return; - } - ranges.push({ from: from2, to }); - } else { - stepMap.forEach((from2, to) => { - ranges.push({ from: from2, to }); - }); - } - ranges.forEach(({ from: from2, to }) => { - const newStart = mapping.slice(index).map(from2, -1); - const newEnd = mapping.slice(index).map(to); - const oldStart = mapping.invert().map(newStart, -1); - const oldEnd = mapping.invert().map(newEnd); - changes.push({ - oldRange: { - from: oldStart, - to: oldEnd - }, - newRange: { - from: newStart, - to: newEnd - } - }); - }); - }); - return simplifyChangedRanges(changes); -} -function getMarksBetween(from2, to, doc2) { - const marks = []; - if (from2 === to) { - doc2.resolve(from2).marks().forEach((mark) => { - const $pos = doc2.resolve(from2); - const range = getMarkRange($pos, mark.type); - if (!range) { - return; - } - marks.push({ - mark, - ...range - }); - }); - } else { - doc2.nodesBetween(from2, to, (node, pos) => { - if (!node || (node == null ? void 0 : node.nodeSize) === void 0) { - return; - } - marks.push( - ...node.marks.map((mark) => ({ - from: pos, - to: pos + node.nodeSize, - mark - })) - ); - }); - } - return marks; -} -var getNodeAtPosition = (state, typeOrName, pos, maxDepth = 20) => { - const $pos = state.doc.resolve(pos); - let currentDepth = maxDepth; - let node = null; - while (currentDepth > 0 && node === null) { - const currentNode = $pos.node(currentDepth); - if ((currentNode == null ? void 0 : currentNode.type.name) === typeOrName) { - node = currentNode; - } else { - currentDepth -= 1; - } - } - return [node, currentDepth]; -}; -function getSchemaTypeByName(name, schema) { - return schema.nodes[name] || schema.marks[name] || null; -} -function getSplittedAttributes(extensionAttributes, typeName, attributes) { - return Object.fromEntries( - Object.entries(attributes).filter(([name]) => { - const extensionAttribute = extensionAttributes.find((item) => { - return item.type === typeName && item.name === name; - }); - if (!extensionAttribute) { - return false; - } - return extensionAttribute.attribute.keepOnSplit; - }) - ); -} -var getTextContentFromNodes = ($from, maxMatch = 500) => { - let textBefore = ""; - const sliceEndPos = $from.parentOffset; - $from.parent.nodesBetween(Math.max(0, sliceEndPos - maxMatch), sliceEndPos, (node, pos, parent, index) => { - var _a, _b; - const chunk = ((_b = (_a = node.type.spec).toText) == null ? void 0 : _b.call(_a, { - node, - pos, - parent, - index - })) || node.textContent || "%leaf%"; - textBefore += node.isAtom && !node.isText ? chunk : chunk.slice(0, Math.max(0, sliceEndPos - pos)); - }); - return textBefore; -}; -function isMarkActive(state, typeOrName, attributes = {}) { - const { empty: empty2, ranges } = state.selection; - const type = typeOrName ? getMarkType(typeOrName, state.schema) : null; - if (empty2) { - return !!(state.storedMarks || state.selection.$from.marks()).filter((mark) => { - if (!type) { - return true; - } - return type.name === mark.type.name; - }).find((mark) => objectIncludes(mark.attrs, attributes, { strict: false })); - } - let selectionRange = 0; - const markRanges = []; - ranges.forEach(({ $from, $to }) => { - const from2 = $from.pos; - const to = $to.pos; - state.doc.nodesBetween(from2, to, (node, pos) => { - if (type && node.inlineContent && !node.type.allowsMarkType(type)) { - return false; - } - if (!node.isText && !node.marks.length) { - return; - } - const relativeFrom = Math.max(from2, pos); - const relativeTo = Math.min(to, pos + node.nodeSize); - const range2 = relativeTo - relativeFrom; - selectionRange += range2; - markRanges.push( - ...node.marks.map((mark) => ({ - mark, - from: relativeFrom, - to: relativeTo - })) - ); - }); - }); - if (selectionRange === 0) { - return false; - } - const matchedRange = markRanges.filter((markRange) => { - if (!type) { - return true; - } - return type.name === markRange.mark.type.name; - }).filter((markRange) => objectIncludes(markRange.mark.attrs, attributes, { strict: false })).reduce((sum, markRange) => sum + markRange.to - markRange.from, 0); - const excludedRange = markRanges.filter((markRange) => { - if (!type) { - return true; - } - return markRange.mark.type !== type && markRange.mark.type.excludes(type); - }).reduce((sum, markRange) => sum + markRange.to - markRange.from, 0); - const range = matchedRange > 0 ? matchedRange + excludedRange : matchedRange; - return range >= selectionRange; -} -function isActive(state, name, attributes = {}) { - if (!name) { - return isNodeActive(state, null, attributes) || isMarkActive(state, null, attributes); - } - const schemaType = getSchemaTypeNameByName(name, state.schema); - if (schemaType === "node") { - return isNodeActive(state, name, attributes); - } - if (schemaType === "mark") { - return isMarkActive(state, name, attributes); - } - return false; -} -var isAtEndOfNode = (state, nodeType) => { - const { $from, $to, $anchor } = state.selection; - if (nodeType) { - const parentNode2 = findParentNode((node) => node.type.name === nodeType)(state.selection); - if (!parentNode2) { - return false; - } - const $parentPos = state.doc.resolve(parentNode2.pos + 1); - if ($anchor.pos + 1 === $parentPos.end()) { - return true; - } - return false; - } - if ($to.parentOffset < $to.parent.nodeSize - 2 || $from.pos !== $to.pos) { - return false; - } - return true; -}; -var isAtStartOfNode = (state) => { - const { $from, $to } = state.selection; - if ($from.parentOffset > 0 || $from.pos !== $to.pos) { - return false; - } - return true; -}; -function isExtensionRulesEnabled(extension, enabled) { - if (Array.isArray(enabled)) { - return enabled.some((enabledExtension) => { - const name = typeof enabledExtension === "string" ? enabledExtension : enabledExtension.name; - return name === extension.name; - }); - } - return enabled; -} -function isList(name, extensions) { - const { nodeExtensions } = splitExtensions(extensions); - const extension = nodeExtensions.find((item) => item.name === name); - if (!extension) { - return false; - } - const context = { - name: extension.name, - options: extension.options, - storage: extension.storage - }; - const group = callOrReturn(getExtensionField(extension, "group", context)); - if (typeof group !== "string") { - return false; - } - return group.split(" ").includes("list"); -} -function isNodeEmpty(node, { - checkChildren = true, - ignoreWhitespace = false -} = {}) { - var _a; - if (ignoreWhitespace) { - if (node.type.name === "hardBreak") { - return true; - } - if (node.isText) { - return !/\S/.test((_a = node.text) != null ? _a : ""); - } - } - if (node.isText) { - return !node.text; - } - if (node.isAtom || node.isLeaf) { - return false; - } - if (node.content.childCount === 0) { - return true; - } - if (checkChildren) { - let isContentEmpty = true; - node.content.forEach((childNode) => { - if (isContentEmpty === false) { - return; - } - if (!isNodeEmpty(childNode, { ignoreWhitespace, checkChildren })) { - isContentEmpty = false; - } - }); - return isContentEmpty; - } - return false; -} -function isNodeSelection(value) { - return value instanceof NodeSelection; -} -var MappablePosition = class _MappablePosition { - constructor(position) { - this.position = position; - } - /** - * Creates a MappablePosition from a JSON object. - */ - static fromJSON(json) { - return new _MappablePosition(json.position); - } - /** - * Converts the MappablePosition to a JSON object. - */ - toJSON() { - return { - position: this.position - }; - } -}; -function getUpdatedPosition(position, transaction) { - const mapResult = transaction.mapping.mapResult(position.position); - return { - position: new MappablePosition(mapResult.pos), - mapResult - }; -} -function createMappablePosition(position) { - return new MappablePosition(position); -} -function canSetMark(state, tr2, newMarkType) { - var _a; - const { selection } = tr2; - let cursor = null; - if (isTextSelection(selection)) { - cursor = selection.$cursor; - } - if (cursor) { - const currentMarks = (_a = state.storedMarks) != null ? _a : cursor.marks(); - const parentAllowsMarkType = cursor.parent.type.allowsMarkType(newMarkType); - return parentAllowsMarkType && (!!newMarkType.isInSet(currentMarks) || !currentMarks.some((mark) => mark.type.excludes(newMarkType))); - } - const { ranges } = selection; - return ranges.some(({ $from, $to }) => { - let someNodeSupportsMark = $from.depth === 0 ? state.doc.inlineContent && state.doc.type.allowsMarkType(newMarkType) : false; - state.doc.nodesBetween($from.pos, $to.pos, (node, _pos, parent) => { - if (someNodeSupportsMark) { - return false; - } - if (node.isInline) { - const parentAllowsMarkType = !parent || parent.type.allowsMarkType(newMarkType); - const currentMarksAllowMarkType = !!newMarkType.isInSet(node.marks) || !node.marks.some((otherMark) => otherMark.type.excludes(newMarkType)); - someNodeSupportsMark = parentAllowsMarkType && currentMarksAllowMarkType; - } - return !someNodeSupportsMark; - }); - return someNodeSupportsMark; - }); -} -var setMark = (typeOrName, attributes = {}) => ({ tr: tr2, state, dispatch }) => { - const { selection } = tr2; - const { empty: empty2, ranges } = selection; - const type = getMarkType(typeOrName, state.schema); - if (dispatch) { - if (empty2) { - const oldAttributes = getMarkAttributes(state, type); - tr2.addStoredMark( - type.create({ - ...oldAttributes, - ...attributes - }) - ); - } else { - ranges.forEach((range) => { - const from2 = range.$from.pos; - const to = range.$to.pos; - state.doc.nodesBetween(from2, to, (node, pos) => { - const trimmedFrom = Math.max(pos, from2); - const trimmedTo = Math.min(pos + node.nodeSize, to); - const someHasMark = node.marks.find((mark) => mark.type === type); - if (someHasMark) { - node.marks.forEach((mark) => { - if (type === mark.type) { - tr2.addMark( - trimmedFrom, - trimmedTo, - type.create({ - ...mark.attrs, - ...attributes - }) - ); - } - }); - } else { - tr2.addMark(trimmedFrom, trimmedTo, type.create(attributes)); - } - }); - }); - } - } - return canSetMark(state, tr2, type); -}; -var setMeta = (key, value) => ({ tr: tr2 }) => { - tr2.setMeta(key, value); - return true; -}; -var setNode = (typeOrName, attributes = {}) => ({ state, dispatch, chain }) => { - const type = getNodeType(typeOrName, state.schema); - let attributesToCopy; - if (state.selection.$anchor.sameParent(state.selection.$head)) { - attributesToCopy = state.selection.$anchor.parent.attrs; - } - if (!type.isTextblock) { - console.warn('[tiptap warn]: Currently "setNode()" only supports text block nodes.'); - return false; - } - return chain().command(({ commands }) => { - const canSetBlock = setBlockType(type, { ...attributesToCopy, ...attributes })(state); - if (canSetBlock) { - return true; - } - return commands.clearNodes(); - }).command(({ state: updatedState }) => { - return setBlockType(type, { ...attributesToCopy, ...attributes })(updatedState, dispatch); - }).run(); -}; -var setNodeSelection = (position) => ({ tr: tr2, dispatch }) => { - if (dispatch) { - const { doc: doc2 } = tr2; - const from2 = minMax(position, 0, doc2.content.size); - const selection = NodeSelection.create(doc2, from2); - tr2.setSelection(selection); - } - return true; -}; -var setTextDirection = (direction, position) => ({ tr: tr2, state, dispatch }) => { - const { selection } = state; - let from2; - let to; - if (typeof position === "number") { - from2 = position; - to = position; - } else if (position && "from" in position && "to" in position) { - from2 = position.from; - to = position.to; - } else { - from2 = selection.from; - to = selection.to; - } - if (dispatch) { - tr2.doc.nodesBetween(from2, to, (node, pos) => { - if (node.isText) { - return; - } - tr2.setNodeMarkup(pos, void 0, { - ...node.attrs, - dir: direction - }); - }); - } - return true; -}; -var setTextSelection = (position) => ({ tr: tr2, dispatch }) => { - if (dispatch) { - const { doc: doc2 } = tr2; - const { from: from2, to } = typeof position === "number" ? { from: position, to: position } : position; - const minPos = TextSelection.atStart(doc2).from; - const maxPos = TextSelection.atEnd(doc2).to; - const resolvedFrom = minMax(from2, minPos, maxPos); - const resolvedEnd = minMax(to, minPos, maxPos); - const selection = TextSelection.create(doc2, resolvedFrom, resolvedEnd); - tr2.setSelection(selection); - } - return true; -}; -var sinkListItem = (typeOrName) => ({ state, dispatch }) => { - const type = getNodeType(typeOrName, state.schema); - return sinkListItem$1(type)(state, dispatch); -}; -function ensureMarks(state, splittableMarks) { - const marks = state.storedMarks || state.selection.$to.parentOffset && state.selection.$from.marks(); - if (marks) { - const filteredMarks = marks.filter((mark) => splittableMarks == null ? void 0 : splittableMarks.includes(mark.type.name)); - state.tr.ensureMarks(filteredMarks); - } -} -var splitBlock = ({ keepMarks = true } = {}) => ({ tr: tr2, state, dispatch, editor }) => { - const { selection, doc: doc2 } = tr2; - const { $from, $to } = selection; - const extensionAttributes = editor.extensionManager.attributes; - const newAttributes = getSplittedAttributes(extensionAttributes, $from.node().type.name, $from.node().attrs); - if (selection instanceof NodeSelection && selection.node.isBlock) { - if (!$from.parentOffset || !canSplit(doc2, $from.pos)) { - return false; - } - if (dispatch) { - if (keepMarks) { - ensureMarks(state, editor.extensionManager.splittableMarks); - } - tr2.split($from.pos).scrollIntoView(); - } - return true; - } - if (!$from.parent.isBlock) { - return false; - } - const atEnd = $to.parentOffset === $to.parent.content.size; - const deflt = $from.depth === 0 ? void 0 : defaultBlockAt($from.node(-1).contentMatchAt($from.indexAfter(-1))); - let types = atEnd && deflt ? [ - { - type: deflt, - attrs: newAttributes - } - ] : void 0; - let can = canSplit(tr2.doc, tr2.mapping.map($from.pos), 1, types); - if (!types && !can && canSplit(tr2.doc, tr2.mapping.map($from.pos), 1, deflt ? [{ type: deflt }] : void 0)) { - can = true; - types = deflt ? [ - { - type: deflt, - attrs: newAttributes - } - ] : void 0; - } - if (dispatch) { - if (can) { - if (selection instanceof TextSelection) { - tr2.deleteSelection(); - } - tr2.split(tr2.mapping.map($from.pos), 1, types); - if (deflt && !atEnd && !$from.parentOffset && $from.parent.type !== deflt) { - const first2 = tr2.mapping.map($from.before()); - const $first = tr2.doc.resolve(first2); - if ($from.node(-1).canReplaceWith($first.index(), $first.index() + 1, deflt)) { - tr2.setNodeMarkup(tr2.mapping.map($from.before()), deflt); - } - } - } - if (keepMarks) { - ensureMarks(state, editor.extensionManager.splittableMarks); - } - tr2.scrollIntoView(); - } - return can; -}; -var splitListItem = (typeOrName, overrideAttrs = {}) => ({ tr: tr2, state, dispatch, editor }) => { - var _a; - const type = getNodeType(typeOrName, state.schema); - const { $from, $to } = state.selection; - const node = state.selection.node; - if (node && node.isBlock || $from.depth < 2 || !$from.sameParent($to)) { - return false; - } - const grandParent = $from.node(-1); - if (grandParent.type !== type) { - return false; - } - const extensionAttributes = editor.extensionManager.attributes; - if ($from.parent.content.size === 0 && $from.node(-1).childCount === $from.indexAfter(-1)) { - if ($from.depth === 2 || $from.node(-3).type !== type || $from.index(-2) !== $from.node(-2).childCount - 1) { - return false; - } - if (dispatch) { - let wrap2 = Fragment.empty; - const depthBefore = $from.index(-1) ? 1 : $from.index(-2) ? 2 : 3; - for (let d = $from.depth - depthBefore; d >= $from.depth - 3; d -= 1) { - wrap2 = Fragment.from($from.node(d).copy(wrap2)); - } - const depthAfter = ( - // eslint-disable-next-line no-nested-ternary - $from.indexAfter(-1) < $from.node(-2).childCount ? 1 : $from.indexAfter(-2) < $from.node(-3).childCount ? 2 : 3 - ); - const newNextTypeAttributes2 = { - ...getSplittedAttributes(extensionAttributes, $from.node().type.name, $from.node().attrs), - ...overrideAttrs - }; - const nextType2 = ((_a = type.contentMatch.defaultType) == null ? void 0 : _a.createAndFill(newNextTypeAttributes2)) || void 0; - wrap2 = wrap2.append(Fragment.from(type.createAndFill(null, nextType2) || void 0)); - const start = $from.before($from.depth - (depthBefore - 1)); - tr2.replace(start, $from.after(-depthAfter), new Slice(wrap2, 4 - depthBefore, 0)); - let sel = -1; - tr2.doc.nodesBetween(start, tr2.doc.content.size, (n, pos) => { - if (sel > -1) { - return false; - } - if (n.isTextblock && n.content.size === 0) { - sel = pos + 1; - } - }); - if (sel > -1) { - tr2.setSelection(TextSelection.near(tr2.doc.resolve(sel))); - } - tr2.scrollIntoView(); - } - return true; - } - const nextType = $to.pos === $from.end() ? grandParent.contentMatchAt(0).defaultType : null; - const newTypeAttributes = { - ...getSplittedAttributes(extensionAttributes, grandParent.type.name, grandParent.attrs), - ...overrideAttrs - }; - const newNextTypeAttributes = { - ...getSplittedAttributes(extensionAttributes, $from.node().type.name, $from.node().attrs), - ...overrideAttrs - }; - tr2.delete($from.pos, $to.pos); - const types = nextType ? [ - { type, attrs: newTypeAttributes }, - { type: nextType, attrs: newNextTypeAttributes } - ] : [{ type, attrs: newTypeAttributes }]; - if (!canSplit(tr2.doc, $from.pos, 2)) { - return false; - } - if (dispatch) { - const { selection, storedMarks } = state; - const { splittableMarks } = editor.extensionManager; - const marks = storedMarks || selection.$to.parentOffset && selection.$from.marks(); - tr2.split($from.pos, 2, types).scrollIntoView(); - if (!marks || !dispatch) { - return true; - } - const filteredMarks = marks.filter((mark) => splittableMarks.includes(mark.type.name)); - tr2.ensureMarks(filteredMarks); - } - return true; -}; -var joinListBackwards = (tr2, listType) => { - const list = findParentNode((node) => node.type === listType)(tr2.selection); - if (!list) { - return true; - } - const before = tr2.doc.resolve(Math.max(0, list.pos - 1)).before(list.depth); - if (before === void 0) { - return true; - } - const nodeBefore = tr2.doc.nodeAt(before); - const canJoinBackwards = list.node.type === (nodeBefore == null ? void 0 : nodeBefore.type) && canJoin(tr2.doc, list.pos); - if (!canJoinBackwards) { - return true; - } - tr2.join(list.pos); - return true; -}; -var joinListForwards = (tr2, listType) => { - const list = findParentNode((node) => node.type === listType)(tr2.selection); - if (!list) { - return true; - } - const after = tr2.doc.resolve(list.start).after(list.depth); - if (after === void 0) { - return true; - } - const nodeAfter = tr2.doc.nodeAt(after); - const canJoinForwards = list.node.type === (nodeAfter == null ? void 0 : nodeAfter.type) && canJoin(tr2.doc, after); - if (!canJoinForwards) { - return true; - } - tr2.join(after); - return true; -}; -var toggleList = (listTypeOrName, itemTypeOrName, keepMarks, attributes = {}) => ({ editor, tr: tr2, state, dispatch, chain, commands, can }) => { - const { extensions, splittableMarks } = editor.extensionManager; - const listType = getNodeType(listTypeOrName, state.schema); - const itemType = getNodeType(itemTypeOrName, state.schema); - const { selection, storedMarks } = state; - const { $from, $to } = selection; - const range = $from.blockRange($to); - const marks = storedMarks || selection.$to.parentOffset && selection.$from.marks(); - if (!range) { - return false; - } - const parentList = findParentNode((node) => isList(node.type.name, extensions))(selection); - if (range.depth >= 1 && parentList && range.depth - parentList.depth <= 1) { - if (parentList.node.type === listType) { - return commands.liftListItem(itemType); - } - if (isList(parentList.node.type.name, extensions) && listType.validContent(parentList.node.content) && dispatch) { - return chain().command(() => { - tr2.setNodeMarkup(parentList.pos, listType); - return true; - }).command(() => joinListBackwards(tr2, listType)).command(() => joinListForwards(tr2, listType)).run(); - } - } - if (!keepMarks || !marks || !dispatch) { - return chain().command(() => { - const canWrapInList = can().wrapInList(listType, attributes); - if (canWrapInList) { - return true; - } - return commands.clearNodes(); - }).wrapInList(listType, attributes).command(() => joinListBackwards(tr2, listType)).command(() => joinListForwards(tr2, listType)).run(); - } - return chain().command(() => { - const canWrapInList = can().wrapInList(listType, attributes); - const filteredMarks = marks.filter((mark) => splittableMarks.includes(mark.type.name)); - tr2.ensureMarks(filteredMarks); - if (canWrapInList) { - return true; - } - return commands.clearNodes(); - }).wrapInList(listType, attributes).command(() => joinListBackwards(tr2, listType)).command(() => joinListForwards(tr2, listType)).run(); -}; -var toggleMark = (typeOrName, attributes = {}, options = {}) => ({ state, commands }) => { - const { extendEmptyMarkRange = false } = options; - const type = getMarkType(typeOrName, state.schema); - const isActive2 = isMarkActive(state, type, attributes); - if (isActive2) { - return commands.unsetMark(type, { extendEmptyMarkRange }); - } - return commands.setMark(type, attributes); -}; -var toggleNode = (typeOrName, toggleTypeOrName, attributes = {}) => ({ state, commands }) => { - const type = getNodeType(typeOrName, state.schema); - const toggleType = getNodeType(toggleTypeOrName, state.schema); - const isActive2 = isNodeActive(state, type, attributes); - let attributesToCopy; - if (state.selection.$anchor.sameParent(state.selection.$head)) { - attributesToCopy = state.selection.$anchor.parent.attrs; - } - if (isActive2) { - return commands.setNode(toggleType, attributesToCopy); - } - return commands.setNode(type, { ...attributesToCopy, ...attributes }); -}; -var toggleWrap = (typeOrName, attributes = {}) => ({ state, commands }) => { - const type = getNodeType(typeOrName, state.schema); - const isActive2 = isNodeActive(state, type, attributes); - if (isActive2) { - return commands.lift(type); - } - return commands.wrapIn(type, attributes); -}; -var undoInputRule = () => ({ state, dispatch }) => { - const plugins = state.plugins; - for (let i = 0; i < plugins.length; i += 1) { - const plugin = plugins[i]; - let undoable; - if (plugin.spec.isInputRules && (undoable = plugin.getState(state))) { - if (dispatch) { - const tr2 = state.tr; - const toUndo = undoable.transform; - for (let j = toUndo.steps.length - 1; j >= 0; j -= 1) { - tr2.step(toUndo.steps[j].invert(toUndo.docs[j])); - } - if (undoable.text) { - const marks = tr2.doc.resolve(undoable.from).marks(); - tr2.replaceWith(undoable.from, undoable.to, state.schema.text(undoable.text, marks)); - } else { - tr2.delete(undoable.from, undoable.to); - } - } - return true; - } - } - return false; -}; -var unsetAllMarks = () => ({ tr: tr2, dispatch }) => { - const { selection } = tr2; - const { empty: empty2, ranges } = selection; - if (empty2) { - return true; - } - if (dispatch) { - ranges.forEach((range) => { - tr2.removeMark(range.$from.pos, range.$to.pos); - }); - } - return true; -}; -var unsetMark = (typeOrName, options = {}) => ({ tr: tr2, state, dispatch }) => { - var _a; - const { extendEmptyMarkRange = false } = options; - const { selection } = tr2; - const type = getMarkType(typeOrName, state.schema); - const { $from, empty: empty2, ranges } = selection; - if (!dispatch) { - return true; - } - if (empty2 && extendEmptyMarkRange) { - let { from: from2, to } = selection; - const attrs = (_a = $from.marks().find((mark) => mark.type === type)) == null ? void 0 : _a.attrs; - const range = getMarkRange($from, type, attrs); - if (range) { - from2 = range.from; - to = range.to; - } - tr2.removeMark(from2, to, type); - } else { - ranges.forEach((range) => { - tr2.removeMark(range.$from.pos, range.$to.pos, type); - }); - } - tr2.removeStoredMark(type); - return true; -}; -var unsetTextDirection = (position) => ({ tr: tr2, state, dispatch }) => { - const { selection } = state; - let from2; - let to; - if (typeof position === "number") { - from2 = position; - to = position; - } else if (position && "from" in position && "to" in position) { - from2 = position.from; - to = position.to; - } else { - from2 = selection.from; - to = selection.to; - } - if (dispatch) { - tr2.doc.nodesBetween(from2, to, (node, pos) => { - if (node.isText) { - return; - } - const newAttrs = { ...node.attrs }; - delete newAttrs.dir; - tr2.setNodeMarkup(pos, void 0, newAttrs); - }); - } - return true; -}; -var updateAttributes = (typeOrName, attributes = {}) => ({ tr: tr2, state, dispatch }) => { - let nodeType = null; - let markType = null; - const schemaType = getSchemaTypeNameByName( - typeof typeOrName === "string" ? typeOrName : typeOrName.name, - state.schema - ); - if (!schemaType) { - return false; - } - if (schemaType === "node") { - nodeType = getNodeType(typeOrName, state.schema); - } - if (schemaType === "mark") { - markType = getMarkType(typeOrName, state.schema); - } - let canUpdate = false; - tr2.selection.ranges.forEach((range) => { - const from2 = range.$from.pos; - const to = range.$to.pos; - let lastPos; - let lastNode; - let trimmedFrom; - let trimmedTo; - if (tr2.selection.empty) { - state.doc.nodesBetween(from2, to, (node, pos) => { - if (nodeType && nodeType === node.type) { - canUpdate = true; - trimmedFrom = Math.max(pos, from2); - trimmedTo = Math.min(pos + node.nodeSize, to); - lastPos = pos; - lastNode = node; - } - }); - } else { - state.doc.nodesBetween(from2, to, (node, pos) => { - if (pos < from2 && nodeType && nodeType === node.type) { - canUpdate = true; - trimmedFrom = Math.max(pos, from2); - trimmedTo = Math.min(pos + node.nodeSize, to); - lastPos = pos; - lastNode = node; - } - if (pos >= from2 && pos <= to) { - if (nodeType && nodeType === node.type) { - canUpdate = true; - if (dispatch) { - tr2.setNodeMarkup(pos, void 0, { - ...node.attrs, - ...attributes - }); - } - } - if (markType && node.marks.length) { - node.marks.forEach((mark) => { - if (markType === mark.type) { - canUpdate = true; - if (dispatch) { - const trimmedFrom2 = Math.max(pos, from2); - const trimmedTo2 = Math.min(pos + node.nodeSize, to); - tr2.addMark( - trimmedFrom2, - trimmedTo2, - markType.create({ - ...mark.attrs, - ...attributes - }) - ); - } - } - }); - } - } - }); - } - if (lastNode) { - if (lastPos !== void 0 && dispatch) { - tr2.setNodeMarkup(lastPos, void 0, { - ...lastNode.attrs, - ...attributes - }); - } - if (markType && lastNode.marks.length) { - lastNode.marks.forEach((mark) => { - if (markType === mark.type && dispatch) { - tr2.addMark( - trimmedFrom, - trimmedTo, - markType.create({ - ...mark.attrs, - ...attributes - }) - ); - } - }); - } - } - }); - return canUpdate; -}; -var wrapIn = (typeOrName, attributes = {}) => ({ state, dispatch }) => { - const type = getNodeType(typeOrName, state.schema); - return wrapIn$1(type, attributes)(state, dispatch); -}; -var wrapInList = (typeOrName, attributes = {}) => ({ state, dispatch }) => { - const type = getNodeType(typeOrName, state.schema); - return wrapInList$1(type, attributes)(state, dispatch); -}; -var EventEmitter = class { - constructor() { - this.callbacks = {}; - } - on(event, fn) { - if (!this.callbacks[event]) { - this.callbacks[event] = []; - } - this.callbacks[event].push(fn); - return this; - } - emit(event, ...args) { - const callbacks = this.callbacks[event]; - if (callbacks) { - callbacks.forEach((callback) => callback.apply(this, args)); - } - return this; - } - off(event, fn) { - const callbacks = this.callbacks[event]; - if (callbacks) { - if (fn) { - this.callbacks[event] = callbacks.filter((callback) => callback !== fn); - } else { - delete this.callbacks[event]; - } - } - return this; - } - once(event, fn) { - const onceFn = (...args) => { - this.off(event, onceFn); - fn.apply(this, args); - }; - return this.on(event, onceFn); - } - removeAllListeners() { - this.callbacks = {}; - } -}; -var InputRule = class { - constructor(config) { - var _a; - this.find = config.find; - this.handler = config.handler; - this.undoable = (_a = config.undoable) != null ? _a : true; - } -}; -var inputRuleMatcherHandler = (text, find2) => { - if (isRegExp(find2)) { - return find2.exec(text); - } - const inputRuleMatch = find2(text); - if (!inputRuleMatch) { - return null; - } - const result = [inputRuleMatch.text]; - result.index = inputRuleMatch.index; - result.input = text; - result.data = inputRuleMatch.data; - if (inputRuleMatch.replaceWith) { - if (!inputRuleMatch.text.includes(inputRuleMatch.replaceWith)) { - console.warn('[tiptap warn]: "inputRuleMatch.replaceWith" must be part of "inputRuleMatch.text".'); - } - result.push(inputRuleMatch.replaceWith); - } - return result; -}; -function run$2(config) { - var _a; - const { editor, from: from2, to, text, rules, plugin } = config; - const { view } = editor; - if (view.composing) { - return false; - } - const $from = view.state.doc.resolve(from2); - if ( - // check for code node - $from.parent.type.spec.code || // check for code mark - !!((_a = $from.nodeBefore || $from.nodeAfter) == null ? void 0 : _a.marks.find((mark) => mark.type.spec.code)) - ) { - return false; - } - let matched = false; - const textBefore = getTextContentFromNodes($from) + text; - rules.forEach((rule) => { - if (matched) { - return; - } - const match = inputRuleMatcherHandler(textBefore, rule.find); - if (!match) { - return; - } - const tr2 = view.state.tr; - const state = createChainableState({ - state: view.state, - transaction: tr2 - }); - const range = { - from: from2 - (match[0].length - text.length), - to - }; - const { commands, chain, can } = new CommandManager({ - editor, - state - }); - const handler = rule.handler({ - state, - range, - match, - commands, - chain, - can - }); - if (handler === null || !tr2.steps.length) { - return; - } - if (rule.undoable) { - tr2.setMeta(plugin, { - transform: tr2, - from: from2, - to, - text - }); - } - view.dispatch(tr2); - matched = true; - }); - return matched; -} -function inputRulesPlugin(props) { - const { editor, rules } = props; - const plugin = new Plugin({ - state: { - init() { - return null; - }, - apply(tr2, prev, state) { - const stored = tr2.getMeta(plugin); - if (stored) { - return stored; - } - const simulatedInputMeta = tr2.getMeta("applyInputRules"); - const isSimulatedInput = !!simulatedInputMeta; - if (isSimulatedInput) { - setTimeout(() => { - let { text } = simulatedInputMeta; - if (typeof text === "string") { - text = text; - } else { - text = getHTMLFromFragment(Fragment.from(text), state.schema); - } - const { from: from2 } = simulatedInputMeta; - const to = from2 + text.length; - run$2({ - editor, - from: from2, - to, - text, - rules, - plugin - }); - }); - } - return tr2.selectionSet || tr2.docChanged ? null : prev; - } - }, - props: { - handleTextInput(view, from2, to, text) { - return run$2({ - editor, - from: from2, - to, - text, - rules, - plugin - }); - }, - handleDOMEvents: { - compositionend: (view) => { - setTimeout(() => { - const { $cursor } = view.state.selection; - if ($cursor) { - run$2({ - editor, - from: $cursor.pos, - to: $cursor.pos, - text: "", - rules, - plugin - }); - } - }); - return false; - } - }, - // add support for input rules to trigger on enter - // this is useful for example for code blocks - handleKeyDown(view, event) { - if (event.key !== "Enter") { - return false; - } - const { $cursor } = view.state.selection; - if ($cursor) { - return run$2({ - editor, - from: $cursor.pos, - to: $cursor.pos, - text: "\n", - rules, - plugin - }); - } - return false; - } - }, - // @ts-ignore - isInputRules: true - }); - return plugin; -} -function getType(value) { - return Object.prototype.toString.call(value).slice(8, -1); -} -function isPlainObject(value) { - if (getType(value) !== "Object") { - return false; - } - return value.constructor === Object && Object.getPrototypeOf(value) === Object.prototype; -} -function mergeDeep(target, source) { - const output = { ...target }; - if (isPlainObject(target) && isPlainObject(source)) { - Object.keys(source).forEach((key) => { - if (isPlainObject(source[key]) && isPlainObject(target[key])) { - output[key] = mergeDeep(target[key], source[key]); - } else { - output[key] = source[key]; - } - }); - } - return output; -} -var Extendable = class { - constructor(config = {}) { - this.type = "extendable"; - this.parent = null; - this.child = null; - this.name = ""; - this.config = { - name: this.name - }; - this.config = { - ...this.config, - ...config - }; - this.name = this.config.name; - } - get options() { - return { - ...callOrReturn( - getExtensionField(this, "addOptions", { - name: this.name - }) - ) || {} - }; - } - get storage() { - return { - ...callOrReturn( - getExtensionField(this, "addStorage", { - name: this.name, - options: this.options - }) - ) || {} - }; - } - configure(options = {}) { - const extension = this.extend({ - ...this.config, - addOptions: () => { - return mergeDeep(this.options, options); - } - }); - extension.name = this.name; - extension.parent = this.parent; - return extension; - } - extend(extendedConfig = {}) { - const extension = new this.constructor({ ...this.config, ...extendedConfig }); - extension.parent = this; - this.child = extension; - extension.name = "name" in extendedConfig ? extendedConfig.name : extension.parent.name; - return extension; - } -}; -var Mark2 = class _Mark extends Extendable { - constructor() { - super(...arguments); - this.type = "mark"; - } - /** - * Create a new Mark instance - * @param config - Mark configuration object or a function that returns a configuration object - */ - static create(config = {}) { - const resolvedConfig = typeof config === "function" ? config() : config; - return new _Mark(resolvedConfig); - } - static handleExit({ editor, mark }) { - const { tr: tr2 } = editor.state; - const currentPos = editor.state.selection.$from; - const isAtEnd = currentPos.pos === currentPos.end(); - if (isAtEnd) { - const currentMarks = currentPos.marks(); - const isInMark = !!currentMarks.find((m) => (m == null ? void 0 : m.type.name) === mark.name); - if (!isInMark) { - return false; - } - const removeMark2 = currentMarks.find((m) => (m == null ? void 0 : m.type.name) === mark.name); - if (removeMark2) { - tr2.removeStoredMark(removeMark2); - } - tr2.insertText(" ", currentPos.pos); - editor.view.dispatch(tr2); - return true; - } - return false; - } - configure(options) { - return super.configure(options); - } - extend(extendedConfig) { - const resolvedConfig = typeof extendedConfig === "function" ? extendedConfig() : extendedConfig; - return super.extend(resolvedConfig); - } -}; -function isNumber(value) { - return typeof value === "number"; -} -var PasteRule = class { - constructor(config) { - this.find = config.find; - this.handler = config.handler; - } -}; -var pasteRuleMatcherHandler = (text, find2, event) => { - if (isRegExp(find2)) { - return [...text.matchAll(find2)]; - } - const matches2 = find2(text, event); - if (!matches2) { - return []; - } - return matches2.map((pasteRuleMatch) => { - const result = [pasteRuleMatch.text]; - result.index = pasteRuleMatch.index; - result.input = text; - result.data = pasteRuleMatch.data; - if (pasteRuleMatch.replaceWith) { - if (!pasteRuleMatch.text.includes(pasteRuleMatch.replaceWith)) { - console.warn('[tiptap warn]: "pasteRuleMatch.replaceWith" must be part of "pasteRuleMatch.text".'); - } - result.push(pasteRuleMatch.replaceWith); - } - return result; - }); -}; -function run2(config) { - const { editor, state, from: from2, to, rule, pasteEvent, dropEvent } = config; - const { commands, chain, can } = new CommandManager({ - editor, - state - }); - const handlers2 = []; - state.doc.nodesBetween(from2, to, (node, pos) => { - var _a, _b, _c, _d, _e; - if (((_b = (_a = node.type) == null ? void 0 : _a.spec) == null ? void 0 : _b.code) || !(node.isText || node.isTextblock || node.isInline)) { - return; - } - const contentSize = (_e = (_d = (_c = node.content) == null ? void 0 : _c.size) != null ? _d : node.nodeSize) != null ? _e : 0; - const resolvedFrom = Math.max(from2, pos); - const resolvedTo = Math.min(to, pos + contentSize); - if (resolvedFrom >= resolvedTo) { - return; - } - const textToMatch = node.isText ? node.text || "" : node.textBetween(resolvedFrom - pos, resolvedTo - pos, void 0, ""); - const matches2 = pasteRuleMatcherHandler(textToMatch, rule.find, pasteEvent); - matches2.forEach((match) => { - if (match.index === void 0) { - return; - } - const start = resolvedFrom + match.index + 1; - const end = start + match[0].length; - const range = { - from: state.tr.mapping.map(start), - to: state.tr.mapping.map(end) - }; - const handler = rule.handler({ - state, - range, - match, - commands, - chain, - can, - pasteEvent, - dropEvent - }); - handlers2.push(handler); - }); - }); - const success = handlers2.every((handler) => handler !== null); - return success; -} -var tiptapDragFromOtherEditor = null; -var createClipboardPasteEvent = (text) => { - var _a; - const event = new ClipboardEvent("paste", { - clipboardData: new DataTransfer() - }); - (_a = event.clipboardData) == null ? void 0 : _a.setData("text/html", text); - return event; -}; -function pasteRulesPlugin(props) { - const { editor, rules } = props; - let dragSourceElement = null; - let isPastedFromProseMirror = false; - let isDroppedFromProseMirror = false; - let pasteEvent = typeof ClipboardEvent !== "undefined" ? new ClipboardEvent("paste") : null; - let dropEvent; - try { - dropEvent = typeof DragEvent !== "undefined" ? new DragEvent("drop") : null; - } catch { - dropEvent = null; - } - const processEvent = ({ - state, - from: from2, - to, - rule, - pasteEvt - }) => { - const tr2 = state.tr; - const chainableState = createChainableState({ - state, - transaction: tr2 - }); - const handler = run2({ - editor, - state: chainableState, - from: Math.max(from2 - 1, 0), - to: to.b - 1, - rule, - pasteEvent: pasteEvt, - dropEvent - }); - if (!handler || !tr2.steps.length) { - return; - } - try { - dropEvent = typeof DragEvent !== "undefined" ? new DragEvent("drop") : null; - } catch { - dropEvent = null; - } - pasteEvent = typeof ClipboardEvent !== "undefined" ? new ClipboardEvent("paste") : null; - return tr2; - }; - const plugins = rules.map((rule) => { - return new Plugin({ - // we register a global drag handler to track the current drag source element - view(view) { - const handleDragstart = (event) => { - var _a; - dragSourceElement = ((_a = view.dom.parentElement) == null ? void 0 : _a.contains(event.target)) ? view.dom.parentElement : null; - if (dragSourceElement) { - tiptapDragFromOtherEditor = editor; - } - }; - const handleDragend = () => { - if (tiptapDragFromOtherEditor) { - tiptapDragFromOtherEditor = null; - } - }; - window.addEventListener("dragstart", handleDragstart); - window.addEventListener("dragend", handleDragend); - return { - destroy() { - window.removeEventListener("dragstart", handleDragstart); - window.removeEventListener("dragend", handleDragend); - } - }; - }, - props: { - handleDOMEvents: { - drop: (view, event) => { - isDroppedFromProseMirror = dragSourceElement === view.dom.parentElement; - dropEvent = event; - if (!isDroppedFromProseMirror) { - const dragFromOtherEditor = tiptapDragFromOtherEditor; - if (dragFromOtherEditor == null ? void 0 : dragFromOtherEditor.isEditable) { - setTimeout(() => { - const selection = dragFromOtherEditor.state.selection; - if (selection) { - dragFromOtherEditor.commands.deleteRange({ from: selection.from, to: selection.to }); - } - }, 10); - } - } - return false; - }, - paste: (_view, event) => { - var _a; - const html = (_a = event.clipboardData) == null ? void 0 : _a.getData("text/html"); - pasteEvent = event; - isPastedFromProseMirror = !!(html == null ? void 0 : html.includes("data-pm-slice")); - return false; - } - } - }, - appendTransaction: (transactions, oldState, state) => { - const transaction = transactions[0]; - const isPaste = transaction.getMeta("uiEvent") === "paste" && !isPastedFromProseMirror; - const isDrop = transaction.getMeta("uiEvent") === "drop" && !isDroppedFromProseMirror; - const simulatedPasteMeta = transaction.getMeta("applyPasteRules"); - const isSimulatedPaste = !!simulatedPasteMeta; - if (!isPaste && !isDrop && !isSimulatedPaste) { - return; - } - if (isSimulatedPaste) { - let { text } = simulatedPasteMeta; - if (typeof text === "string") { - text = text; - } else { - text = getHTMLFromFragment(Fragment.from(text), state.schema); - } - const { from: from22 } = simulatedPasteMeta; - const to2 = from22 + text.length; - const pasteEvt = createClipboardPasteEvent(text); - return processEvent({ - rule, - state, - from: from22, - to: { b: to2 }, - pasteEvt - }); - } - const from2 = oldState.doc.content.findDiffStart(state.doc.content); - const to = oldState.doc.content.findDiffEnd(state.doc.content); - if (!isNumber(from2) || !to || from2 === to.b) { - return; - } - return processEvent({ - rule, - state, - from: from2, - to, - pasteEvt: pasteEvent - }); - } - }); - }); - return plugins; -} -var ExtensionManager = class { - constructor(extensions, editor) { - this.splittableMarks = []; - this.editor = editor; - this.baseExtensions = extensions; - this.extensions = resolveExtensions(extensions); - this.schema = getSchemaByResolvedExtensions(this.extensions, editor); - this.setupExtensions(); - } - /** - * Get all commands from the extensions. - * @returns An object with all commands where the key is the command name and the value is the command function - */ - get commands() { - return this.extensions.reduce((commands, extension) => { - const context = { - name: extension.name, - options: extension.options, - storage: this.editor.extensionStorage[extension.name], - editor: this.editor, - type: getSchemaTypeByName(extension.name, this.schema) - }; - const addCommands = getExtensionField(extension, "addCommands", context); - if (!addCommands) { - return commands; - } - return { - ...commands, - ...addCommands() - }; - }, {}); - } - /** - * Get all registered Prosemirror plugins from the extensions. - * @returns An array of Prosemirror plugins - */ - get plugins() { - const { editor } = this; - const extensions = sortExtensions([...this.extensions].reverse()); - const allPlugins = extensions.flatMap((extension) => { - const context = { - name: extension.name, - options: extension.options, - storage: this.editor.extensionStorage[extension.name], - editor, - type: getSchemaTypeByName(extension.name, this.schema) - }; - const plugins = []; - const addKeyboardShortcuts = getExtensionField( - extension, - "addKeyboardShortcuts", - context - ); - let defaultBindings = {}; - if (extension.type === "mark" && getExtensionField(extension, "exitable", context)) { - defaultBindings.ArrowRight = () => Mark2.handleExit({ editor, mark: extension }); - } - if (addKeyboardShortcuts) { - const bindings = Object.fromEntries( - Object.entries(addKeyboardShortcuts()).map(([shortcut, method]) => { - return [shortcut, () => method({ editor })]; - }) - ); - defaultBindings = { ...defaultBindings, ...bindings }; - } - const keyMapPlugin = keymap(defaultBindings); - plugins.push(keyMapPlugin); - const addInputRules = getExtensionField(extension, "addInputRules", context); - if (isExtensionRulesEnabled(extension, editor.options.enableInputRules) && addInputRules) { - const rules = addInputRules(); - if (rules && rules.length) { - const inputResult = inputRulesPlugin({ - editor, - rules - }); - const inputPlugins = Array.isArray(inputResult) ? inputResult : [inputResult]; - plugins.push(...inputPlugins); - } - } - const addPasteRules = getExtensionField(extension, "addPasteRules", context); - if (isExtensionRulesEnabled(extension, editor.options.enablePasteRules) && addPasteRules) { - const rules = addPasteRules(); - if (rules && rules.length) { - const pasteRules = pasteRulesPlugin({ editor, rules }); - plugins.push(...pasteRules); - } - } - const addProseMirrorPlugins = getExtensionField( - extension, - "addProseMirrorPlugins", - context - ); - if (addProseMirrorPlugins) { - const proseMirrorPlugins = addProseMirrorPlugins(); - plugins.push(...proseMirrorPlugins); - } - return plugins; - }); - return allPlugins; - } - /** - * Get all attributes from the extensions. - * @returns An array of attributes - */ - get attributes() { - return getAttributesFromExtensions(this.extensions); - } - /** - * Get all node views from the extensions. - * @returns An object with all node views where the key is the node name and the value is the node view function - */ - get nodeViews() { - const { editor } = this; - const { nodeExtensions } = splitExtensions(this.extensions); - return Object.fromEntries( - nodeExtensions.filter((extension) => !!getExtensionField(extension, "addNodeView")).map((extension) => { - const extensionAttributes = this.attributes.filter((attribute) => attribute.type === extension.name); - const context = { - name: extension.name, - options: extension.options, - storage: this.editor.extensionStorage[extension.name], - editor, - type: getNodeType(extension.name, this.schema) - }; - const addNodeView = getExtensionField(extension, "addNodeView", context); - if (!addNodeView) { - return []; - } - const nodeViewResult = addNodeView(); - if (!nodeViewResult) { - return []; - } - const nodeview = (node, view, getPos, decorations, innerDecorations) => { - const HTMLAttributes = getRenderedAttributes(node, extensionAttributes); - return nodeViewResult({ - // pass-through - node, - view, - getPos, - decorations, - innerDecorations, - // tiptap-specific - editor, - extension, - HTMLAttributes - }); - }; - return [extension.name, nodeview]; - }) - ); - } - /** - * Get the composed dispatchTransaction function from all extensions. - * @param baseDispatch The base dispatch function (e.g. from the editor or user props) - * @returns A composed dispatch function - */ - dispatchTransaction(baseDispatch) { - const { editor } = this; - const extensions = sortExtensions([...this.extensions].reverse()); - return extensions.reduceRight((next, extension) => { - const context = { - name: extension.name, - options: extension.options, - storage: this.editor.extensionStorage[extension.name], - editor, - type: getSchemaTypeByName(extension.name, this.schema) - }; - const dispatchTransaction = getExtensionField( - extension, - "dispatchTransaction", - context - ); - if (!dispatchTransaction) { - return next; - } - return (transaction) => { - dispatchTransaction.call(context, { transaction, next }); - }; - }, baseDispatch); - } - /** - * Get the composed transformPastedHTML function from all extensions. - * @param baseTransform The base transform function (e.g. from the editor props) - * @returns A composed transform function that chains all extension transforms - */ - transformPastedHTML(baseTransform) { - const { editor } = this; - const extensions = sortExtensions([...this.extensions]); - return extensions.reduce( - (transform, extension) => { - const context = { - name: extension.name, - options: extension.options, - storage: this.editor.extensionStorage[extension.name], - editor, - type: getSchemaTypeByName(extension.name, this.schema) - }; - const extensionTransform = getExtensionField( - extension, - "transformPastedHTML", - context - ); - if (!extensionTransform) { - return transform; - } - return (html, view) => { - const transformedHtml = transform(html, view); - return extensionTransform.call(context, transformedHtml); - }; - }, - baseTransform || ((html) => html) - ); - } - get markViews() { - const { editor } = this; - const { markExtensions } = splitExtensions(this.extensions); - return Object.fromEntries( - markExtensions.filter((extension) => !!getExtensionField(extension, "addMarkView")).map((extension) => { - const extensionAttributes = this.attributes.filter((attribute) => attribute.type === extension.name); - const context = { - name: extension.name, - options: extension.options, - storage: this.editor.extensionStorage[extension.name], - editor, - type: getMarkType(extension.name, this.schema) - }; - const addMarkView = getExtensionField(extension, "addMarkView", context); - if (!addMarkView) { - return []; - } - const markView = (mark, view, inline) => { - const HTMLAttributes = getRenderedAttributes(mark, extensionAttributes); - return addMarkView()({ - // pass-through - mark, - view, - inline, - // tiptap-specific - editor, - extension, - HTMLAttributes, - updateAttributes: (attrs) => { - updateMarkViewAttributes(mark, editor, attrs); - } - }); - }; - return [extension.name, markView]; - }) - ); - } - /** - * Go through all extensions, create extension storages & setup marks - * & bind editor event listener. - */ - setupExtensions() { - const extensions = this.extensions; - this.editor.extensionStorage = Object.fromEntries( - extensions.map((extension) => [extension.name, extension.storage]) - ); - extensions.forEach((extension) => { - var _a; - const context = { - name: extension.name, - options: extension.options, - storage: this.editor.extensionStorage[extension.name], - editor: this.editor, - type: getSchemaTypeByName(extension.name, this.schema) - }; - if (extension.type === "mark") { - const keepOnSplit = (_a = callOrReturn(getExtensionField(extension, "keepOnSplit", context))) != null ? _a : true; - if (keepOnSplit) { - this.splittableMarks.push(extension.name); - } - } - const onBeforeCreate = getExtensionField(extension, "onBeforeCreate", context); - const onCreate = getExtensionField(extension, "onCreate", context); - const onUpdate = getExtensionField(extension, "onUpdate", context); - const onSelectionUpdate = getExtensionField( - extension, - "onSelectionUpdate", - context - ); - const onTransaction = getExtensionField(extension, "onTransaction", context); - const onFocus = getExtensionField(extension, "onFocus", context); - const onBlur = getExtensionField(extension, "onBlur", context); - const onDestroy = getExtensionField(extension, "onDestroy", context); - if (onBeforeCreate) { - this.editor.on("beforeCreate", onBeforeCreate); - } - if (onCreate) { - this.editor.on("create", onCreate); - } - if (onUpdate) { - this.editor.on("update", onUpdate); - } - if (onSelectionUpdate) { - this.editor.on("selectionUpdate", onSelectionUpdate); - } - if (onTransaction) { - this.editor.on("transaction", onTransaction); - } - if (onFocus) { - this.editor.on("focus", onFocus); - } - if (onBlur) { - this.editor.on("blur", onBlur); - } - if (onDestroy) { - this.editor.on("destroy", onDestroy); - } - }); - } -}; -ExtensionManager.resolve = resolveExtensions; -ExtensionManager.sort = sortExtensions; -ExtensionManager.flatten = flattenExtensions; -var extensions_exports = {}; -__export$1(extensions_exports, { - ClipboardTextSerializer: () => ClipboardTextSerializer, - Commands: () => Commands, - Delete: () => Delete, - Drop: () => Drop, - Editable: () => Editable, - FocusEvents: () => FocusEvents, - Keymap: () => Keymap, - Paste: () => Paste, - Tabindex: () => Tabindex, - TextDirection: () => TextDirection, - focusEventsPluginKey: () => focusEventsPluginKey -}); -var Extension = class _Extension extends Extendable { - constructor() { - super(...arguments); - this.type = "extension"; - } - /** - * Create a new Extension instance - * @param config - Extension configuration object or a function that returns a configuration object - */ - static create(config = {}) { - const resolvedConfig = typeof config === "function" ? config() : config; - return new _Extension(resolvedConfig); - } - configure(options) { - return super.configure(options); - } - extend(extendedConfig) { - const resolvedConfig = typeof extendedConfig === "function" ? extendedConfig() : extendedConfig; - return super.extend(resolvedConfig); - } -}; -var ClipboardTextSerializer = Extension.create({ - name: "clipboardTextSerializer", - addOptions() { - return { - blockSeparator: void 0 - }; - }, - addProseMirrorPlugins() { - return [ - new Plugin({ - key: new PluginKey("clipboardTextSerializer"), - props: { - clipboardTextSerializer: () => { - const { editor } = this; - const { state, schema } = editor; - const { doc: doc2, selection } = state; - const { ranges } = selection; - const from2 = Math.min(...ranges.map((range2) => range2.$from.pos)); - const to = Math.max(...ranges.map((range2) => range2.$to.pos)); - const textSerializers = getTextSerializersFromSchema(schema); - const range = { from: from2, to }; - return getTextBetween(doc2, range, { - ...this.options.blockSeparator !== void 0 ? { blockSeparator: this.options.blockSeparator } : {}, - textSerializers - }); - } - } - }) - ]; - } -}); -var Commands = Extension.create({ - name: "commands", - addCommands() { - return { - ...commands_exports - }; - } -}); -var Delete = Extension.create({ - name: "delete", - onUpdate({ transaction, appendedTransactions }) { - var _a, _b, _c; - const callback = () => { - var _a2, _b2, _c2, _d; - if ((_d = (_c2 = (_b2 = (_a2 = this.editor.options.coreExtensionOptions) == null ? void 0 : _a2.delete) == null ? void 0 : _b2.filterTransaction) == null ? void 0 : _c2.call(_b2, transaction)) != null ? _d : transaction.getMeta("y-sync$")) { - return; - } - const nextTransaction = combineTransactionSteps(transaction.before, [transaction, ...appendedTransactions]); - const changes = getChangedRanges(nextTransaction); - changes.forEach((change) => { - if (nextTransaction.mapping.mapResult(change.oldRange.from).deletedAfter && nextTransaction.mapping.mapResult(change.oldRange.to).deletedBefore) { - nextTransaction.before.nodesBetween(change.oldRange.from, change.oldRange.to, (node, from2) => { - const to = from2 + node.nodeSize - 2; - const isFullyWithinRange = change.oldRange.from <= from2 && to <= change.oldRange.to; - this.editor.emit("delete", { - type: "node", - node, - from: from2, - to, - newFrom: nextTransaction.mapping.map(from2), - newTo: nextTransaction.mapping.map(to), - deletedRange: change.oldRange, - newRange: change.newRange, - partial: !isFullyWithinRange, - editor: this.editor, - transaction, - combinedTransform: nextTransaction - }); - }); - } - }); - const mapping = nextTransaction.mapping; - nextTransaction.steps.forEach((step, index) => { - var _a3, _b3; - if (step instanceof RemoveMarkStep) { - const newStart = mapping.slice(index).map(step.from, -1); - const newEnd = mapping.slice(index).map(step.to); - const oldStart = mapping.invert().map(newStart, -1); - const oldEnd = mapping.invert().map(newEnd); - const foundBeforeMark = newStart > 0 ? (_a3 = nextTransaction.doc.nodeAt(newStart - 1)) == null ? void 0 : _a3.marks.some((mark) => mark.eq(step.mark)) : false; - const foundAfterMark = (_b3 = nextTransaction.doc.nodeAt(newEnd)) == null ? void 0 : _b3.marks.some((mark) => mark.eq(step.mark)); - this.editor.emit("delete", { - type: "mark", - mark: step.mark, - from: step.from, - to: step.to, - deletedRange: { - from: oldStart, - to: oldEnd - }, - newRange: { - from: newStart, - to: newEnd - }, - partial: Boolean(foundAfterMark || foundBeforeMark), - editor: this.editor, - transaction, - combinedTransform: nextTransaction - }); - } - }); - }; - if ((_c = (_b = (_a = this.editor.options.coreExtensionOptions) == null ? void 0 : _a.delete) == null ? void 0 : _b.async) != null ? _c : true) { - setTimeout(callback, 0); - } else { - callback(); - } - } -}); -var Drop = Extension.create({ - name: "drop", - addProseMirrorPlugins() { - return [ - new Plugin({ - key: new PluginKey("tiptapDrop"), - props: { - handleDrop: (_, e, slice2, moved) => { - this.editor.emit("drop", { - editor: this.editor, - event: e, - slice: slice2, - moved - }); - } - } - }) - ]; - } -}); -var Editable = Extension.create({ - name: "editable", - addProseMirrorPlugins() { - return [ - new Plugin({ - key: new PluginKey("editable"), - props: { - editable: () => this.editor.options.editable - } - }) - ]; - } -}); -var focusEventsPluginKey = new PluginKey("focusEvents"); -var FocusEvents = Extension.create({ - name: "focusEvents", - addProseMirrorPlugins() { - const { editor } = this; - return [ - new Plugin({ - key: focusEventsPluginKey, - props: { - handleDOMEvents: { - focus: (view, event) => { - editor.isFocused = true; - const transaction = editor.state.tr.setMeta("focus", { event }).setMeta("addToHistory", false); - view.dispatch(transaction); - return false; - }, - blur: (view, event) => { - editor.isFocused = false; - const transaction = editor.state.tr.setMeta("blur", { event }).setMeta("addToHistory", false); - view.dispatch(transaction); - return false; - } - } - } - }) - ]; - } -}); -var Keymap = Extension.create({ - name: "keymap", - addKeyboardShortcuts() { - const handleBackspace2 = () => this.editor.commands.first(({ commands }) => [ - () => commands.undoInputRule(), - // maybe convert first text block node to default node - () => commands.command(({ tr: tr2 }) => { - const { selection, doc: doc2 } = tr2; - const { empty: empty2, $anchor } = selection; - const { pos, parent } = $anchor; - const $parentPos = $anchor.parent.isTextblock && pos > 0 ? tr2.doc.resolve(pos - 1) : $anchor; - const parentIsIsolating = $parentPos.parent.type.spec.isolating; - const parentPos = $anchor.pos - $anchor.parentOffset; - const isAtStart = parentIsIsolating && $parentPos.parent.childCount === 1 ? parentPos === $anchor.pos : Selection.atStart(doc2).from === pos; - if (!empty2 || !parent.type.isTextblock || parent.textContent.length || !isAtStart || isAtStart && $anchor.parent.type.name === "paragraph") { - return false; - } - return commands.clearNodes(); - }), - () => commands.deleteSelection(), - () => commands.joinBackward(), - () => commands.selectNodeBackward() - ]); - const handleDelete2 = () => this.editor.commands.first(({ commands }) => [ - () => commands.deleteSelection(), - () => commands.deleteCurrentNode(), - () => commands.joinForward(), - () => commands.selectNodeForward() - ]); - const handleEnter = () => this.editor.commands.first(({ commands }) => [ - () => commands.newlineInCode(), - () => commands.createParagraphNear(), - () => commands.liftEmptyBlock(), - () => commands.splitBlock() - ]); - const baseKeymap = { - Enter: handleEnter, - "Mod-Enter": () => this.editor.commands.exitCode(), - Backspace: handleBackspace2, - "Mod-Backspace": handleBackspace2, - "Shift-Backspace": handleBackspace2, - Delete: handleDelete2, - "Mod-Delete": handleDelete2, - "Mod-a": () => this.editor.commands.selectAll() - }; - const pcKeymap = { - ...baseKeymap - }; - const macKeymap = { - ...baseKeymap, - "Ctrl-h": handleBackspace2, - "Alt-Backspace": handleBackspace2, - "Ctrl-d": handleDelete2, - "Ctrl-Alt-Backspace": handleDelete2, - "Alt-Delete": handleDelete2, - "Alt-d": handleDelete2, - "Ctrl-a": () => this.editor.commands.selectTextblockStart(), - "Ctrl-e": () => this.editor.commands.selectTextblockEnd() - }; - if (isiOS() || isMacOS()) { - return macKeymap; - } - return pcKeymap; - }, - addProseMirrorPlugins() { - return [ - // With this plugin we check if the whole document was selected and deleted. - // In this case we will additionally call `clearNodes()` to convert e.g. a heading - // to a paragraph if necessary. - // This is an alternative to ProseMirror's `AllSelection`, which doesn’t work well - // with many other commands. - new Plugin({ - key: new PluginKey("clearDocument"), - appendTransaction: (transactions, oldState, newState) => { - if (transactions.some((tr22) => tr22.getMeta("composition"))) { - return; - } - const docChanges = transactions.some((transaction) => transaction.docChanged) && !oldState.doc.eq(newState.doc); - const ignoreTr = transactions.some((transaction) => transaction.getMeta("preventClearDocument")); - if (!docChanges || ignoreTr) { - return; - } - const { empty: empty2, from: from2, to } = oldState.selection; - const allFrom = Selection.atStart(oldState.doc).from; - const allEnd = Selection.atEnd(oldState.doc).to; - const allWasSelected = from2 === allFrom && to === allEnd; - if (empty2 || !allWasSelected) { - return; - } - const isEmpty = isNodeEmpty(newState.doc); - if (!isEmpty) { - return; - } - const tr2 = newState.tr; - const state = createChainableState({ - state: newState, - transaction: tr2 - }); - const { commands } = new CommandManager({ - editor: this.editor, - state - }); - commands.clearNodes(); - if (!tr2.steps.length) { - return; - } - return tr2; - } - }) - ]; - } -}); -var Paste = Extension.create({ - name: "paste", - addProseMirrorPlugins() { - return [ - new Plugin({ - key: new PluginKey("tiptapPaste"), - props: { - handlePaste: (_view, e, slice2) => { - this.editor.emit("paste", { - editor: this.editor, - event: e, - slice: slice2 - }); - } - } - }) - ]; - } -}); -var Tabindex = Extension.create({ - name: "tabindex", - addProseMirrorPlugins() { - return [ - new Plugin({ - key: new PluginKey("tabindex"), - props: { - attributes: () => this.editor.isEditable ? { tabindex: "0" } : {} - } - }) - ]; - } -}); -var TextDirection = Extension.create({ - name: "textDirection", - addOptions() { - return { - direction: void 0 - }; - }, - addGlobalAttributes() { - if (!this.options.direction) { - return []; - } - const { nodeExtensions } = splitExtensions(this.extensions); - return [ - { - types: nodeExtensions.filter((extension) => extension.name !== "text").map((extension) => extension.name), - attributes: { - dir: { - default: this.options.direction, - parseHTML: (element) => { - const dir = element.getAttribute("dir"); - if (dir && (dir === "ltr" || dir === "rtl" || dir === "auto")) { - return dir; - } - return this.options.direction; - }, - renderHTML: (attributes) => { - if (!attributes.dir) { - return {}; - } - return { - dir: attributes.dir - }; - } - } - } - } - ]; - }, - addProseMirrorPlugins() { - return [ - new Plugin({ - key: new PluginKey("textDirection"), - props: { - attributes: () => { - const direction = this.options.direction; - if (!direction) { - return {}; - } - return { - dir: direction - }; - } - } - }) - ]; - } -}); -var NodePos = class _NodePos { - constructor(pos, editor, isBlock = false, node = null) { - this.currentNode = null; - this.actualDepth = null; - this.isBlock = isBlock; - this.resolvedPos = pos; - this.editor = editor; - this.currentNode = node; - } - get name() { - return this.node.type.name; - } - get node() { - return this.currentNode || this.resolvedPos.node(); - } - get element() { - return this.editor.view.domAtPos(this.pos).node; - } - get depth() { - var _a; - return (_a = this.actualDepth) != null ? _a : this.resolvedPos.depth; - } - get pos() { - return this.resolvedPos.pos; - } - get content() { - return this.node.content; - } - set content(content) { - let from2 = this.from; - let to = this.to; - if (this.isBlock) { - if (this.content.size === 0) { - console.error(`You can’t set content on a block node. Tried to set content on ${this.name} at ${this.pos}`); - return; - } - from2 = this.from + 1; - to = this.to - 1; - } - this.editor.commands.insertContentAt({ from: from2, to }, content); - } - get attributes() { - return this.node.attrs; - } - get textContent() { - return this.node.textContent; - } - get size() { - return this.node.nodeSize; - } - get from() { - if (this.isBlock) { - return this.pos; - } - return this.resolvedPos.start(this.resolvedPos.depth); - } - get range() { - return { - from: this.from, - to: this.to - }; - } - get to() { - if (this.isBlock) { - return this.pos + this.size; - } - return this.resolvedPos.end(this.resolvedPos.depth) + (this.node.isText ? 0 : 1); - } - get parent() { - if (this.depth === 0) { - return null; - } - const parentPos = this.resolvedPos.start(this.resolvedPos.depth - 1); - const $pos = this.resolvedPos.doc.resolve(parentPos); - return new _NodePos($pos, this.editor); - } - get before() { - let $pos = this.resolvedPos.doc.resolve(this.from - (this.isBlock ? 1 : 2)); - if ($pos.depth !== this.depth) { - $pos = this.resolvedPos.doc.resolve(this.from - 3); - } - return new _NodePos($pos, this.editor); - } - get after() { - let $pos = this.resolvedPos.doc.resolve(this.to + (this.isBlock ? 2 : 1)); - if ($pos.depth !== this.depth) { - $pos = this.resolvedPos.doc.resolve(this.to + 3); - } - return new _NodePos($pos, this.editor); - } - get children() { - const children = []; - this.node.content.forEach((node, offset) => { - const isBlock = node.isBlock && !node.isTextblock; - const isNonTextAtom = node.isAtom && !node.isText; - const isInline2 = node.isInline; - const targetPos = this.pos + offset + (isNonTextAtom ? 0 : 1); - if (targetPos < 0 || targetPos > this.resolvedPos.doc.nodeSize - 2) { - return; - } - const $pos = this.resolvedPos.doc.resolve(targetPos); - if (!isBlock && !isInline2 && $pos.depth <= this.depth) { - return; - } - const childNodePos = new _NodePos($pos, this.editor, isBlock, isBlock || isInline2 ? node : null); - if (isBlock) { - childNodePos.actualDepth = this.depth + 1; - } - children.push(childNodePos); - }); - return children; - } - get firstChild() { - return this.children[0] || null; - } - get lastChild() { - const children = this.children; - return children[children.length - 1] || null; - } - closest(selector, attributes = {}) { - let node = null; - let currentNode = this.parent; - while (currentNode && !node) { - if (currentNode.node.type.name === selector) { - if (Object.keys(attributes).length > 0) { - const nodeAttributes = currentNode.node.attrs; - const attrKeys = Object.keys(attributes); - for (let index = 0; index < attrKeys.length; index += 1) { - const key = attrKeys[index]; - if (nodeAttributes[key] !== attributes[key]) { - break; - } - } - } else { - node = currentNode; - } - } - currentNode = currentNode.parent; - } - return node; - } - querySelector(selector, attributes = {}) { - return this.querySelectorAll(selector, attributes, true)[0] || null; - } - querySelectorAll(selector, attributes = {}, firstItemOnly = false) { - let nodes = []; - if (!this.children || this.children.length === 0) { - return nodes; - } - const attrKeys = Object.keys(attributes); - this.children.forEach((childPos) => { - if (firstItemOnly && nodes.length > 0) { - return; - } - if (childPos.node.type.name === selector) { - const doesAllAttributesMatch = attrKeys.every((key) => attributes[key] === childPos.node.attrs[key]); - if (doesAllAttributesMatch) { - nodes.push(childPos); - } - } - if (firstItemOnly && nodes.length > 0) { - return; - } - nodes = nodes.concat(childPos.querySelectorAll(selector, attributes, firstItemOnly)); - }); - return nodes; - } - setAttribute(attributes) { - const { tr: tr2 } = this.editor.state; - tr2.setNodeMarkup(this.from, void 0, { - ...this.node.attrs, - ...attributes - }); - this.editor.view.dispatch(tr2); - } -}; -var style = `.ProseMirror { - position: relative; -} - -.ProseMirror { - word-wrap: break-word; - white-space: pre-wrap; - white-space: break-spaces; - -webkit-font-variant-ligatures: none; - font-variant-ligatures: none; - font-feature-settings: "liga" 0; /* the above doesn't seem to work in Edge */ -} - -.ProseMirror [contenteditable="false"] { - white-space: normal; -} - -.ProseMirror [contenteditable="false"] [contenteditable="true"] { - white-space: pre-wrap; -} - -.ProseMirror pre { - white-space: pre-wrap; -} - -img.ProseMirror-separator { - display: inline !important; - border: none !important; - margin: 0 !important; - width: 0 !important; - height: 0 !important; -} - -.ProseMirror-gapcursor { - display: none; - pointer-events: none; - position: absolute; - margin: 0; -} - -.ProseMirror-gapcursor:after { - content: ""; - display: block; - position: absolute; - top: -2px; - width: 20px; - border-top: 1px solid black; - animation: ProseMirror-cursor-blink 1.1s steps(2, start) infinite; -} - -@keyframes ProseMirror-cursor-blink { - to { - visibility: hidden; - } -} - -.ProseMirror-hideselection *::selection { - background: transparent; -} - -.ProseMirror-hideselection *::-moz-selection { - background: transparent; -} - -.ProseMirror-hideselection * { - caret-color: transparent; -} - -.ProseMirror-focused .ProseMirror-gapcursor { - display: block; -}`; -function createStyleTag(style2, nonce, suffix) { - const tiptapStyleTag = document.querySelector(`style[data-tiptap-style${""}]`); - if (tiptapStyleTag !== null) { - return tiptapStyleTag; - } - const styleNode = document.createElement("style"); - if (nonce) { - styleNode.setAttribute("nonce", nonce); - } - styleNode.setAttribute(`data-tiptap-style${""}`, ""); - styleNode.innerHTML = style2; - document.getElementsByTagName("head")[0].appendChild(styleNode); - return styleNode; -} -var Editor = class extends EventEmitter { - constructor(options = {}) { - super(); - this.css = null; - this.className = "tiptap"; - this.editorView = null; - this.isFocused = false; - this.isInitialized = false; - this.extensionStorage = {}; - this.instanceId = Math.random().toString(36).slice(2, 9); - this.options = { - element: typeof document !== "undefined" ? document.createElement("div") : null, - content: "", - injectCSS: true, - injectNonce: void 0, - extensions: [], - autofocus: false, - editable: true, - textDirection: void 0, - editorProps: {}, - parseOptions: {}, - coreExtensionOptions: {}, - enableInputRules: true, - enablePasteRules: true, - enableCoreExtensions: true, - enableContentCheck: false, - emitContentError: false, - onBeforeCreate: () => null, - onCreate: () => null, - onMount: () => null, - onUnmount: () => null, - onUpdate: () => null, - onSelectionUpdate: () => null, - onTransaction: () => null, - onFocus: () => null, - onBlur: () => null, - onDestroy: () => null, - onContentError: ({ error }) => { - throw error; - }, - onPaste: () => null, - onDrop: () => null, - onDelete: () => null, - enableExtensionDispatchTransaction: true - }; - this.isCapturingTransaction = false; - this.capturedTransaction = null; - this.utils = { - getUpdatedPosition, - createMappablePosition - }; - this.setOptions(options); - this.createExtensionManager(); - this.createCommandManager(); - this.createSchema(); - this.on("beforeCreate", this.options.onBeforeCreate); - this.emit("beforeCreate", { editor: this }); - this.on("mount", this.options.onMount); - this.on("unmount", this.options.onUnmount); - this.on("contentError", this.options.onContentError); - this.on("create", this.options.onCreate); - this.on("update", this.options.onUpdate); - this.on("selectionUpdate", this.options.onSelectionUpdate); - this.on("transaction", this.options.onTransaction); - this.on("focus", this.options.onFocus); - this.on("blur", this.options.onBlur); - this.on("destroy", this.options.onDestroy); - this.on("drop", ({ event, slice: slice2, moved }) => this.options.onDrop(event, slice2, moved)); - this.on("paste", ({ event, slice: slice2 }) => this.options.onPaste(event, slice2)); - this.on("delete", this.options.onDelete); - const initialDoc = this.createDoc(); - const selection = resolveFocusPosition(initialDoc, this.options.autofocus); - this.editorState = EditorState.create({ - doc: initialDoc, - schema: this.schema, - selection: selection || void 0 - }); - if (this.options.element) { - this.mount(this.options.element); - } - } - /** - * Attach the editor to the DOM, creating a new editor view. - */ - mount(el) { - if (typeof document === "undefined") { - throw new Error( - `[tiptap error]: The editor cannot be mounted because there is no 'document' defined in this environment.` - ); - } - this.createView(el); - this.emit("mount", { editor: this }); - if (this.css && !document.head.contains(this.css)) { - document.head.appendChild(this.css); - } - window.setTimeout(() => { - if (this.isDestroyed) { - return; - } - if (this.options.autofocus !== false && this.options.autofocus !== null) { - this.commands.focus(this.options.autofocus); - } - this.emit("create", { editor: this }); - this.isInitialized = true; - }, 0); - } - /** - * Remove the editor from the DOM, but still allow remounting at a different point in time - */ - unmount() { - if (this.editorView) { - const dom = this.editorView.dom; - if (dom == null ? void 0 : dom.editor) { - delete dom.editor; - } - this.editorView.destroy(); - } - this.editorView = null; - this.isInitialized = false; - if (this.css && !document.querySelectorAll(`.${this.className}`).length) { - try { - if (typeof this.css.remove === "function") { - this.css.remove(); - } else if (this.css.parentNode) { - this.css.parentNode.removeChild(this.css); - } - } catch (error) { - console.warn("Failed to remove CSS element:", error); - } - } - this.css = null; - this.emit("unmount", { editor: this }); - } - /** - * Returns the editor storage. - */ - get storage() { - return this.extensionStorage; - } - /** - * An object of all registered commands. - */ - get commands() { - return this.commandManager.commands; - } - /** - * Create a command chain to call multiple commands at once. - */ - chain() { - return this.commandManager.chain(); - } - /** - * Check if a command or a command chain can be executed. Without executing it. - */ - can() { - return this.commandManager.can(); - } - /** - * Inject CSS styles. - */ - injectCSS() { - if (this.options.injectCSS && typeof document !== "undefined") { - this.css = createStyleTag(style, this.options.injectNonce); - } - } - /** - * Update editor options. - * - * @param options A list of options - */ - setOptions(options = {}) { - this.options = { - ...this.options, - ...options - }; - if (!this.editorView || !this.state || this.isDestroyed) { - return; - } - if (this.options.editorProps) { - this.view.setProps(this.options.editorProps); - } - this.view.updateState(this.state); - } - /** - * Update editable state of the editor. - */ - setEditable(editable, emitUpdate = true) { - this.setOptions({ editable }); - if (emitUpdate) { - this.emit("update", { editor: this, transaction: this.state.tr, appendedTransactions: [] }); - } - } - /** - * Returns whether the editor is editable. - */ - get isEditable() { - return this.options.editable && this.view && this.view.editable; - } - /** - * Returns the editor view. - */ - get view() { - if (this.editorView) { - return this.editorView; - } - return new Proxy( - { - state: this.editorState, - updateState: (state) => { - this.editorState = state; - }, - dispatch: (tr2) => { - this.dispatchTransaction(tr2); - }, - // Stub some commonly accessed properties to prevent errors - composing: false, - dragging: null, - editable: true, - isDestroyed: false - }, - { - get: (obj, key) => { - if (this.editorView) { - return this.editorView[key]; - } - if (key === "state") { - return this.editorState; - } - if (key in obj) { - return Reflect.get(obj, key); - } - throw new Error( - `[tiptap error]: The editor view is not available. Cannot access view['${key}']. The editor may not be mounted yet.` - ); - } - } - ); - } - /** - * Returns the editor state. - */ - get state() { - if (this.editorView) { - this.editorState = this.view.state; - } - return this.editorState; - } - /** - * Register a ProseMirror plugin. - * - * @param plugin A ProseMirror plugin - * @param handlePlugins Control how to merge the plugin into the existing plugins. - * @returns The new editor state - */ - registerPlugin(plugin, handlePlugins) { - const plugins = isFunction(handlePlugins) ? handlePlugins(plugin, [...this.state.plugins]) : [...this.state.plugins, plugin]; - const state = this.state.reconfigure({ plugins }); - this.view.updateState(state); - return state; - } - /** - * Unregister a ProseMirror plugin. - * - * @param nameOrPluginKeyToRemove The plugins name - * @returns The new editor state or undefined if the editor is destroyed - */ - unregisterPlugin(nameOrPluginKeyToRemove) { - if (this.isDestroyed) { - return void 0; - } - const prevPlugins = this.state.plugins; - let plugins = prevPlugins; - [].concat(nameOrPluginKeyToRemove).forEach((nameOrPluginKey) => { - const name = typeof nameOrPluginKey === "string" ? `${nameOrPluginKey}$` : nameOrPluginKey.key; - plugins = plugins.filter((plugin) => !plugin.key.startsWith(name)); - }); - if (prevPlugins.length === plugins.length) { - return void 0; - } - const state = this.state.reconfigure({ - plugins - }); - this.view.updateState(state); - return state; - } - /** - * Creates an extension manager. - */ - createExtensionManager() { - var _a, _b; - const coreExtensions = this.options.enableCoreExtensions ? [ - Editable, - ClipboardTextSerializer.configure({ - blockSeparator: (_b = (_a = this.options.coreExtensionOptions) == null ? void 0 : _a.clipboardTextSerializer) == null ? void 0 : _b.blockSeparator - }), - Commands, - FocusEvents, - Keymap, - Tabindex, - Drop, - Paste, - Delete, - TextDirection.configure({ - direction: this.options.textDirection - }) - ].filter((ext) => { - if (typeof this.options.enableCoreExtensions === "object") { - return this.options.enableCoreExtensions[ext.name] !== false; - } - return true; - }) : []; - const allExtensions = [...coreExtensions, ...this.options.extensions].filter((extension) => { - return ["extension", "node", "mark"].includes(extension == null ? void 0 : extension.type); - }); - this.extensionManager = new ExtensionManager(allExtensions, this); - } - /** - * Creates an command manager. - */ - createCommandManager() { - this.commandManager = new CommandManager({ - editor: this - }); - } - /** - * Creates a ProseMirror schema. - */ - createSchema() { - this.schema = this.extensionManager.schema; - } - /** - * Creates the initial document. - */ - createDoc() { - let doc2; - try { - doc2 = createDocument(this.options.content, this.schema, this.options.parseOptions, { - errorOnInvalidContent: this.options.enableContentCheck - }); - } catch (e) { - if (!(e instanceof Error) || !["[tiptap error]: Invalid JSON content", "[tiptap error]: Invalid HTML content"].includes(e.message)) { - throw e; - } - this.emit("contentError", { - editor: this, - error: e, - disableCollaboration: () => { - if ("collaboration" in this.storage && typeof this.storage.collaboration === "object" && this.storage.collaboration) { - this.storage.collaboration.isDisabled = true; - } - this.options.extensions = this.options.extensions.filter((extension) => extension.name !== "collaboration"); - this.createExtensionManager(); - } - }); - doc2 = createDocument(this.options.content, this.schema, this.options.parseOptions, { - errorOnInvalidContent: false - }); - } - return doc2; - } - /** - * Creates a ProseMirror view. - */ - createView(element) { - const { editorProps, enableExtensionDispatchTransaction } = this.options; - const baseDispatch = editorProps.dispatchTransaction || this.dispatchTransaction.bind(this); - const dispatch = enableExtensionDispatchTransaction ? this.extensionManager.dispatchTransaction(baseDispatch) : baseDispatch; - const baseTransformPastedHTML = editorProps.transformPastedHTML; - const transformPastedHTML = this.extensionManager.transformPastedHTML(baseTransformPastedHTML); - this.editorView = new EditorView(element, { - ...editorProps, - attributes: { - // add `role="textbox"` to the editor element - role: "textbox", - ...editorProps == null ? void 0 : editorProps.attributes - }, - dispatchTransaction: dispatch, - transformPastedHTML, - state: this.editorState, - markViews: this.extensionManager.markViews, - nodeViews: this.extensionManager.nodeViews - }); - const newState = this.state.reconfigure({ - plugins: this.extensionManager.plugins - }); - this.view.updateState(newState); - this.prependClass(); - this.injectCSS(); - const dom = this.view.dom; - dom.editor = this; - } - /** - * Creates all node and mark views. - */ - createNodeViews() { - if (this.view.isDestroyed) { - return; - } - this.view.setProps({ - markViews: this.extensionManager.markViews, - nodeViews: this.extensionManager.nodeViews - }); - } - /** - * Prepend class name to element. - */ - prependClass() { - this.view.dom.className = `${this.className} ${this.view.dom.className}`; - } - captureTransaction(fn) { - this.isCapturingTransaction = true; - fn(); - this.isCapturingTransaction = false; - const tr2 = this.capturedTransaction; - this.capturedTransaction = null; - return tr2; - } - /** - * The callback over which to send transactions (state updates) produced by the view. - * - * @param transaction An editor state transaction - */ - dispatchTransaction(transaction) { - if (this.view.isDestroyed) { - return; - } - if (this.isCapturingTransaction) { - if (!this.capturedTransaction) { - this.capturedTransaction = transaction; - return; - } - transaction.steps.forEach((step) => { - var _a; - return (_a = this.capturedTransaction) == null ? void 0 : _a.step(step); - }); - return; - } - const { state, transactions } = this.state.applyTransaction(transaction); - const selectionHasChanged = !this.state.selection.eq(state.selection); - const rootTrWasApplied = transactions.includes(transaction); - const prevState = this.state; - this.emit("beforeTransaction", { - editor: this, - transaction, - nextState: state - }); - if (!rootTrWasApplied) { - return; - } - this.view.updateState(state); - this.emit("transaction", { - editor: this, - transaction, - appendedTransactions: transactions.slice(1) - }); - if (selectionHasChanged) { - this.emit("selectionUpdate", { - editor: this, - transaction - }); - } - const mostRecentFocusTr = transactions.findLast((tr2) => tr2.getMeta("focus") || tr2.getMeta("blur")); - const focus2 = mostRecentFocusTr == null ? void 0 : mostRecentFocusTr.getMeta("focus"); - const blur2 = mostRecentFocusTr == null ? void 0 : mostRecentFocusTr.getMeta("blur"); - if (focus2) { - this.emit("focus", { - editor: this, - event: focus2.event, - // eslint-disable-next-line @typescript-eslint/no-non-null-assertion - transaction: mostRecentFocusTr - }); - } - if (blur2) { - this.emit("blur", { - editor: this, - event: blur2.event, - // eslint-disable-next-line @typescript-eslint/no-non-null-assertion - transaction: mostRecentFocusTr - }); - } - if (transaction.getMeta("preventUpdate") || !transactions.some((tr2) => tr2.docChanged) || prevState.doc.eq(state.doc)) { - return; - } - this.emit("update", { - editor: this, - transaction, - appendedTransactions: transactions.slice(1) - }); - } - /** - * Get attributes of the currently selected node or mark. - */ - getAttributes(nameOrType) { - return getAttributes(this.state, nameOrType); - } - isActive(nameOrAttributes, attributesOrUndefined) { - const name = typeof nameOrAttributes === "string" ? nameOrAttributes : null; - const attributes = typeof nameOrAttributes === "string" ? attributesOrUndefined : nameOrAttributes; - return isActive(this.state, name, attributes); - } - /** - * Get the document as JSON. - */ - getJSON() { - return this.state.doc.toJSON(); - } - /** - * Get the document as HTML. - */ - getHTML() { - return getHTMLFromFragment(this.state.doc.content, this.schema); - } - /** - * Get the document as text. - */ - getText(options) { - const { blockSeparator = "\n\n", textSerializers = {} } = options || {}; - return getText(this.state.doc, { - blockSeparator, - textSerializers: { - ...getTextSerializersFromSchema(this.schema), - ...textSerializers - } - }); - } - /** - * Check if there is no content. - */ - get isEmpty() { - return isNodeEmpty(this.state.doc); - } - /** - * Destroy the editor. - */ - destroy() { - this.emit("destroy"); - this.unmount(); - this.removeAllListeners(); - } - /** - * Check if the editor is already destroyed. - */ - get isDestroyed() { - var _a, _b; - return (_b = (_a = this.editorView) == null ? void 0 : _a.isDestroyed) != null ? _b : true; - } - $node(selector, attributes) { - var _a; - return ((_a = this.$doc) == null ? void 0 : _a.querySelector(selector, attributes)) || null; - } - $nodes(selector, attributes) { - var _a; - return ((_a = this.$doc) == null ? void 0 : _a.querySelectorAll(selector, attributes)) || null; - } - $pos(pos) { - const $pos = this.state.doc.resolve(pos); - return new NodePos($pos, this); - } - get $doc() { - return this.$pos(0); - } -}; -function markInputRule(config) { - return new InputRule({ - find: config.find, - handler: ({ state, range, match }) => { - const attributes = callOrReturn(config.getAttributes, void 0, match); - if (attributes === false || attributes === null) { - return null; - } - const { tr: tr2 } = state; - const captureGroup = match[match.length - 1]; - const fullMatch = match[0]; - if (captureGroup) { - const startSpaces = fullMatch.search(/\S/); - const textStart = range.from + fullMatch.indexOf(captureGroup); - const textEnd = textStart + captureGroup.length; - const excludedMarks = getMarksBetween(range.from, range.to, state.doc).filter((item) => { - const excluded = item.mark.type.excluded; - return excluded.find((type) => type === config.type && type !== item.mark.type); - }).filter((item) => item.to > textStart); - if (excludedMarks.length) { - return null; - } - if (textEnd < range.to) { - tr2.delete(textEnd, range.to); - } - if (textStart > range.from) { - tr2.delete(range.from + startSpaces, textStart); - } - const markEnd = range.from + startSpaces + captureGroup.length; - tr2.addMark(range.from + startSpaces, markEnd, config.type.create(attributes || {})); - tr2.removeStoredMark(config.type); - } - }, - undoable: config.undoable - }); -} -function nodeInputRule(config) { - return new InputRule({ - find: config.find, - handler: ({ state, range, match }) => { - const attributes = callOrReturn(config.getAttributes, void 0, match) || {}; - const { tr: tr2 } = state; - const start = range.from; - let end = range.to; - const newNode = config.type.create(attributes); - if (match[1]) { - const offset = match[0].lastIndexOf(match[1]); - let matchStart = start + offset; - if (matchStart > end) { - matchStart = end; - } else { - end = matchStart + match[1].length; - } - const lastChar = match[0][match[0].length - 1]; - tr2.insertText(lastChar, start + match[0].length - 1); - tr2.replaceWith(matchStart, end, newNode); - } else if (match[0]) { - const insertionStart = config.type.isInline ? start : start - 1; - tr2.insert(insertionStart, config.type.create(attributes)).delete(tr2.mapping.map(start), tr2.mapping.map(end)); - } - tr2.scrollIntoView(); - }, - undoable: config.undoable - }); -} -function textblockTypeInputRule(config) { - return new InputRule({ - find: config.find, - handler: ({ state, range, match }) => { - const $start = state.doc.resolve(range.from); - const attributes = callOrReturn(config.getAttributes, void 0, match) || {}; - if (!$start.node(-1).canReplaceWith($start.index(-1), $start.indexAfter(-1), config.type)) { - return null; - } - state.tr.delete(range.from, range.to).setBlockType(range.from, range.from, config.type, attributes); - }, - undoable: config.undoable - }); -} -function wrappingInputRule(config) { - return new InputRule({ - find: config.find, - handler: ({ state, range, match, chain }) => { - const attributes = callOrReturn(config.getAttributes, void 0, match) || {}; - const tr2 = state.tr.delete(range.from, range.to); - const $start = tr2.doc.resolve(range.from); - const blockRange = $start.blockRange(); - const wrapping = blockRange && findWrapping(blockRange, config.type, attributes); - if (!wrapping) { - return null; - } - tr2.wrap(blockRange, wrapping); - if (config.keepMarks && config.editor) { - const { selection, storedMarks } = state; - const { splittableMarks } = config.editor.extensionManager; - const marks = storedMarks || selection.$to.parentOffset && selection.$from.marks(); - if (marks) { - const filteredMarks = marks.filter((mark) => splittableMarks.includes(mark.type.name)); - tr2.ensureMarks(filteredMarks); - } - } - if (config.keepAttributes) { - const nodeType = config.type.name === "bulletList" || config.type.name === "orderedList" ? "listItem" : "taskList"; - chain().updateAttributes(nodeType, attributes).run(); - } - const before = tr2.doc.resolve(range.from - 1).nodeBefore; - if (before && before.type === config.type && canJoin(tr2.doc, range.from - 1) && (!config.joinPredicate || config.joinPredicate(match, before))) { - tr2.join(range.from - 1); - } - }, - undoable: config.undoable - }); -} -var isTouchEvent = (e) => { - return "touches" in e; -}; -var ResizableNodeView = class { - /** - * Creates a new ResizableNodeView instance. - * - * The constructor sets up the resize handles, applies initial sizing from - * node attributes, and configures all resize behavior options. - * - * @param options - Configuration options for the resizable node view - */ - constructor(options) { - this.directions = ["bottom-left", "bottom-right", "top-left", "top-right"]; - this.minSize = { - height: 8, - width: 8 - }; - this.preserveAspectRatio = false; - this.classNames = { - container: "", - wrapper: "", - handle: "", - resizing: "" - }; - this.initialWidth = 0; - this.initialHeight = 0; - this.aspectRatio = 1; - this.isResizing = false; - this.activeHandle = null; - this.startX = 0; - this.startY = 0; - this.startWidth = 0; - this.startHeight = 0; - this.isShiftKeyPressed = false; - this.lastEditableState = void 0; - this.handleMap = /* @__PURE__ */ new Map(); - this.handleMouseMove = (event) => { - if (!this.isResizing || !this.activeHandle) { - return; - } - const deltaX = event.clientX - this.startX; - const deltaY = event.clientY - this.startY; - this.handleResize(deltaX, deltaY); - }; - this.handleTouchMove = (event) => { - if (!this.isResizing || !this.activeHandle) { - return; - } - const touch = event.touches[0]; - if (!touch) { - return; - } - const deltaX = touch.clientX - this.startX; - const deltaY = touch.clientY - this.startY; - this.handleResize(deltaX, deltaY); - }; - this.handleMouseUp = () => { - if (!this.isResizing) { - return; - } - const finalWidth = this.element.offsetWidth; - const finalHeight = this.element.offsetHeight; - this.onCommit(finalWidth, finalHeight); - this.isResizing = false; - this.activeHandle = null; - this.container.dataset.resizeState = "false"; - if (this.classNames.resizing) { - this.container.classList.remove(this.classNames.resizing); - } - document.removeEventListener("mousemove", this.handleMouseMove); - document.removeEventListener("mouseup", this.handleMouseUp); - document.removeEventListener("keydown", this.handleKeyDown); - document.removeEventListener("keyup", this.handleKeyUp); - }; - this.handleKeyDown = (event) => { - if (event.key === "Shift") { - this.isShiftKeyPressed = true; - } - }; - this.handleKeyUp = (event) => { - if (event.key === "Shift") { - this.isShiftKeyPressed = false; - } - }; - var _a, _b, _c, _d, _e, _f; - this.node = options.node; - this.editor = options.editor; - this.element = options.element; - this.contentElement = options.contentElement; - this.getPos = options.getPos; - this.onResize = options.onResize; - this.onCommit = options.onCommit; - this.onUpdate = options.onUpdate; - if ((_a = options.options) == null ? void 0 : _a.min) { - this.minSize = { - ...this.minSize, - ...options.options.min - }; - } - if ((_b = options.options) == null ? void 0 : _b.max) { - this.maxSize = options.options.max; - } - if ((_c = options == null ? void 0 : options.options) == null ? void 0 : _c.directions) { - this.directions = options.options.directions; - } - if ((_d = options.options) == null ? void 0 : _d.preserveAspectRatio) { - this.preserveAspectRatio = options.options.preserveAspectRatio; - } - if ((_e = options.options) == null ? void 0 : _e.className) { - this.classNames = { - container: options.options.className.container || "", - wrapper: options.options.className.wrapper || "", - handle: options.options.className.handle || "", - resizing: options.options.className.resizing || "" - }; - } - if ((_f = options.options) == null ? void 0 : _f.createCustomHandle) { - this.createCustomHandle = options.options.createCustomHandle; - } - this.wrapper = this.createWrapper(); - this.container = this.createContainer(); - this.applyInitialSize(); - this.attachHandles(); - this.editor.on("update", this.handleEditorUpdate.bind(this)); - } - /** - * Returns the top-level DOM node that should be placed in the editor. - * - * This is required by the ProseMirror NodeView interface. The container - * includes the wrapper, handles, and the actual content element. - * - * @returns The container element to be inserted into the editor - */ - get dom() { - return this.container; - } - get contentDOM() { - var _a; - return (_a = this.contentElement) != null ? _a : null; - } - handleEditorUpdate() { - const isEditable = this.editor.isEditable; - if (isEditable === this.lastEditableState) { - return; - } - this.lastEditableState = isEditable; - if (!isEditable) { - this.removeHandles(); - } else if (isEditable && this.handleMap.size === 0) { - this.attachHandles(); - } - } - /** - * Called when the node's content or attributes change. - * - * Updates the internal node reference. If a custom `onUpdate` callback - * was provided, it will be called to handle additional update logic. - * - * @param node - The new/updated node - * @param decorations - Node decorations - * @param innerDecorations - Inner decorations - * @returns `false` if the node type has changed (requires full rebuild), otherwise the result of `onUpdate` or `true` - */ - update(node, decorations, innerDecorations) { - if (node.type !== this.node.type) { - return false; - } - this.node = node; - if (this.onUpdate) { - return this.onUpdate(node, decorations, innerDecorations); - } - return true; - } - /** - * Cleanup method called when the node view is being removed. - * - * Removes all event listeners to prevent memory leaks. This is required - * by the ProseMirror NodeView interface. If a resize is active when - * destroy is called, it will be properly cancelled. - */ - destroy() { - if (this.isResizing) { - this.container.dataset.resizeState = "false"; - if (this.classNames.resizing) { - this.container.classList.remove(this.classNames.resizing); - } - document.removeEventListener("mousemove", this.handleMouseMove); - document.removeEventListener("mouseup", this.handleMouseUp); - document.removeEventListener("keydown", this.handleKeyDown); - document.removeEventListener("keyup", this.handleKeyUp); - this.isResizing = false; - this.activeHandle = null; - } - this.editor.off("update", this.handleEditorUpdate.bind(this)); - this.container.remove(); - } - /** - * Creates the outer container element. - * - * The container is the top-level element returned by the NodeView and - * wraps the entire resizable node. It's set up with flexbox to handle - * alignment and includes data attributes for styling and identification. - * - * @returns The container element - */ - createContainer() { - const element = document.createElement("div"); - element.dataset.resizeContainer = ""; - element.dataset.node = this.node.type.name; - element.style.display = this.node.type.isInline ? "inline-flex" : "flex"; - if (this.classNames.container) { - element.className = this.classNames.container; - } - element.appendChild(this.wrapper); - return element; - } - /** - * Creates the wrapper element that contains the content and handles. - * - * The wrapper uses relative positioning so that resize handles can be - * positioned absolutely within it. This is the direct parent of the - * content element being made resizable. - * - * @returns The wrapper element - */ - createWrapper() { - const element = document.createElement("div"); - element.style.position = "relative"; - element.style.display = "block"; - element.dataset.resizeWrapper = ""; - if (this.classNames.wrapper) { - element.className = this.classNames.wrapper; - } - element.appendChild(this.element); - return element; - } - /** - * Creates a resize handle element for a specific direction. - * - * Each handle is absolutely positioned and includes a data attribute - * identifying its direction for styling purposes. - * - * @param direction - The resize direction for this handle - * @returns The handle element - */ - createHandle(direction) { - const handle = document.createElement("div"); - handle.dataset.resizeHandle = direction; - handle.style.position = "absolute"; - if (this.classNames.handle) { - handle.className = this.classNames.handle; - } - return handle; - } - /** - * Positions a handle element according to its direction. - * - * Corner handles (e.g., 'top-left') are positioned at the intersection - * of two edges. Edge handles (e.g., 'top') span the full width or height. - * - * @param handle - The handle element to position - * @param direction - The direction determining the position - */ - positionHandle(handle, direction) { - const isTop = direction.includes("top"); - const isBottom = direction.includes("bottom"); - const isLeft = direction.includes("left"); - const isRight = direction.includes("right"); - if (isTop) { - handle.style.top = "0"; - } - if (isBottom) { - handle.style.bottom = "0"; - } - if (isLeft) { - handle.style.left = "0"; - } - if (isRight) { - handle.style.right = "0"; - } - if (direction === "top" || direction === "bottom") { - handle.style.left = "0"; - handle.style.right = "0"; - } - if (direction === "left" || direction === "right") { - handle.style.top = "0"; - handle.style.bottom = "0"; - } - } - /** - * Creates and attaches all resize handles to the wrapper. - * - * Iterates through the configured directions, creates a handle for each, - * positions it, attaches the mousedown listener, and appends it to the DOM. - */ - attachHandles() { - this.directions.forEach((direction) => { - let handle; - if (this.createCustomHandle) { - handle = this.createCustomHandle(direction); - } else { - handle = this.createHandle(direction); - } - if (!(handle instanceof HTMLElement)) { - console.warn( - `[ResizableNodeView] createCustomHandle("${direction}") did not return an HTMLElement. Falling back to default handle.` - ); - handle = this.createHandle(direction); - } - if (!this.createCustomHandle) { - this.positionHandle(handle, direction); - } - handle.addEventListener("mousedown", (event) => this.handleResizeStart(event, direction)); - handle.addEventListener("touchstart", (event) => this.handleResizeStart(event, direction)); - this.handleMap.set(direction, handle); - this.wrapper.appendChild(handle); - }); - } - /** - * Removes all resize handles from the wrapper. - * - * Cleans up the handle map and removes each handle element from the DOM. - */ - removeHandles() { - this.handleMap.forEach((el) => el.remove()); - this.handleMap.clear(); - } - /** - * Applies initial sizing from node attributes to the element. - * - * If width/height attributes exist on the node, they're applied to the element. - * Otherwise, the element's natural/current dimensions are measured. The aspect - * ratio is calculated for later use in aspect-ratio-preserving resizes. - */ - applyInitialSize() { - const width = this.node.attrs.width; - const height = this.node.attrs.height; - if (width) { - this.element.style.width = `${width}px`; - this.initialWidth = width; - } else { - this.initialWidth = this.element.offsetWidth; - } - if (height) { - this.element.style.height = `${height}px`; - this.initialHeight = height; - } else { - this.initialHeight = this.element.offsetHeight; - } - if (this.initialWidth > 0 && this.initialHeight > 0) { - this.aspectRatio = this.initialWidth / this.initialHeight; - } - } - /** - * Initiates a resize operation when a handle is clicked. - * - * Captures the starting mouse position and element dimensions, sets up - * the resize state, adds the resizing class and state attribute, and - * attaches document-level listeners for mouse movement and keyboard input. - * - * @param event - The mouse down event - * @param direction - The direction of the handle being dragged - */ - handleResizeStart(event, direction) { - event.preventDefault(); - event.stopPropagation(); - this.isResizing = true; - this.activeHandle = direction; - if (isTouchEvent(event)) { - this.startX = event.touches[0].clientX; - this.startY = event.touches[0].clientY; - } else { - this.startX = event.clientX; - this.startY = event.clientY; - } - this.startWidth = this.element.offsetWidth; - this.startHeight = this.element.offsetHeight; - if (this.startWidth > 0 && this.startHeight > 0) { - this.aspectRatio = this.startWidth / this.startHeight; - } - this.getPos(); - this.container.dataset.resizeState = "true"; - if (this.classNames.resizing) { - this.container.classList.add(this.classNames.resizing); - } - document.addEventListener("mousemove", this.handleMouseMove); - document.addEventListener("touchmove", this.handleTouchMove); - document.addEventListener("mouseup", this.handleMouseUp); - document.addEventListener("keydown", this.handleKeyDown); - document.addEventListener("keyup", this.handleKeyUp); - } - handleResize(deltaX, deltaY) { - if (!this.activeHandle) { - return; - } - const shouldPreserveAspectRatio = this.preserveAspectRatio || this.isShiftKeyPressed; - const { width, height } = this.calculateNewDimensions(this.activeHandle, deltaX, deltaY); - const constrained = this.applyConstraints(width, height, shouldPreserveAspectRatio); - this.element.style.width = `${constrained.width}px`; - this.element.style.height = `${constrained.height}px`; - if (this.onResize) { - this.onResize(constrained.width, constrained.height); - } - } - /** - * Calculates new dimensions based on mouse delta and resize direction. - * - * Takes the starting dimensions and applies the mouse movement delta - * according to the handle direction. For corner handles, both dimensions - * are affected. For edge handles, only one dimension changes. If aspect - * ratio should be preserved, delegates to applyAspectRatio. - * - * @param direction - The active resize handle direction - * @param deltaX - Horizontal mouse movement since resize start - * @param deltaY - Vertical mouse movement since resize start - * @returns The calculated width and height - */ - calculateNewDimensions(direction, deltaX, deltaY) { - let newWidth = this.startWidth; - let newHeight = this.startHeight; - const isRight = direction.includes("right"); - const isLeft = direction.includes("left"); - const isBottom = direction.includes("bottom"); - const isTop = direction.includes("top"); - if (isRight) { - newWidth = this.startWidth + deltaX; - } else if (isLeft) { - newWidth = this.startWidth - deltaX; - } - if (isBottom) { - newHeight = this.startHeight + deltaY; - } else if (isTop) { - newHeight = this.startHeight - deltaY; - } - if (direction === "right" || direction === "left") { - newWidth = this.startWidth + (isRight ? deltaX : -deltaX); - } - if (direction === "top" || direction === "bottom") { - newHeight = this.startHeight + (isBottom ? deltaY : -deltaY); - } - const shouldPreserveAspectRatio = this.preserveAspectRatio || this.isShiftKeyPressed; - if (shouldPreserveAspectRatio) { - return this.applyAspectRatio(newWidth, newHeight, direction); - } - return { width: newWidth, height: newHeight }; - } - /** - * Applies min/max constraints to dimensions. - * - * When aspect ratio is NOT preserved, constraints are applied independently - * to width and height. When aspect ratio IS preserved, constraints are - * applied while maintaining the aspect ratio—if one dimension hits a limit, - * the other is recalculated proportionally. - * - * This ensures that aspect ratio is never broken when constrained. - * - * @param width - The unconstrained width - * @param height - The unconstrained height - * @param preserveAspectRatio - Whether to maintain aspect ratio while constraining - * @returns The constrained dimensions - */ - applyConstraints(width, height, preserveAspectRatio) { - var _a, _b, _c, _d; - if (!preserveAspectRatio) { - let constrainedWidth2 = Math.max(this.minSize.width, width); - let constrainedHeight2 = Math.max(this.minSize.height, height); - if ((_a = this.maxSize) == null ? void 0 : _a.width) { - constrainedWidth2 = Math.min(this.maxSize.width, constrainedWidth2); - } - if ((_b = this.maxSize) == null ? void 0 : _b.height) { - constrainedHeight2 = Math.min(this.maxSize.height, constrainedHeight2); - } - return { width: constrainedWidth2, height: constrainedHeight2 }; - } - let constrainedWidth = width; - let constrainedHeight = height; - if (constrainedWidth < this.minSize.width) { - constrainedWidth = this.minSize.width; - constrainedHeight = constrainedWidth / this.aspectRatio; - } - if (constrainedHeight < this.minSize.height) { - constrainedHeight = this.minSize.height; - constrainedWidth = constrainedHeight * this.aspectRatio; - } - if (((_c = this.maxSize) == null ? void 0 : _c.width) && constrainedWidth > this.maxSize.width) { - constrainedWidth = this.maxSize.width; - constrainedHeight = constrainedWidth / this.aspectRatio; - } - if (((_d = this.maxSize) == null ? void 0 : _d.height) && constrainedHeight > this.maxSize.height) { - constrainedHeight = this.maxSize.height; - constrainedWidth = constrainedHeight * this.aspectRatio; - } - return { width: constrainedWidth, height: constrainedHeight }; - } - /** - * Adjusts dimensions to maintain the original aspect ratio. - * - * For horizontal handles (left/right), uses width as the primary dimension - * and calculates height from it. For vertical handles (top/bottom), uses - * height as primary and calculates width. For corner handles, uses width - * as the primary dimension. - * - * @param width - The new width - * @param height - The new height - * @param direction - The active resize direction - * @returns Dimensions adjusted to preserve aspect ratio - */ - applyAspectRatio(width, height, direction) { - const isHorizontal = direction === "left" || direction === "right"; - const isVertical = direction === "top" || direction === "bottom"; - if (isHorizontal) { - return { - width, - height: width / this.aspectRatio - }; - } - if (isVertical) { - return { - width: height * this.aspectRatio, - height - }; - } - return { - width, - height: width / this.aspectRatio - }; - } -}; -function canInsertNode(state, nodeType) { - const { selection } = state; - const { $from } = selection; - if (selection instanceof NodeSelection) { - const index = $from.index(); - const parent = $from.parent; - return parent.canReplaceWith(index, index + 1, nodeType); - } - let depth = $from.depth; - while (depth >= 0) { - const index = $from.index(depth); - const parent = $from.node(depth); - const match = parent.contentMatchAt(index); - if (match.matchType(nodeType)) { - return true; - } - depth -= 1; - } - return false; -} -function escapeForRegEx(string) { - return string.replace(/[-/\\^$*+?.()|[\]{}]/g, "\\$&"); -} -var markdown_exports = {}; -__export$1(markdown_exports, { - createAtomBlockMarkdownSpec: () => createAtomBlockMarkdownSpec, - createBlockMarkdownSpec: () => createBlockMarkdownSpec, - createInlineMarkdownSpec: () => createInlineMarkdownSpec, - parseAttributes: () => parseAttributes, - parseIndentedBlocks: () => parseIndentedBlocks, - renderNestedMarkdownContent: () => renderNestedMarkdownContent, - serializeAttributes: () => serializeAttributes -}); -function parseAttributes(attrString) { - if (!(attrString == null ? void 0 : attrString.trim())) { - return {}; - } - const attributes = {}; - const quotedStrings = []; - const tempString = attrString.replace(/["']([^"']*)["']/g, (match) => { - quotedStrings.push(match); - return `__QUOTED_${quotedStrings.length - 1}__`; - }); - const classMatches = tempString.match(/(?:^|\s)\.([a-zA-Z][\w-]*)/g); - if (classMatches) { - const classes = classMatches.map((match) => match.trim().slice(1)); - attributes.class = classes.join(" "); - } - const idMatch = tempString.match(/(?:^|\s)#([a-zA-Z][\w-]*)/); - if (idMatch) { - attributes.id = idMatch[1]; - } - const kvRegex = /([a-zA-Z][\w-]*)\s*=\s*(__QUOTED_\d+__)/g; - const kvMatches = Array.from(tempString.matchAll(kvRegex)); - kvMatches.forEach(([, key, quotedRef]) => { - var _a; - const quotedIndex = parseInt(((_a = quotedRef.match(/__QUOTED_(\d+)__/)) == null ? void 0 : _a[1]) || "0", 10); - const quotedValue = quotedStrings[quotedIndex]; - if (quotedValue) { - attributes[key] = quotedValue.slice(1, -1); - } - }); - const cleanString = tempString.replace(/(?:^|\s)\.([a-zA-Z][\w-]*)/g, "").replace(/(?:^|\s)#([a-zA-Z][\w-]*)/g, "").replace(/([a-zA-Z][\w-]*)\s*=\s*__QUOTED_\d+__/g, "").trim(); - if (cleanString) { - const booleanAttrs = cleanString.split(/\s+/).filter(Boolean); - booleanAttrs.forEach((attr) => { - if (attr.match(/^[a-zA-Z][\w-]*$/)) { - attributes[attr] = true; - } - }); - } - return attributes; -} -function serializeAttributes(attributes) { - if (!attributes || Object.keys(attributes).length === 0) { - return ""; - } - const parts = []; - if (attributes.class) { - const classes = String(attributes.class).split(/\s+/).filter(Boolean); - classes.forEach((cls) => parts.push(`.${cls}`)); - } - if (attributes.id) { - parts.push(`#${attributes.id}`); - } - Object.entries(attributes).forEach(([key, value]) => { - if (key === "class" || key === "id") { - return; - } - if (value === true) { - parts.push(key); - } else if (value !== false && value != null) { - parts.push(`${key}="${String(value)}"`); - } - }); - return parts.join(" "); -} -function createAtomBlockMarkdownSpec(options) { - const { - nodeName, - name: markdownName, - parseAttributes: parseAttributes2 = parseAttributes, - serializeAttributes: serializeAttributes2 = serializeAttributes, - defaultAttributes = {}, - requiredAttributes = [], - allowedAttributes - } = options; - const blockName = markdownName || nodeName; - const filterAttributes = (attrs) => { - if (!allowedAttributes) { - return attrs; - } - const filtered = {}; - allowedAttributes.forEach((key) => { - if (key in attrs) { - filtered[key] = attrs[key]; - } - }); - return filtered; - }; - return { - parseMarkdown: (token, h2) => { - const attrs = { ...defaultAttributes, ...token.attributes }; - return h2.createNode(nodeName, attrs, []); - }, - markdownTokenizer: { - name: nodeName, - level: "block", - start(src) { - var _a; - const regex = new RegExp(`^:::${blockName}(?:\\s|$)`, "m"); - const index = (_a = src.match(regex)) == null ? void 0 : _a.index; - return index !== void 0 ? index : -1; - }, - tokenize(src, _tokens, _lexer) { - const regex = new RegExp(`^:::${blockName}(?:\\s+\\{([^}]*)\\})?\\s*:::(?:\\n|$)`); - const match = src.match(regex); - if (!match) { - return void 0; - } - const attrString = match[1] || ""; - const attributes = parseAttributes2(attrString); - const missingRequired = requiredAttributes.find((required) => !(required in attributes)); - if (missingRequired) { - return void 0; - } - return { - type: nodeName, - raw: match[0], - attributes - }; - } - }, - renderMarkdown: (node) => { - const filteredAttrs = filterAttributes(node.attrs || {}); - const attrs = serializeAttributes2(filteredAttrs); - const attrString = attrs ? ` {${attrs}}` : ""; - return `:::${blockName}${attrString} :::`; - } - }; -} -function createBlockMarkdownSpec(options) { - const { - nodeName, - name: markdownName, - getContent, - parseAttributes: parseAttributes2 = parseAttributes, - serializeAttributes: serializeAttributes2 = serializeAttributes, - defaultAttributes = {}, - content = "block", - allowedAttributes - } = options; - const blockName = markdownName || nodeName; - const filterAttributes = (attrs) => { - if (!allowedAttributes) { - return attrs; - } - const filtered = {}; - allowedAttributes.forEach((key) => { - if (key in attrs) { - filtered[key] = attrs[key]; - } - }); - return filtered; - }; - return { - parseMarkdown: (token, h2) => { - let nodeContent; - if (getContent) { - const contentResult = getContent(token); - nodeContent = typeof contentResult === "string" ? [{ type: "text", text: contentResult }] : contentResult; - } else if (content === "block") { - nodeContent = h2.parseChildren(token.tokens || []); - } else { - nodeContent = h2.parseInline(token.tokens || []); - } - const attrs = { ...defaultAttributes, ...token.attributes }; - return h2.createNode(nodeName, attrs, nodeContent); - }, - markdownTokenizer: { - name: nodeName, - level: "block", - start(src) { - var _a; - const regex = new RegExp(`^:::${blockName}`, "m"); - const index = (_a = src.match(regex)) == null ? void 0 : _a.index; - return index !== void 0 ? index : -1; - }, - tokenize(src, _tokens, lexer) { - var _a; - const openingRegex = new RegExp(`^:::${blockName}(?:\\s+\\{([^}]*)\\})?\\s*\\n`); - const openingMatch = src.match(openingRegex); - if (!openingMatch) { - return void 0; - } - const [openingTag, attrString = ""] = openingMatch; - const attributes = parseAttributes2(attrString); - let level = 1; - const position = openingTag.length; - let matchedContent = ""; - const blockPattern = /^:::([\w-]*)(\s.*)?/gm; - const remaining = src.slice(position); - blockPattern.lastIndex = 0; - for (; ; ) { - const match = blockPattern.exec(remaining); - if (match === null) { - break; - } - const matchPos = match.index; - const blockType = match[1]; - if ((_a = match[2]) == null ? void 0 : _a.endsWith(":::")) { - continue; - } - if (blockType) { - level += 1; - } else { - level -= 1; - if (level === 0) { - const rawContent = remaining.slice(0, matchPos); - matchedContent = rawContent.trim(); - const fullMatch = src.slice(0, position + matchPos + match[0].length); - let contentTokens = []; - if (matchedContent) { - if (content === "block") { - contentTokens = lexer.blockTokens(rawContent); - contentTokens.forEach((token) => { - if (token.text && (!token.tokens || token.tokens.length === 0)) { - token.tokens = lexer.inlineTokens(token.text); - } - }); - while (contentTokens.length > 0) { - const lastToken = contentTokens[contentTokens.length - 1]; - if (lastToken.type === "paragraph" && (!lastToken.text || lastToken.text.trim() === "")) { - contentTokens.pop(); - } else { - break; - } - } - } else { - contentTokens = lexer.inlineTokens(matchedContent); - } - } - return { - type: nodeName, - raw: fullMatch, - attributes, - content: matchedContent, - tokens: contentTokens - }; - } - } - } - return void 0; - } - }, - renderMarkdown: (node, h2) => { - const filteredAttrs = filterAttributes(node.attrs || {}); - const attrs = serializeAttributes2(filteredAttrs); - const attrString = attrs ? ` {${attrs}}` : ""; - const renderedContent = h2.renderChildren(node.content || [], "\n\n"); - return `:::${blockName}${attrString} - -${renderedContent} - -:::`; - } - }; -} -function parseShortcodeAttributes(attrString) { - if (!attrString.trim()) { - return {}; - } - const attributes = {}; - const regex = /(\w+)=(?:"([^"]*)"|'([^']*)')/g; - let match = regex.exec(attrString); - while (match !== null) { - const [, key, doubleQuoted, singleQuoted] = match; - attributes[key] = doubleQuoted || singleQuoted; - match = regex.exec(attrString); - } - return attributes; -} -function serializeShortcodeAttributes(attrs) { - return Object.entries(attrs).filter(([, value]) => value !== void 0 && value !== null).map(([key, value]) => `${key}="${value}"`).join(" "); -} -function createInlineMarkdownSpec(options) { - const { - nodeName, - name: shortcodeName, - getContent, - parseAttributes: parseAttributes2 = parseShortcodeAttributes, - serializeAttributes: serializeAttributes2 = serializeShortcodeAttributes, - defaultAttributes = {}, - selfClosing = false, - allowedAttributes - } = options; - const shortcode = shortcodeName || nodeName; - const filterAttributes = (attrs) => { - if (!allowedAttributes) { - return attrs; - } - const filtered = {}; - allowedAttributes.forEach((attr) => { - const attrName = typeof attr === "string" ? attr : attr.name; - const skipIfDefault = typeof attr === "string" ? void 0 : attr.skipIfDefault; - if (attrName in attrs) { - const value = attrs[attrName]; - if (skipIfDefault !== void 0 && value === skipIfDefault) { - return; - } - filtered[attrName] = value; - } - }); - return filtered; - }; - const escapedShortcode = shortcode.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); - return { - parseMarkdown: (token, h2) => { - const attrs = { ...defaultAttributes, ...token.attributes }; - if (selfClosing) { - return h2.createNode(nodeName, attrs); - } - const content = getContent ? getContent(token) : token.content || ""; - if (content) { - return h2.createNode(nodeName, attrs, [h2.createTextNode(content)]); - } - return h2.createNode(nodeName, attrs, []); - }, - markdownTokenizer: { - name: nodeName, - level: "inline", - start(src) { - const startPattern = selfClosing ? new RegExp(`\\[${escapedShortcode}\\s*[^\\]]*\\]`) : new RegExp(`\\[${escapedShortcode}\\s*[^\\]]*\\][\\s\\S]*?\\[\\/${escapedShortcode}\\]`); - const match = src.match(startPattern); - const index = match == null ? void 0 : match.index; - return index !== void 0 ? index : -1; - }, - tokenize(src, _tokens, _lexer) { - const tokenPattern = selfClosing ? new RegExp(`^\\[${escapedShortcode}\\s*([^\\]]*)\\]`) : new RegExp(`^\\[${escapedShortcode}\\s*([^\\]]*)\\]([\\s\\S]*?)\\[\\/${escapedShortcode}\\]`); - const match = src.match(tokenPattern); - if (!match) { - return void 0; - } - let content = ""; - let attrString = ""; - if (selfClosing) { - const [, attrs] = match; - attrString = attrs; - } else { - const [, attrs, contentMatch] = match; - attrString = attrs; - content = contentMatch || ""; - } - const attributes = parseAttributes2(attrString.trim()); - return { - type: nodeName, - raw: match[0], - content: content.trim(), - attributes - }; - } - }, - renderMarkdown: (node) => { - let content = ""; - if (getContent) { - content = getContent(node); - } else if (node.content && node.content.length > 0) { - content = node.content.filter((child) => child.type === "text").map((child) => child.text).join(""); - } - const filteredAttrs = filterAttributes(node.attrs || {}); - const attrs = serializeAttributes2(filteredAttrs); - const attrString = attrs ? ` ${attrs}` : ""; - if (selfClosing) { - return `[${shortcode}${attrString}]`; - } - return `[${shortcode}${attrString}]${content}[/${shortcode}]`; - } - }; -} -function parseIndentedBlocks(src, config, lexer) { - var _a, _b, _c, _d; - const lines = src.split("\n"); - const items = []; - let totalRaw = ""; - let i = 0; - const baseIndentSize = config.baseIndentSize || 2; - while (i < lines.length) { - const currentLine = lines[i]; - const itemMatch = currentLine.match(config.itemPattern); - if (!itemMatch) { - if (items.length > 0) { - break; - } else if (currentLine.trim() === "") { - i += 1; - totalRaw = `${totalRaw}${currentLine} -`; - continue; - } else { - return void 0; - } - } - const itemData = config.extractItemData(itemMatch); - const { indentLevel, mainContent } = itemData; - totalRaw = `${totalRaw}${currentLine} -`; - const itemContent = [mainContent]; - i += 1; - while (i < lines.length) { - const nextLine = lines[i]; - if (nextLine.trim() === "") { - const nextNonEmptyIndex = lines.slice(i + 1).findIndex((l) => l.trim() !== ""); - if (nextNonEmptyIndex === -1) { - break; - } - const nextNonEmpty = lines[i + 1 + nextNonEmptyIndex]; - const nextIndent2 = ((_b = (_a = nextNonEmpty.match(/^(\s*)/)) == null ? void 0 : _a[1]) == null ? void 0 : _b.length) || 0; - if (nextIndent2 > indentLevel) { - itemContent.push(nextLine); - totalRaw = `${totalRaw}${nextLine} -`; - i += 1; - continue; - } else { - break; - } - } - const nextIndent = ((_d = (_c = nextLine.match(/^(\s*)/)) == null ? void 0 : _c[1]) == null ? void 0 : _d.length) || 0; - if (nextIndent > indentLevel) { - itemContent.push(nextLine); - totalRaw = `${totalRaw}${nextLine} -`; - i += 1; - } else { - break; - } - } - let nestedTokens; - const nestedContent = itemContent.slice(1); - if (nestedContent.length > 0) { - const dedentedNested = nestedContent.map((nestedLine) => nestedLine.slice(indentLevel + baseIndentSize)).join("\n"); - if (dedentedNested.trim()) { - if (config.customNestedParser) { - nestedTokens = config.customNestedParser(dedentedNested); - } else { - nestedTokens = lexer.blockTokens(dedentedNested); - } - } - } - const token = config.createToken(itemData, nestedTokens); - items.push(token); - } - if (items.length === 0) { - return void 0; - } - return { - items, - raw: totalRaw - }; -} -function renderNestedMarkdownContent(node, h2, prefixOrGenerator, ctx) { - if (!node || !Array.isArray(node.content)) { - return ""; - } - const prefix = typeof prefixOrGenerator === "function" ? prefixOrGenerator(ctx) : prefixOrGenerator; - const [content, ...children] = node.content; - const mainContent = h2.renderChildren([content]); - let output = `${prefix}${mainContent}`; - if (children && children.length > 0) { - children.forEach((child, index) => { - var _a, _b; - const childContent = (_b = (_a = h2.renderChild) == null ? void 0 : _a.call(h2, child, index + 1)) != null ? _b : h2.renderChildren([child]); - if (childContent !== void 0 && childContent !== null) { - const indentedChild = childContent.split("\n").map((line) => line ? h2.indent(line) : h2.indent("")).join("\n"); - output += child.type === "paragraph" ? ` - -${indentedChild}` : ` -${indentedChild}`; - } - }); - } - return output; -} -function updateMarkViewAttributes(checkMark, editor, attrs = {}) { - const { state } = editor; - const { doc: doc2, tr: tr2 } = state; - const thisMark = checkMark; - doc2.descendants((node, pos) => { - const from2 = tr2.mapping.map(pos); - const to = tr2.mapping.map(pos) + node.nodeSize; - let foundMark = null; - node.marks.forEach((mark) => { - if (mark !== thisMark) { - return false; - } - foundMark = mark; - }); - if (!foundMark) { - return; - } - let needsUpdate = false; - Object.keys(attrs).forEach((k) => { - if (attrs[k] !== foundMark.attrs[k]) { - needsUpdate = true; - } - }); - if (needsUpdate) { - const updatedMark = checkMark.type.create({ - ...checkMark.attrs, - ...attrs - }); - tr2.removeMark(from2, to, checkMark.type); - tr2.addMark(from2, to, updatedMark); - } - }); - if (tr2.docChanged) { - editor.view.dispatch(tr2); - } -} -var Node3 = class _Node extends Extendable { - constructor() { - super(...arguments); - this.type = "node"; - } - /** - * Create a new Node instance - * @param config - Node configuration object or a function that returns a configuration object - */ - static create(config = {}) { - const resolvedConfig = typeof config === "function" ? config() : config; - return new _Node(resolvedConfig); - } - configure(options) { - return super.configure(options); - } - extend(extendedConfig) { - const resolvedConfig = typeof extendedConfig === "function" ? extendedConfig() : extendedConfig; - return super.extend(resolvedConfig); - } -}; -function markPasteRule(config) { - return new PasteRule({ - find: config.find, - handler: ({ state, range, match, pasteEvent }) => { - const attributes = callOrReturn(config.getAttributes, void 0, match, pasteEvent); - if (attributes === false || attributes === null) { - return null; - } - const { tr: tr2 } = state; - const captureGroup = match[match.length - 1]; - const fullMatch = match[0]; - let markEnd = range.to; - if (captureGroup) { - const startSpaces = fullMatch.search(/\S/); - const textStart = range.from + fullMatch.indexOf(captureGroup); - const textEnd = textStart + captureGroup.length; - const excludedMarks = getMarksBetween(range.from, range.to, state.doc).filter((item) => { - const excluded = item.mark.type.excluded; - return excluded.find((type) => type === config.type && type !== item.mark.type); - }).filter((item) => item.to > textStart); - if (excludedMarks.length) { - return null; - } - if (textEnd < range.to) { - tr2.delete(textEnd, range.to); - } - if (textStart > range.from) { - tr2.delete(range.from + startSpaces, textStart); - } - markEnd = range.from + startSpaces + captureGroup.length; - tr2.addMark(range.from + startSpaces, markEnd, config.type.create(attributes || {})); - tr2.removeStoredMark(config.type); - } - } - }); -} -const { getOwnPropertyNames, getOwnPropertySymbols } = Object; -const { hasOwnProperty } = Object.prototype; -function combineComparators(comparatorA, comparatorB) { - return function isEqual(a, b, state) { - return comparatorA(a, b, state) && comparatorB(a, b, state); - }; -} -function createIsCircular(areItemsEqual) { - return function isCircular(a, b, state) { - if (!a || !b || typeof a !== "object" || typeof b !== "object") { - return areItemsEqual(a, b, state); - } - const { cache } = state; - const cachedA = cache.get(a); - const cachedB = cache.get(b); - if (cachedA && cachedB) { - return cachedA === b && cachedB === a; - } - cache.set(a, b); - cache.set(b, a); - const result = areItemsEqual(a, b, state); - cache.delete(a); - cache.delete(b); - return result; - }; -} -function getShortTag(value) { - return value != null ? value[Symbol.toStringTag] : void 0; -} -function getStrictProperties(object) { - return getOwnPropertyNames(object).concat(getOwnPropertySymbols(object)); -} -const hasOwn = ( - // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition - Object.hasOwn || ((object, property) => hasOwnProperty.call(object, property)) -); -function sameValueZeroEqual(a, b) { - return a === b || !a && !b && a !== a && b !== b; -} -const PREACT_VNODE = "__v"; -const PREACT_OWNER = "__o"; -const REACT_OWNER = "_owner"; -const { getOwnPropertyDescriptor, keys } = Object; -function areArrayBuffersEqual(a, b) { - return a.byteLength === b.byteLength && areTypedArraysEqual(new Uint8Array(a), new Uint8Array(b)); -} -function areArraysEqual(a, b, state) { - let index = a.length; - if (b.length !== index) { - return false; - } - while (index-- > 0) { - if (!state.equals(a[index], b[index], index, index, a, b, state)) { - return false; - } - } - return true; -} -function areDataViewsEqual(a, b) { - return a.byteLength === b.byteLength && areTypedArraysEqual(new Uint8Array(a.buffer, a.byteOffset, a.byteLength), new Uint8Array(b.buffer, b.byteOffset, b.byteLength)); -} -function areDatesEqual(a, b) { - return sameValueZeroEqual(a.getTime(), b.getTime()); -} -function areErrorsEqual(a, b) { - return a.name === b.name && a.message === b.message && a.cause === b.cause && a.stack === b.stack; -} -function areFunctionsEqual(a, b) { - return a === b; -} -function areMapsEqual(a, b, state) { - const size = a.size; - if (size !== b.size) { - return false; - } - if (!size) { - return true; - } - const matchedIndices = new Array(size); - const aIterable = a.entries(); - let aResult; - let bResult; - let index = 0; - while (aResult = aIterable.next()) { - if (aResult.done) { - break; - } - const bIterable = b.entries(); - let hasMatch = false; - let matchIndex = 0; - while (bResult = bIterable.next()) { - if (bResult.done) { - break; - } - if (matchedIndices[matchIndex]) { - matchIndex++; - continue; - } - const aEntry = aResult.value; - const bEntry = bResult.value; - if (state.equals(aEntry[0], bEntry[0], index, matchIndex, a, b, state) && state.equals(aEntry[1], bEntry[1], aEntry[0], bEntry[0], a, b, state)) { - hasMatch = matchedIndices[matchIndex] = true; - break; - } - matchIndex++; - } - if (!hasMatch) { - return false; - } - index++; - } - return true; -} -const areNumbersEqual = sameValueZeroEqual; -function areObjectsEqual(a, b, state) { - const properties = keys(a); - let index = properties.length; - if (keys(b).length !== index) { - return false; - } - while (index-- > 0) { - if (!isPropertyEqual(a, b, state, properties[index])) { - return false; - } - } - return true; -} -function areObjectsEqualStrict(a, b, state) { - const properties = getStrictProperties(a); - let index = properties.length; - if (getStrictProperties(b).length !== index) { - return false; - } - let property; - let descriptorA; - let descriptorB; - while (index-- > 0) { - property = properties[index]; - if (!isPropertyEqual(a, b, state, property)) { - return false; - } - descriptorA = getOwnPropertyDescriptor(a, property); - descriptorB = getOwnPropertyDescriptor(b, property); - if ((descriptorA || descriptorB) && (!descriptorA || !descriptorB || descriptorA.configurable !== descriptorB.configurable || descriptorA.enumerable !== descriptorB.enumerable || descriptorA.writable !== descriptorB.writable)) { - return false; - } - } - return true; -} -function arePrimitiveWrappersEqual(a, b) { - return sameValueZeroEqual(a.valueOf(), b.valueOf()); -} -function areRegExpsEqual(a, b) { - return a.source === b.source && a.flags === b.flags; -} -function areSetsEqual(a, b, state) { - const size = a.size; - if (size !== b.size) { - return false; - } - if (!size) { - return true; - } - const matchedIndices = new Array(size); - const aIterable = a.values(); - let aResult; - let bResult; - while (aResult = aIterable.next()) { - if (aResult.done) { - break; - } - const bIterable = b.values(); - let hasMatch = false; - let matchIndex = 0; - while (bResult = bIterable.next()) { - if (bResult.done) { - break; - } - if (!matchedIndices[matchIndex] && state.equals(aResult.value, bResult.value, aResult.value, bResult.value, a, b, state)) { - hasMatch = matchedIndices[matchIndex] = true; - break; - } - matchIndex++; - } - if (!hasMatch) { - return false; - } - } - return true; -} -function areTypedArraysEqual(a, b) { - let index = a.byteLength; - if (b.byteLength !== index || a.byteOffset !== b.byteOffset) { - return false; - } - while (index-- > 0) { - if (a[index] !== b[index]) { - return false; - } - } - return true; -} -function areUrlsEqual(a, b) { - return a.hostname === b.hostname && a.pathname === b.pathname && a.protocol === b.protocol && a.port === b.port && a.hash === b.hash && a.username === b.username && a.password === b.password; -} -function isPropertyEqual(a, b, state, property) { - if ((property === REACT_OWNER || property === PREACT_OWNER || property === PREACT_VNODE) && (a.$$typeof || b.$$typeof)) { - return true; - } - return hasOwn(b, property) && state.equals(a[property], b[property], property, property, a, b, state); -} -const ARRAY_BUFFER_TAG = "[object ArrayBuffer]"; -const ARGUMENTS_TAG = "[object Arguments]"; -const BOOLEAN_TAG = "[object Boolean]"; -const DATA_VIEW_TAG = "[object DataView]"; -const DATE_TAG = "[object Date]"; -const ERROR_TAG = "[object Error]"; -const MAP_TAG = "[object Map]"; -const NUMBER_TAG = "[object Number]"; -const OBJECT_TAG = "[object Object]"; -const REG_EXP_TAG = "[object RegExp]"; -const SET_TAG = "[object Set]"; -const STRING_TAG = "[object String]"; -const TYPED_ARRAY_TAGS = { - "[object Int8Array]": true, - "[object Uint8Array]": true, - "[object Uint8ClampedArray]": true, - "[object Int16Array]": true, - "[object Uint16Array]": true, - "[object Int32Array]": true, - "[object Uint32Array]": true, - "[object Float16Array]": true, - "[object Float32Array]": true, - "[object Float64Array]": true, - "[object BigInt64Array]": true, - "[object BigUint64Array]": true -}; -const URL_TAG = "[object URL]"; -const toString = Object.prototype.toString; -function createEqualityComparator({ areArrayBuffersEqual: areArrayBuffersEqual2, areArraysEqual: areArraysEqual2, areDataViewsEqual: areDataViewsEqual2, areDatesEqual: areDatesEqual2, areErrorsEqual: areErrorsEqual2, areFunctionsEqual: areFunctionsEqual2, areMapsEqual: areMapsEqual2, areNumbersEqual: areNumbersEqual2, areObjectsEqual: areObjectsEqual2, arePrimitiveWrappersEqual: arePrimitiveWrappersEqual2, areRegExpsEqual: areRegExpsEqual2, areSetsEqual: areSetsEqual2, areTypedArraysEqual: areTypedArraysEqual2, areUrlsEqual: areUrlsEqual2, unknownTagComparators }) { - return function comparator(a, b, state) { - if (a === b) { - return true; - } - if (a == null || b == null) { - return false; - } - const type = typeof a; - if (type !== typeof b) { - return false; - } - if (type !== "object") { - if (type === "number") { - return areNumbersEqual2(a, b, state); - } - if (type === "function") { - return areFunctionsEqual2(a, b, state); - } - return false; - } - const constructor = a.constructor; - if (constructor !== b.constructor) { - return false; - } - if (constructor === Object) { - return areObjectsEqual2(a, b, state); - } - if (Array.isArray(a)) { - return areArraysEqual2(a, b, state); - } - if (constructor === Date) { - return areDatesEqual2(a, b, state); - } - if (constructor === RegExp) { - return areRegExpsEqual2(a, b, state); - } - if (constructor === Map) { - return areMapsEqual2(a, b, state); - } - if (constructor === Set) { - return areSetsEqual2(a, b, state); - } - const tag = toString.call(a); - if (tag === DATE_TAG) { - return areDatesEqual2(a, b, state); - } - if (tag === REG_EXP_TAG) { - return areRegExpsEqual2(a, b, state); - } - if (tag === MAP_TAG) { - return areMapsEqual2(a, b, state); - } - if (tag === SET_TAG) { - return areSetsEqual2(a, b, state); - } - if (tag === OBJECT_TAG) { - return typeof a.then !== "function" && typeof b.then !== "function" && areObjectsEqual2(a, b, state); - } - if (tag === URL_TAG) { - return areUrlsEqual2(a, b, state); - } - if (tag === ERROR_TAG) { - return areErrorsEqual2(a, b, state); - } - if (tag === ARGUMENTS_TAG) { - return areObjectsEqual2(a, b, state); - } - if (TYPED_ARRAY_TAGS[tag]) { - return areTypedArraysEqual2(a, b, state); - } - if (tag === ARRAY_BUFFER_TAG) { - return areArrayBuffersEqual2(a, b, state); - } - if (tag === DATA_VIEW_TAG) { - return areDataViewsEqual2(a, b, state); - } - if (tag === BOOLEAN_TAG || tag === NUMBER_TAG || tag === STRING_TAG) { - return arePrimitiveWrappersEqual2(a, b, state); - } - if (unknownTagComparators) { - let unknownTagComparator = unknownTagComparators[tag]; - if (!unknownTagComparator) { - const shortTag = getShortTag(a); - if (shortTag) { - unknownTagComparator = unknownTagComparators[shortTag]; - } - } - if (unknownTagComparator) { - return unknownTagComparator(a, b, state); - } - } - return false; - }; -} -function createEqualityComparatorConfig({ circular, createCustomConfig, strict }) { - let config = { - areArrayBuffersEqual, - areArraysEqual: strict ? areObjectsEqualStrict : areArraysEqual, - areDataViewsEqual, - areDatesEqual, - areErrorsEqual, - areFunctionsEqual, - areMapsEqual: strict ? combineComparators(areMapsEqual, areObjectsEqualStrict) : areMapsEqual, - areNumbersEqual, - areObjectsEqual: strict ? areObjectsEqualStrict : areObjectsEqual, - arePrimitiveWrappersEqual, - areRegExpsEqual, - areSetsEqual: strict ? combineComparators(areSetsEqual, areObjectsEqualStrict) : areSetsEqual, - areTypedArraysEqual: strict ? combineComparators(areTypedArraysEqual, areObjectsEqualStrict) : areTypedArraysEqual, - areUrlsEqual, - unknownTagComparators: void 0 - }; - if (createCustomConfig) { - config = Object.assign({}, config, createCustomConfig(config)); - } - if (circular) { - const areArraysEqual2 = createIsCircular(config.areArraysEqual); - const areMapsEqual2 = createIsCircular(config.areMapsEqual); - const areObjectsEqual2 = createIsCircular(config.areObjectsEqual); - const areSetsEqual2 = createIsCircular(config.areSetsEqual); - config = Object.assign({}, config, { - areArraysEqual: areArraysEqual2, - areMapsEqual: areMapsEqual2, - areObjectsEqual: areObjectsEqual2, - areSetsEqual: areSetsEqual2 - }); - } - return config; -} -function createInternalEqualityComparator(compare) { - return function(a, b, _indexOrKeyA, _indexOrKeyB, _parentA, _parentB, state) { - return compare(a, b, state); - }; -} -function createIsEqual({ circular, comparator, createState, equals, strict }) { - if (createState) { - return function isEqual(a, b) { - const { cache = circular ? /* @__PURE__ */ new WeakMap() : void 0, meta } = createState(); - return comparator(a, b, { - cache, - equals, - meta, - strict - }); - }; - } - if (circular) { - return function isEqual(a, b) { - return comparator(a, b, { - cache: /* @__PURE__ */ new WeakMap(), - equals, - meta: void 0, - strict - }); - }; - } - const state = { - cache: void 0, - equals, - meta: void 0, - strict - }; - return function isEqual(a, b) { - return comparator(a, b, state); - }; -} -const deepEqual = createCustomEqual(); -createCustomEqual({ strict: true }); -createCustomEqual({ circular: true }); -createCustomEqual({ - circular: true, - strict: true -}); -createCustomEqual({ - createInternalComparator: () => sameValueZeroEqual -}); -createCustomEqual({ - strict: true, - createInternalComparator: () => sameValueZeroEqual -}); -createCustomEqual({ - circular: true, - createInternalComparator: () => sameValueZeroEqual -}); -createCustomEqual({ - circular: true, - createInternalComparator: () => sameValueZeroEqual, - strict: true -}); -function createCustomEqual(options = {}) { - const { circular = false, createInternalComparator: createCustomInternalComparator, createState, strict = false } = options; - const config = createEqualityComparatorConfig(options); - const comparator = createEqualityComparator(config); - const equals = createCustomInternalComparator ? createCustomInternalComparator(comparator) : createInternalEqualityComparator(comparator); - return createIsEqual({ circular, comparator, createState, equals, strict }); -} -var withSelector = { exports: {} }; -var withSelector_production = {}; -var hasRequiredWithSelector_production; -function requireWithSelector_production() { - if (hasRequiredWithSelector_production) return withSelector_production; - hasRequiredWithSelector_production = 1; - var React2 = requireReact(), shim2 = requireShim(); - function is(x, y) { - return x === y && (0 !== x || 1 / x === 1 / y) || x !== x && y !== y; - } - var objectIs = "function" === typeof Object.is ? Object.is : is, useSyncExternalStore = shim2.useSyncExternalStore, useRef = React2.useRef, useEffect = React2.useEffect, useMemo = React2.useMemo, useDebugValue = React2.useDebugValue; - withSelector_production.useSyncExternalStoreWithSelector = function(subscribe, getSnapshot, getServerSnapshot, selector, isEqual) { - var instRef = useRef(null); - if (null === instRef.current) { - var inst = { hasValue: false, value: null }; - instRef.current = inst; - } else inst = instRef.current; - instRef = useMemo( - function() { - function memoizedSelector(nextSnapshot) { - if (!hasMemo) { - hasMemo = true; - memoizedSnapshot = nextSnapshot; - nextSnapshot = selector(nextSnapshot); - if (void 0 !== isEqual && inst.hasValue) { - var currentSelection = inst.value; - if (isEqual(currentSelection, nextSnapshot)) - return memoizedSelection = currentSelection; - } - return memoizedSelection = nextSnapshot; - } - currentSelection = memoizedSelection; - if (objectIs(memoizedSnapshot, nextSnapshot)) return currentSelection; - var nextSelection = selector(nextSnapshot); - if (void 0 !== isEqual && isEqual(currentSelection, nextSelection)) - return memoizedSnapshot = nextSnapshot, currentSelection; - memoizedSnapshot = nextSnapshot; - return memoizedSelection = nextSelection; - } - var hasMemo = false, memoizedSnapshot, memoizedSelection, maybeGetServerSnapshot = void 0 === getServerSnapshot ? null : getServerSnapshot; - return [ - function() { - return memoizedSelector(getSnapshot()); - }, - null === maybeGetServerSnapshot ? void 0 : function() { - return memoizedSelector(maybeGetServerSnapshot()); - } - ]; - }, - [getSnapshot, getServerSnapshot, selector, isEqual] - ); - var value = useSyncExternalStore(subscribe, instRef[0], instRef[1]); - useEffect( - function() { - inst.hasValue = true; - inst.value = value; - }, - [value] - ); - useDebugValue(value); - return value; - }; - return withSelector_production; -} -var withSelector_development = {}; -var hasRequiredWithSelector_development; -function requireWithSelector_development() { - if (hasRequiredWithSelector_development) return withSelector_development; - hasRequiredWithSelector_development = 1; - "production" !== process.env.NODE_ENV && (function() { - function is(x, y) { - return x === y && (0 !== x || 1 / x === 1 / y) || x !== x && y !== y; - } - "undefined" !== typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ && "function" === typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart && __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(Error()); - var React2 = requireReact(), shim2 = requireShim(), objectIs = "function" === typeof Object.is ? Object.is : is, useSyncExternalStore = shim2.useSyncExternalStore, useRef = React2.useRef, useEffect = React2.useEffect, useMemo = React2.useMemo, useDebugValue = React2.useDebugValue; - withSelector_development.useSyncExternalStoreWithSelector = function(subscribe, getSnapshot, getServerSnapshot, selector, isEqual) { - var instRef = useRef(null); - if (null === instRef.current) { - var inst = { hasValue: false, value: null }; - instRef.current = inst; - } else inst = instRef.current; - instRef = useMemo( - function() { - function memoizedSelector(nextSnapshot) { - if (!hasMemo) { - hasMemo = true; - memoizedSnapshot = nextSnapshot; - nextSnapshot = selector(nextSnapshot); - if (void 0 !== isEqual && inst.hasValue) { - var currentSelection = inst.value; - if (isEqual(currentSelection, nextSnapshot)) - return memoizedSelection = currentSelection; - } - return memoizedSelection = nextSnapshot; - } - currentSelection = memoizedSelection; - if (objectIs(memoizedSnapshot, nextSnapshot)) - return currentSelection; - var nextSelection = selector(nextSnapshot); - if (void 0 !== isEqual && isEqual(currentSelection, nextSelection)) - return memoizedSnapshot = nextSnapshot, currentSelection; - memoizedSnapshot = nextSnapshot; - return memoizedSelection = nextSelection; - } - var hasMemo = false, memoizedSnapshot, memoizedSelection, maybeGetServerSnapshot = void 0 === getServerSnapshot ? null : getServerSnapshot; - return [ - function() { - return memoizedSelector(getSnapshot()); - }, - null === maybeGetServerSnapshot ? void 0 : function() { - return memoizedSelector(maybeGetServerSnapshot()); - } - ]; - }, - [getSnapshot, getServerSnapshot, selector, isEqual] - ); - var value = useSyncExternalStore(subscribe, instRef[0], instRef[1]); - useEffect( - function() { - inst.hasValue = true; - inst.value = value; - }, - [value] - ); - useDebugValue(value); - return value; - }; - "undefined" !== typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ && "function" === typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop && __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(Error()); - })(); - return withSelector_development; -} -var hasRequiredWithSelector; -function requireWithSelector() { - if (hasRequiredWithSelector) return withSelector.exports; - hasRequiredWithSelector = 1; - if (process.env.NODE_ENV === "production") { - withSelector.exports = requireWithSelector_production(); - } else { - withSelector.exports = requireWithSelector_development(); - } - return withSelector.exports; -} -var withSelectorExports = requireWithSelector(); -var mergeRefs = (...refs) => { - return (node) => { - refs.forEach((ref) => { - if (typeof ref === "function") { - ref(node); - } else if (ref) { - ref.current = node; - } - }); - }; -}; -var Portals = ({ contentComponent }) => { - const renderers = shimExports.useSyncExternalStore( - contentComponent.subscribe, - contentComponent.getSnapshot, - contentComponent.getServerSnapshot - ); - return /* @__PURE__ */ jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment, { children: Object.values(renderers) }); -}; -function getInstance() { - const subscribers = /* @__PURE__ */ new Set(); - let renderers = {}; - return { - /** - * Subscribe to the editor instance's changes. - */ - subscribe(callback) { - subscribers.add(callback); - return () => { - subscribers.delete(callback); - }; - }, - getSnapshot() { - return renderers; - }, - getServerSnapshot() { - return renderers; - }, - /** - * Adds a new NodeView Renderer to the editor. - */ - setRenderer(id, renderer) { - renderers = { - ...renderers, - [id]: ReactDOM.createPortal(renderer.reactElement, renderer.element, id) - }; - subscribers.forEach((subscriber) => subscriber()); - }, - /** - * Removes a NodeView Renderer from the editor. - */ - removeRenderer(id) { - const nextRenderers = { ...renderers }; - delete nextRenderers[id]; - renderers = nextRenderers; - subscribers.forEach((subscriber) => subscriber()); - } - }; -} -var PureEditorContent = class extends React.Component { - constructor(props) { - var _a; - super(props); - this.editorContentRef = React.createRef(); - this.initialized = false; - this.state = { - hasContentComponentInitialized: Boolean((_a = props.editor) == null ? void 0 : _a.contentComponent) - }; - } - componentDidMount() { - this.init(); - } - componentDidUpdate() { - this.init(); - } - init() { - var _a; - const editor = this.props.editor; - if (editor && !editor.isDestroyed && ((_a = editor.view.dom) == null ? void 0 : _a.parentNode)) { - if (editor.contentComponent) { - return; - } - const element = this.editorContentRef.current; - element.append(...editor.view.dom.parentNode.childNodes); - editor.setOptions({ - element - }); - editor.contentComponent = getInstance(); - if (!this.state.hasContentComponentInitialized) { - this.unsubscribeToContentComponent = editor.contentComponent.subscribe(() => { - this.setState((prevState) => { - if (!prevState.hasContentComponentInitialized) { - return { - hasContentComponentInitialized: true - }; - } - return prevState; - }); - if (this.unsubscribeToContentComponent) { - this.unsubscribeToContentComponent(); - } - }); - } - editor.createNodeViews(); - this.initialized = true; - } - } - componentWillUnmount() { - var _a; - const editor = this.props.editor; - if (!editor) { - return; - } - this.initialized = false; - if (!editor.isDestroyed) { - editor.view.setProps({ - nodeViews: {} - }); - } - if (this.unsubscribeToContentComponent) { - this.unsubscribeToContentComponent(); - } - editor.contentComponent = null; - try { - if (!((_a = editor.view.dom) == null ? void 0 : _a.parentNode)) { - return; - } - const newElement = document.createElement("div"); - newElement.append(...editor.view.dom.parentNode.childNodes); - editor.setOptions({ - element: newElement - }); - } catch { - } - } - render() { - const { editor, innerRef, ...rest } = this.props; - return /* @__PURE__ */ jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [ - /* @__PURE__ */ jsxRuntimeExports.jsx("div", { ref: mergeRefs(innerRef, this.editorContentRef), ...rest }), - (editor == null ? void 0 : editor.contentComponent) && /* @__PURE__ */ jsxRuntimeExports.jsx(Portals, { contentComponent: editor.contentComponent }) - ] }); - } -}; -var EditorContentWithKey = reactExports.forwardRef( - (props, ref) => { - const key = React.useMemo(() => { - return Math.floor(Math.random() * 4294967295).toString(); - }, [props.editor]); - return React.createElement(PureEditorContent, { - key, - innerRef: ref, - ...props - }); - } -); -var EditorContent = React.memo(EditorContentWithKey); -var useIsomorphicLayoutEffect = typeof window !== "undefined" ? reactExports.useLayoutEffect : reactExports.useEffect; -var EditorStateManager = class { - constructor(initialEditor) { - this.transactionNumber = 0; - this.lastTransactionNumber = 0; - this.subscribers = /* @__PURE__ */ new Set(); - this.editor = initialEditor; - this.lastSnapshot = { editor: initialEditor, transactionNumber: 0 }; - this.getSnapshot = this.getSnapshot.bind(this); - this.getServerSnapshot = this.getServerSnapshot.bind(this); - this.watch = this.watch.bind(this); - this.subscribe = this.subscribe.bind(this); - } - /** - * Get the current editor instance. - */ - getSnapshot() { - if (this.transactionNumber === this.lastTransactionNumber) { - return this.lastSnapshot; - } - this.lastTransactionNumber = this.transactionNumber; - this.lastSnapshot = { editor: this.editor, transactionNumber: this.transactionNumber }; - return this.lastSnapshot; - } - /** - * Always disable the editor on the server-side. - */ - getServerSnapshot() { - return { editor: null, transactionNumber: 0 }; - } - /** - * Subscribe to the editor instance's changes. - */ - subscribe(callback) { - this.subscribers.add(callback); - return () => { - this.subscribers.delete(callback); - }; - } - /** - * Watch the editor instance for changes. - */ - watch(nextEditor) { - this.editor = nextEditor; - if (this.editor) { - const fn = () => { - this.transactionNumber += 1; - this.subscribers.forEach((callback) => callback()); - }; - const currentEditor = this.editor; - currentEditor.on("transaction", fn); - return () => { - currentEditor.off("transaction", fn); - }; - } - return void 0; - } -}; -function useEditorState(options) { - var _a; - const [editorStateManager] = reactExports.useState(() => new EditorStateManager(options.editor)); - const selectedState = withSelectorExports.useSyncExternalStoreWithSelector( - editorStateManager.subscribe, - editorStateManager.getSnapshot, - editorStateManager.getServerSnapshot, - options.selector, - (_a = options.equalityFn) != null ? _a : deepEqual - ); - useIsomorphicLayoutEffect(() => { - return editorStateManager.watch(options.editor); - }, [options.editor, editorStateManager]); - reactExports.useDebugValue(selectedState); - return selectedState; -} -var isDev = process.env.NODE_ENV !== "production"; -var isSSR = typeof window === "undefined"; -var isNext = isSSR || Boolean(typeof window !== "undefined" && window.next); -var EditorInstanceManager = class _EditorInstanceManager { - constructor(options) { - this.editor = null; - this.subscriptions = /* @__PURE__ */ new Set(); - this.isComponentMounted = false; - this.previousDeps = null; - this.instanceId = ""; - this.options = options; - this.subscriptions = /* @__PURE__ */ new Set(); - this.setEditor(this.getInitialEditor()); - this.scheduleDestroy(); - this.getEditor = this.getEditor.bind(this); - this.getServerSnapshot = this.getServerSnapshot.bind(this); - this.subscribe = this.subscribe.bind(this); - this.refreshEditorInstance = this.refreshEditorInstance.bind(this); - this.scheduleDestroy = this.scheduleDestroy.bind(this); - this.onRender = this.onRender.bind(this); - this.createEditor = this.createEditor.bind(this); - } - setEditor(editor) { - this.editor = editor; - this.instanceId = Math.random().toString(36).slice(2, 9); - this.subscriptions.forEach((cb) => cb()); - } - getInitialEditor() { - if (this.options.current.immediatelyRender === void 0) { - if (isSSR || isNext) { - if (isDev) { - throw new Error( - "Tiptap Error: SSR has been detected, please set `immediatelyRender` explicitly to `false` to avoid hydration mismatches." - ); - } - return null; - } - return this.createEditor(); - } - if (this.options.current.immediatelyRender && isSSR && isDev) { - throw new Error( - "Tiptap Error: SSR has been detected, and `immediatelyRender` has been set to `true` this is an unsupported configuration that may result in errors, explicitly set `immediatelyRender` to `false` to avoid hydration mismatches." - ); - } - if (this.options.current.immediatelyRender) { - return this.createEditor(); - } - return null; - } - /** - * Create a new editor instance. And attach event listeners. - */ - createEditor() { - const optionsToApply = { - ...this.options.current, - // Always call the most recent version of the callback function by default - onBeforeCreate: (...args) => { - var _a, _b; - return (_b = (_a = this.options.current).onBeforeCreate) == null ? void 0 : _b.call(_a, ...args); - }, - onBlur: (...args) => { - var _a, _b; - return (_b = (_a = this.options.current).onBlur) == null ? void 0 : _b.call(_a, ...args); - }, - onCreate: (...args) => { - var _a, _b; - return (_b = (_a = this.options.current).onCreate) == null ? void 0 : _b.call(_a, ...args); - }, - onDestroy: (...args) => { - var _a, _b; - return (_b = (_a = this.options.current).onDestroy) == null ? void 0 : _b.call(_a, ...args); - }, - onFocus: (...args) => { - var _a, _b; - return (_b = (_a = this.options.current).onFocus) == null ? void 0 : _b.call(_a, ...args); - }, - onSelectionUpdate: (...args) => { - var _a, _b; - return (_b = (_a = this.options.current).onSelectionUpdate) == null ? void 0 : _b.call(_a, ...args); - }, - onTransaction: (...args) => { - var _a, _b; - return (_b = (_a = this.options.current).onTransaction) == null ? void 0 : _b.call(_a, ...args); - }, - onUpdate: (...args) => { - var _a, _b; - return (_b = (_a = this.options.current).onUpdate) == null ? void 0 : _b.call(_a, ...args); - }, - onContentError: (...args) => { - var _a, _b; - return (_b = (_a = this.options.current).onContentError) == null ? void 0 : _b.call(_a, ...args); - }, - onDrop: (...args) => { - var _a, _b; - return (_b = (_a = this.options.current).onDrop) == null ? void 0 : _b.call(_a, ...args); - }, - onPaste: (...args) => { - var _a, _b; - return (_b = (_a = this.options.current).onPaste) == null ? void 0 : _b.call(_a, ...args); - }, - onDelete: (...args) => { - var _a, _b; - return (_b = (_a = this.options.current).onDelete) == null ? void 0 : _b.call(_a, ...args); - } - }; - const editor = new Editor(optionsToApply); - return editor; - } - /** - * Get the current editor instance. - */ - getEditor() { - return this.editor; - } - /** - * Always disable the editor on the server-side. - */ - getServerSnapshot() { - return null; - } - /** - * Subscribe to the editor instance's changes. - */ - subscribe(onStoreChange) { - this.subscriptions.add(onStoreChange); - return () => { - this.subscriptions.delete(onStoreChange); - }; - } - static compareOptions(a, b) { - return Object.keys(a).every((key) => { - if ([ - "onCreate", - "onBeforeCreate", - "onDestroy", - "onUpdate", - "onTransaction", - "onFocus", - "onBlur", - "onSelectionUpdate", - "onContentError", - "onDrop", - "onPaste" - ].includes(key)) { - return true; - } - if (key === "extensions" && a.extensions && b.extensions) { - if (a.extensions.length !== b.extensions.length) { - return false; - } - return a.extensions.every((extension, index) => { - var _a; - if (extension !== ((_a = b.extensions) == null ? void 0 : _a[index])) { - return false; - } - return true; - }); - } - if (a[key] !== b[key]) { - return false; - } - return true; - }); - } - /** - * On each render, we will create, update, or destroy the editor instance. - * @param deps The dependencies to watch for changes - * @returns A cleanup function - */ - onRender(deps) { - return () => { - this.isComponentMounted = true; - clearTimeout(this.scheduledDestructionTimeout); - if (this.editor && !this.editor.isDestroyed && deps.length === 0) { - if (!_EditorInstanceManager.compareOptions(this.options.current, this.editor.options)) { - this.editor.setOptions({ - ...this.options.current, - editable: this.editor.isEditable - }); - } - } else { - this.refreshEditorInstance(deps); - } - return () => { - this.isComponentMounted = false; - this.scheduleDestroy(); - }; - }; - } - /** - * Recreate the editor instance if the dependencies have changed. - */ - refreshEditorInstance(deps) { - if (this.editor && !this.editor.isDestroyed) { - if (this.previousDeps === null) { - this.previousDeps = deps; - return; - } - const depsAreEqual = this.previousDeps.length === deps.length && this.previousDeps.every((dep, index) => dep === deps[index]); - if (depsAreEqual) { - return; - } - } - if (this.editor && !this.editor.isDestroyed) { - this.editor.destroy(); - } - this.setEditor(this.createEditor()); - this.previousDeps = deps; - } - /** - * Schedule the destruction of the editor instance. - * This will only destroy the editor if it was not mounted on the next tick. - * This is to avoid destroying the editor instance when it's actually still mounted. - */ - scheduleDestroy() { - const currentInstanceId = this.instanceId; - const currentEditor = this.editor; - this.scheduledDestructionTimeout = setTimeout(() => { - if (this.isComponentMounted && this.instanceId === currentInstanceId) { - if (currentEditor) { - currentEditor.setOptions(this.options.current); - } - return; - } - if (currentEditor && !currentEditor.isDestroyed) { - currentEditor.destroy(); - if (this.instanceId === currentInstanceId) { - this.setEditor(null); - } - } - }, 1); - } -}; -function useEditor(options = {}, deps = []) { - const mostRecentOptions = reactExports.useRef(options); - mostRecentOptions.current = options; - const [instanceManager] = reactExports.useState(() => new EditorInstanceManager(mostRecentOptions)); - const editor = shimExports.useSyncExternalStore( - instanceManager.subscribe, - instanceManager.getEditor, - instanceManager.getServerSnapshot - ); - reactExports.useDebugValue(editor); - reactExports.useEffect(instanceManager.onRender(deps)); - useEditorState({ - editor, - selector: ({ transactionNumber }) => { - if (options.shouldRerenderOnTransaction === false || options.shouldRerenderOnTransaction === void 0) { - return null; - } - if (options.immediatelyRender && transactionNumber === 0) { - return 0; - } - return transactionNumber + 1; - } - }); - return editor; -} -var EditorContext = reactExports.createContext({ - editor: null -}); -EditorContext.Consumer; -var ReactNodeViewContext = reactExports.createContext({ - onDragStart: () => { - }, - nodeViewContentChildren: void 0, - nodeViewContentRef: () => { - } -}); -var useReactNodeView = () => reactExports.useContext(ReactNodeViewContext); -React.forwardRef((props, ref) => { - const { onDragStart } = useReactNodeView(); - const Tag = props.as || "div"; - return ( - // @ts-ignore - /* @__PURE__ */ jsxRuntimeExports.jsx( - Tag, - { - ...props, - ref, - "data-node-view-wrapper": "", - onDragStart, - style: { - whiteSpace: "normal", - ...props.style - } - } - ) - ); -}); -function isClassComponent(Component) { - return !!(typeof Component === "function" && Component.prototype && Component.prototype.isReactComponent); -} -function isForwardRefComponent(Component) { - return !!(typeof Component === "object" && Component.$$typeof && (Component.$$typeof.toString() === "Symbol(react.forward_ref)" || Component.$$typeof.description === "react.forward_ref")); -} -function isMemoComponent(Component) { - return !!(typeof Component === "object" && Component.$$typeof && (Component.$$typeof.toString() === "Symbol(react.memo)" || Component.$$typeof.description === "react.memo")); -} -function canReceiveRef(Component) { - if (isClassComponent(Component)) { - return true; - } - if (isForwardRefComponent(Component)) { - return true; - } - if (isMemoComponent(Component)) { - const wrappedComponent = Component.type; - if (wrappedComponent) { - return isClassComponent(wrappedComponent) || isForwardRefComponent(wrappedComponent); - } - } - return false; -} -function isReact19Plus() { - try { - if (reactExports.version) { - const majorVersion = parseInt(reactExports.version.split(".")[0], 10); - return majorVersion >= 19; - } - } catch { - } - return false; -} -var ReactRenderer = class { - /** - * Immediately creates element and renders the provided React component. - */ - constructor(component, { editor, props = {}, as = "div", className = "" }) { - this.ref = null; - this.destroyed = false; - this.id = Math.floor(Math.random() * 4294967295).toString(); - this.component = component; - this.editor = editor; - this.props = props; - this.element = document.createElement(as); - this.element.classList.add("react-renderer"); - if (className) { - this.element.classList.add(...className.split(" ")); - } - if (this.editor.isInitialized) { - reactDomExports.flushSync(() => { - this.render(); - }); - } else { - queueMicrotask(() => { - if (this.destroyed) { - return; - } - this.render(); - }); - } - } - /** - * Render the React component. - */ - render() { - var _a; - if (this.destroyed) { - return; - } - const Component = this.component; - const props = this.props; - const editor = this.editor; - const isReact19 = isReact19Plus(); - const componentCanReceiveRef = canReceiveRef(Component); - const elementProps = { ...props }; - if (elementProps.ref && !(isReact19 || componentCanReceiveRef)) { - delete elementProps.ref; - } - if (!elementProps.ref && (isReact19 || componentCanReceiveRef)) { - elementProps.ref = (ref) => { - this.ref = ref; - }; - } - this.reactElement = /* @__PURE__ */ jsxRuntimeExports.jsx(Component, { ...elementProps }); - (_a = editor == null ? void 0 : editor.contentComponent) == null ? void 0 : _a.setRenderer(this.id, this); - } - /** - * Re-renders the React component with new props. - */ - updateProps(props = {}) { - if (this.destroyed) { - return; - } - this.props = { - ...this.props, - ...props - }; - this.render(); - } - /** - * Destroy the React component. - */ - destroy() { - var _a; - this.destroyed = true; - const editor = this.editor; - (_a = editor == null ? void 0 : editor.contentComponent) == null ? void 0 : _a.removeRenderer(this.id); - try { - if (this.element && this.element.parentNode) { - this.element.parentNode.removeChild(this.element); - } - } catch { - } - } - /** - * Update the attributes of the element that holds the React component. - */ - updateAttributes(attributes) { - Object.keys(attributes).forEach((key) => { - this.element.setAttribute(key, attributes[key]); - }); - } -}; -React.createContext({ - markViewContentRef: () => { - } -}); -var TiptapContext = reactExports.createContext({ - get editor() { - throw new Error("useTiptap must be used within a provider"); - } -}); -TiptapContext.displayName = "TiptapContext"; -var useTiptap = () => reactExports.useContext(TiptapContext); -function TiptapWrapper({ editor, instance, children }) { - const resolvedEditor = editor != null ? editor : instance; - if (!resolvedEditor) { - throw new Error("Tiptap: An editor instance is required. Pass a non-null `editor` prop."); - } - const tiptapContextValue = reactExports.useMemo(() => ({ editor: resolvedEditor }), [resolvedEditor]); - const legacyContextValue = reactExports.useMemo(() => ({ editor: resolvedEditor }), [resolvedEditor]); - return /* @__PURE__ */ jsxRuntimeExports.jsx(EditorContext.Provider, { value: legacyContextValue, children: /* @__PURE__ */ jsxRuntimeExports.jsx(TiptapContext.Provider, { value: tiptapContextValue, children }) }); -} -TiptapWrapper.displayName = "Tiptap"; -function TiptapContent({ ...rest }) { - const { editor } = useTiptap(); - return /* @__PURE__ */ jsxRuntimeExports.jsx(EditorContent, { editor, ...rest }); -} -TiptapContent.displayName = "Tiptap.Content"; -Object.assign(TiptapWrapper, { - /** - * The Tiptap Content component that renders the EditorContent with the editor instance from the context. - * @see TiptapContent - */ - Content: TiptapContent -}); -var h = (tag, attributes) => { - if (tag === "slot") { - return 0; - } - if (tag instanceof Function) { - return tag(attributes); - } - const { children, ...rest } = attributes != null ? attributes : {}; - if (tag === "svg") { - throw new Error("SVG elements are not supported in the JSX syntax, use the array syntax instead"); - } - return [tag, rest, children]; -}; -var inputRegex$4 = /^\s*>\s$/; -var Blockquote = Node3.create({ - name: "blockquote", - addOptions() { - return { - HTMLAttributes: {} - }; - }, - content: "block+", - group: "block", - defining: true, - parseHTML() { - return [{ tag: "blockquote" }]; - }, - renderHTML({ HTMLAttributes }) { - return /* @__PURE__ */ h("blockquote", { ...mergeAttributes(this.options.HTMLAttributes, HTMLAttributes), children: /* @__PURE__ */ h("slot", {}) }); - }, - parseMarkdown: (token, helpers) => { - var _a; - const parseBlockChildren = (_a = helpers.parseBlockChildren) != null ? _a : helpers.parseChildren; - return helpers.createNode("blockquote", void 0, parseBlockChildren(token.tokens || [])); - }, - renderMarkdown: (node, h2) => { - if (!node.content) { - return ""; - } - const prefix = ">"; - const result = []; - node.content.forEach((child, index) => { - var _a, _b; - const childContent = (_b = (_a = h2.renderChild) == null ? void 0 : _a.call(h2, child, index)) != null ? _b : h2.renderChildren([child]); - const lines = childContent.split("\n"); - const linesWithPrefix = lines.map((line) => { - if (line.trim() === "") { - return prefix; - } - return `${prefix} ${line}`; - }); - result.push(linesWithPrefix.join("\n")); - }); - return result.join(` -${prefix} -`); - }, - addCommands() { - return { - setBlockquote: () => ({ commands }) => { - return commands.wrapIn(this.name); - }, - toggleBlockquote: () => ({ commands }) => { - return commands.toggleWrap(this.name); - }, - unsetBlockquote: () => ({ commands }) => { - return commands.lift(this.name); - } - }; - }, - addKeyboardShortcuts() { - return { - "Mod-Shift-b": () => this.editor.commands.toggleBlockquote() - }; - }, - addInputRules() { - return [ - wrappingInputRule({ - find: inputRegex$4, - type: this.type - }) - ]; - } -}); -var starInputRegex$1 = /(?:^|\s)(\*\*(?!\s+\*\*)((?:[^*]+))\*\*(?!\s+\*\*))$/; -var starPasteRegex$1 = /(?:^|\s)(\*\*(?!\s+\*\*)((?:[^*]+))\*\*(?!\s+\*\*))/g; -var underscoreInputRegex$1 = /(?:^|\s)(__(?!\s+__)((?:[^_]+))__(?!\s+__))$/; -var underscorePasteRegex$1 = /(?:^|\s)(__(?!\s+__)((?:[^_]+))__(?!\s+__))/g; -var Bold = Mark2.create({ - name: "bold", - addOptions() { - return { - HTMLAttributes: {} - }; - }, - parseHTML() { - return [ - { - tag: "strong" - }, - { - tag: "b", - getAttrs: (node) => node.style.fontWeight !== "normal" && null - }, - { - style: "font-weight=400", - clearMark: (mark) => mark.type.name === this.name - }, - { - style: "font-weight", - getAttrs: (value) => /^(bold(er)?|[5-9]\d{2,})$/.test(value) && null - } - ]; - }, - renderHTML({ HTMLAttributes }) { - return /* @__PURE__ */ h("strong", { ...mergeAttributes(this.options.HTMLAttributes, HTMLAttributes), children: /* @__PURE__ */ h("slot", {}) }); - }, - markdownTokenName: "strong", - parseMarkdown: (token, helpers) => { - return helpers.applyMark("bold", helpers.parseInline(token.tokens || [])); - }, - markdownOptions: { - htmlReopen: { - open: "", - close: "" - } - }, - renderMarkdown: (node, h2) => { - return `**${h2.renderChildren(node)}**`; - }, - addCommands() { - return { - setBold: () => ({ commands }) => { - return commands.setMark(this.name); - }, - toggleBold: () => ({ commands }) => { - return commands.toggleMark(this.name); - }, - unsetBold: () => ({ commands }) => { - return commands.unsetMark(this.name); - } - }; - }, - addKeyboardShortcuts() { - return { - "Mod-b": () => this.editor.commands.toggleBold(), - "Mod-B": () => this.editor.commands.toggleBold() - }; - }, - addInputRules() { - return [ - markInputRule({ - find: starInputRegex$1, - type: this.type - }), - markInputRule({ - find: underscoreInputRegex$1, - type: this.type - }) - ]; - }, - addPasteRules() { - return [ - markPasteRule({ - find: starPasteRegex$1, - type: this.type - }), - markPasteRule({ - find: underscorePasteRegex$1, - type: this.type - }) - ]; - } -}); -var inputRegex$3 = /(^|[^`])`([^`]+)`(?!`)$/; -var pasteRegex$1 = /(^|[^`])`([^`]+)`(?!`)/g; -var Code = Mark2.create({ - name: "code", - addOptions() { - return { - HTMLAttributes: {} - }; - }, - excludes: "_", - code: true, - exitable: true, - parseHTML() { - return [{ tag: "code" }]; - }, - renderHTML({ HTMLAttributes }) { - return ["code", mergeAttributes(this.options.HTMLAttributes, HTMLAttributes), 0]; - }, - markdownTokenName: "codespan", - parseMarkdown: (token, helpers) => { - return helpers.applyMark("code", [{ type: "text", text: token.text || "" }]); - }, - renderMarkdown: (node, h2) => { - if (!node.content) { - return ""; - } - return `\`${h2.renderChildren(node.content)}\``; - }, - addCommands() { - return { - setCode: () => ({ commands }) => { - return commands.setMark(this.name); - }, - toggleCode: () => ({ commands }) => { - return commands.toggleMark(this.name); - }, - unsetCode: () => ({ commands }) => { - return commands.unsetMark(this.name); - } - }; - }, - addKeyboardShortcuts() { - return { - "Mod-e": () => this.editor.commands.toggleCode() - }; - }, - addInputRules() { - return [ - markInputRule({ - find: inputRegex$3, - type: this.type - }) - ]; - }, - addPasteRules() { - return [ - markPasteRule({ - find: pasteRegex$1, - type: this.type - }) - ]; - } -}); -var DEFAULT_TAB_SIZE = 4; -var backtickInputRegex = /^```([a-z]+)?[\s\n]$/; -var tildeInputRegex = /^~~~([a-z]+)?[\s\n]$/; -var CodeBlock = Node3.create({ - name: "codeBlock", - addOptions() { - return { - languageClassPrefix: "language-", - exitOnTripleEnter: true, - exitOnArrowDown: true, - defaultLanguage: null, - enableTabIndentation: false, - tabSize: DEFAULT_TAB_SIZE, - HTMLAttributes: {} - }; - }, - content: "text*", - marks: "", - group: "block", - code: true, - defining: true, - addAttributes() { - return { - language: { - default: this.options.defaultLanguage, - parseHTML: (element) => { - var _a; - const { languageClassPrefix } = this.options; - if (!languageClassPrefix) { - return null; - } - const classNames = [...((_a = element.firstElementChild) == null ? void 0 : _a.classList) || []]; - const languages = classNames.filter((className) => className.startsWith(languageClassPrefix)).map((className) => className.replace(languageClassPrefix, "")); - const language = languages[0]; - if (!language) { - return null; - } - return language; - }, - rendered: false - } - }; - }, - parseHTML() { - return [ - { - tag: "pre", - preserveWhitespace: "full" - } - ]; - }, - renderHTML({ node, HTMLAttributes }) { - return [ - "pre", - mergeAttributes(this.options.HTMLAttributes, HTMLAttributes), - [ - "code", - { - class: node.attrs.language ? this.options.languageClassPrefix + node.attrs.language : null - }, - 0 - ] - ]; - }, - markdownTokenName: "code", - parseMarkdown: (token, helpers) => { - var _a, _b; - if (((_a = token.raw) == null ? void 0 : _a.startsWith("```")) === false && ((_b = token.raw) == null ? void 0 : _b.startsWith("~~~")) === false && token.codeBlockStyle !== "indented") { - return []; - } - return helpers.createNode( - "codeBlock", - { language: token.lang || null }, - token.text ? [helpers.createTextNode(token.text)] : [] - ); - }, - renderMarkdown: (node, h2) => { - var _a; - let output = ""; - const language = ((_a = node.attrs) == null ? void 0 : _a.language) || ""; - if (!node.content) { - output = `\`\`\`${language} - -\`\`\``; - } else { - const lines = [`\`\`\`${language}`, h2.renderChildren(node.content), "```"]; - output = lines.join("\n"); - } - return output; - }, - addCommands() { - return { - setCodeBlock: (attributes) => ({ commands }) => { - return commands.setNode(this.name, attributes); - }, - toggleCodeBlock: (attributes) => ({ commands }) => { - return commands.toggleNode(this.name, "paragraph", attributes); - } - }; - }, - addKeyboardShortcuts() { - return { - "Mod-Alt-c": () => this.editor.commands.toggleCodeBlock(), - // remove code block when at start of document or code block is empty - Backspace: () => { - const { empty: empty2, $anchor } = this.editor.state.selection; - const isAtStart = $anchor.pos === 1; - if (!empty2 || $anchor.parent.type.name !== this.name) { - return false; - } - if (isAtStart || !$anchor.parent.textContent.length) { - return this.editor.commands.clearNodes(); - } - return false; - }, - // handle tab indentation - Tab: ({ editor }) => { - var _a; - if (!this.options.enableTabIndentation) { - return false; - } - const tabSize = (_a = this.options.tabSize) != null ? _a : DEFAULT_TAB_SIZE; - const { state } = editor; - const { selection } = state; - const { $from, empty: empty2 } = selection; - if ($from.parent.type !== this.type) { - return false; - } - const indent = " ".repeat(tabSize); - if (empty2) { - return editor.commands.insertContent(indent); - } - return editor.commands.command(({ tr: tr2 }) => { - const { from: from2, to } = selection; - const text = state.doc.textBetween(from2, to, "\n", "\n"); - const lines = text.split("\n"); - const indentedText = lines.map((line) => indent + line).join("\n"); - tr2.replaceWith(from2, to, state.schema.text(indentedText)); - return true; - }); - }, - // handle shift+tab reverse indentation - "Shift-Tab": ({ editor }) => { - var _a; - if (!this.options.enableTabIndentation) { - return false; - } - const tabSize = (_a = this.options.tabSize) != null ? _a : DEFAULT_TAB_SIZE; - const { state } = editor; - const { selection } = state; - const { $from, empty: empty2 } = selection; - if ($from.parent.type !== this.type) { - return false; - } - if (empty2) { - return editor.commands.command(({ tr: tr2 }) => { - var _a2; - const { pos } = $from; - const codeBlockStart = $from.start(); - const codeBlockEnd = $from.end(); - const allText = state.doc.textBetween(codeBlockStart, codeBlockEnd, "\n", "\n"); - const lines = allText.split("\n"); - let currentLineIndex = 0; - let charCount = 0; - const relativeCursorPos = pos - codeBlockStart; - for (let i = 0; i < lines.length; i += 1) { - if (charCount + lines[i].length >= relativeCursorPos) { - currentLineIndex = i; - break; - } - charCount += lines[i].length + 1; - } - const currentLine = lines[currentLineIndex]; - const leadingSpaces = ((_a2 = currentLine.match(/^ */)) == null ? void 0 : _a2[0]) || ""; - const spacesToRemove = Math.min(leadingSpaces.length, tabSize); - if (spacesToRemove === 0) { - return true; - } - let lineStartPos = codeBlockStart; - for (let i = 0; i < currentLineIndex; i += 1) { - lineStartPos += lines[i].length + 1; - } - tr2.delete(lineStartPos, lineStartPos + spacesToRemove); - const cursorPosInLine = pos - lineStartPos; - if (cursorPosInLine <= spacesToRemove) { - tr2.setSelection(TextSelection.create(tr2.doc, lineStartPos)); - } - return true; - }); - } - return editor.commands.command(({ tr: tr2 }) => { - const { from: from2, to } = selection; - const text = state.doc.textBetween(from2, to, "\n", "\n"); - const lines = text.split("\n"); - const reverseIndentText = lines.map((line) => { - var _a2; - const leadingSpaces = ((_a2 = line.match(/^ */)) == null ? void 0 : _a2[0]) || ""; - const spacesToRemove = Math.min(leadingSpaces.length, tabSize); - return line.slice(spacesToRemove); - }).join("\n"); - tr2.replaceWith(from2, to, state.schema.text(reverseIndentText)); - return true; - }); - }, - // exit node on triple enter - Enter: ({ editor }) => { - if (!this.options.exitOnTripleEnter) { - return false; - } - const { state } = editor; - const { selection } = state; - const { $from, empty: empty2 } = selection; - if (!empty2 || $from.parent.type !== this.type) { - return false; - } - const isAtEnd = $from.parentOffset === $from.parent.nodeSize - 2; - const endsWithDoubleNewline = $from.parent.textContent.endsWith("\n\n"); - if (!isAtEnd || !endsWithDoubleNewline) { - return false; - } - return editor.chain().command(({ tr: tr2 }) => { - tr2.delete($from.pos - 2, $from.pos); - return true; - }).exitCode().run(); - }, - // exit node on arrow down - ArrowDown: ({ editor }) => { - if (!this.options.exitOnArrowDown) { - return false; - } - const { state } = editor; - const { selection, doc: doc2 } = state; - const { $from, empty: empty2 } = selection; - if (!empty2 || $from.parent.type !== this.type) { - return false; - } - const isAtEnd = $from.parentOffset === $from.parent.nodeSize - 2; - if (!isAtEnd) { - return false; - } - const after = $from.after(); - if (after === void 0) { - return false; - } - const nodeAfter = doc2.nodeAt(after); - if (nodeAfter) { - return editor.commands.command(({ tr: tr2 }) => { - tr2.setSelection(Selection.near(doc2.resolve(after))); - return true; - }); - } - return editor.commands.exitCode(); - } - }; - }, - addInputRules() { - return [ - textblockTypeInputRule({ - find: backtickInputRegex, - type: this.type, - getAttributes: (match) => ({ - language: match[1] - }) - }), - textblockTypeInputRule({ - find: tildeInputRegex, - type: this.type, - getAttributes: (match) => ({ - language: match[1] - }) - }) - ]; - }, - addProseMirrorPlugins() { - return [ - // this plugin creates a code block for pasted content from VS Code - // we can also detect the copied code language - new Plugin({ - key: new PluginKey("codeBlockVSCodeHandler"), - props: { - handlePaste: (view, event) => { - if (!event.clipboardData) { - return false; - } - if (this.editor.isActive(this.type.name)) { - return false; - } - const text = event.clipboardData.getData("text/plain"); - const vscode = event.clipboardData.getData("vscode-editor-data"); - const vscodeData = vscode ? JSON.parse(vscode) : void 0; - const language = vscodeData == null ? void 0 : vscodeData.mode; - if (!text || !language) { - return false; - } - const { tr: tr2, schema } = view.state; - const textNode = schema.text(text.replace(/\r\n?/g, "\n")); - tr2.replaceSelectionWith(this.type.create({ language }, textNode)); - if (tr2.selection.$from.parent.type !== this.type) { - tr2.setSelection(TextSelection.near(tr2.doc.resolve(Math.max(0, tr2.selection.from - 2)))); - } - tr2.setMeta("paste", true); - view.dispatch(tr2); - return true; - } - } - }) - ]; - } -}); -var Document = Node3.create({ - name: "doc", - topNode: true, - content: "block+", - renderMarkdown: (node, h2) => { - if (!node.content) { - return ""; - } - return h2.renderChildren(node.content, "\n\n"); - } -}); -var HardBreak = Node3.create({ - name: "hardBreak", - markdownTokenName: "br", - addOptions() { - return { - keepMarks: true, - HTMLAttributes: {} - }; - }, - inline: true, - group: "inline", - selectable: false, - linebreakReplacement: true, - parseHTML() { - return [{ tag: "br" }]; - }, - renderHTML({ HTMLAttributes }) { - return ["br", mergeAttributes(this.options.HTMLAttributes, HTMLAttributes)]; - }, - renderText() { - return "\n"; - }, - renderMarkdown: () => ` -`, - parseMarkdown: () => { - return { - type: "hardBreak" - }; - }, - addCommands() { - return { - setHardBreak: () => ({ commands, chain, state, editor }) => { - return commands.first([ - () => commands.exitCode(), - () => commands.command(() => { - const { selection, storedMarks } = state; - if (selection.$from.parent.type.spec.isolating) { - return false; - } - const { keepMarks } = this.options; - const { splittableMarks } = editor.extensionManager; - const marks = storedMarks || selection.$to.parentOffset && selection.$from.marks(); - return chain().insertContent({ type: this.name }).command(({ tr: tr2, dispatch }) => { - if (dispatch && marks && keepMarks) { - const filteredMarks = marks.filter((mark) => splittableMarks.includes(mark.type.name)); - tr2.ensureMarks(filteredMarks); - } - return true; - }).run(); - }) - ]); - } - }; - }, - addKeyboardShortcuts() { - return { - "Mod-Enter": () => this.editor.commands.setHardBreak(), - "Shift-Enter": () => this.editor.commands.setHardBreak() - }; - } -}); -var Heading = Node3.create({ - name: "heading", - addOptions() { - return { - levels: [1, 2, 3, 4, 5, 6], - HTMLAttributes: {} - }; - }, - content: "inline*", - group: "block", - defining: true, - addAttributes() { - return { - level: { - default: 1, - rendered: false - } - }; - }, - parseHTML() { - return this.options.levels.map((level) => ({ - tag: `h${level}`, - attrs: { level } - })); - }, - renderHTML({ node, HTMLAttributes }) { - const hasLevel = this.options.levels.includes(node.attrs.level); - const level = hasLevel ? node.attrs.level : this.options.levels[0]; - return [`h${level}`, mergeAttributes(this.options.HTMLAttributes, HTMLAttributes), 0]; - }, - parseMarkdown: (token, helpers) => { - return helpers.createNode("heading", { level: token.depth || 1 }, helpers.parseInline(token.tokens || [])); - }, - renderMarkdown: (node, h2) => { - var _a; - const level = ((_a = node.attrs) == null ? void 0 : _a.level) ? parseInt(node.attrs.level, 10) : 1; - const headingChars = "#".repeat(level); - if (!node.content) { - return ""; - } - return `${headingChars} ${h2.renderChildren(node.content)}`; - }, - addCommands() { - return { - setHeading: (attributes) => ({ commands }) => { - if (!this.options.levels.includes(attributes.level)) { - return false; - } - return commands.setNode(this.name, attributes); - }, - toggleHeading: (attributes) => ({ commands }) => { - if (!this.options.levels.includes(attributes.level)) { - return false; - } - return commands.toggleNode(this.name, "paragraph", attributes); - } - }; - }, - addKeyboardShortcuts() { - return this.options.levels.reduce( - (items, level) => ({ - ...items, - ...{ - [`Mod-Alt-${level}`]: () => this.editor.commands.toggleHeading({ level }) - } - }), - {} - ); - }, - addInputRules() { - return this.options.levels.map((level) => { - return textblockTypeInputRule({ - find: new RegExp(`^(#{${Math.min(...this.options.levels)},${level}})\\s$`), - type: this.type, - getAttributes: { - level - } - }); - }); - } -}); -var HorizontalRule = Node3.create({ - name: "horizontalRule", - addOptions() { - return { - HTMLAttributes: {}, - nextNodeType: "paragraph" - }; - }, - group: "block", - parseHTML() { - return [{ tag: "hr" }]; - }, - renderHTML({ HTMLAttributes }) { - return ["hr", mergeAttributes(this.options.HTMLAttributes, HTMLAttributes)]; - }, - markdownTokenName: "hr", - parseMarkdown: (token, helpers) => { - return helpers.createNode("horizontalRule"); - }, - renderMarkdown: () => { - return "---"; - }, - addCommands() { - return { - setHorizontalRule: () => ({ chain, state }) => { - if (!canInsertNode(state, state.schema.nodes[this.name])) { - return false; - } - const { selection } = state; - const { $to: $originTo } = selection; - const currentChain = chain(); - if (isNodeSelection(selection)) { - currentChain.insertContentAt($originTo.pos, { - type: this.name - }); - } else { - currentChain.insertContent({ type: this.name }); - } - return currentChain.command(({ state: chainState, tr: tr2, dispatch }) => { - if (dispatch) { - const { $to } = tr2.selection; - const posAfter = $to.end(); - if ($to.nodeAfter) { - if ($to.nodeAfter.isTextblock) { - tr2.setSelection(TextSelection.create(tr2.doc, $to.pos + 1)); - } else if ($to.nodeAfter.isBlock) { - tr2.setSelection(NodeSelection.create(tr2.doc, $to.pos)); - } else { - tr2.setSelection(TextSelection.create(tr2.doc, $to.pos)); - } - } else { - const nodeType = chainState.schema.nodes[this.options.nextNodeType] || $to.parent.type.contentMatch.defaultType; - const node = nodeType == null ? void 0 : nodeType.create(); - if (node) { - tr2.insert(posAfter, node); - tr2.setSelection(TextSelection.create(tr2.doc, posAfter + 1)); - } - } - tr2.scrollIntoView(); - } - return true; - }).run(); - } - }; - }, - addInputRules() { - return [ - nodeInputRule({ - find: /^(?:---|—-|___\s|\*\*\*\s)$/, - type: this.type - }) - ]; - } -}); -var starInputRegex = /(?:^|\s)(\*(?!\s+\*)((?:[^*]+))\*(?!\s+\*))$/; -var starPasteRegex = /(?:^|\s)(\*(?!\s+\*)((?:[^*]+))\*(?!\s+\*))/g; -var underscoreInputRegex = /(?:^|\s)(_(?!\s+_)((?:[^_]+))_(?!\s+_))$/; -var underscorePasteRegex = /(?:^|\s)(_(?!\s+_)((?:[^_]+))_(?!\s+_))/g; -var Italic = Mark2.create({ - name: "italic", - addOptions() { - return { - HTMLAttributes: {} - }; - }, - parseHTML() { - return [ - { - tag: "em" - }, - { - tag: "i", - getAttrs: (node) => node.style.fontStyle !== "normal" && null - }, - { - style: "font-style=normal", - clearMark: (mark) => mark.type.name === this.name - }, - { - style: "font-style=italic" - } - ]; - }, - renderHTML({ HTMLAttributes }) { - return ["em", mergeAttributes(this.options.HTMLAttributes, HTMLAttributes), 0]; - }, - addCommands() { - return { - setItalic: () => ({ commands }) => { - return commands.setMark(this.name); - }, - toggleItalic: () => ({ commands }) => { - return commands.toggleMark(this.name); - }, - unsetItalic: () => ({ commands }) => { - return commands.unsetMark(this.name); - } - }; - }, - markdownTokenName: "em", - parseMarkdown: (token, helpers) => { - return helpers.applyMark("italic", helpers.parseInline(token.tokens || [])); - }, - markdownOptions: { - htmlReopen: { - open: "", - close: "" - } - }, - renderMarkdown: (node, h2) => { - return `*${h2.renderChildren(node)}*`; - }, - addKeyboardShortcuts() { - return { - "Mod-i": () => this.editor.commands.toggleItalic(), - "Mod-I": () => this.editor.commands.toggleItalic() - }; - }, - addInputRules() { - return [ - markInputRule({ - find: starInputRegex, - type: this.type - }), - markInputRule({ - find: underscoreInputRegex, - type: this.type - }) - ]; - }, - addPasteRules() { - return [ - markPasteRule({ - find: starPasteRegex, - type: this.type - }), - markPasteRule({ - find: underscorePasteRegex, - type: this.type - }) - ]; - } -}); -const encodedTlds = "aaa1rp3bb0ott3vie4c1le2ogado5udhabi7c0ademy5centure6ountant0s9o1tor4d0s1ult4e0g1ro2tna4f0l1rica5g0akhan5ency5i0g1rbus3force5tel5kdn3l0ibaba4pay4lfinanz6state5y2sace3tom5m0azon4ericanexpress7family11x2fam3ica3sterdam8nalytics7droid5quan4z2o0l2partments8p0le4q0uarelle8r0ab1mco4chi3my2pa2t0e3s0da2ia2sociates9t0hleta5torney7u0ction5di0ble3o3spost5thor3o0s4w0s2x0a2z0ure5ba0by2idu3namex4d1k2r0celona5laycard4s5efoot5gains6seball5ketball8uhaus5yern5b0c1t1va3cg1n2d1e0ats2uty4er2rlin4st0buy5t2f1g1h0arti5i0ble3d1ke2ng0o3o1z2j1lack0friday9ockbuster8g1omberg7ue3m0s1w2n0pparibas9o0ats3ehringer8fa2m1nd2o0k0ing5sch2tik2on4t1utique6x2r0adesco6idgestone9oadway5ker3ther5ussels7s1t1uild0ers6siness6y1zz3v1w1y1z0h3ca0b1fe2l0l1vinklein9m0era3p2non3petown5ital0one8r0avan4ds2e0er0s4s2sa1e1h1ino4t0ering5holic7ba1n1re3c1d1enter4o1rn3f0a1d2g1h0anel2nel4rity4se2t2eap3intai5ristmas6ome4urch5i0priani6rcle4sco3tadel4i0c2y3k1l0aims4eaning6ick2nic1que6othing5ud3ub0med6m1n1o0ach3des3ffee4llege4ogne5m0mbank4unity6pany2re3uter5sec4ndos3struction8ulting7tact3ractors9oking4l1p2rsica5untry4pon0s4rses6pa2r0edit0card4union9icket5own3s1uise0s6u0isinella9v1w1x1y0mru3ou3z2dad1nce3ta1e1ing3sun4y2clk3ds2e0al0er2s3gree4livery5l1oitte5ta3mocrat6ntal2ist5si0gn4v2hl2iamonds6et2gital5rect0ory7scount3ver5h2y2j1k1m1np2o0cs1tor4g1mains5t1wnload7rive4tv2ubai3nlop4pont4rban5vag2r2z2earth3t2c0o2deka3u0cation8e1g1mail3erck5nergy4gineer0ing9terprises10pson4quipment8r0icsson6ni3s0q1tate5t1u0rovision8s2vents5xchange6pert3osed4ress5traspace10fage2il1rwinds6th3mily4n0s2rm0ers5shion4t3edex3edback6rrari3ero6i0delity5o2lm2nal1nce1ial7re0stone6mdale6sh0ing5t0ness6j1k1lickr3ghts4r2orist4wers5y2m1o0o0d1tball6rd1ex2sale4um3undation8x2r0ee1senius7l1ogans4ntier7tr2ujitsu5n0d2rniture7tbol5yi3ga0l0lery3o1up4me0s3p1rden4y2b0iz3d0n2e0a1nt0ing5orge5f1g0ee3h1i0ft0s3ves2ing5l0ass3e1obal2o4m0ail3bh2o1x2n1odaddy5ld0point6f2o0dyear5g0le4p1t1v2p1q1r0ainger5phics5tis4een3ipe3ocery4up4s1t1u0cci3ge2ide2tars5ru3w1y2hair2mburg5ngout5us3bo2dfc0bank7ealth0care8lp1sinki6re1mes5iphop4samitsu7tachi5v2k0t2m1n1ockey4ldings5iday5medepot5goods5s0ense7nda3rse3spital5t0ing5t0els3mail5use3w2r1sbc3t1u0ghes5yatt3undai7ibm2cbc2e1u2d1e0ee3fm2kano4l1m0amat4db2mo0bilien9n0c1dustries8finiti5o2g1k1stitute6urance4e4t0ernational10uit4vestments10o1piranga7q1r0ish4s0maili5t0anbul7t0au2v3jaguar4va3cb2e0ep2tzt3welry6io2ll2m0p2nj2o0bs1urg4t1y2p0morgan6rs3uegos4niper7kaufen5ddi3e0rryhotels6properties14fh2g1h1i0a1ds2m1ndle4tchen5wi3m1n1oeln3matsu5sher5p0mg2n2r0d1ed3uokgroup8w1y0oto4z2la0caixa5mborghini8er3nd0rover6xess5salle5t0ino3robe5w0yer5b1c1ds2ease3clerc5frak4gal2o2xus4gbt3i0dl2fe0insurance9style7ghting6ke2lly3mited4o2ncoln4k2ve1ing5k1lc1p2oan0s3cker3us3l1ndon4tte1o3ve3pl0financial11r1s1t0d0a3u0ndbeck6xe1ury5v1y2ma0drid4if1son4keup4n0agement7go3p1rket0ing3s4riott5shalls7ttel5ba2c0kinsey7d1e0d0ia3et2lbourne7me1orial6n0u2rckmsd7g1h1iami3crosoft7l1ni1t2t0subishi9k1l0b1s2m0a2n1o0bi0le4da2e1i1m1nash3ey2ster5rmon3tgage6scow4to0rcycles9v0ie4p1q1r1s0d2t0n1r2u0seum3ic4v1w1x1y1z2na0b1goya4me2vy3ba2c1e0c1t0bank4flix4work5ustar5w0s2xt0direct7us4f0l2g0o2hk2i0co2ke1on3nja3ssan1y5l1o0kia3rton4w0ruz3tv4p1r0a1w2tt2u1yc2z2obi1server7ffice5kinawa6layan0group9lo3m0ega4ne1g1l0ine5oo2pen3racle3nge4g0anic5igins6saka4tsuka4t2vh3pa0ge2nasonic7ris2s1tners4s1y3y2ccw3e0t2f0izer5g1h0armacy6d1ilips5one2to0graphy6s4ysio5ics1tet2ures6d1n0g1k2oneer5zza4k1l0ace2y0station9umbing5s3m1n0c2ohl2ker3litie5rn2st3r0axi3ess3ime3o0d0uctions8f1gressive8mo2perties3y5tection8u0dential9s1t1ub2w0c2y2qa1pon3uebec3st5racing4dio4e0ad1lestate6tor2y4cipes5d0stone5umbrella9hab3ise0n3t2liance6n0t0als5pair3ort3ublican8st0aurant8view0s5xroth6ich0ardli6oh3l1o1p2o0cks3deo3gers4om3s0vp3u0gby3hr2n2w0e2yukyu6sa0arland6fe0ty4kura4le1on3msclub4ung5ndvik0coromant12ofi4p1rl2s1ve2xo3b0i1s2c0b1haeffler7midt4olarships8ol3ule3warz5ience5ot3d1e0arch3t2cure1ity6ek2lect4ner3rvices6ven3w1x0y3fr2g1h0angrila6rp3ell3ia1ksha5oes2p0ping5uji3w3i0lk2na1gles5te3j1k0i0n2y0pe4l0ing4m0art3ile4n0cf3o0ccer3ial4ftbank4ware6hu2lar2utions7ng1y2y2pa0ce3ort2t3r0l2s1t0ada2ples4r1tebank4farm7c0group6ockholm6rage3e3ream4udio2y3yle4u0cks3pplies3y2ort5rf1gery5zuki5v1watch4iss4x1y0dney4stems6z2tab1ipei4lk2obao4rget4tamotors6r2too4x0i3c0i2d0k2eam2ch0nology8l1masek5nnis4va3f1g1h0d1eater2re6iaa2ckets5enda4ps2res2ol4j0maxx4x2k0maxx5l1m0all4n1o0day3kyo3ols3p1ray3shiba5tal3urs3wn2yota3s3r0ade1ing4ining5vel0ers0insurance16ust3v2t1ube2i1nes3shu4v0s2w1z2ua1bank3s2g1k1nicom3versity8o2ol2ps2s1y1z2va0cations7na1guard7c1e0gas3ntures6risign5mögensberater2ung14sicherung10t2g1i0ajes4deo3g1king4llas4n1p1rgin4sa1ion4va1o3laanderen9n1odka3lvo3te1ing3o2yage5u2wales2mart4ter4ng0gou5tch0es6eather0channel12bcam3er2site5d0ding5ibo2r3f1hoswho6ien2ki2lliamhill9n0dows4e1ners6me2olterskluwer11odside6rk0s2ld3w2s1tc1f3xbox3erox4ihuan4n2xx2yz3yachts4hoo3maxun5ndex5e1odobashi7ga2kohama6u0tube6t1un3za0ppos4ra3ero3ip2m1one3uerich6w2"; -const encodedUtlds = "ελ1υ2бг1ел3дети4ею2католик6ом3мкд2он1сква6онлайн5рг3рус2ф2сайт3рб3укр3қаз3հայ3ישראל5קום3ابوظبي5رامكو5لاردن4بحرين5جزائر5سعودية6عليان5مغرب5مارات5یران5بارت2زار4يتك3ھارت5تونس4سودان3رية5شبكة4عراق2ب2مان4فلسطين6قطر3كاثوليك6وم3مصر2ليسيا5وريتانيا7قع4همراه5پاکستان7ڀارت4कॉम3नेट3भारत0म्3ोत5संगठन5বাংলা5ভারত2ৰত4ਭਾਰਤ4ભારત4ଭାରତ4இந்தியா6லங்கை6சிங்கப்பூர்11భారత్5ಭಾರತ4ഭാരതം5ලංකා4คอม3ไทย3ລາວ3გე2みんな3アマゾン4クラウド4グーグル4コム2ストア3セール3ファッション6ポイント4世界2中信1国1國1文网3亚马逊3企业2佛山2信息2健康2八卦2公司1益2台湾1灣2商城1店1标2嘉里0大酒店5在线2大拿2天主教3娱乐2家電2广东2微博2慈善2我爱你3手机2招聘2政务1府2新加坡2闻2时尚2書籍2机构2淡马锡3游戏2澳門2点看2移动2组织机构4网址1店1站1络2联通2谷歌2购物2通販2集团2電訊盈科4飞利浦3食品2餐厅2香格里拉3港2닷넷1컴2삼성2한국2"; -const numeric = "numeric"; -const ascii = "ascii"; -const alpha = "alpha"; -const asciinumeric = "asciinumeric"; -const alphanumeric = "alphanumeric"; -const domain = "domain"; -const emoji = "emoji"; -const scheme = "scheme"; -const slashscheme = "slashscheme"; -const whitespace = "whitespace"; -function registerGroup(name, groups) { - if (!(name in groups)) { - groups[name] = []; - } - return groups[name]; -} -function addToGroups(t, flags, groups) { - if (flags[numeric]) { - flags[asciinumeric] = true; - flags[alphanumeric] = true; - } - if (flags[ascii]) { - flags[asciinumeric] = true; - flags[alpha] = true; - } - if (flags[asciinumeric]) { - flags[alphanumeric] = true; - } - if (flags[alpha]) { - flags[alphanumeric] = true; - } - if (flags[alphanumeric]) { - flags[domain] = true; - } - if (flags[emoji]) { - flags[domain] = true; - } - for (const k in flags) { - const group = registerGroup(k, groups); - if (group.indexOf(t) < 0) { - group.push(t); - } - } -} -function flagsForToken(t, groups) { - const result = {}; - for (const c in groups) { - if (groups[c].indexOf(t) >= 0) { - result[c] = true; - } - } - return result; -} -function State(token = null) { - this.j = {}; - this.jr = []; - this.jd = null; - this.t = token; -} -State.groups = {}; -State.prototype = { - accepts() { - return !!this.t; - }, - /** - * Follow an existing transition from the given input to the next state. - * Does not mutate. - * @param {string} input character or token type to transition on - * @returns {?State} the next state, if any - */ - go(input) { - const state = this; - const nextState = state.j[input]; - if (nextState) { - return nextState; - } - for (let i = 0; i < state.jr.length; i++) { - const regex = state.jr[i][0]; - const nextState2 = state.jr[i][1]; - if (nextState2 && regex.test(input)) { - return nextState2; - } - } - return state.jd; - }, - /** - * Whether the state has a transition for the given input. Set the second - * argument to true to only look for an exact match (and not a default or - * regular-expression-based transition) - * @param {string} input - * @param {boolean} exactOnly - */ - has(input, exactOnly = false) { - return exactOnly ? input in this.j : !!this.go(input); - }, - /** - * Short for "transition all"; create a transition from the array of items - * in the given list to the same final resulting state. - * @param {string | string[]} inputs Group of inputs to transition on - * @param {Transition | State} [next] Transition options - * @param {Flags} [flags] Collections flags to add token to - * @param {Collections} [groups] Master list of token groups - */ - ta(inputs, next, flags, groups) { - for (let i = 0; i < inputs.length; i++) { - this.tt(inputs[i], next, flags, groups); - } - }, - /** - * Short for "take regexp transition"; defines a transition for this state - * when it encounters a token which matches the given regular expression - * @param {RegExp} regexp Regular expression transition (populate first) - * @param {T | State} [next] Transition options - * @param {Flags} [flags] Collections flags to add token to - * @param {Collections} [groups] Master list of token groups - * @returns {State} taken after the given input - */ - tr(regexp, next, flags, groups) { - groups = groups || State.groups; - let nextState; - if (next && next.j) { - nextState = next; - } else { - nextState = new State(next); - if (flags && groups) { - addToGroups(next, flags, groups); - } - } - this.jr.push([regexp, nextState]); - return nextState; - }, - /** - * Short for "take transitions", will take as many sequential transitions as - * the length of the given input and returns the - * resulting final state. - * @param {string | string[]} input - * @param {T | State} [next] Transition options - * @param {Flags} [flags] Collections flags to add token to - * @param {Collections} [groups] Master list of token groups - * @returns {State} taken after the given input - */ - ts(input, next, flags, groups) { - let state = this; - const len = input.length; - if (!len) { - return state; - } - for (let i = 0; i < len - 1; i++) { - state = state.tt(input[i]); - } - return state.tt(input[len - 1], next, flags, groups); - }, - /** - * Short for "take transition", this is a method for building/working with - * state machines. - * - * If a state already exists for the given input, returns it. - * - * If a token is specified, that state will emit that token when reached by - * the linkify engine. - * - * If no state exists, it will be initialized with some default transitions - * that resemble existing default transitions. - * - * If a state is given for the second argument, that state will be - * transitioned to on the given input regardless of what that input - * previously did. - * - * Specify a token group flags to define groups that this token belongs to. - * The token will be added to corresponding entires in the given groups - * object. - * - * @param {string} input character, token type to transition on - * @param {T | State} [next] Transition options - * @param {Flags} [flags] Collections flags to add token to - * @param {Collections} [groups] Master list of groups - * @returns {State} taken after the given input - */ - tt(input, next, flags, groups) { - groups = groups || State.groups; - const state = this; - if (next && next.j) { - state.j[input] = next; - return next; - } - const t = next; - let nextState, templateState = state.go(input); - if (templateState) { - nextState = new State(); - Object.assign(nextState.j, templateState.j); - nextState.jr.push.apply(nextState.jr, templateState.jr); - nextState.jd = templateState.jd; - nextState.t = templateState.t; - } else { - nextState = new State(); - } - if (t) { - if (groups) { - if (nextState.t && typeof nextState.t === "string") { - const allFlags = Object.assign(flagsForToken(nextState.t, groups), flags); - addToGroups(t, allFlags, groups); - } else if (flags) { - addToGroups(t, flags, groups); - } - } - nextState.t = t; - } - state.j[input] = nextState; - return nextState; - } -}; -const ta = (state, input, next, flags, groups) => state.ta(input, next, flags, groups); -const tr = (state, regexp, next, flags, groups) => state.tr(regexp, next, flags, groups); -const ts = (state, input, next, flags, groups) => state.ts(input, next, flags, groups); -const tt = (state, input, next, flags, groups) => state.tt(input, next, flags, groups); -const WORD = "WORD"; -const UWORD = "UWORD"; -const ASCIINUMERICAL = "ASCIINUMERICAL"; -const ALPHANUMERICAL = "ALPHANUMERICAL"; -const LOCALHOST = "LOCALHOST"; -const TLD = "TLD"; -const UTLD = "UTLD"; -const SCHEME = "SCHEME"; -const SLASH_SCHEME = "SLASH_SCHEME"; -const NUM = "NUM"; -const WS = "WS"; -const NL = "NL"; -const OPENBRACE = "OPENBRACE"; -const CLOSEBRACE = "CLOSEBRACE"; -const OPENBRACKET = "OPENBRACKET"; -const CLOSEBRACKET = "CLOSEBRACKET"; -const OPENPAREN = "OPENPAREN"; -const CLOSEPAREN = "CLOSEPAREN"; -const OPENANGLEBRACKET = "OPENANGLEBRACKET"; -const CLOSEANGLEBRACKET = "CLOSEANGLEBRACKET"; -const FULLWIDTHLEFTPAREN = "FULLWIDTHLEFTPAREN"; -const FULLWIDTHRIGHTPAREN = "FULLWIDTHRIGHTPAREN"; -const LEFTCORNERBRACKET = "LEFTCORNERBRACKET"; -const RIGHTCORNERBRACKET = "RIGHTCORNERBRACKET"; -const LEFTWHITECORNERBRACKET = "LEFTWHITECORNERBRACKET"; -const RIGHTWHITECORNERBRACKET = "RIGHTWHITECORNERBRACKET"; -const FULLWIDTHLESSTHAN = "FULLWIDTHLESSTHAN"; -const FULLWIDTHGREATERTHAN = "FULLWIDTHGREATERTHAN"; -const AMPERSAND = "AMPERSAND"; -const APOSTROPHE = "APOSTROPHE"; -const ASTERISK = "ASTERISK"; -const AT = "AT"; -const BACKSLASH = "BACKSLASH"; -const BACKTICK = "BACKTICK"; -const CARET = "CARET"; -const COLON = "COLON"; -const COMMA = "COMMA"; -const DOLLAR = "DOLLAR"; -const DOT = "DOT"; -const EQUALS = "EQUALS"; -const EXCLAMATION = "EXCLAMATION"; -const HYPHEN = "HYPHEN"; -const PERCENT = "PERCENT"; -const PIPE = "PIPE"; -const PLUS = "PLUS"; -const POUND = "POUND"; -const QUERY = "QUERY"; -const QUOTE = "QUOTE"; -const FULLWIDTHMIDDLEDOT = "FULLWIDTHMIDDLEDOT"; -const SEMI = "SEMI"; -const SLASH = "SLASH"; -const TILDE = "TILDE"; -const UNDERSCORE = "UNDERSCORE"; -const EMOJI$1 = "EMOJI"; -const SYM = "SYM"; -var tk = /* @__PURE__ */ Object.freeze({ - __proto__: null, - ALPHANUMERICAL, - AMPERSAND, - APOSTROPHE, - ASCIINUMERICAL, - ASTERISK, - AT, - BACKSLASH, - BACKTICK, - CARET, - CLOSEANGLEBRACKET, - CLOSEBRACE, - CLOSEBRACKET, - CLOSEPAREN, - COLON, - COMMA, - DOLLAR, - DOT, - EMOJI: EMOJI$1, - EQUALS, - EXCLAMATION, - FULLWIDTHGREATERTHAN, - FULLWIDTHLEFTPAREN, - FULLWIDTHLESSTHAN, - FULLWIDTHMIDDLEDOT, - FULLWIDTHRIGHTPAREN, - HYPHEN, - LEFTCORNERBRACKET, - LEFTWHITECORNERBRACKET, - LOCALHOST, - NL, - NUM, - OPENANGLEBRACKET, - OPENBRACE, - OPENBRACKET, - OPENPAREN, - PERCENT, - PIPE, - PLUS, - POUND, - QUERY, - QUOTE, - RIGHTCORNERBRACKET, - RIGHTWHITECORNERBRACKET, - SCHEME, - SEMI, - SLASH, - SLASH_SCHEME, - SYM, - TILDE, - TLD, - UNDERSCORE, - UTLD, - UWORD, - WORD, - WS -}); -const ASCII_LETTER = /[a-z]/; -const LETTER = new RegExp("\\p{L}", "u"); -const EMOJI = new RegExp("\\p{Emoji}", "u"); -const DIGIT = /\d/; -const SPACE = /\s/; -const CR = "\r"; -const LF = "\n"; -const EMOJI_VARIATION = "️"; -const EMOJI_JOINER = "‍"; -const OBJECT_REPLACEMENT = ""; -let tlds = null, utlds = null; -function init$2(customSchemes = []) { - const groups = {}; - State.groups = groups; - const Start = new State(); - if (tlds == null) { - tlds = decodeTlds(encodedTlds); - } - if (utlds == null) { - utlds = decodeTlds(encodedUtlds); - } - tt(Start, "'", APOSTROPHE); - tt(Start, "{", OPENBRACE); - tt(Start, "}", CLOSEBRACE); - tt(Start, "[", OPENBRACKET); - tt(Start, "]", CLOSEBRACKET); - tt(Start, "(", OPENPAREN); - tt(Start, ")", CLOSEPAREN); - tt(Start, "<", OPENANGLEBRACKET); - tt(Start, ">", CLOSEANGLEBRACKET); - tt(Start, "(", FULLWIDTHLEFTPAREN); - tt(Start, ")", FULLWIDTHRIGHTPAREN); - tt(Start, "「", LEFTCORNERBRACKET); - tt(Start, "」", RIGHTCORNERBRACKET); - tt(Start, "『", LEFTWHITECORNERBRACKET); - tt(Start, "』", RIGHTWHITECORNERBRACKET); - tt(Start, "<", FULLWIDTHLESSTHAN); - tt(Start, ">", FULLWIDTHGREATERTHAN); - tt(Start, "&", AMPERSAND); - tt(Start, "*", ASTERISK); - tt(Start, "@", AT); - tt(Start, "`", BACKTICK); - tt(Start, "^", CARET); - tt(Start, ":", COLON); - tt(Start, ",", COMMA); - tt(Start, "$", DOLLAR); - tt(Start, ".", DOT); - tt(Start, "=", EQUALS); - tt(Start, "!", EXCLAMATION); - tt(Start, "-", HYPHEN); - tt(Start, "%", PERCENT); - tt(Start, "|", PIPE); - tt(Start, "+", PLUS); - tt(Start, "#", POUND); - tt(Start, "?", QUERY); - tt(Start, '"', QUOTE); - tt(Start, "/", SLASH); - tt(Start, ";", SEMI); - tt(Start, "~", TILDE); - tt(Start, "_", UNDERSCORE); - tt(Start, "\\", BACKSLASH); - tt(Start, "・", FULLWIDTHMIDDLEDOT); - const Num = tr(Start, DIGIT, NUM, { - [numeric]: true - }); - tr(Num, DIGIT, Num); - const Asciinumeric = tr(Num, ASCII_LETTER, ASCIINUMERICAL, { - [asciinumeric]: true - }); - const Alphanumeric = tr(Num, LETTER, ALPHANUMERICAL, { - [alphanumeric]: true - }); - const Word = tr(Start, ASCII_LETTER, WORD, { - [ascii]: true - }); - tr(Word, DIGIT, Asciinumeric); - tr(Word, ASCII_LETTER, Word); - tr(Asciinumeric, DIGIT, Asciinumeric); - tr(Asciinumeric, ASCII_LETTER, Asciinumeric); - const UWord = tr(Start, LETTER, UWORD, { - [alpha]: true - }); - tr(UWord, ASCII_LETTER); - tr(UWord, DIGIT, Alphanumeric); - tr(UWord, LETTER, UWord); - tr(Alphanumeric, DIGIT, Alphanumeric); - tr(Alphanumeric, ASCII_LETTER); - tr(Alphanumeric, LETTER, Alphanumeric); - const Nl2 = tt(Start, LF, NL, { - [whitespace]: true - }); - const Cr = tt(Start, CR, WS, { - [whitespace]: true - }); - const Ws = tr(Start, SPACE, WS, { - [whitespace]: true - }); - tt(Start, OBJECT_REPLACEMENT, Ws); - tt(Cr, LF, Nl2); - tt(Cr, OBJECT_REPLACEMENT, Ws); - tr(Cr, SPACE, Ws); - tt(Ws, CR); - tt(Ws, LF); - tr(Ws, SPACE, Ws); - tt(Ws, OBJECT_REPLACEMENT, Ws); - const Emoji = tr(Start, EMOJI, EMOJI$1, { - [emoji]: true - }); - tt(Emoji, "#"); - tr(Emoji, EMOJI, Emoji); - tt(Emoji, EMOJI_VARIATION, Emoji); - const EmojiJoiner = tt(Emoji, EMOJI_JOINER); - tt(EmojiJoiner, "#"); - tr(EmojiJoiner, EMOJI, Emoji); - const wordjr = [[ASCII_LETTER, Word], [DIGIT, Asciinumeric]]; - const uwordjr = [[ASCII_LETTER, null], [LETTER, UWord], [DIGIT, Alphanumeric]]; - for (let i = 0; i < tlds.length; i++) { - fastts(Start, tlds[i], TLD, WORD, wordjr); - } - for (let i = 0; i < utlds.length; i++) { - fastts(Start, utlds[i], UTLD, UWORD, uwordjr); - } - addToGroups(TLD, { - tld: true, - ascii: true - }, groups); - addToGroups(UTLD, { - utld: true, - alpha: true - }, groups); - fastts(Start, "file", SCHEME, WORD, wordjr); - fastts(Start, "mailto", SCHEME, WORD, wordjr); - fastts(Start, "http", SLASH_SCHEME, WORD, wordjr); - fastts(Start, "https", SLASH_SCHEME, WORD, wordjr); - fastts(Start, "ftp", SLASH_SCHEME, WORD, wordjr); - fastts(Start, "ftps", SLASH_SCHEME, WORD, wordjr); - addToGroups(SCHEME, { - scheme: true, - ascii: true - }, groups); - addToGroups(SLASH_SCHEME, { - slashscheme: true, - ascii: true - }, groups); - customSchemes = customSchemes.sort((a, b) => a[0] > b[0] ? 1 : -1); - for (let i = 0; i < customSchemes.length; i++) { - const sch = customSchemes[i][0]; - const optionalSlashSlash = customSchemes[i][1]; - const flags = optionalSlashSlash ? { - [scheme]: true - } : { - [slashscheme]: true - }; - if (sch.indexOf("-") >= 0) { - flags[domain] = true; - } else if (!ASCII_LETTER.test(sch)) { - flags[numeric] = true; - } else if (DIGIT.test(sch)) { - flags[asciinumeric] = true; - } else { - flags[ascii] = true; - } - ts(Start, sch, sch, flags); - } - ts(Start, "localhost", LOCALHOST, { - ascii: true - }); - Start.jd = new State(SYM); - return { - start: Start, - tokens: Object.assign({ - groups - }, tk) - }; -} -function run$1(start, str) { - const iterable = stringToArray(str.replace(/[A-Z]/g, (c) => c.toLowerCase())); - const charCount = iterable.length; - const tokens = []; - let cursor = 0; - let charCursor = 0; - while (charCursor < charCount) { - let state = start; - let nextState = null; - let tokenLength = 0; - let latestAccepting = null; - let sinceAccepts = -1; - let charsSinceAccepts = -1; - while (charCursor < charCount && (nextState = state.go(iterable[charCursor]))) { - state = nextState; - if (state.accepts()) { - sinceAccepts = 0; - charsSinceAccepts = 0; - latestAccepting = state; - } else if (sinceAccepts >= 0) { - sinceAccepts += iterable[charCursor].length; - charsSinceAccepts++; - } - tokenLength += iterable[charCursor].length; - cursor += iterable[charCursor].length; - charCursor++; - } - cursor -= sinceAccepts; - charCursor -= charsSinceAccepts; - tokenLength -= sinceAccepts; - tokens.push({ - t: latestAccepting.t, - // token type/name - v: str.slice(cursor - tokenLength, cursor), - // string value - s: cursor - tokenLength, - // start index - e: cursor - // end index (excluding) - }); - } - return tokens; -} -function stringToArray(str) { - const result = []; - const len = str.length; - let index = 0; - while (index < len) { - let first2 = str.charCodeAt(index); - let second; - let char = first2 < 55296 || first2 > 56319 || index + 1 === len || (second = str.charCodeAt(index + 1)) < 56320 || second > 57343 ? str[index] : str.slice(index, index + 2); - result.push(char); - index += char.length; - } - return result; -} -function fastts(state, input, t, defaultt, jr) { - let next; - const len = input.length; - for (let i = 0; i < len - 1; i++) { - const char = input[i]; - if (state.j[char]) { - next = state.j[char]; - } else { - next = new State(defaultt); - next.jr = jr.slice(); - state.j[char] = next; - } - state = next; - } - next = new State(t); - next.jr = jr.slice(); - state.j[input[len - 1]] = next; - return next; -} -function decodeTlds(encoded) { - const words = []; - const stack = []; - let i = 0; - let digits = "0123456789"; - while (i < encoded.length) { - let popDigitCount = 0; - while (digits.indexOf(encoded[i + popDigitCount]) >= 0) { - popDigitCount++; - } - if (popDigitCount > 0) { - words.push(stack.join("")); - for (let popCount = parseInt(encoded.substring(i, i + popDigitCount), 10); popCount > 0; popCount--) { - stack.pop(); - } - i += popDigitCount; - } else { - stack.push(encoded[i]); - i++; - } - } - return words; -} -const defaults = { - defaultProtocol: "http", - events: null, - format: noop, - formatHref: noop, - nl2br: false, - tagName: "a", - target: null, - rel: null, - validate: true, - truncate: Infinity, - className: null, - attributes: null, - ignoreTags: [], - render: null -}; -function Options(opts, defaultRender = null) { - let o = Object.assign({}, defaults); - if (opts) { - o = Object.assign(o, opts instanceof Options ? opts.o : opts); - } - const ignoredTags = o.ignoreTags; - const uppercaseIgnoredTags = []; - for (let i = 0; i < ignoredTags.length; i++) { - uppercaseIgnoredTags.push(ignoredTags[i].toUpperCase()); - } - this.o = o; - if (defaultRender) { - this.defaultRender = defaultRender; - } - this.ignoreTags = uppercaseIgnoredTags; -} -Options.prototype = { - o: defaults, - /** - * @type string[] - */ - ignoreTags: [], - /** - * @param {IntermediateRepresentation} ir - * @returns {any} - */ - defaultRender(ir) { - return ir; - }, - /** - * Returns true or false based on whether a token should be displayed as a - * link based on the user options. - * @param {MultiToken} token - * @returns {boolean} - */ - check(token) { - return this.get("validate", token.toString(), token); - }, - // Private methods - /** - * Resolve an option's value based on the value of the option and the given - * params. If operator and token are specified and the target option is - * callable, automatically calls the function with the given argument. - * @template {keyof Opts} K - * @param {K} key Name of option to use - * @param {string} [operator] will be passed to the target option if it's a - * function. If not specified, RAW function value gets returned - * @param {MultiToken} [token] The token from linkify.tokenize - * @returns {Opts[K] | any} - */ - get(key, operator, token) { - const isCallable = operator != null; - let option = this.o[key]; - if (!option) { - return option; - } - if (typeof option === "object") { - option = token.t in option ? option[token.t] : defaults[key]; - if (typeof option === "function" && isCallable) { - option = option(operator, token); - } - } else if (typeof option === "function" && isCallable) { - option = option(operator, token.t, token); - } - return option; - }, - /** - * @template {keyof Opts} L - * @param {L} key Name of options object to use - * @param {string} [operator] - * @param {MultiToken} [token] - * @returns {Opts[L] | any} - */ - getObj(key, operator, token) { - let obj = this.o[key]; - if (typeof obj === "function" && operator != null) { - obj = obj(operator, token.t, token); - } - return obj; - }, - /** - * Convert the given token to a rendered element that may be added to the - * calling-interface's DOM - * @param {MultiToken} token Token to render to an HTML element - * @returns {any} Render result; e.g., HTML string, DOM element, React - * Component, etc. - */ - render(token) { - const ir = token.render(this); - const renderFn = this.get("render", null, token) || this.defaultRender; - return renderFn(ir, token.t, token); - } -}; -function noop(val) { - return val; -} -function MultiToken(value, tokens) { - this.t = "token"; - this.v = value; - this.tk = tokens; -} -MultiToken.prototype = { - isLink: false, - /** - * Return the string this token represents. - * @return {string} - */ - toString() { - return this.v; - }, - /** - * What should the value for this token be in the `href` HTML attribute? - * Returns the `.toString` value by default. - * @param {string} [scheme] - * @return {string} - */ - toHref(scheme2) { - return this.toString(); - }, - /** - * @param {Options} options Formatting options - * @returns {string} - */ - toFormattedString(options) { - const val = this.toString(); - const truncate = options.get("truncate", val, this); - const formatted = options.get("format", val, this); - return truncate && formatted.length > truncate ? formatted.substring(0, truncate) + "…" : formatted; - }, - /** - * - * @param {Options} options - * @returns {string} - */ - toFormattedHref(options) { - return options.get("formatHref", this.toHref(options.get("defaultProtocol")), this); - }, - /** - * The start index of this token in the original input string - * @returns {number} - */ - startIndex() { - return this.tk[0].s; - }, - /** - * The end index of this token in the original input string (up to this - * index but not including it) - * @returns {number} - */ - endIndex() { - return this.tk[this.tk.length - 1].e; - }, - /** - Returns an object of relevant values for this token, which includes keys - * type - Kind of token ('url', 'email', etc.) - * value - Original text - * href - The value that should be added to the anchor tag's href - attribute - @method toObject - @param {string} [protocol] `'http'` by default - */ - toObject(protocol = defaults.defaultProtocol) { - return { - type: this.t, - value: this.toString(), - isLink: this.isLink, - href: this.toHref(protocol), - start: this.startIndex(), - end: this.endIndex() - }; - }, - /** - * - * @param {Options} options Formatting option - */ - toFormattedObject(options) { - return { - type: this.t, - value: this.toFormattedString(options), - isLink: this.isLink, - href: this.toFormattedHref(options), - start: this.startIndex(), - end: this.endIndex() - }; - }, - /** - * Whether this token should be rendered as a link according to the given options - * @param {Options} options - * @returns {boolean} - */ - validate(options) { - return options.get("validate", this.toString(), this); - }, - /** - * Return an object that represents how this link should be rendered. - * @param {Options} options Formattinng options - */ - render(options) { - const token = this; - const href = this.toHref(options.get("defaultProtocol")); - const formattedHref = options.get("formatHref", href, this); - const tagName = options.get("tagName", href, token); - const content = this.toFormattedString(options); - const attributes = {}; - const className = options.get("className", href, token); - const target = options.get("target", href, token); - const rel = options.get("rel", href, token); - const attrs = options.getObj("attributes", href, token); - const eventListeners = options.getObj("events", href, token); - attributes.href = formattedHref; - if (className) { - attributes.class = className; - } - if (target) { - attributes.target = target; - } - if (rel) { - attributes.rel = rel; - } - if (attrs) { - Object.assign(attributes, attrs); - } - return { - tagName, - attributes, - content, - eventListeners - }; - } -}; -function createTokenClass(type, props) { - class Token extends MultiToken { - constructor(value, tokens) { - super(value, tokens); - this.t = type; - } - } - for (const p in props) { - Token.prototype[p] = props[p]; - } - Token.t = type; - return Token; -} -const Email = createTokenClass("email", { - isLink: true, - toHref() { - return "mailto:" + this.toString(); - } -}); -const Text$1 = createTokenClass("text"); -const Nl = createTokenClass("nl"); -const Url = createTokenClass("url", { - isLink: true, - /** - Lowercases relevant parts of the domain and adds the protocol if - required. Note that this will not escape unsafe HTML characters in the - URL. - @param {string} [scheme] default scheme (e.g., 'https') - @return {string} the full href - */ - toHref(scheme2 = defaults.defaultProtocol) { - return this.hasProtocol() ? this.v : `${scheme2}://${this.v}`; - }, - /** - * Check whether this URL token has a protocol - * @return {boolean} - */ - hasProtocol() { - const tokens = this.tk; - return tokens.length >= 2 && tokens[0].t !== LOCALHOST && tokens[1].t === COLON; - } -}); -const makeState = (arg) => new State(arg); -function init$1({ - groups -}) { - const qsAccepting = groups.domain.concat([AMPERSAND, ASTERISK, AT, BACKSLASH, BACKTICK, CARET, DOLLAR, EQUALS, HYPHEN, NUM, PERCENT, PIPE, PLUS, POUND, SLASH, SYM, TILDE, UNDERSCORE]); - const qsNonAccepting = [APOSTROPHE, COLON, COMMA, DOT, EXCLAMATION, PERCENT, QUERY, QUOTE, SEMI, OPENANGLEBRACKET, CLOSEANGLEBRACKET, OPENBRACE, CLOSEBRACE, CLOSEBRACKET, OPENBRACKET, OPENPAREN, CLOSEPAREN, FULLWIDTHLEFTPAREN, FULLWIDTHRIGHTPAREN, LEFTCORNERBRACKET, RIGHTCORNERBRACKET, LEFTWHITECORNERBRACKET, RIGHTWHITECORNERBRACKET, FULLWIDTHLESSTHAN, FULLWIDTHGREATERTHAN]; - const localpartAccepting = [AMPERSAND, APOSTROPHE, ASTERISK, BACKSLASH, BACKTICK, CARET, DOLLAR, EQUALS, HYPHEN, OPENBRACE, CLOSEBRACE, PERCENT, PIPE, PLUS, POUND, QUERY, SLASH, SYM, TILDE, UNDERSCORE]; - const Start = makeState(); - const Localpart = tt(Start, TILDE); - ta(Localpart, localpartAccepting, Localpart); - ta(Localpart, groups.domain, Localpart); - const Domain = makeState(), Scheme = makeState(), SlashScheme = makeState(); - ta(Start, groups.domain, Domain); - ta(Start, groups.scheme, Scheme); - ta(Start, groups.slashscheme, SlashScheme); - ta(Domain, localpartAccepting, Localpart); - ta(Domain, groups.domain, Domain); - const LocalpartAt = tt(Domain, AT); - tt(Localpart, AT, LocalpartAt); - tt(Scheme, AT, LocalpartAt); - tt(SlashScheme, AT, LocalpartAt); - const LocalpartDot = tt(Localpart, DOT); - ta(LocalpartDot, localpartAccepting, Localpart); - ta(LocalpartDot, groups.domain, Localpart); - const EmailDomain = makeState(); - ta(LocalpartAt, groups.domain, EmailDomain); - ta(EmailDomain, groups.domain, EmailDomain); - const EmailDomainDot = tt(EmailDomain, DOT); - ta(EmailDomainDot, groups.domain, EmailDomain); - const Email$1 = makeState(Email); - ta(EmailDomainDot, groups.tld, Email$1); - ta(EmailDomainDot, groups.utld, Email$1); - tt(LocalpartAt, LOCALHOST, Email$1); - const EmailDomainHyphen = tt(EmailDomain, HYPHEN); - tt(EmailDomainHyphen, HYPHEN, EmailDomainHyphen); - ta(EmailDomainHyphen, groups.domain, EmailDomain); - ta(Email$1, groups.domain, EmailDomain); - tt(Email$1, DOT, EmailDomainDot); - tt(Email$1, HYPHEN, EmailDomainHyphen); - const EmailColon = tt(Email$1, COLON); - ta(EmailColon, groups.numeric, Email); - const DomainHyphen = tt(Domain, HYPHEN); - const DomainDot = tt(Domain, DOT); - tt(DomainHyphen, HYPHEN, DomainHyphen); - ta(DomainHyphen, groups.domain, Domain); - ta(DomainDot, localpartAccepting, Localpart); - ta(DomainDot, groups.domain, Domain); - const DomainDotTld = makeState(Url); - ta(DomainDot, groups.tld, DomainDotTld); - ta(DomainDot, groups.utld, DomainDotTld); - ta(DomainDotTld, groups.domain, Domain); - ta(DomainDotTld, localpartAccepting, Localpart); - tt(DomainDotTld, DOT, DomainDot); - tt(DomainDotTld, HYPHEN, DomainHyphen); - tt(DomainDotTld, AT, LocalpartAt); - const DomainDotTldColon = tt(DomainDotTld, COLON); - const DomainDotTldColonPort = makeState(Url); - ta(DomainDotTldColon, groups.numeric, DomainDotTldColonPort); - const Url$1 = makeState(Url); - const UrlNonaccept = makeState(); - ta(Url$1, qsAccepting, Url$1); - ta(Url$1, qsNonAccepting, UrlNonaccept); - ta(UrlNonaccept, qsAccepting, Url$1); - ta(UrlNonaccept, qsNonAccepting, UrlNonaccept); - tt(DomainDotTld, SLASH, Url$1); - tt(DomainDotTldColonPort, SLASH, Url$1); - const SchemeColon = tt(Scheme, COLON); - const SlashSchemeColon = tt(SlashScheme, COLON); - const SlashSchemeColonSlash = tt(SlashSchemeColon, SLASH); - const UriPrefix = tt(SlashSchemeColonSlash, SLASH); - ta(Scheme, groups.domain, Domain); - tt(Scheme, DOT, DomainDot); - tt(Scheme, HYPHEN, DomainHyphen); - ta(SlashScheme, groups.domain, Domain); - tt(SlashScheme, DOT, DomainDot); - tt(SlashScheme, HYPHEN, DomainHyphen); - ta(SchemeColon, groups.domain, Url$1); - tt(SchemeColon, SLASH, Url$1); - tt(SchemeColon, QUERY, Url$1); - ta(UriPrefix, groups.domain, Url$1); - ta(UriPrefix, qsAccepting, Url$1); - tt(UriPrefix, SLASH, Url$1); - const bracketPairs = [ - [OPENBRACE, CLOSEBRACE], - // {} - [OPENBRACKET, CLOSEBRACKET], - // [] - [OPENPAREN, CLOSEPAREN], - // () - [OPENANGLEBRACKET, CLOSEANGLEBRACKET], - // <> - [FULLWIDTHLEFTPAREN, FULLWIDTHRIGHTPAREN], - // () - [LEFTCORNERBRACKET, RIGHTCORNERBRACKET], - // 「」 - [LEFTWHITECORNERBRACKET, RIGHTWHITECORNERBRACKET], - // 『』 - [FULLWIDTHLESSTHAN, FULLWIDTHGREATERTHAN] - // <> - ]; - for (let i = 0; i < bracketPairs.length; i++) { - const [OPEN, CLOSE] = bracketPairs[i]; - const UrlOpen = tt(Url$1, OPEN); - tt(UrlNonaccept, OPEN, UrlOpen); - tt(UrlOpen, CLOSE, Url$1); - const UrlOpenQ = makeState(Url); - ta(UrlOpen, qsAccepting, UrlOpenQ); - const UrlOpenSyms = makeState(); - ta(UrlOpen, qsNonAccepting); - ta(UrlOpenQ, qsAccepting, UrlOpenQ); - ta(UrlOpenQ, qsNonAccepting, UrlOpenSyms); - ta(UrlOpenSyms, qsAccepting, UrlOpenQ); - ta(UrlOpenSyms, qsNonAccepting, UrlOpenSyms); - tt(UrlOpenQ, CLOSE, Url$1); - tt(UrlOpenSyms, CLOSE, Url$1); - } - tt(Start, LOCALHOST, DomainDotTld); - tt(Start, NL, Nl); - return { - start: Start, - tokens: tk - }; -} -function run(start, input, tokens) { - let len = tokens.length; - let cursor = 0; - let multis = []; - let textTokens = []; - while (cursor < len) { - let state = start; - let secondState = null; - let nextState = null; - let multiLength = 0; - let latestAccepting = null; - let sinceAccepts = -1; - while (cursor < len && !(secondState = state.go(tokens[cursor].t))) { - textTokens.push(tokens[cursor++]); - } - while (cursor < len && (nextState = secondState || state.go(tokens[cursor].t))) { - secondState = null; - state = nextState; - if (state.accepts()) { - sinceAccepts = 0; - latestAccepting = state; - } else if (sinceAccepts >= 0) { - sinceAccepts++; - } - cursor++; - multiLength++; - } - if (sinceAccepts < 0) { - cursor -= multiLength; - if (cursor < len) { - textTokens.push(tokens[cursor]); - cursor++; - } - } else { - if (textTokens.length > 0) { - multis.push(initMultiToken(Text$1, input, textTokens)); - textTokens = []; - } - cursor -= sinceAccepts; - multiLength -= sinceAccepts; - const Multi = latestAccepting.t; - const subtokens = tokens.slice(cursor - multiLength, cursor); - multis.push(initMultiToken(Multi, input, subtokens)); - } - } - if (textTokens.length > 0) { - multis.push(initMultiToken(Text$1, input, textTokens)); - } - return multis; -} -function initMultiToken(Multi, input, tokens) { - const startIdx = tokens[0].s; - const endIdx = tokens[tokens.length - 1].e; - const value = input.slice(startIdx, endIdx); - return new Multi(value, tokens); -} -const warn = typeof console !== "undefined" && console && console.warn || (() => { -}); -const warnAdvice = "until manual call of linkify.init(). Register all schemes and plugins before invoking linkify the first time."; -const INIT = { - scanner: null, - parser: null, - tokenQueue: [], - pluginQueue: [], - customSchemes: [], - initialized: false -}; -function reset() { - State.groups = {}; - INIT.scanner = null; - INIT.parser = null; - INIT.tokenQueue = []; - INIT.pluginQueue = []; - INIT.customSchemes = []; - INIT.initialized = false; - return INIT; -} -function registerCustomProtocol(scheme2, optionalSlashSlash = false) { - if (INIT.initialized) { - warn(`linkifyjs: already initialized - will not register custom scheme "${scheme2}" ${warnAdvice}`); - } - if (!/^[0-9a-z]+(-[0-9a-z]+)*$/.test(scheme2)) { - throw new Error(`linkifyjs: incorrect scheme format. -1. Must only contain digits, lowercase ASCII letters or "-" -2. Cannot start or end with "-" -3. "-" cannot repeat`); - } - INIT.customSchemes.push([scheme2, optionalSlashSlash]); -} -function init() { - INIT.scanner = init$2(INIT.customSchemes); - for (let i = 0; i < INIT.tokenQueue.length; i++) { - INIT.tokenQueue[i][1]({ - scanner: INIT.scanner - }); - } - INIT.parser = init$1(INIT.scanner.tokens); - for (let i = 0; i < INIT.pluginQueue.length; i++) { - INIT.pluginQueue[i][1]({ - scanner: INIT.scanner, - parser: INIT.parser - }); - } - INIT.initialized = true; - return INIT; -} -function tokenize(str) { - if (!INIT.initialized) { - init(); - } - return run(INIT.parser.start, str, run$1(INIT.scanner.start, str)); -} -tokenize.scan = run$1; -function find(str, type = null, opts = null) { - if (type && typeof type === "object") { - if (opts) { - throw Error(`linkifyjs: Invalid link type ${type}; must be a string`); - } - opts = type; - type = null; - } - const options = new Options(opts); - const tokens = tokenize(str); - const filtered = []; - for (let i = 0; i < tokens.length; i++) { - const token = tokens[i]; - if (token.isLink && (!type || token.t === type) && options.check(token)) { - filtered.push(token.toFormattedObject(options)); - } - } - return filtered; -} -var UNICODE_WHITESPACE_PATTERN = "[\0-   ᠎ -\u2029  ]"; -var UNICODE_WHITESPACE_REGEX = new RegExp(UNICODE_WHITESPACE_PATTERN); -var UNICODE_WHITESPACE_REGEX_END = new RegExp(`${UNICODE_WHITESPACE_PATTERN}$`); -var UNICODE_WHITESPACE_REGEX_GLOBAL = new RegExp(UNICODE_WHITESPACE_PATTERN, "g"); -function isValidLinkStructure(tokens) { - if (tokens.length === 1) { - return tokens[0].isLink; - } - if (tokens.length === 3 && tokens[1].isLink) { - return ["()", "[]"].includes(tokens[0].value + tokens[2].value); - } - return false; -} -function autolink(options) { - return new Plugin({ - key: new PluginKey("autolink"), - appendTransaction: (transactions, oldState, newState) => { - const docChanges = transactions.some((transaction) => transaction.docChanged) && !oldState.doc.eq(newState.doc); - const preventAutolink = transactions.some((transaction) => transaction.getMeta("preventAutolink")); - if (!docChanges || preventAutolink) { - return; - } - const { tr: tr2 } = newState; - const transform = combineTransactionSteps(oldState.doc, [...transactions]); - const changes = getChangedRanges(transform); - changes.forEach(({ newRange }) => { - const nodesInChangedRanges = findChildrenInRange(newState.doc, newRange, (node) => node.isTextblock); - let textBlock; - let textBeforeWhitespace; - if (nodesInChangedRanges.length > 1) { - textBlock = nodesInChangedRanges[0]; - textBeforeWhitespace = newState.doc.textBetween( - textBlock.pos, - textBlock.pos + textBlock.node.nodeSize, - void 0, - " " - ); - } else if (nodesInChangedRanges.length) { - const endText = newState.doc.textBetween(newRange.from, newRange.to, " ", " "); - if (!UNICODE_WHITESPACE_REGEX_END.test(endText)) { - return; - } - textBlock = nodesInChangedRanges[0]; - textBeforeWhitespace = newState.doc.textBetween(textBlock.pos, newRange.to, void 0, " "); - } - if (textBlock && textBeforeWhitespace) { - const wordsBeforeWhitespace = textBeforeWhitespace.split(UNICODE_WHITESPACE_REGEX).filter(Boolean); - if (wordsBeforeWhitespace.length <= 0) { - return false; - } - const lastWordBeforeSpace = wordsBeforeWhitespace[wordsBeforeWhitespace.length - 1]; - const lastWordAndBlockOffset = textBlock.pos + textBeforeWhitespace.lastIndexOf(lastWordBeforeSpace); - if (!lastWordBeforeSpace) { - return false; - } - const linksBeforeSpace = tokenize(lastWordBeforeSpace).map((t) => t.toObject(options.defaultProtocol)); - if (!isValidLinkStructure(linksBeforeSpace)) { - return false; - } - linksBeforeSpace.filter((link) => link.isLink).map((link) => ({ - ...link, - from: lastWordAndBlockOffset + link.start + 1, - to: lastWordAndBlockOffset + link.end + 1 - })).filter((link) => { - if (!newState.schema.marks.code) { - return true; - } - return !newState.doc.rangeHasMark(link.from, link.to, newState.schema.marks.code); - }).filter((link) => options.validate(link.value)).filter((link) => options.shouldAutoLink(link.value)).forEach((link) => { - if (getMarksBetween(link.from, link.to, newState.doc).some((item) => item.mark.type === options.type)) { - return; - } - tr2.addMark( - link.from, - link.to, - options.type.create({ - href: link.href - }) - ); - }); - } - }); - if (!tr2.steps.length) { - return; - } - return tr2; - } - }); -} -function clickHandler(options) { - return new Plugin({ - key: new PluginKey("handleClickLink"), - props: { - handleClick: (view, pos, event) => { - var _a, _b; - if (event.button !== 0) { - return false; - } - if (!view.editable) { - return false; - } - let link = null; - if (event.target instanceof HTMLAnchorElement) { - link = event.target; - } else { - const target = event.target; - if (!target) { - return false; - } - const root = options.editor.view.dom; - link = target.closest("a"); - if (link && !root.contains(link)) { - link = null; - } - } - if (!link) { - return false; - } - let handled = false; - if (options.enableClickSelection) { - const commandResult = options.editor.commands.extendMarkRange(options.type.name); - handled = commandResult; - } - if (options.openOnClick) { - const attrs = getAttributes(view.state, options.type.name); - const href = (_a = link.href) != null ? _a : attrs.href; - const target = (_b = link.target) != null ? _b : attrs.target; - if (href) { - window.open(href, target); - handled = true; - } - } - return handled; - } - } - }); -} -function pasteHandler(options) { - return new Plugin({ - key: new PluginKey("handlePasteLink"), - props: { - handlePaste: (view, _event, slice2) => { - const { shouldAutoLink } = options; - const { state } = view; - const { selection } = state; - const { empty: empty2 } = selection; - if (empty2) { - return false; - } - let textContent = ""; - slice2.content.forEach((node) => { - textContent += node.textContent; - }); - const link = find(textContent, { defaultProtocol: options.defaultProtocol }).find( - (item) => item.isLink && item.value === textContent - ); - if (!textContent || !link || shouldAutoLink !== void 0 && !shouldAutoLink(link.value)) { - return false; - } - return options.editor.commands.setMark(options.type, { - href: link.href - }); - } - } - }); -} -function isAllowedUri(uri, protocols) { - const allowedProtocols = ["http", "https", "ftp", "ftps", "mailto", "tel", "callto", "sms", "cid", "xmpp"]; - if (protocols) { - protocols.forEach((protocol) => { - const nextProtocol = typeof protocol === "string" ? protocol : protocol.scheme; - if (nextProtocol) { - allowedProtocols.push(nextProtocol); - } - }); - } - return !uri || uri.replace(UNICODE_WHITESPACE_REGEX_GLOBAL, "").match( - new RegExp( - // eslint-disable-next-line no-useless-escape - `^(?:(?:${allowedProtocols.join("|")}):|[^a-z]|[a-z0-9+.-]+(?:[^a-z+.-:]|$))`, - "i" - ) - ); -} -var Link = Mark2.create({ - name: "link", - priority: 1e3, - keepOnSplit: false, - exitable: true, - onCreate() { - if (this.options.validate && !this.options.shouldAutoLink) { - this.options.shouldAutoLink = this.options.validate; - console.warn("The `validate` option is deprecated. Rename to the `shouldAutoLink` option instead."); - } - this.options.protocols.forEach((protocol) => { - if (typeof protocol === "string") { - registerCustomProtocol(protocol); - return; - } - registerCustomProtocol(protocol.scheme, protocol.optionalSlashes); - }); - }, - onDestroy() { - reset(); - }, - inclusive() { - return this.options.autolink; - }, - addOptions() { - return { - openOnClick: true, - enableClickSelection: false, - linkOnPaste: true, - autolink: true, - protocols: [], - defaultProtocol: "http", - HTMLAttributes: { - target: "_blank", - rel: "noopener noreferrer nofollow", - class: null - }, - isAllowedUri: (url, ctx) => !!isAllowedUri(url, ctx.protocols), - validate: (url) => !!url, - shouldAutoLink: (url) => { - const hasProtocol = /^[a-z][a-z0-9+.-]*:\/\//i.test(url); - const hasMaybeProtocol = /^[a-z][a-z0-9+.-]*:/i.test(url); - if (hasProtocol || hasMaybeProtocol && !url.includes("@")) { - return true; - } - const urlWithoutUserinfo = url.includes("@") ? url.split("@").pop() : url; - const hostname = urlWithoutUserinfo.split(/[/?#:]/)[0]; - if (/^\d{1,3}(\.\d{1,3}){3}$/.test(hostname)) { - return false; - } - if (!/\./.test(hostname)) { - return false; - } - return true; - } - }; - }, - addAttributes() { - return { - href: { - default: null, - parseHTML(element) { - return element.getAttribute("href"); - } - }, - target: { - default: this.options.HTMLAttributes.target - }, - rel: { - default: this.options.HTMLAttributes.rel - }, - class: { - default: this.options.HTMLAttributes.class - }, - title: { - default: null - } - }; - }, - parseHTML() { - return [ - { - tag: "a[href]", - getAttrs: (dom) => { - const href = dom.getAttribute("href"); - if (!href || !this.options.isAllowedUri(href, { - defaultValidate: (url) => !!isAllowedUri(url, this.options.protocols), - protocols: this.options.protocols, - defaultProtocol: this.options.defaultProtocol - })) { - return false; - } - return null; - } - } - ]; - }, - renderHTML({ HTMLAttributes }) { - if (!this.options.isAllowedUri(HTMLAttributes.href, { - defaultValidate: (href) => !!isAllowedUri(href, this.options.protocols), - protocols: this.options.protocols, - defaultProtocol: this.options.defaultProtocol - })) { - return ["a", mergeAttributes(this.options.HTMLAttributes, { ...HTMLAttributes, href: "" }), 0]; - } - return ["a", mergeAttributes(this.options.HTMLAttributes, HTMLAttributes), 0]; - }, - markdownTokenName: "link", - parseMarkdown: (token, helpers) => { - return helpers.applyMark("link", helpers.parseInline(token.tokens || []), { - href: token.href, - title: token.title || null - }); - }, - renderMarkdown: (node, h2) => { - var _a, _b, _c, _d; - const href = (_b = (_a = node.attrs) == null ? void 0 : _a.href) != null ? _b : ""; - const title = (_d = (_c = node.attrs) == null ? void 0 : _c.title) != null ? _d : ""; - const text = h2.renderChildren(node); - return title ? `[${text}](${href} "${title}")` : `[${text}](${href})`; - }, - addCommands() { - return { - setLink: (attributes) => ({ chain }) => { - const { href } = attributes; - if (!this.options.isAllowedUri(href, { - defaultValidate: (url) => !!isAllowedUri(url, this.options.protocols), - protocols: this.options.protocols, - defaultProtocol: this.options.defaultProtocol - })) { - return false; - } - return chain().setMark(this.name, attributes).setMeta("preventAutolink", true).run(); - }, - toggleLink: (attributes) => ({ chain }) => { - const { href } = attributes || {}; - if (href && !this.options.isAllowedUri(href, { - defaultValidate: (url) => !!isAllowedUri(url, this.options.protocols), - protocols: this.options.protocols, - defaultProtocol: this.options.defaultProtocol - })) { - return false; - } - return chain().toggleMark(this.name, attributes, { extendEmptyMarkRange: true }).setMeta("preventAutolink", true).run(); - }, - unsetLink: () => ({ chain }) => { - return chain().unsetMark(this.name, { extendEmptyMarkRange: true }).setMeta("preventAutolink", true).run(); - } - }; - }, - addPasteRules() { - return [ - markPasteRule({ - find: (text) => { - const foundLinks = []; - if (text) { - const { protocols, defaultProtocol } = this.options; - const links = find(text).filter( - (item) => item.isLink && this.options.isAllowedUri(item.value, { - defaultValidate: (href) => !!isAllowedUri(href, protocols), - protocols, - defaultProtocol - }) - ); - if (links.length) { - links.forEach((link) => { - if (!this.options.shouldAutoLink(link.value)) { - return; - } - foundLinks.push({ - text: link.value, - data: { - href: link.href - }, - index: link.start - }); - }); - } - } - return foundLinks; - }, - type: this.type, - getAttributes: (match) => { - var _a; - return { - href: (_a = match.data) == null ? void 0 : _a.href - }; - } - }) - ]; - }, - addProseMirrorPlugins() { - const plugins = []; - const { protocols, defaultProtocol } = this.options; - if (this.options.autolink) { - plugins.push( - autolink({ - type: this.type, - defaultProtocol: this.options.defaultProtocol, - validate: (url) => this.options.isAllowedUri(url, { - defaultValidate: (href) => !!isAllowedUri(href, protocols), - protocols, - defaultProtocol - }), - shouldAutoLink: this.options.shouldAutoLink - }) - ); - } - plugins.push( - clickHandler({ - type: this.type, - editor: this.editor, - openOnClick: this.options.openOnClick === "whenNotEditable" ? true : this.options.openOnClick, - enableClickSelection: this.options.enableClickSelection - }) - ); - if (this.options.linkOnPaste) { - plugins.push( - pasteHandler({ - editor: this.editor, - defaultProtocol: this.options.defaultProtocol, - type: this.type, - shouldAutoLink: this.options.shouldAutoLink - }) - ); - } - return plugins; - } -}); -var index_default$5 = Link; -var __defProp = Object.defineProperty; -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var ListItemName = "listItem"; -var TextStyleName = "textStyle"; -var bulletListInputRegex = /^\s*([-+*])\s$/; -var BulletList = Node3.create({ - name: "bulletList", - addOptions() { - return { - itemTypeName: "listItem", - HTMLAttributes: {}, - keepMarks: false, - keepAttributes: false - }; - }, - group: "block list", - content() { - return `${this.options.itemTypeName}+`; - }, - parseHTML() { - return [{ tag: "ul" }]; - }, - renderHTML({ HTMLAttributes }) { - return ["ul", mergeAttributes(this.options.HTMLAttributes, HTMLAttributes), 0]; - }, - markdownTokenName: "list", - parseMarkdown: (token, helpers) => { - if (token.type !== "list" || token.ordered) { - return []; - } - return { - type: "bulletList", - content: token.items ? helpers.parseChildren(token.items) : [] - }; - }, - renderMarkdown: (node, h2) => { - if (!node.content) { - return ""; - } - return h2.renderChildren(node.content, "\n"); - }, - markdownOptions: { - indentsContent: true - }, - addCommands() { - return { - toggleBulletList: () => ({ commands, chain }) => { - if (this.options.keepAttributes) { - return chain().toggleList(this.name, this.options.itemTypeName, this.options.keepMarks).updateAttributes(ListItemName, this.editor.getAttributes(TextStyleName)).run(); - } - return commands.toggleList(this.name, this.options.itemTypeName, this.options.keepMarks); - } - }; - }, - addKeyboardShortcuts() { - return { - "Mod-Shift-8": () => this.editor.commands.toggleBulletList() - }; - }, - addInputRules() { - let inputRule = wrappingInputRule({ - find: bulletListInputRegex, - type: this.type - }); - if (this.options.keepMarks || this.options.keepAttributes) { - inputRule = wrappingInputRule({ - find: bulletListInputRegex, - type: this.type, - keepMarks: this.options.keepMarks, - keepAttributes: this.options.keepAttributes, - getAttributes: () => { - return this.editor.getAttributes(TextStyleName); - }, - editor: this.editor - }); - } - return [inputRule]; - } -}); -var ListItem = Node3.create({ - name: "listItem", - addOptions() { - return { - HTMLAttributes: {}, - bulletListTypeName: "bulletList", - orderedListTypeName: "orderedList" - }; - }, - content: "paragraph block*", - defining: true, - parseHTML() { - return [ - { - tag: "li" - } - ]; - }, - renderHTML({ HTMLAttributes }) { - return ["li", mergeAttributes(this.options.HTMLAttributes, HTMLAttributes), 0]; - }, - markdownTokenName: "list_item", - parseMarkdown: (token, helpers) => { - var _a; - if (token.type !== "list_item") { - return []; - } - const parseBlockChildren = (_a = helpers.parseBlockChildren) != null ? _a : helpers.parseChildren; - let content = []; - if (token.tokens && token.tokens.length > 0) { - const hasParagraphTokens = token.tokens.some((t) => t.type === "paragraph"); - if (hasParagraphTokens) { - content = parseBlockChildren(token.tokens); - } else { - const firstToken = token.tokens[0]; - if (firstToken && firstToken.type === "text" && firstToken.tokens && firstToken.tokens.length > 0) { - const inlineContent = helpers.parseInline(firstToken.tokens); - content = [ - { - type: "paragraph", - content: inlineContent - } - ]; - if (token.tokens.length > 1) { - const remainingTokens = token.tokens.slice(1); - const additionalContent = parseBlockChildren(remainingTokens); - content.push(...additionalContent); - } - } else { - content = parseBlockChildren(token.tokens); - } - } - } - if (content.length === 0) { - content = [ - { - type: "paragraph", - content: [] - } - ]; - } - return { - type: "listItem", - content - }; - }, - renderMarkdown: (node, h2, ctx) => { - return renderNestedMarkdownContent( - node, - h2, - (context) => { - var _a, _b; - if (context.parentType === "bulletList") { - return "- "; - } - if (context.parentType === "orderedList") { - const start = ((_b = (_a = context.meta) == null ? void 0 : _a.parentAttrs) == null ? void 0 : _b.start) || 1; - return `${start + context.index}. `; - } - return "- "; - }, - ctx - ); - }, - addKeyboardShortcuts() { - return { - Enter: () => this.editor.commands.splitListItem(this.name), - Tab: () => this.editor.commands.sinkListItem(this.name), - "Shift-Tab": () => this.editor.commands.liftListItem(this.name) - }; - } -}); -var listHelpers_exports = {}; -__export(listHelpers_exports, { - findListItemPos: () => findListItemPos, - getNextListDepth: () => getNextListDepth, - handleBackspace: () => handleBackspace, - handleDelete: () => handleDelete, - hasListBefore: () => hasListBefore, - hasListItemAfter: () => hasListItemAfter, - hasListItemBefore: () => hasListItemBefore, - listItemHasSubList: () => listItemHasSubList, - nextListIsDeeper: () => nextListIsDeeper, - nextListIsHigher: () => nextListIsHigher -}); -var findListItemPos = (typeOrName, state) => { - const { $from } = state.selection; - const nodeType = getNodeType(typeOrName, state.schema); - let currentNode = null; - let currentDepth = $from.depth; - let currentPos = $from.pos; - let targetDepth = null; - while (currentDepth > 0 && targetDepth === null) { - currentNode = $from.node(currentDepth); - if (currentNode.type === nodeType) { - targetDepth = currentDepth; - } else { - currentDepth -= 1; - currentPos -= 1; - } - } - if (targetDepth === null) { - return null; - } - return { $pos: state.doc.resolve(currentPos), depth: targetDepth }; -}; -var getNextListDepth = (typeOrName, state) => { - const listItemPos = findListItemPos(typeOrName, state); - if (!listItemPos) { - return false; - } - const [, depth] = getNodeAtPosition(state, typeOrName, listItemPos.$pos.pos + 4); - return depth; -}; -var hasListBefore = (editorState, name, parentListTypes) => { - const { $anchor } = editorState.selection; - const previousNodePos = Math.max(0, $anchor.pos - 2); - const previousNode = editorState.doc.resolve(previousNodePos).node(); - if (!previousNode || !parentListTypes.includes(previousNode.type.name)) { - return false; - } - return true; -}; -var hasListItemBefore = (typeOrName, state) => { - var _a; - const { $anchor } = state.selection; - const $targetPos = state.doc.resolve($anchor.pos - 2); - if ($targetPos.index() === 0) { - return false; - } - if (((_a = $targetPos.nodeBefore) == null ? void 0 : _a.type.name) !== typeOrName) { - return false; - } - return true; -}; -var listItemHasSubList = (typeOrName, state, node) => { - if (!node) { - return false; - } - const nodeType = getNodeType(typeOrName, state.schema); - let hasSubList = false; - node.descendants((child) => { - if (child.type === nodeType) { - hasSubList = true; - } - }); - return hasSubList; -}; -var handleBackspace = (editor, name, parentListTypes) => { - if (editor.commands.undoInputRule()) { - return true; - } - if (editor.state.selection.from !== editor.state.selection.to) { - return false; - } - if (!isNodeActive(editor.state, name) && hasListBefore(editor.state, name, parentListTypes)) { - const { $anchor } = editor.state.selection; - const $listPos = editor.state.doc.resolve($anchor.before() - 1); - const listDescendants = []; - $listPos.node().descendants((node, pos) => { - if (node.type.name === name) { - listDescendants.push({ node, pos }); - } - }); - const lastItem = listDescendants.at(-1); - if (!lastItem) { - return false; - } - const $lastItemPos = editor.state.doc.resolve($listPos.start() + lastItem.pos + 1); - return editor.chain().cut({ from: $anchor.start() - 1, to: $anchor.end() + 1 }, $lastItemPos.end()).joinForward().run(); - } - if (!isNodeActive(editor.state, name)) { - return false; - } - if (!isAtStartOfNode(editor.state)) { - return false; - } - const listItemPos = findListItemPos(name, editor.state); - if (!listItemPos) { - return false; - } - const $prev = editor.state.doc.resolve(listItemPos.$pos.pos - 2); - const prevNode = $prev.node(listItemPos.depth); - const previousListItemHasSubList = listItemHasSubList(name, editor.state, prevNode); - if (hasListItemBefore(name, editor.state) && !previousListItemHasSubList) { - return editor.commands.joinItemBackward(); - } - return editor.chain().liftListItem(name).run(); -}; -var nextListIsDeeper = (typeOrName, state) => { - const listDepth = getNextListDepth(typeOrName, state); - const listItemPos = findListItemPos(typeOrName, state); - if (!listItemPos || !listDepth) { - return false; - } - if (listDepth > listItemPos.depth) { - return true; - } - return false; -}; -var nextListIsHigher = (typeOrName, state) => { - const listDepth = getNextListDepth(typeOrName, state); - const listItemPos = findListItemPos(typeOrName, state); - if (!listItemPos || !listDepth) { - return false; - } - if (listDepth < listItemPos.depth) { - return true; - } - return false; -}; -var handleDelete = (editor, name) => { - if (!isNodeActive(editor.state, name)) { - return false; - } - if (!isAtEndOfNode(editor.state, name)) { - return false; - } - const { selection } = editor.state; - const { $from, $to } = selection; - if (!selection.empty && $from.sameParent($to)) { - return false; - } - if (nextListIsDeeper(name, editor.state)) { - return editor.chain().focus(editor.state.selection.from + 4).lift(name).joinBackward().run(); - } - if (nextListIsHigher(name, editor.state)) { - return editor.chain().joinForward().joinBackward().run(); - } - return editor.commands.joinItemForward(); -}; -var hasListItemAfter = (typeOrName, state) => { - var _a; - const { $anchor } = state.selection; - const $targetPos = state.doc.resolve($anchor.pos - $anchor.parentOffset - 2); - if ($targetPos.index() === $targetPos.parent.childCount - 1) { - return false; - } - if (((_a = $targetPos.nodeAfter) == null ? void 0 : _a.type.name) !== typeOrName) { - return false; - } - return true; -}; -var ListKeymap = Extension.create({ - name: "listKeymap", - addOptions() { - return { - listTypes: [ - { - itemName: "listItem", - wrapperNames: ["bulletList", "orderedList"] - }, - { - itemName: "taskItem", - wrapperNames: ["taskList"] - } - ] - }; - }, - addKeyboardShortcuts() { - return { - Delete: ({ editor }) => { - let handled = false; - this.options.listTypes.forEach(({ itemName }) => { - if (editor.state.schema.nodes[itemName] === void 0) { - return; - } - if (handleDelete(editor, itemName)) { - handled = true; - } - }); - return handled; - }, - "Mod-Delete": ({ editor }) => { - let handled = false; - this.options.listTypes.forEach(({ itemName }) => { - if (editor.state.schema.nodes[itemName] === void 0) { - return; - } - if (handleDelete(editor, itemName)) { - handled = true; - } - }); - return handled; - }, - Backspace: ({ editor }) => { - let handled = false; - this.options.listTypes.forEach(({ itemName, wrapperNames }) => { - if (editor.state.schema.nodes[itemName] === void 0) { - return; - } - if (handleBackspace(editor, itemName, wrapperNames)) { - handled = true; - } - }); - return handled; - }, - "Mod-Backspace": ({ editor }) => { - let handled = false; - this.options.listTypes.forEach(({ itemName, wrapperNames }) => { - if (editor.state.schema.nodes[itemName] === void 0) { - return; - } - if (handleBackspace(editor, itemName, wrapperNames)) { - handled = true; - } - }); - return handled; - } - }; - } -}); -var ORDERED_LIST_ITEM_REGEX = /^(\s*)(\d+)\.\s+(.*)$/; -var INDENTED_LINE_REGEX = /^\s/; -function collectOrderedListItems(lines) { - const listItems = []; - let currentLineIndex = 0; - let consumed = 0; - while (currentLineIndex < lines.length) { - const line = lines[currentLineIndex]; - const match = line.match(ORDERED_LIST_ITEM_REGEX); - if (!match) { - break; - } - const [, indent, number, content] = match; - const indentLevel = indent.length; - let itemContent = content; - let nextLineIndex = currentLineIndex + 1; - const itemLines = [line]; - while (nextLineIndex < lines.length) { - const nextLine = lines[nextLineIndex]; - const nextMatch = nextLine.match(ORDERED_LIST_ITEM_REGEX); - if (nextMatch) { - break; - } - if (nextLine.trim() === "") { - itemLines.push(nextLine); - itemContent += "\n"; - nextLineIndex += 1; - } else if (nextLine.match(INDENTED_LINE_REGEX)) { - itemLines.push(nextLine); - itemContent += ` -${nextLine.slice(indentLevel + 2)}`; - nextLineIndex += 1; - } else { - break; - } - } - listItems.push({ - indent: indentLevel, - number: parseInt(number, 10), - content: itemContent.trim(), - raw: itemLines.join("\n") - }); - consumed = nextLineIndex; - currentLineIndex = nextLineIndex; - } - return [listItems, consumed]; -} -function buildNestedStructure(items, baseIndent, lexer) { - var _a; - const result = []; - let currentIndex = 0; - while (currentIndex < items.length) { - const item = items[currentIndex]; - if (item.indent === baseIndent) { - const contentLines = item.content.split("\n"); - const mainText = ((_a = contentLines[0]) == null ? void 0 : _a.trim()) || ""; - const tokens = []; - if (mainText) { - tokens.push({ - type: "paragraph", - raw: mainText, - tokens: lexer.inlineTokens(mainText) - }); - } - const additionalContent = contentLines.slice(1).join("\n").trim(); - if (additionalContent) { - const blockTokens = lexer.blockTokens(additionalContent); - tokens.push(...blockTokens); - } - let lookAheadIndex = currentIndex + 1; - const nestedItems = []; - while (lookAheadIndex < items.length && items[lookAheadIndex].indent > baseIndent) { - nestedItems.push(items[lookAheadIndex]); - lookAheadIndex += 1; - } - if (nestedItems.length > 0) { - const nextIndent = Math.min(...nestedItems.map((nestedItem) => nestedItem.indent)); - const nestedListItems = buildNestedStructure(nestedItems, nextIndent, lexer); - tokens.push({ - type: "list", - ordered: true, - start: nestedItems[0].number, - items: nestedListItems, - raw: nestedItems.map((nestedItem) => nestedItem.raw).join("\n") - }); - } - result.push({ - type: "list_item", - raw: item.raw, - tokens - }); - currentIndex = lookAheadIndex; - } else { - currentIndex += 1; - } - } - return result; -} -function parseListItems(items, helpers) { - return items.map((item) => { - if (item.type !== "list_item") { - return helpers.parseChildren([item])[0]; - } - const content = []; - if (item.tokens && item.tokens.length > 0) { - item.tokens.forEach((itemToken) => { - if (itemToken.type === "paragraph" || itemToken.type === "list" || itemToken.type === "blockquote" || itemToken.type === "code") { - content.push(...helpers.parseChildren([itemToken])); - } else if (itemToken.type === "text" && itemToken.tokens) { - const inlineContent = helpers.parseChildren([itemToken]); - content.push({ - type: "paragraph", - content: inlineContent - }); - } else { - const parsed = helpers.parseChildren([itemToken]); - if (parsed.length > 0) { - content.push(...parsed); - } - } - }); - } - return { - type: "listItem", - content - }; - }); -} -var ListItemName2 = "listItem"; -var TextStyleName2 = "textStyle"; -var orderedListInputRegex = /^(\d+)\.\s$/; -var OrderedList = Node3.create({ - name: "orderedList", - addOptions() { - return { - itemTypeName: "listItem", - HTMLAttributes: {}, - keepMarks: false, - keepAttributes: false - }; - }, - group: "block list", - content() { - return `${this.options.itemTypeName}+`; - }, - addAttributes() { - return { - start: { - default: 1, - parseHTML: (element) => { - return element.hasAttribute("start") ? parseInt(element.getAttribute("start") || "", 10) : 1; - } - }, - type: { - default: null, - parseHTML: (element) => element.getAttribute("type") - } - }; - }, - parseHTML() { - return [ - { - tag: "ol" - } - ]; - }, - renderHTML({ HTMLAttributes }) { - const { start, ...attributesWithoutStart } = HTMLAttributes; - return start === 1 ? ["ol", mergeAttributes(this.options.HTMLAttributes, attributesWithoutStart), 0] : ["ol", mergeAttributes(this.options.HTMLAttributes, HTMLAttributes), 0]; - }, - markdownTokenName: "list", - parseMarkdown: (token, helpers) => { - if (token.type !== "list" || !token.ordered) { - return []; - } - const startValue = token.start || 1; - const content = token.items ? parseListItems(token.items, helpers) : []; - if (startValue !== 1) { - return { - type: "orderedList", - attrs: { start: startValue }, - content - }; - } - return { - type: "orderedList", - content - }; - }, - renderMarkdown: (node, h2) => { - if (!node.content) { - return ""; - } - return h2.renderChildren(node.content, "\n"); - }, - markdownTokenizer: { - name: "orderedList", - level: "block", - start: (src) => { - const match = src.match(/^(\s*)(\d+)\.\s+/); - const index = match == null ? void 0 : match.index; - return index !== void 0 ? index : -1; - }, - tokenize: (src, _tokens, lexer) => { - var _a; - const lines = src.split("\n"); - const [listItems, consumed] = collectOrderedListItems(lines); - if (listItems.length === 0) { - return void 0; - } - const items = buildNestedStructure(listItems, 0, lexer); - if (items.length === 0) { - return void 0; - } - const startValue = ((_a = listItems[0]) == null ? void 0 : _a.number) || 1; - return { - type: "list", - ordered: true, - start: startValue, - items, - raw: lines.slice(0, consumed).join("\n") - }; - } - }, - markdownOptions: { - indentsContent: true - }, - addCommands() { - return { - toggleOrderedList: () => ({ commands, chain }) => { - if (this.options.keepAttributes) { - return chain().toggleList(this.name, this.options.itemTypeName, this.options.keepMarks).updateAttributes(ListItemName2, this.editor.getAttributes(TextStyleName2)).run(); - } - return commands.toggleList(this.name, this.options.itemTypeName, this.options.keepMarks); - } - }; - }, - addKeyboardShortcuts() { - return { - "Mod-Shift-7": () => this.editor.commands.toggleOrderedList() - }; - }, - addInputRules() { - let inputRule = wrappingInputRule({ - find: orderedListInputRegex, - type: this.type, - getAttributes: (match) => ({ start: +match[1] }), - joinPredicate: (match, node) => node.childCount + node.attrs.start === +match[1] - }); - if (this.options.keepMarks || this.options.keepAttributes) { - inputRule = wrappingInputRule({ - find: orderedListInputRegex, - type: this.type, - keepMarks: this.options.keepMarks, - keepAttributes: this.options.keepAttributes, - getAttributes: (match) => ({ start: +match[1], ...this.editor.getAttributes(TextStyleName2) }), - joinPredicate: (match, node) => node.childCount + node.attrs.start === +match[1], - editor: this.editor - }); - } - return [inputRule]; - } -}); -var inputRegex$2 = /^\s*(\[([( |x])?\])\s$/; -var TaskItem = Node3.create({ - name: "taskItem", - addOptions() { - return { - nested: false, - HTMLAttributes: {}, - taskListTypeName: "taskList", - a11y: void 0 - }; - }, - content() { - return this.options.nested ? "paragraph block*" : "paragraph+"; - }, - defining: true, - addAttributes() { - return { - checked: { - default: false, - keepOnSplit: false, - parseHTML: (element) => { - const dataChecked = element.getAttribute("data-checked"); - return dataChecked === "" || dataChecked === "true"; - }, - renderHTML: (attributes) => ({ - "data-checked": attributes.checked - }) - } - }; - }, - parseHTML() { - return [ - { - tag: `li[data-type="${this.name}"]`, - priority: 51 - } - ]; - }, - renderHTML({ node, HTMLAttributes }) { - return [ - "li", - mergeAttributes(this.options.HTMLAttributes, HTMLAttributes, { - "data-type": this.name - }), - [ - "label", - [ - "input", - { - type: "checkbox", - checked: node.attrs.checked ? "checked" : null - } - ], - ["span"] - ], - ["div", 0] - ]; - }, - parseMarkdown: (token, h2) => { - const content = []; - if (token.tokens && token.tokens.length > 0) { - content.push(h2.createNode("paragraph", {}, h2.parseInline(token.tokens))); - } else if (token.text) { - content.push(h2.createNode("paragraph", {}, [h2.createNode("text", { text: token.text })])); - } else { - content.push(h2.createNode("paragraph", {}, [])); - } - if (token.nestedTokens && token.nestedTokens.length > 0) { - const nestedContent = h2.parseChildren(token.nestedTokens); - content.push(...nestedContent); - } - return h2.createNode("taskItem", { checked: token.checked || false }, content); - }, - renderMarkdown: (node, h2) => { - var _a; - const checkedChar = ((_a = node.attrs) == null ? void 0 : _a.checked) ? "x" : " "; - const prefix = `- [${checkedChar}] `; - return renderNestedMarkdownContent(node, h2, prefix); - }, - addKeyboardShortcuts() { - const shortcuts = { - Enter: () => this.editor.commands.splitListItem(this.name), - "Shift-Tab": () => this.editor.commands.liftListItem(this.name) - }; - if (!this.options.nested) { - return shortcuts; - } - return { - ...shortcuts, - Tab: () => this.editor.commands.sinkListItem(this.name) - }; - }, - addNodeView() { - return ({ node, HTMLAttributes, getPos, editor }) => { - const listItem = document.createElement("li"); - const checkboxWrapper = document.createElement("label"); - const checkboxStyler = document.createElement("span"); - const checkbox = document.createElement("input"); - const content = document.createElement("div"); - const updateA11Y = (currentNode) => { - var _a, _b; - checkbox.ariaLabel = ((_b = (_a = this.options.a11y) == null ? void 0 : _a.checkboxLabel) == null ? void 0 : _b.call(_a, currentNode, checkbox.checked)) || `Task item checkbox for ${currentNode.textContent || "empty task item"}`; - }; - updateA11Y(node); - checkboxWrapper.contentEditable = "false"; - checkbox.type = "checkbox"; - checkbox.addEventListener("mousedown", (event) => event.preventDefault()); - checkbox.addEventListener("change", (event) => { - if (!editor.isEditable && !this.options.onReadOnlyChecked) { - checkbox.checked = !checkbox.checked; - return; - } - const { checked } = event.target; - if (editor.isEditable && typeof getPos === "function") { - editor.chain().focus(void 0, { scrollIntoView: false }).command(({ tr: tr2 }) => { - const position = getPos(); - if (typeof position !== "number") { - return false; - } - const currentNode = tr2.doc.nodeAt(position); - tr2.setNodeMarkup(position, void 0, { - ...currentNode == null ? void 0 : currentNode.attrs, - checked - }); - return true; - }).run(); - } - if (!editor.isEditable && this.options.onReadOnlyChecked) { - if (!this.options.onReadOnlyChecked(node, checked)) { - checkbox.checked = !checkbox.checked; - } - } - }); - Object.entries(this.options.HTMLAttributes).forEach(([key, value]) => { - listItem.setAttribute(key, value); - }); - listItem.dataset.checked = node.attrs.checked; - checkbox.checked = node.attrs.checked; - checkboxWrapper.append(checkbox, checkboxStyler); - listItem.append(checkboxWrapper, content); - Object.entries(HTMLAttributes).forEach(([key, value]) => { - listItem.setAttribute(key, value); - }); - let prevRenderedAttributeKeys = new Set(Object.keys(HTMLAttributes)); - return { - dom: listItem, - contentDOM: content, - update: (updatedNode) => { - if (updatedNode.type !== this.type) { - return false; - } - listItem.dataset.checked = updatedNode.attrs.checked; - checkbox.checked = updatedNode.attrs.checked; - updateA11Y(updatedNode); - const extensionAttributes = editor.extensionManager.attributes; - const newHTMLAttributes = getRenderedAttributes(updatedNode, extensionAttributes); - const newKeys = new Set(Object.keys(newHTMLAttributes)); - const staticAttrs = this.options.HTMLAttributes; - prevRenderedAttributeKeys.forEach((key) => { - if (!newKeys.has(key)) { - if (key in staticAttrs) { - listItem.setAttribute(key, staticAttrs[key]); - } else { - listItem.removeAttribute(key); - } - } - }); - Object.entries(newHTMLAttributes).forEach(([key, value]) => { - if (value === null || value === void 0) { - if (key in staticAttrs) { - listItem.setAttribute(key, staticAttrs[key]); - } else { - listItem.removeAttribute(key); - } - } else { - listItem.setAttribute(key, value); - } - }); - prevRenderedAttributeKeys = newKeys; - return true; - } - }; - }; - }, - addInputRules() { - return [ - wrappingInputRule({ - find: inputRegex$2, - type: this.type, - getAttributes: (match) => ({ - checked: match[match.length - 1] === "x" - }) - }) - ]; - } -}); -var TaskList = Node3.create({ - name: "taskList", - addOptions() { - return { - itemTypeName: "taskItem", - HTMLAttributes: {} - }; - }, - group: "block list", - content() { - return `${this.options.itemTypeName}+`; - }, - parseHTML() { - return [ - { - tag: `ul[data-type="${this.name}"]`, - priority: 51 - } - ]; - }, - renderHTML({ HTMLAttributes }) { - return ["ul", mergeAttributes(this.options.HTMLAttributes, HTMLAttributes, { "data-type": this.name }), 0]; - }, - parseMarkdown: (token, h2) => { - return h2.createNode("taskList", {}, h2.parseChildren(token.items || [])); - }, - renderMarkdown: (node, h2) => { - if (!node.content) { - return ""; - } - return h2.renderChildren(node.content, "\n"); - }, - markdownTokenizer: { - name: "taskList", - level: "block", - start(src) { - var _a; - const index = (_a = src.match(/^\s*[-+*]\s+\[([ xX])\]\s+/)) == null ? void 0 : _a.index; - return index !== void 0 ? index : -1; - }, - tokenize(src, tokens, lexer) { - const parseTaskListContent = (content) => { - const nestedResult = parseIndentedBlocks( - content, - { - itemPattern: /^(\s*)([-+*])\s+\[([ xX])\]\s+(.*)$/, - extractItemData: (match) => ({ - indentLevel: match[1].length, - mainContent: match[4], - checked: match[3].toLowerCase() === "x" - }), - createToken: (data, nestedTokens) => ({ - type: "taskItem", - raw: "", - mainContent: data.mainContent, - indentLevel: data.indentLevel, - checked: data.checked, - text: data.mainContent, - tokens: lexer.inlineTokens(data.mainContent), - nestedTokens - }), - // Allow recursive nesting - customNestedParser: parseTaskListContent - }, - lexer - ); - if (nestedResult) { - return [ - { - type: "taskList", - raw: nestedResult.raw, - items: nestedResult.items - } - ]; - } - return lexer.blockTokens(content); - }; - const result = parseIndentedBlocks( - src, - { - itemPattern: /^(\s*)([-+*])\s+\[([ xX])\]\s+(.*)$/, - extractItemData: (match) => ({ - indentLevel: match[1].length, - mainContent: match[4], - checked: match[3].toLowerCase() === "x" - }), - createToken: (data, nestedTokens) => ({ - type: "taskItem", - raw: "", - mainContent: data.mainContent, - indentLevel: data.indentLevel, - checked: data.checked, - text: data.mainContent, - tokens: lexer.inlineTokens(data.mainContent), - nestedTokens - }), - // Use the recursive parser for nested content - customNestedParser: parseTaskListContent - }, - lexer - ); - if (!result) { - return void 0; - } - return { - type: "taskList", - raw: result.raw, - items: result.items - }; - } - }, - markdownOptions: { - indentsContent: true - }, - addCommands() { - return { - toggleTaskList: () => ({ commands }) => { - return commands.toggleList(this.name, this.options.itemTypeName); - } - }; - }, - addKeyboardShortcuts() { - return { - "Mod-Shift-9": () => this.editor.commands.toggleTaskList() - }; - } -}); -Extension.create({ - name: "listKit", - addExtensions() { - const extensions = []; - if (this.options.bulletList !== false) { - extensions.push(BulletList.configure(this.options.bulletList)); - } - if (this.options.listItem !== false) { - extensions.push(ListItem.configure(this.options.listItem)); - } - if (this.options.listKeymap !== false) { - extensions.push(ListKeymap.configure(this.options.listKeymap)); - } - if (this.options.orderedList !== false) { - extensions.push(OrderedList.configure(this.options.orderedList)); - } - if (this.options.taskItem !== false) { - extensions.push(TaskItem.configure(this.options.taskItem)); - } - if (this.options.taskList !== false) { - extensions.push(TaskList.configure(this.options.taskList)); - } - return extensions; - } -}); -var EMPTY_PARAGRAPH_MARKDOWN = " "; -var NBSP_CHAR = " "; -var Paragraph = Node3.create({ - name: "paragraph", - priority: 1e3, - addOptions() { - return { - HTMLAttributes: {} - }; - }, - group: "block", - content: "inline*", - parseHTML() { - return [{ tag: "p" }]; - }, - renderHTML({ HTMLAttributes }) { - return ["p", mergeAttributes(this.options.HTMLAttributes, HTMLAttributes), 0]; - }, - parseMarkdown: (token, helpers) => { - const tokens = token.tokens || []; - if (tokens.length === 1 && tokens[0].type === "image") { - return helpers.parseChildren([tokens[0]]); - } - const content = helpers.parseInline(tokens); - const hasExplicitEmptyParagraphMarker = tokens.length === 1 && tokens[0].type === "text" && (tokens[0].raw === EMPTY_PARAGRAPH_MARKDOWN || tokens[0].text === EMPTY_PARAGRAPH_MARKDOWN || tokens[0].raw === NBSP_CHAR || tokens[0].text === NBSP_CHAR); - if (hasExplicitEmptyParagraphMarker && content.length === 1 && content[0].type === "text" && (content[0].text === EMPTY_PARAGRAPH_MARKDOWN || content[0].text === NBSP_CHAR)) { - return helpers.createNode("paragraph", void 0, []); - } - return helpers.createNode("paragraph", void 0, content); - }, - renderMarkdown: (node, h2, ctx) => { - var _a, _b; - if (!node) { - return ""; - } - const content = Array.isArray(node.content) ? node.content : []; - if (content.length === 0) { - const previousContent = Array.isArray((_a = ctx == null ? void 0 : ctx.previousNode) == null ? void 0 : _a.content) ? ctx.previousNode.content : []; - const previousNodeIsEmptyParagraph = ((_b = ctx == null ? void 0 : ctx.previousNode) == null ? void 0 : _b.type) === "paragraph" && previousContent.length === 0; - return previousNodeIsEmptyParagraph ? EMPTY_PARAGRAPH_MARKDOWN : ""; - } - return h2.renderChildren(content); - }, - addCommands() { - return { - setParagraph: () => ({ commands }) => { - return commands.setNode(this.name); - } - }; - }, - addKeyboardShortcuts() { - return { - "Mod-Alt-0": () => this.editor.commands.setParagraph() - }; - } -}); -var inputRegex$1 = /(?:^|\s)(~~(?!\s+~~)((?:[^~]+))~~(?!\s+~~))$/; -var pasteRegex = /(?:^|\s)(~~(?!\s+~~)((?:[^~]+))~~(?!\s+~~))/g; -var Strike = Mark2.create({ - name: "strike", - addOptions() { - return { - HTMLAttributes: {} - }; - }, - parseHTML() { - return [ - { - tag: "s" - }, - { - tag: "del" - }, - { - tag: "strike" - }, - { - style: "text-decoration", - consuming: false, - getAttrs: (style2) => style2.includes("line-through") ? {} : false - } - ]; - }, - renderHTML({ HTMLAttributes }) { - return ["s", mergeAttributes(this.options.HTMLAttributes, HTMLAttributes), 0]; - }, - markdownTokenName: "del", - parseMarkdown: (token, helpers) => { - return helpers.applyMark("strike", helpers.parseInline(token.tokens || [])); - }, - renderMarkdown: (node, h2) => { - return `~~${h2.renderChildren(node)}~~`; - }, - addCommands() { - return { - setStrike: () => ({ commands }) => { - return commands.setMark(this.name); - }, - toggleStrike: () => ({ commands }) => { - return commands.toggleMark(this.name); - }, - unsetStrike: () => ({ commands }) => { - return commands.unsetMark(this.name); - } - }; - }, - addKeyboardShortcuts() { - return { - "Mod-Shift-s": () => this.editor.commands.toggleStrike() - }; - }, - addInputRules() { - return [ - markInputRule({ - find: inputRegex$1, - type: this.type - }) - ]; - }, - addPasteRules() { - return [ - markPasteRule({ - find: pasteRegex, - type: this.type - }) - ]; - } -}); -var Text = Node3.create({ - name: "text", - group: "inline", - parseMarkdown: (token) => { - return { - type: "text", - text: token.text || "" - }; - }, - renderMarkdown: (node) => node.text || "" -}); -var Underline = Mark2.create({ - name: "underline", - addOptions() { - return { - HTMLAttributes: {} - }; - }, - parseHTML() { - return [ - { - tag: "u" - }, - { - style: "text-decoration", - consuming: false, - getAttrs: (style2) => style2.includes("underline") ? {} : false - } - ]; - }, - renderHTML({ HTMLAttributes }) { - return ["u", mergeAttributes(this.options.HTMLAttributes, HTMLAttributes), 0]; - }, - parseMarkdown(token, helpers) { - return helpers.applyMark(this.name || "underline", helpers.parseInline(token.tokens || [])); - }, - renderMarkdown(node, helpers) { - return `++${helpers.renderChildren(node)}++`; - }, - markdownTokenizer: { - name: "underline", - level: "inline", - start(src) { - return src.indexOf("++"); - }, - tokenize(src, _tokens, lexer) { - const rule = /^(\+\+)([\s\S]+?)(\+\+)/; - const match = rule.exec(src); - if (!match) { - return void 0; - } - const innerContent = match[2].trim(); - return { - type: "underline", - raw: match[0], - text: innerContent, - tokens: lexer.inlineTokens(innerContent) - }; - } - }, - addCommands() { - return { - setUnderline: () => ({ commands }) => { - return commands.setMark(this.name); - }, - toggleUnderline: () => ({ commands }) => { - return commands.toggleMark(this.name); - }, - unsetUnderline: () => ({ commands }) => { - return commands.unsetMark(this.name); - } - }; - }, - addKeyboardShortcuts() { - return { - "Mod-u": () => this.editor.commands.toggleUnderline(), - "Mod-U": () => this.editor.commands.toggleUnderline() - }; - } -}); -var index_default$4 = Underline; -function dropCursor(options = {}) { - return new Plugin({ - view(editorView) { - return new DropCursorView(editorView, options); - } - }); -} -class DropCursorView { - constructor(editorView, options) { - var _a; - this.editorView = editorView; - this.cursorPos = null; - this.element = null; - this.timeout = -1; - this.width = (_a = options.width) !== null && _a !== void 0 ? _a : 1; - this.color = options.color === false ? void 0 : options.color || "black"; - this.class = options.class; - this.handlers = ["dragover", "dragend", "drop", "dragleave"].map((name) => { - let handler = (e) => { - this[name](e); - }; - editorView.dom.addEventListener(name, handler); - return { name, handler }; - }); - } - destroy() { - this.handlers.forEach(({ name, handler }) => this.editorView.dom.removeEventListener(name, handler)); - } - update(editorView, prevState) { - if (this.cursorPos != null && prevState.doc != editorView.state.doc) { - if (this.cursorPos > editorView.state.doc.content.size) - this.setCursor(null); - else - this.updateOverlay(); - } - } - setCursor(pos) { - if (pos == this.cursorPos) - return; - this.cursorPos = pos; - if (pos == null) { - this.element.parentNode.removeChild(this.element); - this.element = null; - } else { - this.updateOverlay(); - } - } - updateOverlay() { - let $pos = this.editorView.state.doc.resolve(this.cursorPos); - let isBlock = !$pos.parent.inlineContent, rect; - let editorDOM = this.editorView.dom, editorRect = editorDOM.getBoundingClientRect(); - let scaleX = editorRect.width / editorDOM.offsetWidth, scaleY = editorRect.height / editorDOM.offsetHeight; - if (isBlock) { - let before = $pos.nodeBefore, after = $pos.nodeAfter; - if (before || after) { - let node = this.editorView.nodeDOM(this.cursorPos - (before ? before.nodeSize : 0)); - if (node) { - let nodeRect = node.getBoundingClientRect(); - let top = before ? nodeRect.bottom : nodeRect.top; - if (before && after) - top = (top + this.editorView.nodeDOM(this.cursorPos).getBoundingClientRect().top) / 2; - let halfWidth = this.width / 2 * scaleY; - rect = { left: nodeRect.left, right: nodeRect.right, top: top - halfWidth, bottom: top + halfWidth }; - } - } - } - if (!rect) { - let coords = this.editorView.coordsAtPos(this.cursorPos); - let halfWidth = this.width / 2 * scaleX; - rect = { left: coords.left - halfWidth, right: coords.left + halfWidth, top: coords.top, bottom: coords.bottom }; - } - let parent = this.editorView.dom.offsetParent; - if (!this.element) { - this.element = parent.appendChild(document.createElement("div")); - if (this.class) - this.element.className = this.class; - this.element.style.cssText = "position: absolute; z-index: 50; pointer-events: none;"; - if (this.color) { - this.element.style.backgroundColor = this.color; - } - } - this.element.classList.toggle("prosemirror-dropcursor-block", isBlock); - this.element.classList.toggle("prosemirror-dropcursor-inline", !isBlock); - let parentLeft, parentTop; - if (!parent || parent == document.body && getComputedStyle(parent).position == "static") { - parentLeft = -pageXOffset; - parentTop = -pageYOffset; - } else { - let rect2 = parent.getBoundingClientRect(); - let parentScaleX = rect2.width / parent.offsetWidth, parentScaleY = rect2.height / parent.offsetHeight; - parentLeft = rect2.left - parent.scrollLeft * parentScaleX; - parentTop = rect2.top - parent.scrollTop * parentScaleY; - } - this.element.style.left = (rect.left - parentLeft) / scaleX + "px"; - this.element.style.top = (rect.top - parentTop) / scaleY + "px"; - this.element.style.width = (rect.right - rect.left) / scaleX + "px"; - this.element.style.height = (rect.bottom - rect.top) / scaleY + "px"; - } - scheduleRemoval(timeout) { - clearTimeout(this.timeout); - this.timeout = setTimeout(() => this.setCursor(null), timeout); - } - dragover(event) { - if (!this.editorView.editable) - return; - let pos = this.editorView.posAtCoords({ left: event.clientX, top: event.clientY }); - let node = pos && pos.inside >= 0 && this.editorView.state.doc.nodeAt(pos.inside); - let disableDropCursor = node && node.type.spec.disableDropCursor; - let disabled = typeof disableDropCursor == "function" ? disableDropCursor(this.editorView, pos, event) : disableDropCursor; - if (pos && !disabled) { - let target = pos.pos; - if (this.editorView.dragging && this.editorView.dragging.slice) { - let point = dropPoint(this.editorView.state.doc, target, this.editorView.dragging.slice); - if (point != null) - target = point; - } - this.setCursor(target); - this.scheduleRemoval(5e3); - } - } - dragend() { - this.scheduleRemoval(20); - } - drop() { - this.scheduleRemoval(20); - } - dragleave(event) { - if (!this.editorView.dom.contains(event.relatedTarget)) - this.setCursor(null); - } -} -class GapCursor extends Selection { - /** - Create a gap cursor. - */ - constructor($pos) { - super($pos, $pos); - } - map(doc2, mapping) { - let $pos = doc2.resolve(mapping.map(this.head)); - return GapCursor.valid($pos) ? new GapCursor($pos) : Selection.near($pos); - } - content() { - return Slice.empty; - } - eq(other) { - return other instanceof GapCursor && other.head == this.head; - } - toJSON() { - return { type: "gapcursor", pos: this.head }; - } - /** - @internal - */ - static fromJSON(doc2, json) { - if (typeof json.pos != "number") - throw new RangeError("Invalid input for GapCursor.fromJSON"); - return new GapCursor(doc2.resolve(json.pos)); - } - /** - @internal - */ - getBookmark() { - return new GapBookmark(this.anchor); - } - /** - @internal - */ - static valid($pos) { - let parent = $pos.parent; - if (parent.inlineContent || !closedBefore($pos) || !closedAfter($pos)) - return false; - let override = parent.type.spec.allowGapCursor; - if (override != null) - return override; - let deflt = parent.contentMatchAt($pos.index()).defaultType; - return deflt && deflt.isTextblock; - } - /** - @internal - */ - static findGapCursorFrom($pos, dir, mustMove = false) { - search: for (; ; ) { - if (!mustMove && GapCursor.valid($pos)) - return $pos; - let pos = $pos.pos, next = null; - for (let d = $pos.depth; ; d--) { - let parent = $pos.node(d); - if (dir > 0 ? $pos.indexAfter(d) < parent.childCount : $pos.index(d) > 0) { - next = parent.child(dir > 0 ? $pos.indexAfter(d) : $pos.index(d) - 1); - break; - } else if (d == 0) { - return null; - } - pos += dir; - let $cur = $pos.doc.resolve(pos); - if (GapCursor.valid($cur)) - return $cur; - } - for (; ; ) { - let inside = dir > 0 ? next.firstChild : next.lastChild; - if (!inside) { - if (next.isAtom && !next.isText && !NodeSelection.isSelectable(next)) { - $pos = $pos.doc.resolve(pos + next.nodeSize * dir); - mustMove = false; - continue search; - } - break; - } - next = inside; - pos += dir; - let $cur = $pos.doc.resolve(pos); - if (GapCursor.valid($cur)) - return $cur; - } - return null; - } - } -} -GapCursor.prototype.visible = false; -GapCursor.findFrom = GapCursor.findGapCursorFrom; -Selection.jsonID("gapcursor", GapCursor); -class GapBookmark { - constructor(pos) { - this.pos = pos; - } - map(mapping) { - return new GapBookmark(mapping.map(this.pos)); - } - resolve(doc2) { - let $pos = doc2.resolve(this.pos); - return GapCursor.valid($pos) ? new GapCursor($pos) : Selection.near($pos); - } -} -function needsGap(type) { - return type.isAtom || type.spec.isolating || type.spec.createGapCursor; -} -function closedBefore($pos) { - for (let d = $pos.depth; d >= 0; d--) { - let index = $pos.index(d), parent = $pos.node(d); - if (index == 0) { - if (parent.type.spec.isolating) - return true; - continue; - } - for (let before = parent.child(index - 1); ; before = before.lastChild) { - if (before.childCount == 0 && !before.inlineContent || needsGap(before.type)) - return true; - if (before.inlineContent) - return false; - } - } - return true; -} -function closedAfter($pos) { - for (let d = $pos.depth; d >= 0; d--) { - let index = $pos.indexAfter(d), parent = $pos.node(d); - if (index == parent.childCount) { - if (parent.type.spec.isolating) - return true; - continue; - } - for (let after = parent.child(index); ; after = after.firstChild) { - if (after.childCount == 0 && !after.inlineContent || needsGap(after.type)) - return true; - if (after.inlineContent) - return false; - } - } - return true; -} -function gapCursor() { - return new Plugin({ - props: { - decorations: drawGapCursor, - createSelectionBetween(_view, $anchor, $head) { - return $anchor.pos == $head.pos && GapCursor.valid($head) ? new GapCursor($head) : null; - }, - handleClick, - handleKeyDown, - handleDOMEvents: { beforeinput } - } - }); -} -const handleKeyDown = keydownHandler({ - "ArrowLeft": arrow("horiz", -1), - "ArrowRight": arrow("horiz", 1), - "ArrowUp": arrow("vert", -1), - "ArrowDown": arrow("vert", 1) -}); -function arrow(axis, dir) { - const dirStr = axis == "vert" ? dir > 0 ? "down" : "up" : dir > 0 ? "right" : "left"; - return function(state, dispatch, view) { - let sel = state.selection; - let $start = dir > 0 ? sel.$to : sel.$from, mustMove = sel.empty; - if (sel instanceof TextSelection) { - if (!view.endOfTextblock(dirStr) || $start.depth == 0) - return false; - mustMove = false; - $start = state.doc.resolve(dir > 0 ? $start.after() : $start.before()); - } - let $found = GapCursor.findGapCursorFrom($start, dir, mustMove); - if (!$found) - return false; - if (dispatch) - dispatch(state.tr.setSelection(new GapCursor($found))); - return true; - }; -} -function handleClick(view, pos, event) { - if (!view || !view.editable) - return false; - let $pos = view.state.doc.resolve(pos); - if (!GapCursor.valid($pos)) - return false; - let clickPos = view.posAtCoords({ left: event.clientX, top: event.clientY }); - if (clickPos && clickPos.inside > -1 && NodeSelection.isSelectable(view.state.doc.nodeAt(clickPos.inside))) - return false; - view.dispatch(view.state.tr.setSelection(new GapCursor($pos))); - return true; -} -function beforeinput(view, event) { - if (event.inputType != "insertCompositionText" || !(view.state.selection instanceof GapCursor)) - return false; - let { $from } = view.state.selection; - let insert = $from.parent.contentMatchAt($from.index()).findWrapping(view.state.schema.nodes.text); - if (!insert) - return false; - let frag = Fragment.empty; - for (let i = insert.length - 1; i >= 0; i--) - frag = Fragment.from(insert[i].createAndFill(null, frag)); - let tr2 = view.state.tr.replace($from.pos, $from.pos, new Slice(frag, 0, 0)); - tr2.setSelection(TextSelection.near(tr2.doc.resolve($from.pos + 1))); - view.dispatch(tr2); - return false; -} -function drawGapCursor(state) { - if (!(state.selection instanceof GapCursor)) - return null; - let node = document.createElement("div"); - node.className = "ProseMirror-gapcursor"; - return DecorationSet.create(state.doc, [Decoration.widget(state.selection.head, node, { key: "gapcursor" })]); -} -var GOOD_LEAF_SIZE = 200; -var RopeSequence = function RopeSequence2() { -}; -RopeSequence.prototype.append = function append(other) { - if (!other.length) { - return this; - } - other = RopeSequence.from(other); - return !this.length && other || other.length < GOOD_LEAF_SIZE && this.leafAppend(other) || this.length < GOOD_LEAF_SIZE && other.leafPrepend(this) || this.appendInner(other); -}; -RopeSequence.prototype.prepend = function prepend(other) { - if (!other.length) { - return this; - } - return RopeSequence.from(other).append(this); -}; -RopeSequence.prototype.appendInner = function appendInner(other) { - return new Append(this, other); -}; -RopeSequence.prototype.slice = function slice(from2, to) { - if (from2 === void 0) from2 = 0; - if (to === void 0) to = this.length; - if (from2 >= to) { - return RopeSequence.empty; - } - return this.sliceInner(Math.max(0, from2), Math.min(this.length, to)); -}; -RopeSequence.prototype.get = function get(i) { - if (i < 0 || i >= this.length) { - return void 0; - } - return this.getInner(i); -}; -RopeSequence.prototype.forEach = function forEach2(f, from2, to) { - if (from2 === void 0) from2 = 0; - if (to === void 0) to = this.length; - if (from2 <= to) { - this.forEachInner(f, from2, to, 0); - } else { - this.forEachInvertedInner(f, from2, to, 0); - } -}; -RopeSequence.prototype.map = function map(f, from2, to) { - if (from2 === void 0) from2 = 0; - if (to === void 0) to = this.length; - var result = []; - this.forEach(function(elt, i) { - return result.push(f(elt, i)); - }, from2, to); - return result; -}; -RopeSequence.from = function from(values) { - if (values instanceof RopeSequence) { - return values; - } - return values && values.length ? new Leaf(values) : RopeSequence.empty; -}; -var Leaf = /* @__PURE__ */ (function(RopeSequence3) { - function Leaf2(values) { - RopeSequence3.call(this); - this.values = values; - } - if (RopeSequence3) Leaf2.__proto__ = RopeSequence3; - Leaf2.prototype = Object.create(RopeSequence3 && RopeSequence3.prototype); - Leaf2.prototype.constructor = Leaf2; - var prototypeAccessors = { length: { configurable: true }, depth: { configurable: true } }; - Leaf2.prototype.flatten = function flatten() { - return this.values; - }; - Leaf2.prototype.sliceInner = function sliceInner(from2, to) { - if (from2 == 0 && to == this.length) { - return this; - } - return new Leaf2(this.values.slice(from2, to)); - }; - Leaf2.prototype.getInner = function getInner(i) { - return this.values[i]; - }; - Leaf2.prototype.forEachInner = function forEachInner(f, from2, to, start) { - for (var i = from2; i < to; i++) { - if (f(this.values[i], start + i) === false) { - return false; - } - } - }; - Leaf2.prototype.forEachInvertedInner = function forEachInvertedInner(f, from2, to, start) { - for (var i = from2 - 1; i >= to; i--) { - if (f(this.values[i], start + i) === false) { - return false; - } - } - }; - Leaf2.prototype.leafAppend = function leafAppend(other) { - if (this.length + other.length <= GOOD_LEAF_SIZE) { - return new Leaf2(this.values.concat(other.flatten())); - } - }; - Leaf2.prototype.leafPrepend = function leafPrepend(other) { - if (this.length + other.length <= GOOD_LEAF_SIZE) { - return new Leaf2(other.flatten().concat(this.values)); - } - }; - prototypeAccessors.length.get = function() { - return this.values.length; - }; - prototypeAccessors.depth.get = function() { - return 0; - }; - Object.defineProperties(Leaf2.prototype, prototypeAccessors); - return Leaf2; -})(RopeSequence); -RopeSequence.empty = new Leaf([]); -var Append = /* @__PURE__ */ (function(RopeSequence3) { - function Append2(left, right) { - RopeSequence3.call(this); - this.left = left; - this.right = right; - this.length = left.length + right.length; - this.depth = Math.max(left.depth, right.depth) + 1; - } - if (RopeSequence3) Append2.__proto__ = RopeSequence3; - Append2.prototype = Object.create(RopeSequence3 && RopeSequence3.prototype); - Append2.prototype.constructor = Append2; - Append2.prototype.flatten = function flatten() { - return this.left.flatten().concat(this.right.flatten()); - }; - Append2.prototype.getInner = function getInner(i) { - return i < this.left.length ? this.left.get(i) : this.right.get(i - this.left.length); - }; - Append2.prototype.forEachInner = function forEachInner(f, from2, to, start) { - var leftLen = this.left.length; - if (from2 < leftLen && this.left.forEachInner(f, from2, Math.min(to, leftLen), start) === false) { - return false; - } - if (to > leftLen && this.right.forEachInner(f, Math.max(from2 - leftLen, 0), Math.min(this.length, to) - leftLen, start + leftLen) === false) { - return false; - } - }; - Append2.prototype.forEachInvertedInner = function forEachInvertedInner(f, from2, to, start) { - var leftLen = this.left.length; - if (from2 > leftLen && this.right.forEachInvertedInner(f, from2 - leftLen, Math.max(to, leftLen) - leftLen, start + leftLen) === false) { - return false; - } - if (to < leftLen && this.left.forEachInvertedInner(f, Math.min(from2, leftLen), to, start) === false) { - return false; - } - }; - Append2.prototype.sliceInner = function sliceInner(from2, to) { - if (from2 == 0 && to == this.length) { - return this; - } - var leftLen = this.left.length; - if (to <= leftLen) { - return this.left.slice(from2, to); - } - if (from2 >= leftLen) { - return this.right.slice(from2 - leftLen, to - leftLen); - } - return this.left.slice(from2, leftLen).append(this.right.slice(0, to - leftLen)); - }; - Append2.prototype.leafAppend = function leafAppend(other) { - var inner = this.right.leafAppend(other); - if (inner) { - return new Append2(this.left, inner); - } - }; - Append2.prototype.leafPrepend = function leafPrepend(other) { - var inner = this.left.leafPrepend(other); - if (inner) { - return new Append2(inner, this.right); - } - }; - Append2.prototype.appendInner = function appendInner2(other) { - if (this.left.depth >= Math.max(this.right.depth, other.depth) + 1) { - return new Append2(this.left, new Append2(this.right, other)); - } - return new Append2(this, other); - }; - return Append2; -})(RopeSequence); -const max_empty_items = 500; -class Branch { - constructor(items, eventCount) { - this.items = items; - this.eventCount = eventCount; - } - // Pop the latest event off the branch's history and apply it - // to a document transform. - popEvent(state, preserveItems) { - if (this.eventCount == 0) - return null; - let end = this.items.length; - for (; ; end--) { - let next = this.items.get(end - 1); - if (next.selection) { - --end; - break; - } - } - let remap, mapFrom; - if (preserveItems) { - remap = this.remapping(end, this.items.length); - mapFrom = remap.maps.length; - } - let transform = state.tr; - let selection, remaining; - let addAfter = [], addBefore = []; - this.items.forEach((item, i) => { - if (!item.step) { - if (!remap) { - remap = this.remapping(end, i + 1); - mapFrom = remap.maps.length; - } - mapFrom--; - addBefore.push(item); - return; - } - if (remap) { - addBefore.push(new Item(item.map)); - let step = item.step.map(remap.slice(mapFrom)), map2; - if (step && transform.maybeStep(step).doc) { - map2 = transform.mapping.maps[transform.mapping.maps.length - 1]; - addAfter.push(new Item(map2, void 0, void 0, addAfter.length + addBefore.length)); - } - mapFrom--; - if (map2) - remap.appendMap(map2, mapFrom); - } else { - transform.maybeStep(item.step); - } - if (item.selection) { - selection = remap ? item.selection.map(remap.slice(mapFrom)) : item.selection; - remaining = new Branch(this.items.slice(0, end).append(addBefore.reverse().concat(addAfter)), this.eventCount - 1); - return false; - } - }, this.items.length, 0); - return { remaining, transform, selection }; - } - // Create a new branch with the given transform added. - addTransform(transform, selection, histOptions, preserveItems) { - let newItems = [], eventCount = this.eventCount; - let oldItems = this.items, lastItem = !preserveItems && oldItems.length ? oldItems.get(oldItems.length - 1) : null; - for (let i = 0; i < transform.steps.length; i++) { - let step = transform.steps[i].invert(transform.docs[i]); - let item = new Item(transform.mapping.maps[i], step, selection), merged; - if (merged = lastItem && lastItem.merge(item)) { - item = merged; - if (i) - newItems.pop(); - else - oldItems = oldItems.slice(0, oldItems.length - 1); - } - newItems.push(item); - if (selection) { - eventCount++; - selection = void 0; - } - if (!preserveItems) - lastItem = item; - } - let overflow = eventCount - histOptions.depth; - if (overflow > DEPTH_OVERFLOW) { - oldItems = cutOffEvents(oldItems, overflow); - eventCount -= overflow; - } - return new Branch(oldItems.append(newItems), eventCount); - } - remapping(from2, to) { - let maps = new Mapping(); - this.items.forEach((item, i) => { - let mirrorPos = item.mirrorOffset != null && i - item.mirrorOffset >= from2 ? maps.maps.length - item.mirrorOffset : void 0; - maps.appendMap(item.map, mirrorPos); - }, from2, to); - return maps; - } - addMaps(array) { - if (this.eventCount == 0) - return this; - return new Branch(this.items.append(array.map((map2) => new Item(map2))), this.eventCount); - } - // When the collab module receives remote changes, the history has - // to know about those, so that it can adjust the steps that were - // rebased on top of the remote changes, and include the position - // maps for the remote changes in its array of items. - rebased(rebasedTransform, rebasedCount) { - if (!this.eventCount) - return this; - let rebasedItems = [], start = Math.max(0, this.items.length - rebasedCount); - let mapping = rebasedTransform.mapping; - let newUntil = rebasedTransform.steps.length; - let eventCount = this.eventCount; - this.items.forEach((item) => { - if (item.selection) - eventCount--; - }, start); - let iRebased = rebasedCount; - this.items.forEach((item) => { - let pos = mapping.getMirror(--iRebased); - if (pos == null) - return; - newUntil = Math.min(newUntil, pos); - let map2 = mapping.maps[pos]; - if (item.step) { - let step = rebasedTransform.steps[pos].invert(rebasedTransform.docs[pos]); - let selection = item.selection && item.selection.map(mapping.slice(iRebased + 1, pos)); - if (selection) - eventCount++; - rebasedItems.push(new Item(map2, step, selection)); - } else { - rebasedItems.push(new Item(map2)); - } - }, start); - let newMaps = []; - for (let i = rebasedCount; i < newUntil; i++) - newMaps.push(new Item(mapping.maps[i])); - let items = this.items.slice(0, start).append(newMaps).append(rebasedItems); - let branch = new Branch(items, eventCount); - if (branch.emptyItemCount() > max_empty_items) - branch = branch.compress(this.items.length - rebasedItems.length); - return branch; - } - emptyItemCount() { - let count = 0; - this.items.forEach((item) => { - if (!item.step) - count++; - }); - return count; - } - // Compressing a branch means rewriting it to push the air (map-only - // items) out. During collaboration, these naturally accumulate - // because each remote change adds one. The `upto` argument is used - // to ensure that only the items below a given level are compressed, - // because `rebased` relies on a clean, untouched set of items in - // order to associate old items with rebased steps. - compress(upto = this.items.length) { - let remap = this.remapping(0, upto), mapFrom = remap.maps.length; - let items = [], events = 0; - this.items.forEach((item, i) => { - if (i >= upto) { - items.push(item); - if (item.selection) - events++; - } else if (item.step) { - let step = item.step.map(remap.slice(mapFrom)), map2 = step && step.getMap(); - mapFrom--; - if (map2) - remap.appendMap(map2, mapFrom); - if (step) { - let selection = item.selection && item.selection.map(remap.slice(mapFrom)); - if (selection) - events++; - let newItem = new Item(map2.invert(), step, selection), merged, last = items.length - 1; - if (merged = items.length && items[last].merge(newItem)) - items[last] = merged; - else - items.push(newItem); - } - } else if (item.map) { - mapFrom--; - } - }, this.items.length, 0); - return new Branch(RopeSequence.from(items.reverse()), events); - } -} -Branch.empty = new Branch(RopeSequence.empty, 0); -function cutOffEvents(items, n) { - let cutPoint; - items.forEach((item, i) => { - if (item.selection && n-- == 0) { - cutPoint = i; - return false; - } - }); - return items.slice(cutPoint); -} -class Item { - constructor(map2, step, selection, mirrorOffset) { - this.map = map2; - this.step = step; - this.selection = selection; - this.mirrorOffset = mirrorOffset; - } - merge(other) { - if (this.step && other.step && !other.selection) { - let step = other.step.merge(this.step); - if (step) - return new Item(step.getMap().invert(), step, this.selection); - } - } -} -class HistoryState { - constructor(done, undone, prevRanges, prevTime, prevComposition) { - this.done = done; - this.undone = undone; - this.prevRanges = prevRanges; - this.prevTime = prevTime; - this.prevComposition = prevComposition; - } -} -const DEPTH_OVERFLOW = 20; -function applyTransaction(history2, state, tr2, options) { - let historyTr = tr2.getMeta(historyKey), rebased; - if (historyTr) - return historyTr.historyState; - if (tr2.getMeta(closeHistoryKey)) - history2 = new HistoryState(history2.done, history2.undone, null, 0, -1); - let appended = tr2.getMeta("appendedTransaction"); - if (tr2.steps.length == 0) { - return history2; - } else if (appended && appended.getMeta(historyKey)) { - if (appended.getMeta(historyKey).redo) - return new HistoryState(history2.done.addTransform(tr2, void 0, options, mustPreserveItems(state)), history2.undone, rangesFor(tr2.mapping.maps), history2.prevTime, history2.prevComposition); - else - return new HistoryState(history2.done, history2.undone.addTransform(tr2, void 0, options, mustPreserveItems(state)), null, history2.prevTime, history2.prevComposition); - } else if (tr2.getMeta("addToHistory") !== false && !(appended && appended.getMeta("addToHistory") === false)) { - let composition = tr2.getMeta("composition"); - let newGroup = history2.prevTime == 0 || !appended && history2.prevComposition != composition && (history2.prevTime < (tr2.time || 0) - options.newGroupDelay || !isAdjacentTo(tr2, history2.prevRanges)); - let prevRanges = appended ? mapRanges(history2.prevRanges, tr2.mapping) : rangesFor(tr2.mapping.maps); - return new HistoryState(history2.done.addTransform(tr2, newGroup ? state.selection.getBookmark() : void 0, options, mustPreserveItems(state)), Branch.empty, prevRanges, tr2.time, composition == null ? history2.prevComposition : composition); - } else if (rebased = tr2.getMeta("rebased")) { - return new HistoryState(history2.done.rebased(tr2, rebased), history2.undone.rebased(tr2, rebased), mapRanges(history2.prevRanges, tr2.mapping), history2.prevTime, history2.prevComposition); - } else { - return new HistoryState(history2.done.addMaps(tr2.mapping.maps), history2.undone.addMaps(tr2.mapping.maps), mapRanges(history2.prevRanges, tr2.mapping), history2.prevTime, history2.prevComposition); - } -} -function isAdjacentTo(transform, prevRanges) { - if (!prevRanges) - return false; - if (!transform.docChanged) - return true; - let adjacent = false; - transform.mapping.maps[0].forEach((start, end) => { - for (let i = 0; i < prevRanges.length; i += 2) - if (start <= prevRanges[i + 1] && end >= prevRanges[i]) - adjacent = true; - }); - return adjacent; -} -function rangesFor(maps) { - let result = []; - for (let i = maps.length - 1; i >= 0 && result.length == 0; i--) - maps[i].forEach((_from, _to, from2, to) => result.push(from2, to)); - return result; -} -function mapRanges(ranges, mapping) { - if (!ranges) - return null; - let result = []; - for (let i = 0; i < ranges.length; i += 2) { - let from2 = mapping.map(ranges[i], 1), to = mapping.map(ranges[i + 1], -1); - if (from2 <= to) - result.push(from2, to); - } - return result; -} -function histTransaction(history2, state, redo2) { - let preserveItems = mustPreserveItems(state); - let histOptions = historyKey.get(state).spec.config; - let pop = (redo2 ? history2.undone : history2.done).popEvent(state, preserveItems); - if (!pop) - return null; - let selection = pop.selection.resolve(pop.transform.doc); - let added = (redo2 ? history2.done : history2.undone).addTransform(pop.transform, state.selection.getBookmark(), histOptions, preserveItems); - let newHist = new HistoryState(redo2 ? added : pop.remaining, redo2 ? pop.remaining : added, null, 0, -1); - return pop.transform.setSelection(selection).setMeta(historyKey, { redo: redo2, historyState: newHist }); -} -let cachedPreserveItems = false, cachedPreserveItemsPlugins = null; -function mustPreserveItems(state) { - let plugins = state.plugins; - if (cachedPreserveItemsPlugins != plugins) { - cachedPreserveItems = false; - cachedPreserveItemsPlugins = plugins; - for (let i = 0; i < plugins.length; i++) - if (plugins[i].spec.historyPreserveItems) { - cachedPreserveItems = true; - break; - } - } - return cachedPreserveItems; -} -const historyKey = new PluginKey("history"); -const closeHistoryKey = new PluginKey("closeHistory"); -function history(config = {}) { - config = { - depth: config.depth || 100, - newGroupDelay: config.newGroupDelay || 500 - }; - return new Plugin({ - key: historyKey, - state: { - init() { - return new HistoryState(Branch.empty, Branch.empty, null, 0, -1); - }, - apply(tr2, hist, state) { - return applyTransaction(hist, state, tr2, config); - } - }, - config, - props: { - handleDOMEvents: { - beforeinput(view, e) { - let inputType = e.inputType; - let command2 = inputType == "historyUndo" ? undo : inputType == "historyRedo" ? redo : null; - if (!command2 || !view.editable) - return false; - e.preventDefault(); - return command2(view.state, view.dispatch); - } - } - } - }); -} -function buildCommand(redo2, scroll) { - return (state, dispatch) => { - let hist = historyKey.getState(state); - if (!hist || (redo2 ? hist.undone : hist.done).eventCount == 0) - return false; - if (dispatch) { - let tr2 = histTransaction(hist, state, redo2); - if (tr2) - dispatch(scroll ? tr2.scrollIntoView() : tr2); - } - return true; - }; -} -const undo = buildCommand(false, true); -const redo = buildCommand(true, true); -Extension.create({ - name: "characterCount", - addOptions() { - return { - limit: null, - mode: "textSize", - textCounter: (text) => text.length, - wordCounter: (text) => text.split(" ").filter((word) => word !== "").length - }; - }, - addStorage() { - return { - characters: () => 0, - words: () => 0 - }; - }, - onBeforeCreate() { - this.storage.characters = (options) => { - const node = (options == null ? void 0 : options.node) || this.editor.state.doc; - const mode = (options == null ? void 0 : options.mode) || this.options.mode; - if (mode === "textSize") { - const text = node.textBetween(0, node.content.size, void 0, " "); - return this.options.textCounter(text); - } - return node.nodeSize; - }; - this.storage.words = (options) => { - const node = (options == null ? void 0 : options.node) || this.editor.state.doc; - const text = node.textBetween(0, node.content.size, " ", " "); - return this.options.wordCounter(text); - }; - }, - addProseMirrorPlugins() { - let initialEvaluationDone = false; - return [ - new Plugin({ - key: new PluginKey("characterCount"), - appendTransaction: (transactions, oldState, newState) => { - if (initialEvaluationDone) { - return; - } - const limit = this.options.limit; - if (limit === null || limit === void 0 || limit === 0) { - initialEvaluationDone = true; - return; - } - const initialContentSize = this.storage.characters({ node: newState.doc }); - if (initialContentSize > limit) { - const over = initialContentSize - limit; - const from2 = 0; - const to = over; - console.warn( - `[CharacterCount] Initial content exceeded limit of ${limit} characters. Content was automatically trimmed.` - ); - const tr2 = newState.tr.deleteRange(from2, to); - initialEvaluationDone = true; - return tr2; - } - initialEvaluationDone = true; - }, - filterTransaction: (transaction, state) => { - const limit = this.options.limit; - if (!transaction.docChanged || limit === 0 || limit === null || limit === void 0) { - return true; - } - const oldSize = this.storage.characters({ node: state.doc }); - const newSize = this.storage.characters({ node: transaction.doc }); - if (newSize <= limit) { - return true; - } - if (oldSize > limit && newSize > limit && newSize <= oldSize) { - return true; - } - if (oldSize > limit && newSize > limit && newSize > oldSize) { - return false; - } - const isPaste = transaction.getMeta("paste"); - if (!isPaste) { - return false; - } - const pos = transaction.selection.$head.pos; - const over = newSize - limit; - const from2 = pos - over; - const to = pos; - transaction.deleteRange(from2, to); - const updatedSize = this.storage.characters({ node: transaction.doc }); - if (updatedSize > limit) { - return false; - } - return true; - } - }) - ]; - } -}); -var Dropcursor = Extension.create({ - name: "dropCursor", - addOptions() { - return { - color: "currentColor", - width: 1, - class: void 0 - }; - }, - addProseMirrorPlugins() { - return [dropCursor(this.options)]; - } -}); -Extension.create({ - name: "focus", - addOptions() { - return { - className: "has-focus", - mode: "all" - }; - }, - addProseMirrorPlugins() { - return [ - new Plugin({ - key: new PluginKey("focus"), - props: { - decorations: ({ doc: doc2, selection }) => { - const { isEditable, isFocused } = this.editor; - const { anchor } = selection; - const decorations = []; - if (!isEditable || !isFocused) { - return DecorationSet.create(doc2, []); - } - let maxLevels = 0; - if (this.options.mode === "deepest") { - doc2.descendants((node, pos) => { - if (node.isText) { - return; - } - const isCurrent = anchor >= pos && anchor <= pos + node.nodeSize - 1; - if (!isCurrent) { - return false; - } - maxLevels += 1; - }); - } - let currentLevel = 0; - doc2.descendants((node, pos) => { - if (node.isText) { - return false; - } - const isCurrent = anchor >= pos && anchor <= pos + node.nodeSize - 1; - if (!isCurrent) { - return false; - } - currentLevel += 1; - const outOfScope = this.options.mode === "deepest" && maxLevels - currentLevel > 0 || this.options.mode === "shallowest" && currentLevel > 1; - if (outOfScope) { - return this.options.mode === "deepest"; - } - decorations.push( - Decoration.node(pos, pos + node.nodeSize, { - class: this.options.className - }) - ); - }); - return DecorationSet.create(doc2, decorations); - } - } - }) - ]; - } -}); -var Gapcursor = Extension.create({ - name: "gapCursor", - addProseMirrorPlugins() { - return [gapCursor()]; - }, - extendNodeSchema(extension) { - var _a; - const context = { - name: extension.name, - options: extension.options, - storage: extension.storage - }; - return { - allowGapCursor: (_a = callOrReturn(getExtensionField(extension, "allowGapCursor", context))) != null ? _a : null - }; - } -}); -var DEFAULT_DATA_ATTRIBUTE = "placeholder"; -function preparePlaceholderAttribute(attr) { - return attr.replace(/\s+/g, "-").replace(/[^a-zA-Z0-9-]/g, "").replace(/^[0-9-]+/, "").replace(/^-+/, "").toLowerCase(); -} -var Placeholder = Extension.create({ - name: "placeholder", - addOptions() { - return { - emptyEditorClass: "is-editor-empty", - emptyNodeClass: "is-empty", - dataAttribute: DEFAULT_DATA_ATTRIBUTE, - placeholder: "Write something …", - showOnlyWhenEditable: true, - showOnlyCurrent: true, - includeChildren: false - }; - }, - addProseMirrorPlugins() { - const dataAttribute = this.options.dataAttribute ? `data-${preparePlaceholderAttribute(this.options.dataAttribute)}` : `data-${DEFAULT_DATA_ATTRIBUTE}`; - return [ - new Plugin({ - key: new PluginKey("placeholder"), - props: { - decorations: ({ doc: doc2, selection }) => { - const active = this.editor.isEditable || !this.options.showOnlyWhenEditable; - const { anchor } = selection; - const decorations = []; - if (!active) { - return null; - } - const isEmptyDoc = this.editor.isEmpty; - doc2.descendants((node, pos) => { - const hasAnchor = anchor >= pos && anchor <= pos + node.nodeSize; - const isEmpty = !node.isLeaf && isNodeEmpty(node); - if (!node.type.isTextblock) { - return this.options.includeChildren; - } - if ((hasAnchor || !this.options.showOnlyCurrent) && isEmpty) { - const classes = [this.options.emptyNodeClass]; - if (isEmptyDoc) { - classes.push(this.options.emptyEditorClass); - } - const decoration = Decoration.node(pos, pos + node.nodeSize, { - class: classes.join(" "), - [dataAttribute]: typeof this.options.placeholder === "function" ? this.options.placeholder({ - editor: this.editor, - node, - pos, - hasAnchor - }) : this.options.placeholder - }); - decorations.push(decoration); - } - return this.options.includeChildren; - }); - return DecorationSet.create(doc2, decorations); - } - } - }) - ]; - } -}); -Extension.create({ - name: "selection", - addOptions() { - return { - className: "selection" - }; - }, - addProseMirrorPlugins() { - const { editor, options } = this; - return [ - new Plugin({ - key: new PluginKey("selection"), - props: { - decorations(state) { - if (state.selection.empty || editor.isFocused || !editor.isEditable || isNodeSelection(state.selection) || editor.view.dragging) { - return null; - } - return DecorationSet.create(state.doc, [ - Decoration.inline(state.selection.from, state.selection.to, { - class: options.className - }) - ]); - } - } - }) - ]; - } -}); -var skipTrailingNodeMeta = "skipTrailingNode"; -function nodeEqualsType({ types, node }) { - return node && Array.isArray(types) && types.includes(node.type) || (node == null ? void 0 : node.type) === types; -} -var TrailingNode = Extension.create({ - name: "trailingNode", - addOptions() { - return { - node: void 0, - notAfter: [] - }; - }, - addProseMirrorPlugins() { - var _a; - const plugin = new PluginKey(this.name); - const defaultNode = this.options.node || ((_a = this.editor.schema.topNodeType.contentMatch.defaultType) == null ? void 0 : _a.name) || "paragraph"; - const disabledNodes = Object.entries(this.editor.schema.nodes).map(([, value]) => value).filter((node) => (this.options.notAfter || []).concat(defaultNode).includes(node.name)); - return [ - new Plugin({ - key: plugin, - appendTransaction: (transactions, __, state) => { - const { doc: doc2, tr: tr2, schema } = state; - const shouldInsertNodeAtEnd = plugin.getState(state); - const endPosition = doc2.content.size; - const type = schema.nodes[defaultNode]; - if (transactions.some((transaction) => transaction.getMeta(skipTrailingNodeMeta))) { - return; - } - if (!shouldInsertNodeAtEnd) { - return; - } - return tr2.insert(endPosition, type.create()); - }, - state: { - init: (_, state) => { - const lastNode = state.tr.doc.lastChild; - return !nodeEqualsType({ node: lastNode, types: disabledNodes }); - }, - apply: (tr2, value) => { - if (!tr2.docChanged) { - return value; - } - if (tr2.getMeta("__uniqueIDTransaction")) { - return value; - } - const lastNode = tr2.doc.lastChild; - return !nodeEqualsType({ node: lastNode, types: disabledNodes }); - } - } - }) - ]; - } -}); -var UndoRedo = Extension.create({ - name: "undoRedo", - addOptions() { - return { - depth: 100, - newGroupDelay: 500 - }; - }, - addCommands() { - return { - undo: () => ({ state, dispatch }) => { - return undo(state, dispatch); - }, - redo: () => ({ state, dispatch }) => { - return redo(state, dispatch); - } - }; - }, - addProseMirrorPlugins() { - return [history(this.options)]; - }, - addKeyboardShortcuts() { - return { - "Mod-z": () => this.editor.commands.undo(), - "Shift-Mod-z": () => this.editor.commands.redo(), - "Mod-y": () => this.editor.commands.redo(), - // Russian keyboard layouts - "Mod-я": () => this.editor.commands.undo(), - "Shift-Mod-я": () => this.editor.commands.redo() - }; - } -}); -var StarterKit = Extension.create({ - name: "starterKit", - addExtensions() { - var _a, _b, _c, _d; - const extensions = []; - if (this.options.bold !== false) { - extensions.push(Bold.configure(this.options.bold)); - } - if (this.options.blockquote !== false) { - extensions.push(Blockquote.configure(this.options.blockquote)); - } - if (this.options.bulletList !== false) { - extensions.push(BulletList.configure(this.options.bulletList)); - } - if (this.options.code !== false) { - extensions.push(Code.configure(this.options.code)); - } - if (this.options.codeBlock !== false) { - extensions.push(CodeBlock.configure(this.options.codeBlock)); - } - if (this.options.document !== false) { - extensions.push(Document.configure(this.options.document)); - } - if (this.options.dropcursor !== false) { - extensions.push(Dropcursor.configure(this.options.dropcursor)); - } - if (this.options.gapcursor !== false) { - extensions.push(Gapcursor.configure(this.options.gapcursor)); - } - if (this.options.hardBreak !== false) { - extensions.push(HardBreak.configure(this.options.hardBreak)); - } - if (this.options.heading !== false) { - extensions.push(Heading.configure(this.options.heading)); - } - if (this.options.undoRedo !== false) { - extensions.push(UndoRedo.configure(this.options.undoRedo)); - } - if (this.options.horizontalRule !== false) { - extensions.push(HorizontalRule.configure(this.options.horizontalRule)); - } - if (this.options.italic !== false) { - extensions.push(Italic.configure(this.options.italic)); - } - if (this.options.listItem !== false) { - extensions.push(ListItem.configure(this.options.listItem)); - } - if (this.options.listKeymap !== false) { - extensions.push(ListKeymap.configure((_a = this.options) == null ? void 0 : _a.listKeymap)); - } - if (this.options.link !== false) { - extensions.push(Link.configure((_b = this.options) == null ? void 0 : _b.link)); - } - if (this.options.orderedList !== false) { - extensions.push(OrderedList.configure(this.options.orderedList)); - } - if (this.options.paragraph !== false) { - extensions.push(Paragraph.configure(this.options.paragraph)); - } - if (this.options.strike !== false) { - extensions.push(Strike.configure(this.options.strike)); - } - if (this.options.text !== false) { - extensions.push(Text.configure(this.options.text)); - } - if (this.options.underline !== false) { - extensions.push(Underline.configure((_c = this.options) == null ? void 0 : _c.underline)); - } - if (this.options.trailingNode !== false) { - extensions.push(TrailingNode.configure((_d = this.options) == null ? void 0 : _d.trailingNode)); - } - return extensions; - } -}); -var index_default$3 = StarterKit; -var index_default$2 = Placeholder; -var inputRegex = /(?:^|\s)(!\[(.+|:?)]\((\S+)(?:(?:\s+)["'](\S+)["'])?\))$/; -var Image = Node3.create({ - name: "image", - addOptions() { - return { - inline: false, - allowBase64: false, - HTMLAttributes: {}, - resize: false - }; - }, - inline() { - return this.options.inline; - }, - group() { - return this.options.inline ? "inline" : "block"; - }, - draggable: true, - addAttributes() { - return { - src: { - default: null - }, - alt: { - default: null - }, - title: { - default: null - }, - width: { - default: null - }, - height: { - default: null - } - }; - }, - parseHTML() { - return [ - { - tag: this.options.allowBase64 ? "img[src]" : 'img[src]:not([src^="data:"])' - } - ]; - }, - renderHTML({ HTMLAttributes }) { - return ["img", mergeAttributes(this.options.HTMLAttributes, HTMLAttributes)]; - }, - parseMarkdown: (token, helpers) => { - return helpers.createNode("image", { - src: token.href, - title: token.title, - alt: token.text - }); - }, - renderMarkdown: (node) => { - var _a, _b, _c, _d, _e, _f; - const src = (_b = (_a = node.attrs) == null ? void 0 : _a.src) != null ? _b : ""; - const alt = (_d = (_c = node.attrs) == null ? void 0 : _c.alt) != null ? _d : ""; - const title = (_f = (_e = node.attrs) == null ? void 0 : _e.title) != null ? _f : ""; - return title ? `![${alt}](${src} "${title}")` : `![${alt}](${src})`; - }, - addNodeView() { - if (!this.options.resize || !this.options.resize.enabled || typeof document === "undefined") { - return null; - } - const { directions, minWidth, minHeight, alwaysPreserveAspectRatio } = this.options.resize; - return ({ node, getPos, HTMLAttributes, editor }) => { - const el = document.createElement("img"); - Object.entries(HTMLAttributes).forEach(([key, value]) => { - if (value != null) { - switch (key) { - case "width": - case "height": - break; - default: - el.setAttribute(key, value); - break; - } - } - }); - el.src = HTMLAttributes.src; - const nodeView = new ResizableNodeView({ - element: el, - editor, - node, - getPos, - onResize: (width, height) => { - el.style.width = `${width}px`; - el.style.height = `${height}px`; - }, - onCommit: (width, height) => { - const pos = getPos(); - if (pos === void 0) { - return; - } - this.editor.chain().setNodeSelection(pos).updateAttributes(this.name, { - width, - height - }).run(); - }, - onUpdate: (updatedNode, _decorations, _innerDecorations) => { - if (updatedNode.type !== node.type) { - return false; - } - return true; - }, - options: { - directions, - min: { - width: minWidth, - height: minHeight - }, - preserveAspectRatio: alwaysPreserveAspectRatio === true - } - }); - const dom = nodeView.dom; - dom.style.visibility = "hidden"; - dom.style.pointerEvents = "none"; - el.onload = () => { - dom.style.visibility = ""; - dom.style.pointerEvents = ""; - }; - return nodeView; - }; - }, - addCommands() { - return { - setImage: (options) => ({ commands }) => { - return commands.insertContent({ - type: this.name, - attrs: options - }); - } - }; - }, - addInputRules() { - return [ - nodeInputRule({ - find: inputRegex, - type: this.type, - getAttributes: (match) => { - const [, , alt, src, title] = match; - return { src, alt, title }; - } - }) - ]; - } -}); -var index_default$1 = Image; -function findSuggestionMatch(config) { - var _a; - const { char, allowSpaces: allowSpacesOption, allowToIncludeChar, allowedPrefixes, startOfLine, $position } = config; - const allowSpaces = allowSpacesOption && !allowToIncludeChar; - const escapedChar = escapeForRegEx(char); - const suffix = new RegExp(`\\s${escapedChar}$`); - const prefix = startOfLine ? "^" : ""; - const finalEscapedChar = allowToIncludeChar ? "" : escapedChar; - const regexp = allowSpaces ? new RegExp(`${prefix}${escapedChar}.*?(?=\\s${finalEscapedChar}|$)`, "gm") : new RegExp(`${prefix}(?:^)?${escapedChar}[^\\s${finalEscapedChar}]*`, "gm"); - const text = ((_a = $position.nodeBefore) == null ? void 0 : _a.isText) && $position.nodeBefore.text; - if (!text) { - return null; - } - const textFrom = $position.pos - text.length; - const match = Array.from(text.matchAll(regexp)).pop(); - if (!match || match.input === void 0 || match.index === void 0) { - return null; - } - const matchPrefix = match.input.slice(Math.max(0, match.index - 1), match.index); - const matchPrefixIsAllowed = new RegExp(`^[${allowedPrefixes == null ? void 0 : allowedPrefixes.join("")}\0]?$`).test(matchPrefix); - if (allowedPrefixes !== null && !matchPrefixIsAllowed) { - return null; - } - const from2 = textFrom + match.index; - let to = from2 + match[0].length; - if (allowSpaces && suffix.test(text.slice(to - 1, to + 1))) { - match[0] += " "; - to += 1; - } - if (from2 < $position.pos && to >= $position.pos) { - return { - range: { - from: from2, - to - }, - query: match[0].slice(char.length), - text: match[0] - }; - } - return null; -} -function hasInsertedWhitespace(transaction) { - if (!transaction.docChanged) { - return false; - } - return transaction.steps.some((step) => { - const slice2 = step.slice; - if (!(slice2 == null ? void 0 : slice2.content)) { - return false; - } - const inserted = slice2.content.textBetween(0, slice2.content.size, "\n"); - return /\s/.test(inserted); - }); -} -var SuggestionPluginKey = new PluginKey("suggestion"); -function Suggestion({ - pluginKey = SuggestionPluginKey, - editor, - char = "@", - allowSpaces = false, - allowToIncludeChar = false, - allowedPrefixes = [" "], - startOfLine = false, - decorationTag = "span", - decorationClass = "suggestion", - decorationContent = "", - decorationEmptyClass = "is-empty", - command: command2 = () => null, - items = () => [], - render = () => ({}), - allow = () => true, - findSuggestionMatch: findSuggestionMatch2 = findSuggestionMatch, - shouldShow, - shouldResetDismissed -}) { - let props; - const renderer = render == null ? void 0 : render(); - const effectiveAllowSpaces = allowSpaces && !allowToIncludeChar; - const getAnchorClientRect = () => { - const pos = editor.state.selection.$anchor.pos; - const coords = editor.view.coordsAtPos(pos); - const { top, right, bottom, left } = coords; - try { - return new DOMRect(left, top, right - left, bottom - top); - } catch { - return null; - } - }; - const clientRectFor = (view, decorationNode) => { - if (!decorationNode) { - return getAnchorClientRect; - } - return () => { - const state = pluginKey.getState(editor.state); - const decorationId = state == null ? void 0 : state.decorationId; - const currentDecorationNode = view.dom.querySelector(`[data-decoration-id="${decorationId}"]`); - return (currentDecorationNode == null ? void 0 : currentDecorationNode.getBoundingClientRect()) || null; - }; - }; - const shouldKeepDismissed = ({ - match, - dismissedRange, - state, - transaction - }) => { - if (shouldResetDismissed == null ? void 0 : shouldResetDismissed({ - editor, - state, - range: dismissedRange, - match, - transaction, - allowSpaces: effectiveAllowSpaces - })) { - return false; - } - if (effectiveAllowSpaces) { - return match.range.from === dismissedRange.from; - } - return match.range.from === dismissedRange.from && !hasInsertedWhitespace(transaction); - }; - function dispatchExit(view, pluginKeyRef) { - var _a; - try { - const state = pluginKey.getState(view.state); - const decorationNode = (state == null ? void 0 : state.decorationId) ? view.dom.querySelector(`[data-decoration-id="${state.decorationId}"]`) : null; - const exitProps = { - // @ts-ignore editor is available in closure - editor, - range: (state == null ? void 0 : state.range) || { from: 0, to: 0 }, - query: (state == null ? void 0 : state.query) || null, - text: (state == null ? void 0 : state.text) || null, - items: [], - command: (commandProps) => { - return command2({ editor, range: (state == null ? void 0 : state.range) || { from: 0, to: 0 }, props: commandProps }); - }, - decorationNode, - clientRect: clientRectFor(view, decorationNode) - }; - (_a = renderer == null ? void 0 : renderer.onExit) == null ? void 0 : _a.call(renderer, exitProps); - } catch { - } - const tr2 = view.state.tr.setMeta(pluginKeyRef, { exit: true }); - view.dispatch(tr2); - } - const plugin = new Plugin({ - key: pluginKey, - view() { - return { - update: async (view, prevState) => { - var _a, _b, _c, _d, _e, _f, _g; - const prev = (_a = this.key) == null ? void 0 : _a.getState(prevState); - const next = (_b = this.key) == null ? void 0 : _b.getState(view.state); - const moved = prev.active && next.active && prev.range.from !== next.range.from; - const started = !prev.active && next.active; - const stopped = prev.active && !next.active; - const changed = !started && !stopped && prev.query !== next.query; - const handleStart = started || moved && changed; - const handleChange = changed || moved; - const handleExit = stopped || moved && changed; - if (!handleStart && !handleChange && !handleExit) { - return; - } - const state = handleExit && !handleStart ? prev : next; - const decorationNode = view.dom.querySelector(`[data-decoration-id="${state.decorationId}"]`); - props = { - editor, - range: state.range, - query: state.query, - text: state.text, - items: [], - command: (commandProps) => { - return command2({ - editor, - range: state.range, - props: commandProps - }); - }, - decorationNode, - clientRect: clientRectFor(view, decorationNode) - }; - if (handleStart) { - (_c = renderer == null ? void 0 : renderer.onBeforeStart) == null ? void 0 : _c.call(renderer, props); - } - if (handleChange) { - (_d = renderer == null ? void 0 : renderer.onBeforeUpdate) == null ? void 0 : _d.call(renderer, props); - } - if (handleChange || handleStart) { - props.items = await items({ - editor, - query: state.query - }); - } - if (handleExit) { - (_e = renderer == null ? void 0 : renderer.onExit) == null ? void 0 : _e.call(renderer, props); - } - if (handleChange) { - (_f = renderer == null ? void 0 : renderer.onUpdate) == null ? void 0 : _f.call(renderer, props); - } - if (handleStart) { - (_g = renderer == null ? void 0 : renderer.onStart) == null ? void 0 : _g.call(renderer, props); - } - }, - destroy: () => { - var _a; - if (!props) { - return; - } - (_a = renderer == null ? void 0 : renderer.onExit) == null ? void 0 : _a.call(renderer, props); - } - }; - }, - state: { - // Initialize the plugin's internal state. - init() { - const state = { - active: false, - range: { - from: 0, - to: 0 - }, - query: null, - text: null, - composing: false, - dismissedRange: null - }; - return state; - }, - // Apply changes to the plugin state from a view transaction. - apply(transaction, prev, _oldState, state) { - const { isEditable } = editor; - const { composing } = editor.view; - const { selection } = transaction; - const { empty: empty2, from: from2 } = selection; - const next = { ...prev }; - const meta = transaction.getMeta(pluginKey); - if (meta && meta.exit) { - next.active = false; - next.decorationId = null; - next.range = { from: 0, to: 0 }; - next.query = null; - next.text = null; - next.dismissedRange = prev.active ? { ...prev.range } : prev.dismissedRange; - return next; - } - next.composing = composing; - if (transaction.docChanged && next.dismissedRange !== null) { - next.dismissedRange = { - from: transaction.mapping.map(next.dismissedRange.from), - to: transaction.mapping.map(next.dismissedRange.to) - }; - } - if (isEditable && (empty2 || editor.view.composing)) { - if ((from2 < prev.range.from || from2 > prev.range.to) && !composing && !prev.composing) { - next.active = false; - } - const match = findSuggestionMatch2({ - char, - allowSpaces, - allowToIncludeChar, - allowedPrefixes, - startOfLine, - $position: selection.$from - }); - const decorationId = `id_${Math.floor(Math.random() * 4294967295)}`; - if (match && allow({ - editor, - state, - range: match.range, - isActive: prev.active - }) && (!shouldShow || shouldShow({ - editor, - range: match.range, - query: match.query, - text: match.text, - transaction - }))) { - if (next.dismissedRange !== null && !shouldKeepDismissed({ - match, - dismissedRange: next.dismissedRange, - state, - transaction - })) { - next.dismissedRange = null; - } - if (next.dismissedRange === null) { - next.active = true; - next.decorationId = prev.decorationId ? prev.decorationId : decorationId; - next.range = match.range; - next.query = match.query; - next.text = match.text; - } else { - next.active = false; - } - } else { - if (!match) { - next.dismissedRange = null; - } - next.active = false; - } - } else { - next.active = false; - } - if (!next.active) { - next.decorationId = null; - next.range = { from: 0, to: 0 }; - next.query = null; - next.text = null; - } - return next; - } - }, - props: { - // Call the keydown hook if suggestion is active. - handleKeyDown(view, event) { - var _a, _b; - const { active, range } = plugin.getState(view.state); - if (!active) { - return false; - } - if (event.key === "Escape" || event.key === "Esc") { - const state = plugin.getState(view.state); - (_a = renderer == null ? void 0 : renderer.onKeyDown) == null ? void 0 : _a.call(renderer, { view, event, range: state.range }); - dispatchExit(view, pluginKey); - return true; - } - const handled = ((_b = renderer == null ? void 0 : renderer.onKeyDown) == null ? void 0 : _b.call(renderer, { view, event, range })) || false; - return handled; - }, - // Setup decorator on the currently active suggestion. - decorations(state) { - const { active, range, decorationId, query } = plugin.getState(state); - if (!active) { - return null; - } - const isEmpty = !(query == null ? void 0 : query.length); - const classNames = [decorationClass]; - if (isEmpty) { - classNames.push(decorationEmptyClass); - } - return DecorationSet.create(state.doc, [ - Decoration.inline(range.from, range.to, { - nodeName: decorationTag, - class: classNames.join(" "), - "data-decoration-id": decorationId, - "data-decoration-content": decorationContent - }) - ]); - } - } - }); - return plugin; -} -function getSuggestionOptions({ - editor: tiptapEditor, - overrideSuggestionOptions, - extensionName, - char = "@" -}) { - const pluginKey = new PluginKey(); - return { - editor: tiptapEditor, - char, - pluginKey, - command: ({ editor, range, props }) => { - var _a, _b, _c; - const nodeAfter = editor.view.state.selection.$to.nodeAfter; - const overrideSpace = (_a = nodeAfter == null ? void 0 : nodeAfter.text) == null ? void 0 : _a.startsWith(" "); - if (overrideSpace) { - range.to += 1; - } - editor.chain().focus().insertContentAt(range, [ - { - type: extensionName, - attrs: { ...props, mentionSuggestionChar: char } - }, - { - type: "text", - text: " " - } - ]).run(); - (_c = (_b = editor.view.dom.ownerDocument.defaultView) == null ? void 0 : _b.getSelection()) == null ? void 0 : _c.collapseToEnd(); - }, - allow: ({ state, range }) => { - const $from = state.doc.resolve(range.from); - const type = state.schema.nodes[extensionName]; - const allow = !!$from.parent.type.contentMatch.matchType(type); - return allow; - }, - ...overrideSuggestionOptions - }; -} -function getSuggestions(options) { - return (options.options.suggestions.length ? options.options.suggestions : [options.options.suggestion]).map( - (suggestion) => getSuggestionOptions({ - // @ts-ignore `editor` can be `undefined` when converting the document to HTML with the HTML utility - editor: options.editor, - overrideSuggestionOptions: suggestion, - extensionName: options.name, - char: suggestion.char - }) - ); -} -function getSuggestionFromChar(options, char) { - const suggestions = getSuggestions(options); - const suggestion = suggestions.find((s) => s.char === char); - if (suggestion) { - return suggestion; - } - if (suggestions.length) { - return suggestions[0]; - } - return null; -} -var Mention = Node3.create({ - name: "mention", - priority: 101, - addOptions() { - return { - HTMLAttributes: {}, - renderText({ node, suggestion }) { - var _a, _b; - return `${(_a = suggestion == null ? void 0 : suggestion.char) != null ? _a : "@"}${(_b = node.attrs.label) != null ? _b : node.attrs.id}`; - }, - deleteTriggerWithBackspace: false, - renderHTML({ options, node, suggestion }) { - var _a, _b; - return [ - "span", - mergeAttributes(this.HTMLAttributes, options.HTMLAttributes), - `${(_a = suggestion == null ? void 0 : suggestion.char) != null ? _a : "@"}${(_b = node.attrs.label) != null ? _b : node.attrs.id}` - ]; - }, - suggestions: [], - suggestion: {} - }; - }, - group: "inline", - inline: true, - selectable: false, - atom: true, - addAttributes() { - return { - id: { - default: null, - parseHTML: (element) => element.getAttribute("data-id"), - renderHTML: (attributes) => { - if (!attributes.id) { - return {}; - } - return { - "data-id": attributes.id - }; - } - }, - label: { - default: null, - parseHTML: (element) => element.getAttribute("data-label"), - renderHTML: (attributes) => { - if (!attributes.label) { - return {}; - } - return { - "data-label": attributes.label - }; - } - }, - // When there are multiple types of mentions, this attribute helps distinguish them - mentionSuggestionChar: { - default: "@", - parseHTML: (element) => element.getAttribute("data-mention-suggestion-char"), - renderHTML: (attributes) => { - return { - "data-mention-suggestion-char": attributes.mentionSuggestionChar - }; - } - } - }; - }, - parseHTML() { - return [ - { - tag: `span[data-type="${this.name}"]` - } - ]; - }, - renderHTML({ node, HTMLAttributes }) { - const suggestion = getSuggestionFromChar(this, node.attrs.mentionSuggestionChar); - if (this.options.renderLabel !== void 0) { - console.warn("renderLabel is deprecated use renderText and renderHTML instead"); - return [ - "span", - mergeAttributes({ "data-type": this.name }, this.options.HTMLAttributes, HTMLAttributes), - this.options.renderLabel({ - options: this.options, - node, - suggestion - }) - ]; - } - const mergedOptions = { ...this.options }; - mergedOptions.HTMLAttributes = mergeAttributes( - { "data-type": this.name }, - this.options.HTMLAttributes, - HTMLAttributes - ); - const html = this.options.renderHTML({ - options: mergedOptions, - node, - suggestion - }); - if (typeof html === "string") { - return ["span", mergeAttributes({ "data-type": this.name }, this.options.HTMLAttributes, HTMLAttributes), html]; - } - return html; - }, - ...createInlineMarkdownSpec({ - nodeName: "mention", - name: "@", - selfClosing: true, - allowedAttributes: ["id", "label", { name: "mentionSuggestionChar", skipIfDefault: "@" }], - parseAttributes: (attrString) => { - const attrs = {}; - const regex = /(\w+)=(?:"([^"]*)"|'([^']*)')/g; - let match = regex.exec(attrString); - while (match !== null) { - const [, key, doubleQuoted, singleQuoted] = match; - const value = doubleQuoted != null ? doubleQuoted : singleQuoted; - attrs[key === "char" ? "mentionSuggestionChar" : key] = value; - match = regex.exec(attrString); - } - return attrs; - }, - serializeAttributes: (attrs) => { - return Object.entries(attrs).filter(([, value]) => value !== void 0 && value !== null).map(([key, value]) => { - const serializedKey = key === "mentionSuggestionChar" ? "char" : key; - return `${serializedKey}="${value}"`; - }).join(" "); - } - }), - renderText({ node }) { - const args = { - options: this.options, - node, - suggestion: getSuggestionFromChar(this, node.attrs.mentionSuggestionChar) - }; - if (this.options.renderLabel !== void 0) { - console.warn("renderLabel is deprecated use renderText and renderHTML instead"); - return this.options.renderLabel(args); - } - return this.options.renderText(args); - }, - addKeyboardShortcuts() { - return { - Backspace: () => this.editor.commands.command(({ tr: tr2, state }) => { - let isMention = false; - const { selection } = state; - const { empty: empty2, anchor } = selection; - if (!empty2) { - return false; - } - let mentionNode = new Node(); - let mentionPos = 0; - state.doc.nodesBetween(anchor - 1, anchor, (node, pos) => { - if (node.type.name === this.name) { - isMention = true; - mentionNode = node; - mentionPos = pos; - return false; - } - }); - if (isMention) { - tr2.insertText( - this.options.deleteTriggerWithBackspace ? "" : mentionNode.attrs.mentionSuggestionChar, - mentionPos, - mentionPos + mentionNode.nodeSize - ); - } - return isMention; - }) - }; - }, - addProseMirrorPlugins() { - return getSuggestions(this).map(Suggestion); - } -}); -var index_default = Mention; -export { - EditorContent as E, - Node3 as N, - React as R, - reactDomExports as a, - index_default$5 as b, - commonjsGlobal as c, - index_default$2 as d, - requireReact as e, - requireReactDom as f, - getDefaultExportFromCjs as g, - ReactRenderer as h, - index_default$3 as i, - jsxRuntimeExports as j, - index_default$4 as k, - index_default$1 as l, - mergeAttributes as m, - index_default as n, - reactExports as r, - useEditor as u -}; diff --git a/bootstrap/ssr/ssr-manifest.json b/bootstrap/ssr/ssr-manifest.json index a9e2b31d..eb9a3c08 100644 --- a/bootstrap/ssr/ssr-manifest.json +++ b/bootstrap/ssr/ssr-manifest.json @@ -14,10 +14,10 @@ "\u0000D:/Sites/Skinbase26/node_modules/nprogress/nprogress.js?commonjs-es-import": [], "\u0000D:/Sites/Skinbase26/node_modules/nprogress/nprogress.js?commonjs-module": [], "\u0000D:/Sites/Skinbase26/node_modules/pusher-js/dist/node/pusher.js?commonjs-es-import": [ - "/build/assets/vendor-realtime-BGlcW0gB.js" + "/build/assets/vendor-realtime-Koiu-_pw.js" ], "\u0000D:/Sites/Skinbase26/node_modules/pusher-js/dist/node/pusher.js?commonjs-module": [ - "/build/assets/vendor-realtime-BGlcW0gB.js" + "/build/assets/vendor-realtime-Koiu-_pw.js" ], "\u0000D:/Sites/Skinbase26/node_modules/qs/lib/index.js?commonjs-es-import": [], "\u0000D:/Sites/Skinbase26/node_modules/react-dom/cjs/react-dom-client.development.js?commonjs-exports": [], @@ -27,44 +27,44 @@ "\u0000D:/Sites/Skinbase26/node_modules/react-dom/cjs/react-dom-server.node.development.js?commonjs-exports": [], "\u0000D:/Sites/Skinbase26/node_modules/react-dom/cjs/react-dom-server.node.production.js?commonjs-exports": [], "\u0000D:/Sites/Skinbase26/node_modules/react-dom/cjs/react-dom.development.js?commonjs-exports": [ - "/build/assets/vendor-tiptap-BUUKoc3C.js" + "/build/assets/vendor-tiptap-DRFaxGEb.js" ], "\u0000D:/Sites/Skinbase26/node_modules/react-dom/cjs/react-dom.production.js?commonjs-exports": [ - "/build/assets/vendor-tiptap-BUUKoc3C.js" + "/build/assets/vendor-tiptap-DRFaxGEb.js" ], "\u0000D:/Sites/Skinbase26/node_modules/react-dom/client.js?commonjs-es-import": [], "\u0000D:/Sites/Skinbase26/node_modules/react-dom/client.js?commonjs-module": [], "\u0000D:/Sites/Skinbase26/node_modules/react-dom/index.js?commonjs-es-import": [ - "/build/assets/vendor-tiptap-BUUKoc3C.js" + "/build/assets/vendor-tiptap-DRFaxGEb.js" ], "\u0000D:/Sites/Skinbase26/node_modules/react-dom/index.js?commonjs-module": [ - "/build/assets/vendor-tiptap-BUUKoc3C.js" + "/build/assets/vendor-tiptap-DRFaxGEb.js" ], "\u0000D:/Sites/Skinbase26/node_modules/react-dom/server.node.js?commonjs-es-import": [], "\u0000D:/Sites/Skinbase26/node_modules/react-dom/server.node.js?commonjs-exports": [], "\u0000D:/Sites/Skinbase26/node_modules/react/cjs/react-jsx-runtime.development.js?commonjs-exports": [ - "/build/assets/vendor-tiptap-BUUKoc3C.js" + "/build/assets/vendor-tiptap-DRFaxGEb.js" ], "\u0000D:/Sites/Skinbase26/node_modules/react/cjs/react-jsx-runtime.production.js?commonjs-exports": [ - "/build/assets/vendor-tiptap-BUUKoc3C.js" + "/build/assets/vendor-tiptap-DRFaxGEb.js" ], "\u0000D:/Sites/Skinbase26/node_modules/react/cjs/react.development.js?commonjs-module": [ - "/build/assets/vendor-tiptap-BUUKoc3C.js" + "/build/assets/vendor-tiptap-DRFaxGEb.js" ], "\u0000D:/Sites/Skinbase26/node_modules/react/cjs/react.production.js?commonjs-exports": [ - "/build/assets/vendor-tiptap-BUUKoc3C.js" + "/build/assets/vendor-tiptap-DRFaxGEb.js" ], "\u0000D:/Sites/Skinbase26/node_modules/react/index.js?commonjs-es-import": [ - "/build/assets/vendor-tiptap-BUUKoc3C.js" + "/build/assets/vendor-tiptap-DRFaxGEb.js" ], "\u0000D:/Sites/Skinbase26/node_modules/react/index.js?commonjs-module": [ - "/build/assets/vendor-tiptap-BUUKoc3C.js" + "/build/assets/vendor-tiptap-DRFaxGEb.js" ], "\u0000D:/Sites/Skinbase26/node_modules/react/jsx-runtime.js?commonjs-es-import": [ - "/build/assets/vendor-tiptap-BUUKoc3C.js" + "/build/assets/vendor-tiptap-DRFaxGEb.js" ], "\u0000D:/Sites/Skinbase26/node_modules/react/jsx-runtime.js?commonjs-module": [ - "/build/assets/vendor-tiptap-BUUKoc3C.js" + "/build/assets/vendor-tiptap-DRFaxGEb.js" ], "\u0000D:/Sites/Skinbase26/node_modules/scheduler/cjs/scheduler.development.js?commonjs-exports": [], "\u0000D:/Sites/Skinbase26/node_modules/scheduler/cjs/scheduler.production.js?commonjs-exports": [], @@ -73,74 +73,86 @@ "\u0000D:/Sites/Skinbase26/node_modules/style-to-js/cjs/utilities.js?commonjs-exports": [], "\u0000D:/Sites/Skinbase26/node_modules/style-to-object/cjs/index.js?commonjs-exports": [], "\u0000D:/Sites/Skinbase26/node_modules/use-sync-external-store/cjs/use-sync-external-store-shim.development.js?commonjs-exports": [ - "/build/assets/vendor-tiptap-BUUKoc3C.js" + "/build/assets/vendor-tiptap-DRFaxGEb.js" ], "\u0000D:/Sites/Skinbase26/node_modules/use-sync-external-store/cjs/use-sync-external-store-shim.production.js?commonjs-exports": [ - "/build/assets/vendor-tiptap-BUUKoc3C.js" + "/build/assets/vendor-tiptap-DRFaxGEb.js" ], "\u0000D:/Sites/Skinbase26/node_modules/use-sync-external-store/cjs/use-sync-external-store-shim/with-selector.development.js?commonjs-exports": [ - "/build/assets/vendor-tiptap-BUUKoc3C.js" + "/build/assets/vendor-tiptap-DRFaxGEb.js" ], "\u0000D:/Sites/Skinbase26/node_modules/use-sync-external-store/cjs/use-sync-external-store-shim/with-selector.production.js?commonjs-exports": [ - "/build/assets/vendor-tiptap-BUUKoc3C.js" + "/build/assets/vendor-tiptap-DRFaxGEb.js" ], "\u0000D:/Sites/Skinbase26/node_modules/use-sync-external-store/shim/index.js?commonjs-es-import": [ - "/build/assets/vendor-tiptap-BUUKoc3C.js" + "/build/assets/vendor-tiptap-DRFaxGEb.js" ], "\u0000D:/Sites/Skinbase26/node_modules/use-sync-external-store/shim/index.js?commonjs-module": [ - "/build/assets/vendor-tiptap-BUUKoc3C.js" + "/build/assets/vendor-tiptap-DRFaxGEb.js" ], "\u0000D:/Sites/Skinbase26/node_modules/use-sync-external-store/shim/with-selector.js?commonjs-es-import": [ - "/build/assets/vendor-tiptap-BUUKoc3C.js" + "/build/assets/vendor-tiptap-DRFaxGEb.js" ], "\u0000D:/Sites/Skinbase26/node_modules/use-sync-external-store/shim/with-selector.js?commonjs-module": [ - "/build/assets/vendor-tiptap-BUUKoc3C.js" + "/build/assets/vendor-tiptap-DRFaxGEb.js" ], "\u0000assert?commonjs-external": [ - "/build/assets/vendor-realtime-BGlcW0gB.js" + "/build/assets/vendor-realtime-Koiu-_pw.js" ], "\u0000buffer?commonjs-external": [ - "/build/assets/vendor-realtime-BGlcW0gB.js" + "/build/assets/vendor-realtime-Koiu-_pw.js" ], "\u0000child_process?commonjs-external": [ - "/build/assets/vendor-realtime-BGlcW0gB.js" + "/build/assets/vendor-realtime-Koiu-_pw.js" ], "\u0000commonjsHelpers.js": [ - "/build/assets/vendor-tiptap-BUUKoc3C.js" + "/build/assets/vendor-tiptap-DRFaxGEb.js" ], "\u0000crypto?commonjs-external": [ - "/build/assets/vendor-realtime-BGlcW0gB.js" + "/build/assets/vendor-realtime-Koiu-_pw.js" ], "\u0000events?commonjs-external": [ - "/build/assets/vendor-realtime-BGlcW0gB.js" + "/build/assets/vendor-realtime-Koiu-_pw.js" ], "\u0000fs?commonjs-external": [ - "/build/assets/vendor-realtime-BGlcW0gB.js" + "/build/assets/vendor-realtime-Koiu-_pw.js" ], "\u0000http?commonjs-external": [ - "/build/assets/vendor-realtime-BGlcW0gB.js" + "/build/assets/vendor-realtime-Koiu-_pw.js" ], "\u0000https?commonjs-external": [ - "/build/assets/vendor-realtime-BGlcW0gB.js" + "/build/assets/vendor-realtime-Koiu-_pw.js" ], "\u0000net?commonjs-external": [ - "/build/assets/vendor-realtime-BGlcW0gB.js" + "/build/assets/vendor-realtime-Koiu-_pw.js" ], "\u0000stream?commonjs-external": [ - "/build/assets/vendor-realtime-BGlcW0gB.js" + "/build/assets/vendor-realtime-Koiu-_pw.js" ], "\u0000tls?commonjs-external": [ - "/build/assets/vendor-realtime-BGlcW0gB.js" + "/build/assets/vendor-realtime-Koiu-_pw.js" ], "\u0000url?commonjs-external": [ - "/build/assets/vendor-realtime-BGlcW0gB.js" + "/build/assets/vendor-realtime-Koiu-_pw.js" ], "\u0000util?commonjs-external": [ - "/build/assets/vendor-realtime-BGlcW0gB.js" + "/build/assets/vendor-realtime-Koiu-_pw.js" ], "node_modules/@emoji-mart/data/sets/15/native.json": [ "/build/assets/emoji-data-4xGXbtDn.js" ], + "node_modules/@floating-ui/core/dist/floating-ui.core.mjs": [ + "/build/assets/vendor-tiptap-DRFaxGEb.js" + ], + "node_modules/@floating-ui/dom/dist/floating-ui.dom.mjs": [ + "/build/assets/vendor-tiptap-DRFaxGEb.js" + ], + "node_modules/@floating-ui/utils/dist/floating-ui.utils.dom.mjs": [ + "/build/assets/vendor-tiptap-DRFaxGEb.js" + ], + "node_modules/@floating-ui/utils/dist/floating-ui.utils.mjs": [ + "/build/assets/vendor-tiptap-DRFaxGEb.js" + ], "node_modules/@inertiajs/core/dist/index.esm.js": [], "node_modules/@inertiajs/core/dist/server.esm.js": [], "node_modules/@inertiajs/react/dist/index.esm.js": [], @@ -316,109 +328,133 @@ "/build/assets/vendor-tooltip-CIQaDNlG.js" ], "node_modules/@tiptap/core/dist/index.js": [ - "/build/assets/vendor-tiptap-BUUKoc3C.js" + "/build/assets/vendor-tiptap-DRFaxGEb.js" ], "node_modules/@tiptap/core/dist/jsx-runtime/jsx-runtime.js": [ - "/build/assets/vendor-tiptap-BUUKoc3C.js" + "/build/assets/vendor-tiptap-DRFaxGEb.js" ], "node_modules/@tiptap/core/jsx-runtime/index.js": [ - "/build/assets/vendor-tiptap-BUUKoc3C.js" + "/build/assets/vendor-tiptap-DRFaxGEb.js" ], "node_modules/@tiptap/extension-blockquote/dist/index.js": [ - "/build/assets/vendor-tiptap-BUUKoc3C.js" + "/build/assets/vendor-tiptap-DRFaxGEb.js" ], "node_modules/@tiptap/extension-bold/dist/index.js": [ - "/build/assets/vendor-tiptap-BUUKoc3C.js" + "/build/assets/vendor-tiptap-DRFaxGEb.js" + ], + "node_modules/@tiptap/extension-bubble-menu/dist/index.js": [ + "/build/assets/vendor-tiptap-DRFaxGEb.js" ], "node_modules/@tiptap/extension-code-block/dist/index.js": [ - "/build/assets/vendor-tiptap-BUUKoc3C.js" + "/build/assets/vendor-tiptap-DRFaxGEb.js" ], "node_modules/@tiptap/extension-code/dist/index.js": [ - "/build/assets/vendor-tiptap-BUUKoc3C.js" + "/build/assets/vendor-tiptap-DRFaxGEb.js" ], "node_modules/@tiptap/extension-document/dist/index.js": [ - "/build/assets/vendor-tiptap-BUUKoc3C.js" + "/build/assets/vendor-tiptap-DRFaxGEb.js" + ], + "node_modules/@tiptap/extension-floating-menu/dist/index.js": [ + "/build/assets/vendor-tiptap-DRFaxGEb.js" ], "node_modules/@tiptap/extension-hard-break/dist/index.js": [ - "/build/assets/vendor-tiptap-BUUKoc3C.js" + "/build/assets/vendor-tiptap-DRFaxGEb.js" ], "node_modules/@tiptap/extension-heading/dist/index.js": [ - "/build/assets/vendor-tiptap-BUUKoc3C.js" + "/build/assets/vendor-tiptap-DRFaxGEb.js" ], "node_modules/@tiptap/extension-horizontal-rule/dist/index.js": [ - "/build/assets/vendor-tiptap-BUUKoc3C.js" + "/build/assets/vendor-tiptap-DRFaxGEb.js" ], "node_modules/@tiptap/extension-image/dist/index.js": [ - "/build/assets/vendor-tiptap-BUUKoc3C.js" + "/build/assets/vendor-tiptap-DRFaxGEb.js" ], "node_modules/@tiptap/extension-italic/dist/index.js": [ - "/build/assets/vendor-tiptap-BUUKoc3C.js" + "/build/assets/vendor-tiptap-DRFaxGEb.js" ], "node_modules/@tiptap/extension-link/dist/index.js": [ - "/build/assets/vendor-tiptap-BUUKoc3C.js" + "/build/assets/vendor-tiptap-DRFaxGEb.js" ], "node_modules/@tiptap/extension-list/dist/index.js": [ - "/build/assets/vendor-tiptap-BUUKoc3C.js" + "/build/assets/vendor-tiptap-DRFaxGEb.js" ], "node_modules/@tiptap/extension-mention/dist/index.js": [ - "/build/assets/vendor-tiptap-BUUKoc3C.js" + "/build/assets/vendor-tiptap-DRFaxGEb.js" ], "node_modules/@tiptap/extension-paragraph/dist/index.js": [ - "/build/assets/vendor-tiptap-BUUKoc3C.js" + "/build/assets/vendor-tiptap-DRFaxGEb.js" ], "node_modules/@tiptap/extension-placeholder/dist/index.js": [ - "/build/assets/vendor-tiptap-BUUKoc3C.js" + "/build/assets/vendor-tiptap-DRFaxGEb.js" ], "node_modules/@tiptap/extension-strike/dist/index.js": [ - "/build/assets/vendor-tiptap-BUUKoc3C.js" + "/build/assets/vendor-tiptap-DRFaxGEb.js" + ], + "node_modules/@tiptap/extension-table-cell/dist/index.js": [ + "/build/assets/vendor-tiptap-DRFaxGEb.js" + ], + "node_modules/@tiptap/extension-table-header/dist/index.js": [ + "/build/assets/vendor-tiptap-DRFaxGEb.js" + ], + "node_modules/@tiptap/extension-table-row/dist/index.js": [ + "/build/assets/vendor-tiptap-DRFaxGEb.js" + ], + "node_modules/@tiptap/extension-table/dist/index.js": [ + "/build/assets/vendor-tiptap-DRFaxGEb.js" ], "node_modules/@tiptap/extension-text/dist/index.js": [ - "/build/assets/vendor-tiptap-BUUKoc3C.js" + "/build/assets/vendor-tiptap-DRFaxGEb.js" ], "node_modules/@tiptap/extension-underline/dist/index.js": [ - "/build/assets/vendor-tiptap-BUUKoc3C.js" + "/build/assets/vendor-tiptap-DRFaxGEb.js" ], "node_modules/@tiptap/extensions/dist/index.js": [ - "/build/assets/vendor-tiptap-BUUKoc3C.js" + "/build/assets/vendor-tiptap-DRFaxGEb.js" ], "node_modules/@tiptap/pm/dist/commands/index.js": [ - "/build/assets/vendor-tiptap-BUUKoc3C.js" + "/build/assets/vendor-tiptap-DRFaxGEb.js" ], "node_modules/@tiptap/pm/dist/dropcursor/index.js": [ - "/build/assets/vendor-tiptap-BUUKoc3C.js" + "/build/assets/vendor-tiptap-DRFaxGEb.js" ], "node_modules/@tiptap/pm/dist/gapcursor/index.js": [ - "/build/assets/vendor-tiptap-BUUKoc3C.js" + "/build/assets/vendor-tiptap-DRFaxGEb.js" ], "node_modules/@tiptap/pm/dist/history/index.js": [ - "/build/assets/vendor-tiptap-BUUKoc3C.js" + "/build/assets/vendor-tiptap-DRFaxGEb.js" ], "node_modules/@tiptap/pm/dist/keymap/index.js": [ - "/build/assets/vendor-tiptap-BUUKoc3C.js" + "/build/assets/vendor-tiptap-DRFaxGEb.js" ], "node_modules/@tiptap/pm/dist/model/index.js": [ - "/build/assets/vendor-tiptap-BUUKoc3C.js" + "/build/assets/vendor-tiptap-DRFaxGEb.js" ], "node_modules/@tiptap/pm/dist/schema-list/index.js": [ - "/build/assets/vendor-tiptap-BUUKoc3C.js" + "/build/assets/vendor-tiptap-DRFaxGEb.js" ], "node_modules/@tiptap/pm/dist/state/index.js": [ - "/build/assets/vendor-tiptap-BUUKoc3C.js" + "/build/assets/vendor-tiptap-DRFaxGEb.js" + ], + "node_modules/@tiptap/pm/dist/tables/index.js": [ + "/build/assets/vendor-tiptap-DRFaxGEb.js" ], "node_modules/@tiptap/pm/dist/transform/index.js": [ - "/build/assets/vendor-tiptap-BUUKoc3C.js" + "/build/assets/vendor-tiptap-DRFaxGEb.js" ], "node_modules/@tiptap/pm/dist/view/index.js": [ - "/build/assets/vendor-tiptap-BUUKoc3C.js" + "/build/assets/vendor-tiptap-DRFaxGEb.js" ], "node_modules/@tiptap/react/dist/index.js": [ - "/build/assets/vendor-tiptap-BUUKoc3C.js" + "/build/assets/vendor-tiptap-DRFaxGEb.js" + ], + "node_modules/@tiptap/react/dist/menus/index.js": [ + "/build/assets/vendor-tiptap-DRFaxGEb.js" ], "node_modules/@tiptap/starter-kit/dist/index.js": [ - "/build/assets/vendor-tiptap-BUUKoc3C.js" + "/build/assets/vendor-tiptap-DRFaxGEb.js" ], "node_modules/@tiptap/suggestion/dist/index.js": [ - "/build/assets/vendor-tiptap-BUUKoc3C.js" + "/build/assets/vendor-tiptap-DRFaxGEb.js" ], "node_modules/@ungap/structured-clone/esm/deserialize.js": [], "node_modules/@ungap/structured-clone/esm/index.js": [], @@ -524,461 +560,461 @@ "node_modules/estree-util-is-identifier-name/lib/index.js": [], "node_modules/extend/index.js": [], "node_modules/fast-equals/dist/es/index.mjs": [ - "/build/assets/vendor-tiptap-BUUKoc3C.js" + "/build/assets/vendor-tiptap-DRFaxGEb.js" ], "node_modules/follow-redirects/debug.js": [], "node_modules/follow-redirects/index.js": [], "node_modules/form-data/lib/form_data.js": [], "node_modules/form-data/lib/populate.js": [], "node_modules/framer-motion/dist/es/animation/animate/index.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/framer-motion/dist/es/animation/animate/resolve-subjects.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/framer-motion/dist/es/animation/animate/sequence.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/framer-motion/dist/es/animation/animate/subject.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/framer-motion/dist/es/animation/animators/waapi/animate-elements.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/framer-motion/dist/es/animation/animators/waapi/animate-style.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/framer-motion/dist/es/animation/hooks/animation-controls.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/framer-motion/dist/es/animation/hooks/use-animate-style.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/framer-motion/dist/es/animation/hooks/use-animate.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/framer-motion/dist/es/animation/hooks/use-animated-state.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/framer-motion/dist/es/animation/hooks/use-animation.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/framer-motion/dist/es/animation/optimized-appear/handoff.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/framer-motion/dist/es/animation/optimized-appear/start.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/framer-motion/dist/es/animation/optimized-appear/store-id.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/framer-motion/dist/es/animation/optimized-appear/store.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/framer-motion/dist/es/animation/sequence/create.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/framer-motion/dist/es/animation/sequence/utils/calc-repeat-duration.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/framer-motion/dist/es/animation/sequence/utils/calc-time.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/framer-motion/dist/es/animation/sequence/utils/edit.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/framer-motion/dist/es/animation/sequence/utils/normalize-times.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/framer-motion/dist/es/animation/sequence/utils/sort.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/framer-motion/dist/es/animation/utils/create-visual-element.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/framer-motion/dist/es/animation/utils/is-dom-keyframes.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/framer-motion/dist/es/components/AnimatePresence/PopChild.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/framer-motion/dist/es/components/AnimatePresence/PresenceChild.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/framer-motion/dist/es/components/AnimatePresence/index.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/framer-motion/dist/es/components/AnimatePresence/use-presence-data.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/framer-motion/dist/es/components/AnimatePresence/use-presence.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/framer-motion/dist/es/components/AnimatePresence/utils.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/framer-motion/dist/es/components/AnimateSharedLayout.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/framer-motion/dist/es/components/LayoutGroup/index.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/framer-motion/dist/es/components/LazyMotion/index.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/framer-motion/dist/es/components/MotionConfig/index.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/framer-motion/dist/es/components/Reorder/Group.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/framer-motion/dist/es/components/Reorder/Item.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/framer-motion/dist/es/components/Reorder/namespace.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/framer-motion/dist/es/components/Reorder/utils/auto-scroll.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/framer-motion/dist/es/components/Reorder/utils/check-reorder.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/framer-motion/dist/es/context/DeprecatedLayoutGroupContext.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/framer-motion/dist/es/context/LayoutGroupContext.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/framer-motion/dist/es/context/LazyContext.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/framer-motion/dist/es/context/MotionConfigContext.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/framer-motion/dist/es/context/MotionContext/create.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/framer-motion/dist/es/context/MotionContext/index.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/framer-motion/dist/es/context/MotionContext/utils.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/framer-motion/dist/es/context/PresenceContext.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/framer-motion/dist/es/context/ReorderContext.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/framer-motion/dist/es/context/SwitchLayoutGroupContext.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/framer-motion/dist/es/events/add-pointer-event.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/framer-motion/dist/es/events/event-info.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/framer-motion/dist/es/events/use-dom-event.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/framer-motion/dist/es/gestures/drag/VisualElementDragControls.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/framer-motion/dist/es/gestures/drag/index.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/framer-motion/dist/es/gestures/drag/use-drag-controls.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/framer-motion/dist/es/gestures/drag/utils/constraints.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/framer-motion/dist/es/gestures/focus.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/framer-motion/dist/es/gestures/hover.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/framer-motion/dist/es/gestures/pan/PanSession.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/framer-motion/dist/es/gestures/pan/index.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/framer-motion/dist/es/gestures/press.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/framer-motion/dist/es/index.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/framer-motion/dist/es/motion/features/animation/exit.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/framer-motion/dist/es/motion/features/animation/index.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/framer-motion/dist/es/motion/features/animations.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/framer-motion/dist/es/motion/features/definitions.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/framer-motion/dist/es/motion/features/drag.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/framer-motion/dist/es/motion/features/gestures.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/framer-motion/dist/es/motion/features/layout.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/framer-motion/dist/es/motion/features/layout/MeasureLayout.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/framer-motion/dist/es/motion/features/load-features.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/framer-motion/dist/es/motion/features/viewport/index.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/framer-motion/dist/es/motion/features/viewport/observers.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/framer-motion/dist/es/motion/index.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/framer-motion/dist/es/motion/utils/is-motion-component.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/framer-motion/dist/es/motion/utils/symbol.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/framer-motion/dist/es/motion/utils/unwrap-motion-component.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/framer-motion/dist/es/motion/utils/use-motion-ref.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/framer-motion/dist/es/motion/utils/use-visual-element.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/framer-motion/dist/es/motion/utils/use-visual-state.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/framer-motion/dist/es/motion/utils/valid-prop.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/framer-motion/dist/es/projection/use-instant-layout-transition.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/framer-motion/dist/es/projection/use-reset-projection.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/framer-motion/dist/es/render/components/create-proxy.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/framer-motion/dist/es/render/components/m/proxy.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/framer-motion/dist/es/render/components/motion/feature-bundle.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/framer-motion/dist/es/render/components/motion/proxy.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/framer-motion/dist/es/render/dom/create-visual-element.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/framer-motion/dist/es/render/dom/features-animation.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/framer-motion/dist/es/render/dom/features-max.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/framer-motion/dist/es/render/dom/features-min.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/framer-motion/dist/es/render/dom/scroll/attach-animation.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/framer-motion/dist/es/render/dom/scroll/attach-function.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/framer-motion/dist/es/render/dom/scroll/index.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/framer-motion/dist/es/render/dom/scroll/info.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/framer-motion/dist/es/render/dom/scroll/offsets/edge.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/framer-motion/dist/es/render/dom/scroll/offsets/index.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/framer-motion/dist/es/render/dom/scroll/offsets/inset.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/framer-motion/dist/es/render/dom/scroll/offsets/offset.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/framer-motion/dist/es/render/dom/scroll/offsets/presets.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/framer-motion/dist/es/render/dom/scroll/on-scroll-handler.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/framer-motion/dist/es/render/dom/scroll/track.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/framer-motion/dist/es/render/dom/scroll/utils/can-use-native-timeline.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/framer-motion/dist/es/render/dom/scroll/utils/get-timeline.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/framer-motion/dist/es/render/dom/scroll/utils/offset-to-range.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/framer-motion/dist/es/render/dom/use-render.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/framer-motion/dist/es/render/dom/utils/filter-props.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/framer-motion/dist/es/render/dom/utils/is-svg-component.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/framer-motion/dist/es/render/dom/viewport/index.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/framer-motion/dist/es/render/html/use-html-visual-state.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/framer-motion/dist/es/render/html/use-props.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/framer-motion/dist/es/render/html/utils/create-render-state.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/framer-motion/dist/es/render/svg/lowercase-elements.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/framer-motion/dist/es/render/svg/use-props.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/framer-motion/dist/es/render/svg/use-svg-visual-state.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/framer-motion/dist/es/render/svg/utils/create-render-state.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/framer-motion/dist/es/utils/distance.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/framer-motion/dist/es/utils/get-context-window.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/framer-motion/dist/es/utils/is-browser.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/framer-motion/dist/es/utils/is-ref-object.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/framer-motion/dist/es/utils/reduced-motion/use-reduced-motion-config.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/framer-motion/dist/es/utils/reduced-motion/use-reduced-motion.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/framer-motion/dist/es/utils/transform-rotated-parent.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/framer-motion/dist/es/utils/transform-viewbox-point.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/framer-motion/dist/es/utils/use-animation-frame.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/framer-motion/dist/es/utils/use-composed-ref.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/framer-motion/dist/es/utils/use-constant.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/framer-motion/dist/es/utils/use-cycle.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/framer-motion/dist/es/utils/use-force-update.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/framer-motion/dist/es/utils/use-in-view.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/framer-motion/dist/es/utils/use-instant-transition.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/framer-motion/dist/es/utils/use-is-mounted.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/framer-motion/dist/es/utils/use-isomorphic-effect.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/framer-motion/dist/es/utils/use-motion-value-event.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/framer-motion/dist/es/utils/use-page-in-view.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/framer-motion/dist/es/utils/use-unmount-effect.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/framer-motion/dist/es/value/scroll/use-element-scroll.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/framer-motion/dist/es/value/scroll/use-viewport-scroll.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/framer-motion/dist/es/value/use-combine-values.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/framer-motion/dist/es/value/use-computed.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/framer-motion/dist/es/value/use-follow-value.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/framer-motion/dist/es/value/use-inverted-scale.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/framer-motion/dist/es/value/use-motion-template.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/framer-motion/dist/es/value/use-motion-value.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/framer-motion/dist/es/value/use-scroll.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/framer-motion/dist/es/value/use-spring.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/framer-motion/dist/es/value/use-time.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/framer-motion/dist/es/value/use-transform.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/framer-motion/dist/es/value/use-velocity.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/framer-motion/dist/es/value/use-will-change/WillChangeMotionValue.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/framer-motion/dist/es/value/use-will-change/index.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/function-bind/implementation.js": [], "node_modules/function-bind/index.js": [], @@ -999,10 +1035,10 @@ "node_modules/inline-style-parser/cjs/index.js": [], "node_modules/is-plain-obj/index.js": [], "node_modules/laravel-echo/dist/echo.js": [ - "/build/assets/vendor-realtime-BGlcW0gB.js" + "/build/assets/vendor-realtime-Koiu-_pw.js" ], "node_modules/linkifyjs/dist/linkify.mjs": [ - "/build/assets/vendor-tiptap-BUUKoc3C.js" + "/build/assets/vendor-tiptap-DRFaxGEb.js" ], "node_modules/lodash.isequal/index.js": [], "node_modules/math-intrinsics/abs.js": [], @@ -1095,755 +1131,755 @@ "node_modules/mime-db/index.js": [], "node_modules/mime-types/index.js": [], "node_modules/motion-dom/dist/es/animation/AsyncMotionValueAnimation.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/animation/GroupAnimation.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/animation/GroupAnimationWithThen.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/animation/JSAnimation.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/animation/NativeAnimation.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/animation/NativeAnimationExtended.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/animation/NativeAnimationWrapper.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/animation/animate/single-value.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/animation/drivers/frame.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/animation/generators/inertia.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/animation/generators/keyframes.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/animation/generators/spring.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/animation/generators/utils/calc-duration.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/animation/generators/utils/create-generator-easing.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/animation/generators/utils/is-generator.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/animation/generators/utils/velocity.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/animation/interfaces/motion-value.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/animation/interfaces/visual-element-target.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/animation/interfaces/visual-element-variant.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/animation/interfaces/visual-element.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/animation/keyframes/DOMKeyframesResolver.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/animation/keyframes/KeyframesResolver.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/animation/keyframes/get-final.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/animation/keyframes/offsets/default.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/animation/keyframes/offsets/fill.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/animation/keyframes/offsets/time.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/animation/keyframes/utils/apply-px-defaults.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/animation/keyframes/utils/fill-wildcards.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/animation/keyframes/utils/is-none.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/animation/keyframes/utils/make-none-animatable.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/animation/keyframes/utils/unit-conversion.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/animation/optimized-appear/data-id.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/animation/optimized-appear/get-appear-id.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/animation/utils/WithPromise.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/animation/utils/active-animations.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/animation/utils/calc-child-stagger.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/animation/utils/can-animate.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/animation/utils/css-variables-conversion.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/animation/utils/default-transitions.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/animation/utils/get-value-transition.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/animation/utils/is-animatable.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/animation/utils/is-css-variable.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/animation/utils/is-transition-defined.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/animation/utils/make-animation-instant.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/animation/utils/replace-transition-type.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/animation/utils/resolve-transition.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/animation/waapi/easing/cubic-bezier.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/animation/waapi/easing/is-supported.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/animation/waapi/easing/map-easing.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/animation/waapi/easing/supported.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/animation/waapi/start-waapi-animation.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/animation/waapi/supports/partial-keyframes.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/animation/waapi/supports/waapi.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/animation/waapi/utils/accelerated-values.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/animation/waapi/utils/apply-generator.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/animation/waapi/utils/is-browser-color.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/animation/waapi/utils/linear.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/animation/waapi/utils/px-values.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/animation/waapi/utils/unsupported-easing.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/effects/MotionValueState.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/effects/attr/index.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/effects/prop/index.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/effects/style/index.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/effects/style/transform.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/effects/svg/index.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/effects/utils/create-dom-effect.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/effects/utils/create-effect.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/events/add-dom-event.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/frameloop/batcher.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/frameloop/frame.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/frameloop/index-legacy.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/frameloop/microtask.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/frameloop/order.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/frameloop/render-step.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/frameloop/sync-time.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/gestures/drag/state/is-active.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/gestures/drag/state/set-active.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/gestures/hover.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/gestures/press/index.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/gestures/press/utils/is-keyboard-accessible.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/gestures/press/utils/keyboard.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/gestures/press/utils/state.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/gestures/utils/is-node-or-child.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/gestures/utils/is-primary-pointer.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/gestures/utils/setup.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/index.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/layout/LayoutAnimationBuilder.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/projection/animation/mix-values.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/projection/geometry/conversion.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/projection/geometry/copy.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/projection/geometry/delta-apply.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/projection/geometry/delta-calc.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/projection/geometry/delta-remove.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/projection/geometry/models.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/projection/geometry/utils.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/projection/node/DocumentProjectionNode.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/projection/node/HTMLProjectionNode.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/projection/node/create-projection-node.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/projection/node/group.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/projection/node/state.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/projection/shared/stack.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/projection/styles/scale-border-radius.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/projection/styles/scale-box-shadow.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/projection/styles/scale-correction.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/projection/styles/transform.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/projection/utils/compare-by-depth.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/projection/utils/each-axis.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/projection/utils/flat-tree.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/projection/utils/has-transform.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/projection/utils/measure.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/render/Feature.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/render/VisualElement.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/render/dom/DOMVisualElement.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/render/dom/is-css-var.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/render/dom/parse-transform.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/render/dom/style-computed.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/render/dom/style-set.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/render/dom/utils/camel-to-dash.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/render/html/HTMLVisualElement.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/render/html/utils/build-styles.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/render/html/utils/build-transform.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/render/html/utils/render.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/render/html/utils/scrape-motion-values.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/render/object/ObjectVisualElement.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/render/store.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/render/svg/SVGVisualElement.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/render/svg/utils/build-attrs.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/render/svg/utils/camel-case-attrs.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/render/svg/utils/is-svg-tag.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/render/svg/utils/path.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/render/svg/utils/render.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/render/svg/utils/scrape-motion-values.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/render/utils/animation-state.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/render/utils/get-variant-context.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/render/utils/is-animation-controls.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/render/utils/is-controlling-variants.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/render/utils/is-forced-motion-value.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/render/utils/is-keyframes-target.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/render/utils/is-variant-label.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/render/utils/keys-position.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/render/utils/keys-transform.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/render/utils/motion-values.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/render/utils/reduced-motion/index.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/render/utils/reduced-motion/state.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/render/utils/resolve-dynamic-variants.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/render/utils/resolve-variants.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/render/utils/setters.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/render/utils/shallow-compare.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/render/utils/variant-props.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/resize/handle-element.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/resize/handle-window.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/resize/index.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/scroll/observe.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/stats/animation-count.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/stats/buffer.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/stats/index.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/utils/delay.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/utils/interpolate.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/utils/is-html-element.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/utils/is-svg-element.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/utils/is-svg-svg-element.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/utils/mix/color.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/utils/mix/complex.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/utils/mix/immediate.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/utils/mix/index.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/utils/mix/number.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/utils/mix/visibility.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/utils/resolve-elements.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/utils/stagger.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/utils/supports/flags.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/utils/supports/linear-easing.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/utils/supports/memo.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/utils/supports/scroll-timeline.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/utils/transform.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/value/follow-value.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/value/index.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/value/map-value.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/value/spring-value.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/value/subscribe-value.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/value/transform-value.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/value/types/auto.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/value/types/color/hex.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/value/types/color/hsla-to-rgba.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/value/types/color/hsla.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/value/types/color/index.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/value/types/color/rgba.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/value/types/color/utils.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/value/types/complex/filter.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/value/types/complex/index.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/value/types/complex/mask.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/value/types/dimensions.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/value/types/int.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/value/types/maps/defaults.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/value/types/maps/number.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/value/types/maps/transform.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/value/types/numbers/index.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/value/types/numbers/units.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/value/types/test.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/value/types/utils/animatable-none.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/value/types/utils/color-regex.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/value/types/utils/find.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/value/types/utils/float-regex.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/value/types/utils/get-as-type.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/value/types/utils/is-nullish.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/value/types/utils/sanitize.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/value/types/utils/single-color-regex.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/value/utils/is-motion-value.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/value/utils/resolve-motion-value.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/value/will-change/add-will-change.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/value/will-change/is.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/view/index.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/view/queue.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/view/start.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/view/utils/choose-layer-type.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/view/utils/css.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/view/utils/get-layer-info.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/view/utils/get-view-animations.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-dom/dist/es/view/utils/has-target.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-utils/dist/es/array.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-utils/dist/es/clamp.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-utils/dist/es/easing/anticipate.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-utils/dist/es/easing/back.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-utils/dist/es/easing/circ.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-utils/dist/es/easing/cubic-bezier.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-utils/dist/es/easing/ease.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-utils/dist/es/easing/modifiers/mirror.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-utils/dist/es/easing/modifiers/reverse.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-utils/dist/es/easing/steps.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-utils/dist/es/easing/utils/get-easing-for-segment.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-utils/dist/es/easing/utils/is-bezier-definition.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-utils/dist/es/easing/utils/is-easing-array.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-utils/dist/es/easing/utils/map.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-utils/dist/es/errors.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-utils/dist/es/format-error-message.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-utils/dist/es/global-config.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-utils/dist/es/index.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-utils/dist/es/is-numerical-string.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-utils/dist/es/is-object.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-utils/dist/es/is-zero-value-string.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-utils/dist/es/memo.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-utils/dist/es/noop.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-utils/dist/es/pipe.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-utils/dist/es/progress.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-utils/dist/es/subscription-manager.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-utils/dist/es/time-conversion.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-utils/dist/es/velocity-per-second.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-utils/dist/es/warn-once.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/motion-utils/dist/es/wrap.mjs": [ - "/build/assets/vendor-motion-Dg7DlHqj.js" + "/build/assets/vendor-motion-CotXNotG.js" ], "node_modules/ms/index.js": [], "node_modules/nprogress/nprogress.js": [], "node_modules/object-inspect/index.js": [], "node_modules/object-inspect/util.inspect.js": [], "node_modules/orderedmap/dist/index.js": [ - "/build/assets/vendor-tiptap-BUUKoc3C.js" + "/build/assets/vendor-tiptap-DRFaxGEb.js" ], "node_modules/property-information/index.js": [], "node_modules/property-information/lib/aria.js": [], @@ -1864,38 +1900,41 @@ "node_modules/property-information/lib/xml.js": [], "node_modules/property-information/lib/xmlns.js": [], "node_modules/prosemirror-commands/dist/index.js": [ - "/build/assets/vendor-tiptap-BUUKoc3C.js" + "/build/assets/vendor-tiptap-DRFaxGEb.js" ], "node_modules/prosemirror-dropcursor/dist/index.js": [ - "/build/assets/vendor-tiptap-BUUKoc3C.js" + "/build/assets/vendor-tiptap-DRFaxGEb.js" ], "node_modules/prosemirror-gapcursor/dist/index.js": [ - "/build/assets/vendor-tiptap-BUUKoc3C.js" + "/build/assets/vendor-tiptap-DRFaxGEb.js" ], "node_modules/prosemirror-history/dist/index.js": [ - "/build/assets/vendor-tiptap-BUUKoc3C.js" + "/build/assets/vendor-tiptap-DRFaxGEb.js" ], "node_modules/prosemirror-keymap/dist/index.js": [ - "/build/assets/vendor-tiptap-BUUKoc3C.js" + "/build/assets/vendor-tiptap-DRFaxGEb.js" ], "node_modules/prosemirror-model/dist/index.js": [ - "/build/assets/vendor-tiptap-BUUKoc3C.js" + "/build/assets/vendor-tiptap-DRFaxGEb.js" ], "node_modules/prosemirror-schema-list/dist/index.js": [ - "/build/assets/vendor-tiptap-BUUKoc3C.js" + "/build/assets/vendor-tiptap-DRFaxGEb.js" ], "node_modules/prosemirror-state/dist/index.js": [ - "/build/assets/vendor-tiptap-BUUKoc3C.js" + "/build/assets/vendor-tiptap-DRFaxGEb.js" + ], + "node_modules/prosemirror-tables/dist/index.js": [ + "/build/assets/vendor-tiptap-DRFaxGEb.js" ], "node_modules/prosemirror-transform/dist/index.js": [ - "/build/assets/vendor-tiptap-BUUKoc3C.js" + "/build/assets/vendor-tiptap-DRFaxGEb.js" ], "node_modules/prosemirror-view/dist/index.js": [ - "/build/assets/vendor-tiptap-BUUKoc3C.js" + "/build/assets/vendor-tiptap-DRFaxGEb.js" ], "node_modules/proxy-from-env/index.js": [], "node_modules/pusher-js/dist/node/pusher.js": [ - "/build/assets/vendor-realtime-BGlcW0gB.js" + "/build/assets/vendor-realtime-Koiu-_pw.js" ], "node_modules/qs/lib/formats.js": [], "node_modules/qs/lib/index.js": [], @@ -1909,39 +1948,39 @@ "node_modules/react-dom/cjs/react-dom-server.node.development.js": [], "node_modules/react-dom/cjs/react-dom-server.node.production.js": [], "node_modules/react-dom/cjs/react-dom.development.js": [ - "/build/assets/vendor-tiptap-BUUKoc3C.js" + "/build/assets/vendor-tiptap-DRFaxGEb.js" ], "node_modules/react-dom/cjs/react-dom.production.js": [ - "/build/assets/vendor-tiptap-BUUKoc3C.js" + "/build/assets/vendor-tiptap-DRFaxGEb.js" ], "node_modules/react-dom/client.js": [], "node_modules/react-dom/index.js": [ - "/build/assets/vendor-tiptap-BUUKoc3C.js" + "/build/assets/vendor-tiptap-DRFaxGEb.js" ], "node_modules/react-dom/server.node.js": [], "node_modules/react-markdown/lib/index.js": [], "node_modules/react/cjs/react-jsx-runtime.development.js": [ - "/build/assets/vendor-tiptap-BUUKoc3C.js" + "/build/assets/vendor-tiptap-DRFaxGEb.js" ], "node_modules/react/cjs/react-jsx-runtime.production.js": [ - "/build/assets/vendor-tiptap-BUUKoc3C.js" + "/build/assets/vendor-tiptap-DRFaxGEb.js" ], "node_modules/react/cjs/react.development.js": [ - "/build/assets/vendor-tiptap-BUUKoc3C.js" + "/build/assets/vendor-tiptap-DRFaxGEb.js" ], "node_modules/react/cjs/react.production.js": [ - "/build/assets/vendor-tiptap-BUUKoc3C.js" + "/build/assets/vendor-tiptap-DRFaxGEb.js" ], "node_modules/react/index.js": [ - "/build/assets/vendor-tiptap-BUUKoc3C.js" + "/build/assets/vendor-tiptap-DRFaxGEb.js" ], "node_modules/react/jsx-runtime.js": [ - "/build/assets/vendor-tiptap-BUUKoc3C.js" + "/build/assets/vendor-tiptap-DRFaxGEb.js" ], "node_modules/remark-parse/lib/index.js": [], "node_modules/remark-rehype/lib/index.js": [], "node_modules/rope-sequence/dist/index.js": [ - "/build/assets/vendor-tiptap-BUUKoc3C.js" + "/build/assets/vendor-tiptap-DRFaxGEb.js" ], "node_modules/scheduler/cjs/scheduler.development.js": [], "node_modules/scheduler/cjs/scheduler.production.js": [], @@ -1969,28 +2008,28 @@ "node_modules/unist-util-visit-parents/lib/index.js": [], "node_modules/unist-util-visit/lib/index.js": [], "node_modules/use-sync-external-store/cjs/use-sync-external-store-shim.development.js": [ - "/build/assets/vendor-tiptap-BUUKoc3C.js" + "/build/assets/vendor-tiptap-DRFaxGEb.js" ], "node_modules/use-sync-external-store/cjs/use-sync-external-store-shim.production.js": [ - "/build/assets/vendor-tiptap-BUUKoc3C.js" + "/build/assets/vendor-tiptap-DRFaxGEb.js" ], "node_modules/use-sync-external-store/cjs/use-sync-external-store-shim/with-selector.development.js": [ - "/build/assets/vendor-tiptap-BUUKoc3C.js" + "/build/assets/vendor-tiptap-DRFaxGEb.js" ], "node_modules/use-sync-external-store/cjs/use-sync-external-store-shim/with-selector.production.js": [ - "/build/assets/vendor-tiptap-BUUKoc3C.js" + "/build/assets/vendor-tiptap-DRFaxGEb.js" ], "node_modules/use-sync-external-store/shim/index.js": [ - "/build/assets/vendor-tiptap-BUUKoc3C.js" + "/build/assets/vendor-tiptap-DRFaxGEb.js" ], "node_modules/use-sync-external-store/shim/with-selector.js": [ - "/build/assets/vendor-tiptap-BUUKoc3C.js" + "/build/assets/vendor-tiptap-DRFaxGEb.js" ], "node_modules/vfile-message/lib/index.js": [], "node_modules/vfile/lib/index.js": [], "node_modules/vfile/lib/minurl.shared.js": [], "node_modules/w3c-keyname/index.js": [ - "/build/assets/vendor-tiptap-BUUKoc3C.js" + "/build/assets/vendor-tiptap-DRFaxGEb.js" ], "resources/js/Layouts/AdminLayout.jsx": [], "resources/js/Layouts/SettingsLayout.jsx": [], @@ -2003,6 +2042,7 @@ "resources/js/Pages/Admin/Academy/CrudForm.jsx": [], "resources/js/Pages/Admin/Academy/CrudIndex.jsx": [], "resources/js/Pages/Admin/Academy/Dashboard.jsx": [], + "resources/js/Pages/Admin/Academy/LessonEditor.jsx": [], "resources/js/Pages/Admin/Academy/Submissions.jsx": [], "resources/js/Pages/Admin/AiBiography.jsx": [], "resources/js/Pages/Admin/Artworks.jsx": [], @@ -2080,25 +2120,6 @@ "resources/js/Pages/Help/troubleshootingHelpContent.js": [], "resources/js/Pages/Help/uploadHelpContent.js": [], "resources/js/Pages/Help/worldsHelpContent.js": [], - "resources/js/Pages/Home/HomeBecauseYouLike.jsx": [], - "resources/js/Pages/Home/HomeCTA.jsx": [], - "resources/js/Pages/Home/HomeCategories.jsx": [], - "resources/js/Pages/Home/HomeCollections.jsx": [], - "resources/js/Pages/Home/HomeCreators.jsx": [], - "resources/js/Pages/Home/HomeFresh.jsx": [], - "resources/js/Pages/Home/HomeFromFollowing.jsx": [], - "resources/js/Pages/Home/HomeGroups.jsx": [], - "resources/js/Pages/Home/HomeHero.jsx": [], - "resources/js/Pages/Home/HomeMedalHighlights.jsx": [], - "resources/js/Pages/Home/HomeNews.jsx": [], - "resources/js/Pages/Home/HomePage.jsx": [], - "resources/js/Pages/Home/HomeRising.jsx": [], - "resources/js/Pages/Home/HomeSuggestedCreators.jsx": [], - "resources/js/Pages/Home/HomeTags.jsx": [], - "resources/js/Pages/Home/HomeTrending.jsx": [], - "resources/js/Pages/Home/HomeTrendingForYou.jsx": [], - "resources/js/Pages/Home/HomeWelcomeRow.jsx": [], - "resources/js/Pages/Home/HomeWorldSpotlight.jsx": [], "resources/js/Pages/Leaderboard/LeaderboardPage.jsx": [], "resources/js/Pages/Messages/Index.jsx": [], "resources/js/Pages/Moderation/AiBiographyAdmin.jsx": [], @@ -2196,14 +2217,13 @@ "resources/js/components/artwork/ArtworkEvolutionSearchPicker.jsx": [], "resources/js/components/artwork/ArtworkFormatBadges.jsx": [], "resources/js/components/artwork/ArtworkGallery.jsx": [], - "resources/js/components/artwork/ArtworkGalleryGrid.jsx": [], "resources/js/components/artwork/ArtworkHero.jsx": [], "resources/js/components/artwork/ArtworkMediaStrip.jsx": [], "resources/js/components/artwork/ArtworkMeta.jsx": [], "resources/js/components/artwork/ArtworkRecommendationsRails.jsx": [], "resources/js/components/artwork/ArtworkShareButton.jsx": [], "resources/js/components/artwork/ArtworkShareModal.jsx": [ - "/build/assets/ArtworkShareModal-BnRQhiXq.js" + "/build/assets/ArtworkShareModal-BPM8yel5.js" ], "resources/js/components/artwork/ArtworkTags.jsx": [], "resources/js/components/artwork/AuthorBioPopover.jsx": [], @@ -2240,6 +2260,9 @@ "resources/js/components/forum/Pagination.jsx": [], "resources/js/components/forum/PostCard.jsx": [], "resources/js/components/forum/ReplyForm.jsx": [], + "resources/js/components/forum/RichCompareNode.jsx": [], + "resources/js/components/forum/RichImageNode.jsx": [], + "resources/js/components/forum/RichTableControls.jsx": [], "resources/js/components/forum/RichTextEditor.jsx": [], "resources/js/components/forum/ThreadRow.jsx": [], "resources/js/components/forum/mentionSuggestion.js": [], diff --git a/bootstrap/ssr/ssr.js b/bootstrap/ssr/ssr.js index 91a0886c..00868560 100644 --- a/bootstrap/ssr/ssr.js +++ b/bootstrap/ssr/ssr.js @@ -1,4 +1,4 @@ -import { g as getDefaultExportFromCjs, c as commonjsGlobal, r as reactExports, R as React, a as reactDomExports, u as useEditor, i as index_default, b as index_default$1, d as index_default$2, E as EditorContent, j as jsxRuntimeExports, e as requireReact, f as requireReactDom, h as ReactRenderer, N as Node3, m as mergeAttributes, k as index_default$3, l as index_default$4, n as index_default$5 } from "./assets/vendor-tiptap-BUUKoc3C.js"; +import { g as getDefaultExportFromCjs, c as commonjsGlobal, r as reactExports, R as React, a as reactDomExports, b as ReactRenderer, i as index_default, d as ReactNodeViewRenderer, m as mergeAttributes, N as NodeViewWrapper, e as Node3, B as BubbleMenu, f as index_default$1, T as TableRow, h as index_default$2, k as index_default$3, l as Table, n as TableHeader, o as TableCell, p as index_default$4, q as index_default$5, u as useEditor, E as EditorContent, j as jsxRuntimeExports, s as requireReact, t as requireReactDom } from "./assets/vendor-tiptap-DRFaxGEb.js"; import require$$0$1 from "util"; import stream, { Readable } from "stream"; import require$$1 from "path"; @@ -13,12 +13,12 @@ import require$$1$2 from "tty"; import require$$0$2 from "os"; import zlib from "zlib"; import { EventEmitter } from "events"; +import { t as tippy } from "./assets/vendor-tooltip-CIQaDNlG.js"; import minproc from "node:process"; import minpath from "node:path"; import { fileURLToPath } from "node:url"; -import { t as tippy } from "./assets/vendor-tooltip-CIQaDNlG.js"; -import { P as Pusher, E as E$1 } from "./assets/vendor-realtime-BGlcW0gB.js"; -import { u as useReducedMotion, m as motion, A as AnimatePresence } from "./assets/vendor-motion-Dg7DlHqj.js"; +import { P as Pusher, E as E$1 } from "./assets/vendor-realtime-Koiu-_pw.js"; +import { u as useReducedMotion, m as motion, A as AnimatePresence } from "./assets/vendor-motion-CotXNotG.js"; import * as s from "process"; import require$$2 from "async_hooks"; import "buffer"; @@ -9052,26 +9052,6 @@ const { getAdapter, mergeConfig } = axios; -const index$1 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ - __proto__: null, - Axios: Axios2, - AxiosError: AxiosError2, - AxiosHeaders: AxiosHeaders2, - Cancel, - CancelToken: CancelToken2, - CanceledError: CanceledError2, - HttpStatusCode, - VERSION, - all: all$1, - default: axios, - formToJSON, - getAdapter, - isAxiosError, - isCancel, - mergeConfig, - spread, - toFormData -}, Symbol.toStringTag, { value: "Module" })); var cjs$3; var hasRequiredCjs$3; function requireCjs$3() { @@ -12833,13 +12813,117 @@ const __vite_glob_0_3 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.def __proto__: null, default: AcademyPricing }, Symbol.toStringTag, { value: "Module" })); +function slugifyHeading(value, fallback = "section") { + const normalized = String(value || "").toLowerCase().trim().replace(/[^a-z0-9\s-]/g, "").replace(/\s+/g, "-").replace(/-+/g, "-").replace(/^-|-$/g, ""); + return normalized || fallback; +} +function formatLessonDate(value) { + if (!value) return "Recently updated"; + const date = new Date(value); + if (Number.isNaN(date.getTime())) return "Recently updated"; + return new Intl.DateTimeFormat("en", { month: "short", day: "numeric", year: "numeric" }).format(date); +} +function formatLessonMinutes(minutes) { + const value = Number(minutes || 0); + return value > 0 ? `${value} min read` : "Quick read"; +} +function StatPill$2({ label, value }) { + return /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3" }, /* @__PURE__ */ React.createElement("p", { className: "text-[10px] font-semibold uppercase tracking-[0.24em] text-slate-400" }, label), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm font-semibold text-white" }, value)); +} +function LessonInfoRow({ label, value }) { + return /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between gap-4 rounded-2xl border border-white/10 bg-black/20 px-4 py-3" }, /* @__PURE__ */ React.createElement("span", { className: "text-[11px] font-semibold uppercase tracking-[0.22em] text-slate-400" }, label), /* @__PURE__ */ React.createElement("span", { className: "text-sm font-semibold text-white" }, value)); +} function LockedPanel({ pricingUrl, label }) { return /* @__PURE__ */ React.createElement("div", { className: "rounded-[28px] border border-amber-300/20 bg-amber-300/10 p-6 text-amber-50" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.22em] text-amber-100/80" }, "Premium content"), /* @__PURE__ */ React.createElement("h2", { className: "mt-3 text-2xl font-semibold tracking-[-0.04em]" }, "Unlock the full ", label, "."), /* @__PURE__ */ React.createElement("p", { className: "mt-3 text-sm leading-7 text-amber-50/90" }, "This preview is visible, but the full Academy content stays server-side until your account has the required Creator or Pro access."), /* @__PURE__ */ React.createElement(xe, { href: pricingUrl, className: "mt-5 inline-flex rounded-full border border-amber-200/25 bg-white/10 px-5 py-3 text-sm font-semibold text-white" }, "See Academy plans")); } -function AcademyShow({ pageType, item, seo, pricingUrl, completeUrl, completed: initialCompleted, saveUrl, unsaveUrl, saved: initialSaved, submitUrl }) { +function copyTextToClipboard(text2) { + const source = String(text2 || ""); + if (!source) return Promise.reject(new Error("Nothing to copy")); + if (navigator.clipboard && typeof navigator.clipboard.writeText === "function") { + return navigator.clipboard.writeText(source); + } + const textarea = document.createElement("textarea"); + textarea.value = source; + textarea.setAttribute("readonly", "true"); + textarea.style.position = "fixed"; + textarea.style.top = "-1000px"; + textarea.style.left = "-1000px"; + document.body.appendChild(textarea); + textarea.select(); + try { + if (document.execCommand("copy")) { + return Promise.resolve(); + } + } finally { + document.body.removeChild(textarea); + } + return Promise.reject(new Error("Clipboard unavailable")); +} +function PromptCopyButton({ prompt }) { + const [status2, setStatus] = reactExports.useState("idle"); + const resetTimerRef = reactExports.useRef(0); + return /* @__PURE__ */ React.createElement( + "button", + { + type: "button", + onClick: () => { + copyTextToClipboard(prompt).then(() => setStatus("copied")).catch(() => setStatus("failed")).finally(() => { + window.clearTimeout(resetTimerRef.current); + resetTimerRef.current = window.setTimeout(() => setStatus("idle"), 1800); + }); + }, + className: "inline-flex items-center gap-2 rounded-full border border-[#ffb9ab]/20 bg-[#ffb9ab]/10 px-4 py-2 text-sm font-semibold text-[#ffe2dc] transition hover:border-[#ffb9ab]/35 hover:bg-[#ffb9ab]/16", + "aria-label": "Copy prompt" + }, + /* @__PURE__ */ React.createElement("i", { className: `fa-solid ${status2 === "copied" ? "fa-check" : status2 === "failed" ? "fa-triangle-exclamation" : "fa-copy"}` }), + /* @__PURE__ */ React.createElement("span", null, status2 === "copied" ? "Copied" : status2 === "failed" ? "Copy failed" : "Copy prompt") + ); +} +function AiComparisonSection({ block }) { + const payload = block?.payload || {}; + const criteria = Array.isArray(payload.criteria) ? payload.criteria.filter(Boolean) : []; + const results = Array.isArray(block?.comparison_results) ? block.comparison_results.filter((result) => result?.active !== false) : []; + const hasPrompt = Boolean(payload.prompt); + const hasNegativePrompt = Boolean(payload.negative_prompt); + const hasUsefulData = Boolean(block?.title || payload.title || payload.intro || hasPrompt || hasNegativePrompt || payload.aspect_ratio || criteria.length || results.length); + if (!hasUsefulData) return null; + return /* @__PURE__ */ React.createElement("section", { className: "rounded-[32px] border border-white/10 bg-[radial-gradient(circle_at_top_left,rgba(255,151,132,0.14),transparent_30%),linear-gradient(180deg,rgba(15,23,42,0.96),rgba(2,6,23,0.92))] p-6 shadow-[0_24px_80px_rgba(2,6,23,0.28)] md:p-7" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-start justify-between gap-4" }, /* @__PURE__ */ React.createElement("div", { className: "max-w-3xl" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.24em] text-[#ffb8aa]" }, "AI Model Comparison"), /* @__PURE__ */ React.createElement("h2", { className: "mt-3 text-2xl font-semibold tracking-[-0.04em] text-white md:text-3xl" }, payload.title || block.title || "Same Prompt, Different AI Models"), payload.intro ? /* @__PURE__ */ React.createElement("p", { className: "mt-3 text-sm leading-7 text-slate-300 md:text-base" }, payload.intro) : null), payload.aspect_ratio ? /* @__PURE__ */ React.createElement("div", { className: "rounded-full border border-white/10 bg-white/[0.04] px-4 py-2 text-xs font-semibold uppercase tracking-[0.18em] text-slate-200" }, "Aspect ratio ", payload.aspect_ratio) : null), hasPrompt ? /* @__PURE__ */ React.createElement("div", { className: "mt-6 rounded-[26px] border border-[#ffb8aa]/15 bg-black/25 p-4 md:p-5" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.22em] text-[#ffd0c6]" }, "Prompt used"), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-xs uppercase tracking-[0.16em] text-slate-500" }, "Shared source prompt across all compared models")), /* @__PURE__ */ React.createElement(PromptCopyButton, { prompt: payload.prompt })), /* @__PURE__ */ React.createElement("pre", { className: "mt-4 whitespace-pre-wrap rounded-[22px] border border-white/10 bg-slate-950/70 p-4 text-sm leading-7 text-slate-100" }, payload.prompt), hasNegativePrompt ? /* @__PURE__ */ React.createElement("div", { className: "mt-4 rounded-[22px] border border-white/10 bg-white/[0.03] p-4" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.2em] text-slate-400" }, "Negative prompt"), /* @__PURE__ */ React.createElement("pre", { className: "mt-3 whitespace-pre-wrap text-sm leading-7 text-slate-300" }, payload.negative_prompt)) : null) : null, criteria.length ? /* @__PURE__ */ React.createElement("div", { className: "mt-6" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.22em] text-slate-400" }, "What we compare"), /* @__PURE__ */ React.createElement("div", { className: "mt-3 flex flex-wrap gap-2" }, criteria.map((criterion) => /* @__PURE__ */ React.createElement("span", { key: criterion, className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-2 text-sm font-medium text-slate-100" }, criterion)))) : null, results.length ? /* @__PURE__ */ React.createElement("div", { className: "mt-6 grid gap-5 md:grid-cols-2 2xl:grid-cols-4" }, results.map((result) => { + const imageUrl = result.thumb_url || result.image_url || result.thumb_path || result.image_path || ""; + const score = Number(result.score || 0); + const hasScore = Number.isFinite(score) && score > 0; + const altText = `${result.model_name || "AI model"} by ${result.provider || "unknown provider"} result for ${payload.prompt || "comparison prompt"}`; + return /* @__PURE__ */ React.createElement("article", { key: result.id || `${result.provider}-${result.model_name}-${result.sort_order || 0}`, className: "overflow-hidden rounded-[28px] border border-white/10 bg-white/[0.04] shadow-[0_16px_40px_rgba(2,6,23,0.18)]" }, /* @__PURE__ */ React.createElement("div", { className: "aspect-video overflow-hidden bg-slate-950/80" }, imageUrl ? /* @__PURE__ */ React.createElement("img", { src: imageUrl, alt: altText, loading: "lazy", className: "h-full w-full object-cover" }) : /* @__PURE__ */ React.createElement("div", { className: "flex h-full items-center justify-center px-6 text-center text-sm text-slate-500" }, "No comparison image provided.")), /* @__PURE__ */ React.createElement("div", { className: "space-y-4 p-5" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-start justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("h3", { className: "text-xl font-semibold tracking-[-0.03em] text-white" }, result.model_name || result.provider || "AI model"), result.provider ? /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-sm text-slate-400" }, result.provider) : null), hasScore ? /* @__PURE__ */ React.createElement("div", { className: "rounded-full border border-[#ffb8aa]/20 bg-[#ffb8aa]/10 px-3 py-1 text-sm font-semibold text-[#ffe3dd]" }, `Skinbase score ${score}/10`) : null), result.settings ? /* @__PURE__ */ React.createElement("div", { className: "rounded-[20px] border border-white/10 bg-black/20 p-4" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, "Settings"), /* @__PURE__ */ React.createElement("p", { className: "mt-2 whitespace-pre-wrap text-sm leading-7 text-slate-300" }, result.settings)) : null, result.strengths ? /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-emerald-200/75" }, "Strengths"), /* @__PURE__ */ React.createElement("p", { className: "mt-2 whitespace-pre-wrap text-sm leading-7 text-slate-200" }, result.strengths)) : null, result.weaknesses ? /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-amber-200/75" }, "Weaknesses"), /* @__PURE__ */ React.createElement("p", { className: "mt-2 whitespace-pre-wrap text-sm leading-7 text-slate-300" }, result.weaknesses)) : null, result.best_for ? /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-sky-200/75" }, "Best for"), /* @__PURE__ */ React.createElement("p", { className: "mt-2 whitespace-pre-wrap text-sm leading-7 text-slate-200" }, result.best_for)) : null)); + })) : null); +} +function AcademyShow({ pageType, item, relatedLessons = [], seo, pricingUrl, completeUrl, completed: initialCompleted, saveUrl, unsaveUrl, saved: initialSaved, submitUrl }) { const flash = X().props.flash || {}; const [completed, setCompleted] = reactExports.useState(Boolean(initialCompleted)); const [saved, setSaved] = reactExports.useState(Boolean(initialSaved)); + const [tableOfContents, setTableOfContents] = reactExports.useState([]); + const [activeHeadingId, setActiveHeadingId] = reactExports.useState(""); + const articleContentRef = reactExports.useRef(null); + const lessonCover = item?.cover_image_url || item?.cover_image || ""; + const lessonCategory = item?.category?.name || "Academy"; + const lessonDifficulty = item?.difficulty || "Intermediate"; + const lessonMinutes = formatLessonMinutes(item?.reading_minutes); + const lessonUpdated = formatLessonDate(item?.published_at); + const lessonBlocks = Array.isArray(item?.blocks) ? item.blocks : []; + const relatedLessonList = Array.isArray(relatedLessons) ? relatedLessons : []; + const lessonSummary = item.excerpt || item.description || item.prompt_preview || item.content_preview || "A focused Academy lesson with practical guidance and examples."; + const fontScaleStorageKey = "academy.lesson.font-scale"; + const fontScaleMin = 0.95; + const fontScaleMax = 1.12; + const fontScaleStep = 0.04; + const [lessonFontScale, setLessonFontScale] = reactExports.useState(() => { + if (typeof window === "undefined") { + return 1.04; + } + const storedValue = Number(window.localStorage.getItem(fontScaleStorageKey)); + if (Number.isFinite(storedValue)) { + return Math.min(fontScaleMax, Math.max(fontScaleMin, storedValue)); + } + return 1.04; + }); const markComplete = () => { if (!completeUrl || completed) return; At.post(completeUrl, {}, { @@ -12855,7 +12939,189 @@ function AcademyShow({ pageType, item, seo, pricingUrl, completeUrl, completed: onSuccess: () => setSaved(!saved) }); }; - return /* @__PURE__ */ React.createElement("main", { className: "min-h-screen bg-[radial-gradient(circle_at_top_left,_rgba(56,189,248,0.15),_transparent_24%),radial-gradient(circle_at_bottom_right,_rgba(251,191,36,0.16),_transparent_24%),linear-gradient(180deg,_#0f172a_0%,_#111827_100%)] px-4 py-8 sm:px-6 lg:px-8" }, /* @__PURE__ */ React.createElement(SeoHead, { seo: seo || {}, title: item?.title, description: item?.excerpt || item?.description }), /* @__PURE__ */ React.createElement("div", { className: "mx-auto max-w-[1200px] space-y-6" }, /* @__PURE__ */ React.createElement("section", { className: "rounded-[38px] border border-white/10 bg-black/20 p-8 md:p-10" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-start justify-between gap-5" }, /* @__PURE__ */ React.createElement("div", { className: "max-w-3xl" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.24em] text-sky-200/80" }, "Skinbase AI Academy"), /* @__PURE__ */ React.createElement("h1", { className: "mt-3 text-4xl font-semibold tracking-[-0.05em] text-white md:text-5xl" }, item.title), /* @__PURE__ */ React.createElement("p", { className: "mt-4 text-base leading-8 text-slate-300" }, item.excerpt || item.description || item.prompt_preview || item.content_preview)), /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-3" }, completeUrl ? /* @__PURE__ */ React.createElement("button", { type: "button", onClick: markComplete, className: "rounded-full border border-emerald-300/25 bg-emerald-300/12 px-5 py-3 text-sm font-semibold text-emerald-100" }, completed ? "Completed" : "Mark complete") : null, saveUrl ? /* @__PURE__ */ React.createElement("button", { type: "button", onClick: toggleSave, className: "rounded-full border border-sky-300/25 bg-sky-300/12 px-5 py-3 text-sm font-semibold text-sky-100" }, saved ? "Saved" : "Save prompt") : null, submitUrl ? /* @__PURE__ */ React.createElement(xe, { href: submitUrl, className: "rounded-full border border-sky-300/25 bg-sky-300/12 px-5 py-3 text-sm font-semibold text-sky-100" }, "Submit artwork") : null))), flash.success ? /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-emerald-300/20 bg-emerald-300/10 px-4 py-3 text-sm text-emerald-100" }, flash.success) : null, flash.error ? /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-rose-300/20 bg-rose-300/10 px-4 py-3 text-sm text-rose-100" }, flash.error) : null, item.locked ? /* @__PURE__ */ React.createElement(LockedPanel, { pricingUrl, label: pageType }) : null, /* @__PURE__ */ React.createElement("section", { className: "rounded-[30px] border border-white/10 bg-white/[0.04] p-6 text-slate-200" }, pageType === "lesson" ? /* @__PURE__ */ React.createElement("div", { className: "whitespace-pre-wrap text-sm leading-8 text-slate-200" }, item.content || item.content_preview) : null, pageType === "prompt" ? /* @__PURE__ */ React.createElement("div", { className: "space-y-6" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.22em] text-slate-400" }, "Prompt"), /* @__PURE__ */ React.createElement("pre", { className: "mt-3 whitespace-pre-wrap rounded-2xl border border-white/10 bg-black/20 p-4 text-sm leading-7 text-slate-200" }, item.prompt || item.prompt_preview)), item.negative_prompt ? /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.22em] text-slate-400" }, "Negative prompt"), /* @__PURE__ */ React.createElement("pre", { className: "mt-3 whitespace-pre-wrap rounded-2xl border border-white/10 bg-black/20 p-4 text-sm leading-7 text-slate-200" }, item.negative_prompt)) : null) : null, pageType === "pack" ? /* @__PURE__ */ React.createElement("div", { className: "space-y-5" }, /* @__PURE__ */ React.createElement("p", { className: "text-sm leading-8 text-slate-200" }, item.description), /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 md:grid-cols-2" }, (item.prompts || []).map((prompt) => /* @__PURE__ */ React.createElement("div", { key: prompt.id, className: "rounded-2xl border border-white/10 bg-black/20 p-4" }, /* @__PURE__ */ React.createElement("h3", { className: "text-lg font-semibold text-white" }, prompt.title), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm leading-7 text-slate-300" }, prompt.excerpt || prompt.prompt_preview))))) : null, pageType === "challenge" ? /* @__PURE__ */ React.createElement("div", { className: "space-y-6" }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-6 md:grid-cols-2" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.22em] text-slate-400" }, "Brief"), /* @__PURE__ */ React.createElement("div", { className: "mt-3 whitespace-pre-wrap text-sm leading-8 text-slate-200" }, item.brief || item.description)), /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.22em] text-slate-400" }, "Rules"), /* @__PURE__ */ React.createElement("div", { className: "mt-3 whitespace-pre-wrap text-sm leading-8 text-slate-200" }, item.rules || "No special rules posted yet."))), (item.submissions || []).length ? /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.22em] text-slate-400" }, "Approved submissions"), /* @__PURE__ */ React.createElement("div", { className: "mt-4 grid gap-4 md:grid-cols-2" }, item.submissions.map((submission) => /* @__PURE__ */ React.createElement("div", { key: submission.id, className: "rounded-2xl border border-white/10 bg-black/20 p-4" }, /* @__PURE__ */ React.createElement("h3", { className: "text-lg font-semibold text-white" }, submission.artwork?.title || "Submission"), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm text-slate-400" }, submission.user?.name || "Unknown creator"))))) : null) : null))); + const decreaseFontSize = () => { + setLessonFontScale((current) => Math.max(fontScaleMin, Number((current - fontScaleStep).toFixed(2)))); + }; + const increaseFontSize = () => { + setLessonFontScale((current) => Math.min(fontScaleMax, Number((current + fontScaleStep).toFixed(2)))); + }; + reactExports.useEffect(() => { + if (pageType !== "lesson" || !item?.content || !articleContentRef.current) { + setTableOfContents([]); + setActiveHeadingId(""); + return; + } + const headings = Array.from(articleContentRef.current.querySelectorAll("h2, h3")); + const seenIds = /* @__PURE__ */ new Map(); + const nextTableOfContents = headings.map((heading2, index2) => { + const baseId = slugifyHeading(heading2.textContent, `section-${index2 + 1}`); + const seenCount = seenIds.get(baseId) ?? 0; + const nextId = seenCount > 0 ? `${baseId}-${seenCount + 1}` : baseId; + seenIds.set(baseId, seenCount + 1); + heading2.id = nextId; + return { + id: nextId, + title: heading2.textContent?.trim() || `Section ${index2 + 1}`, + level: heading2.tagName.toLowerCase() + }; + }); + setTableOfContents(nextTableOfContents); + }, [item?.content, pageType]); + reactExports.useEffect(() => { + if (pageType !== "lesson" || tableOfContents.length === 0 || !articleContentRef.current) { + setActiveHeadingId(""); + return; + } + const headingElements = Array.from(articleContentRef.current.querySelectorAll("h2, h3")); + if (!headingElements.length) { + setActiveHeadingId(""); + return; + } + const observer = new IntersectionObserver((entries) => { + const visibleEntries = entries.filter((entry) => entry.isIntersecting).sort((left, right) => left.boundingClientRect.top - right.boundingClientRect.top); + if (visibleEntries.length) { + setActiveHeadingId((current) => visibleEntries[0].target.id || current); + } + }, { + root: null, + rootMargin: "-18% 0px -68% 0px", + threshold: [0, 1] + }); + headingElements.forEach((heading2) => observer.observe(heading2)); + const firstVisibleHeading = headingElements.find((heading2) => heading2.getBoundingClientRect().top >= 0) || headingElements[0]; + if (firstVisibleHeading?.id) { + setActiveHeadingId(firstVisibleHeading.id); + } + return () => observer.disconnect(); + }, [pageType, tableOfContents, lessonFontScale]); + reactExports.useEffect(() => { + if (typeof window === "undefined") { + return; + } + window.localStorage.setItem(fontScaleStorageKey, String(lessonFontScale)); + }, [lessonFontScale]); + reactExports.useEffect(() => { + if (pageType !== "lesson" || !item?.content || !articleContentRef.current) { + return; + } + const codeBlocks = Array.from(articleContentRef.current.querySelectorAll("pre code")); + if (!codeBlocks.length) { + return; + } + const fallbackCopyText = (text2) => { + const textarea = document.createElement("textarea"); + textarea.value = text2; + textarea.setAttribute("readonly", "true"); + textarea.style.position = "fixed"; + textarea.style.top = "-1000px"; + textarea.style.left = "-1000px"; + document.body.appendChild(textarea); + textarea.select(); + try { + return document.execCommand("copy"); + } catch (_error) { + return false; + } finally { + document.body.removeChild(textarea); + } + }; + const copyText = (text2) => { + if (navigator.clipboard && typeof navigator.clipboard.writeText === "function") { + return navigator.clipboard.writeText(text2); + } + return fallbackCopyText(text2) ? Promise.resolve() : Promise.reject(new Error("Clipboard unavailable")); + }; + codeBlocks.forEach((block) => { + const pre = block.parentElement; + if (!pre || pre.dataset.academyCopyButtonMounted === "true") { + return; + } + const button = document.createElement("button"); + const icon = document.createElement("span"); + const label = document.createElement("span"); + button.type = "button"; + button.className = "story-code-copy-button academy-code-copy-button"; + icon.className = "story-code-copy-icon"; + icon.setAttribute("aria-hidden", "true"); + icon.textContent = "⧉"; + label.className = "story-code-copy-label"; + label.textContent = "Copy"; + button.appendChild(icon); + button.appendChild(label); + button.dataset.copied = "idle"; + button.setAttribute("aria-label", "Copy code block"); + let resetTimer = 0; + button.addEventListener("click", () => { + const source = block.innerText || block.textContent || ""; + copyText(source).then(() => { + icon.textContent = "✓"; + label.textContent = "Copied"; + button.dataset.copied = "true"; + }).catch(() => { + icon.textContent = "!"; + label.textContent = "Failed"; + button.dataset.copied = "false"; + }).finally(() => { + window.clearTimeout(resetTimer); + resetTimer = window.setTimeout(() => { + icon.textContent = "⧉"; + label.textContent = "Copy"; + button.dataset.copied = "idle"; + }, 1800); + }); + }); + pre.appendChild(button); + pre.dataset.academyCopyButtonMounted = "true"; + }); + }, [item?.content, lessonFontScale, pageType]); + return /* @__PURE__ */ React.createElement("main", { className: "min-h-screen bg-[radial-gradient(circle_at_top_left,_rgba(56,189,248,0.15),_transparent_24%),radial-gradient(circle_at_bottom_right,_rgba(251,191,36,0.16),_transparent_24%),linear-gradient(180deg,_#0f172a_0%,_#111827_100%)] px-4 py-8 sm:px-6 lg:px-8" }, /* @__PURE__ */ React.createElement(SeoHead, { seo: seo || {}, title: item?.title, description: item?.excerpt || item?.description }), /* @__PURE__ */ React.createElement("div", { className: "mx-auto max-w-[1320px] space-y-6" }, flash.success ? /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-emerald-300/20 bg-emerald-300/10 px-4 py-3 text-sm text-emerald-100" }, flash.success) : null, flash.error ? /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-rose-300/20 bg-rose-300/10 px-4 py-3 text-sm text-rose-100" }, flash.error) : null, item.locked ? /* @__PURE__ */ React.createElement(LockedPanel, { pricingUrl, label: pageType }) : null, pageType === "lesson" ? /* @__PURE__ */ React.createElement("div", { className: "space-y-8" }, /* @__PURE__ */ React.createElement("section", { className: "overflow-hidden rounded-[40px] border border-white/10 bg-black/20 shadow-[0_24px_90px_rgba(15,23,42,0.34)]" }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-0 lg:grid-cols-[minmax(0,1fr)_360px]" }, /* @__PURE__ */ React.createElement("div", { className: "relative overflow-hidden p-8 md:p-10 lg:p-12" }, lessonCover ? /* @__PURE__ */ React.createElement("img", { src: lessonCover, alt: "", "aria-hidden": "true", className: "absolute inset-0 h-full w-full object-cover opacity-15" }) : null, /* @__PURE__ */ React.createElement("div", { className: "absolute inset-0 bg-[radial-gradient(circle_at_top_left,_rgba(56,189,248,0.22),_transparent_34%),linear-gradient(135deg,_rgba(2,6,23,0.96),_rgba(15,23,42,0.78))]" }), /* @__PURE__ */ React.createElement("div", { className: "relative z-10 max-w-3xl" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-2" }, /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-sky-300/20 bg-sky-300/10 px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.24em] text-sky-100" }, "Skinbase AI Academy"), /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.05] px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.24em] text-slate-300" }, lessonCategory), /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.05] px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.24em] text-slate-300" }, lessonDifficulty)), /* @__PURE__ */ React.createElement("h1", { className: "mt-5 text-4xl font-semibold tracking-[-0.055em] text-white md:text-5xl lg:text-6xl" }, item.title), /* @__PURE__ */ React.createElement("p", { className: "mt-5 max-w-2xl text-base leading-8 text-slate-300 md:text-lg" }, lessonSummary), /* @__PURE__ */ React.createElement("div", { className: "mt-7 flex flex-wrap gap-3" }, completeUrl ? /* @__PURE__ */ React.createElement("button", { type: "button", onClick: markComplete, className: "rounded-full border border-emerald-300/25 bg-emerald-300/12 px-5 py-3 text-sm font-semibold text-emerald-100" }, completed ? "Completed" : "Mark complete") : null, saveUrl ? /* @__PURE__ */ React.createElement("button", { type: "button", onClick: toggleSave, className: "rounded-full border border-sky-300/25 bg-sky-300/12 px-5 py-3 text-sm font-semibold text-sky-100" }, saved ? "Saved" : "Save prompt") : null, submitUrl ? /* @__PURE__ */ React.createElement(xe, { href: submitUrl, className: "rounded-full border border-white/10 bg-white/[0.06] px-5 py-3 text-sm font-semibold text-white transition hover:border-sky-300/25 hover:bg-sky-300/12 hover:text-sky-100" }, "Submit artwork") : null), /* @__PURE__ */ React.createElement("div", { className: "mt-8 grid gap-3 sm:grid-cols-2 xl:grid-cols-4" }, /* @__PURE__ */ React.createElement(StatPill$2, { label: "Category", value: lessonCategory }), /* @__PURE__ */ React.createElement(StatPill$2, { label: "Reading", value: lessonMinutes }), /* @__PURE__ */ React.createElement(StatPill$2, { label: "Updated", value: lessonUpdated }), /* @__PURE__ */ React.createElement(StatPill$2, { label: "Access", value: item.access_level || "free" })))), /* @__PURE__ */ React.createElement("aside", { className: "border-t border-white/10 bg-white/[0.03] p-6 lg:border-l lg:border-t-0 lg:p-8" }, /* @__PURE__ */ React.createElement("div", { className: "space-y-5 lg:sticky lg:top-6" }, /* @__PURE__ */ React.createElement("div", { className: "overflow-hidden rounded-[28px] border border-white/10 bg-black/20" }, lessonCover ? /* @__PURE__ */ React.createElement("img", { src: lessonCover, alt: item.title, className: "h-52 w-full object-cover" }) : /* @__PURE__ */ React.createElement("div", { className: "flex h-52 items-center justify-center bg-[linear-gradient(135deg,_rgba(14,165,233,0.18),_rgba(17,24,39,0.94))] text-sm font-semibold uppercase tracking-[0.24em] text-slate-300" }, "Lesson cover")), /* @__PURE__ */ React.createElement("div", { className: "space-y-3" }, /* @__PURE__ */ React.createElement(LessonInfoRow, { label: "Series", value: lessonCategory }), /* @__PURE__ */ React.createElement(LessonInfoRow, { label: "Difficulty", value: lessonDifficulty }), /* @__PURE__ */ React.createElement(LessonInfoRow, { label: "Reading time", value: lessonMinutes }), /* @__PURE__ */ React.createElement(LessonInfoRow, { label: "Published", value: lessonUpdated })), /* @__PURE__ */ React.createElement("div", { className: "rounded-[28px] border border-white/10 bg-black/20 p-5" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.24em] text-slate-400" }, "Lesson status"), /* @__PURE__ */ React.createElement("p", { className: "mt-3 text-sm leading-7 text-slate-300" }, item.locked ? "This lesson is partially locked for your account level." : "Full lesson content is available below.")))))), /* @__PURE__ */ React.createElement("div", { className: "grid gap-8 lg:grid-cols-[minmax(0,1fr)_360px]" }, /* @__PURE__ */ React.createElement("article", { className: "rounded-[32px] border border-white/10 bg-white/[0.04] p-6 text-slate-200 md:p-8" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center justify-between gap-4 border-b border-white/10 pb-5" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.24em] text-sky-200/80" }, "Article"), /* @__PURE__ */ React.createElement("h2", { className: "mt-2 text-2xl font-semibold tracking-[-0.04em] text-white" }, "Lesson content")), /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center gap-2" }, /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.05] px-3 py-1 text-xs font-semibold uppercase tracking-[0.2em] text-slate-300" }, lessonMinutes), /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-1 rounded-full border border-white/10 bg-black/20 p-1" }, /* @__PURE__ */ React.createElement( + "button", + { + type: "button", + onClick: decreaseFontSize, + disabled: lessonFontScale <= fontScaleMin, + "aria-label": "Decrease article text size", + className: "inline-flex h-8 w-8 items-center justify-center rounded-full border border-white/10 bg-white/[0.04] text-sm font-semibold text-slate-200 transition hover:border-sky-300/30 hover:bg-sky-300/12 hover:text-sky-100 disabled:cursor-not-allowed disabled:opacity-40" + }, + "-" + ), /* @__PURE__ */ React.createElement("span", { className: "min-w-12 px-1 text-center text-[11px] font-semibold uppercase tracking-[0.22em] text-slate-400" }, Math.round(lessonFontScale * 100), "%"), /* @__PURE__ */ React.createElement( + "button", + { + type: "button", + onClick: increaseFontSize, + disabled: lessonFontScale >= fontScaleMax, + "aria-label": "Increase article text size", + className: "inline-flex h-8 w-8 items-center justify-center rounded-full border border-white/10 bg-white/[0.04] text-sm font-semibold text-slate-200 transition hover:border-sky-300/30 hover:bg-sky-300/12 hover:text-sky-100 disabled:cursor-not-allowed disabled:opacity-40" + }, + "+" + )))), /* @__PURE__ */ React.createElement("div", { className: "mt-6" }, item.content ? /* @__PURE__ */ React.createElement("div", { className: "space-y-8" }, /* @__PURE__ */ React.createElement( + "div", + { + ref: articleContentRef, + className: "story-prose academy-lesson-prose prose prose-invert max-w-none", + style: { "--academy-lesson-font-scale": lessonFontScale }, + dangerouslySetInnerHTML: { __html: item.content } + } + ), lessonBlocks.map((block) => /* @__PURE__ */ React.createElement(AiComparisonSection, { key: block.id || `${block.type}-${block.sort_order || 0}`, block }))) : /* @__PURE__ */ React.createElement("div", { className: "space-y-8" }, /* @__PURE__ */ React.createElement("div", { className: "whitespace-pre-wrap text-sm leading-8 text-slate-200" }, item.content_preview), lessonBlocks.map((block) => /* @__PURE__ */ React.createElement(AiComparisonSection, { key: block.id || `${block.type}-${block.sort_order || 0}`, block }))))), /* @__PURE__ */ React.createElement("aside", { className: "space-y-6 lg:sticky lg:top-6 lg:self-start" }, tableOfContents.length ? /* @__PURE__ */ React.createElement("section", { className: "rounded-[32px] border border-white/10 bg-white/[0.04] p-6 text-slate-200" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.24em] text-slate-400" }, "On this page"), /* @__PURE__ */ React.createElement("h3", { className: "mt-2 text-2xl font-semibold tracking-[-0.04em] text-white" }, "Table of contents"), /* @__PURE__ */ React.createElement("nav", { "aria-label": "Lesson table of contents", className: "mt-5 space-y-1.5" }, tableOfContents.map((entry) => /* @__PURE__ */ React.createElement( + "a", + { + key: entry.id, + href: `#${entry.id}`, + "aria-current": activeHeadingId === entry.id ? "location" : void 0, + className: `academy-lesson-toc-link ${entry.level === "h3" ? "academy-lesson-toc-link-subtle" : ""} ${activeHeadingId === entry.id ? "academy-lesson-toc-link-active" : ""}` + }, + /* @__PURE__ */ React.createElement("span", { className: "academy-lesson-toc-link-indicator", "aria-hidden": "true" }), + /* @__PURE__ */ React.createElement("span", null, entry.title) + )))) : null, /* @__PURE__ */ React.createElement("section", { className: "rounded-[32px] border border-white/10 bg-white/[0.04] p-6 text-slate-200" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.24em] text-slate-400" }, "Series info"), /* @__PURE__ */ React.createElement("h3", { className: "mt-2 text-2xl font-semibold tracking-[-0.04em] text-white" }, lessonCategory), /* @__PURE__ */ React.createElement("div", { className: "mt-5 space-y-3" }, /* @__PURE__ */ React.createElement(LessonInfoRow, { label: "Category", value: lessonCategory }), /* @__PURE__ */ React.createElement(LessonInfoRow, { label: "Difficulty", value: lessonDifficulty }), /* @__PURE__ */ React.createElement(LessonInfoRow, { label: "Reading", value: lessonMinutes }), /* @__PURE__ */ React.createElement(LessonInfoRow, { label: "Updated", value: lessonUpdated }))), relatedLessonList.length ? /* @__PURE__ */ React.createElement("section", { className: "rounded-[32px] border border-white/10 bg-white/[0.04] p-6 text-slate-200" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.24em] text-slate-400" }, "Continue learning"), /* @__PURE__ */ React.createElement("h3", { className: "mt-2 text-2xl font-semibold tracking-[-0.04em] text-white" }, "More in ", lessonCategory), /* @__PURE__ */ React.createElement("div", { className: "mt-5 space-y-3" }, relatedLessonList.map((relatedLesson, index2) => /* @__PURE__ */ React.createElement( + xe, + { + key: relatedLesson.id, + href: `/academy/lessons/${relatedLesson.slug}`, + className: "group flex gap-4 rounded-[22px] border border-white/10 bg-black/20 p-4 transition hover:border-sky-300/25 hover:bg-white/[0.06]" + }, + /* @__PURE__ */ React.createElement("div", { className: "flex h-12 w-12 shrink-0 items-center justify-center rounded-2xl border border-sky-300/15 bg-sky-300/10 text-sm font-semibold text-sky-100" }, String(index2 + 1).padStart(2, "0")), + /* @__PURE__ */ React.createElement("div", { className: "min-w-0 flex-1" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-start justify-between gap-3" }, /* @__PURE__ */ React.createElement("h4", { className: "text-sm font-semibold text-white transition group-hover:text-sky-100" }, relatedLesson.title), /* @__PURE__ */ React.createElement("span", { className: "shrink-0 rounded-full border border-white/10 bg-white/[0.04] px-2.5 py-1 text-[10px] font-semibold uppercase tracking-[0.18em] text-slate-400" }, formatLessonMinutes(relatedLesson.reading_minutes))), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-xs leading-6 text-slate-400" }, relatedLesson.excerpt || relatedLesson.content_preview || "Continue the series with the next lesson.")) + )))) : null))) : /* @__PURE__ */ React.createElement("section", { className: "rounded-[30px] border border-white/10 bg-white/[0.04] p-6 text-slate-200" }, pageType === "prompt" ? /* @__PURE__ */ React.createElement("div", { className: "space-y-6" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.22em] text-slate-400" }, "Prompt"), /* @__PURE__ */ React.createElement("pre", { className: "mt-3 whitespace-pre-wrap rounded-2xl border border-white/10 bg-black/20 p-4 text-sm leading-7 text-slate-200" }, item.prompt || item.prompt_preview)), item.negative_prompt ? /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.22em] text-slate-400" }, "Negative prompt"), /* @__PURE__ */ React.createElement("pre", { className: "mt-3 whitespace-pre-wrap rounded-2xl border border-white/10 bg-black/20 p-4 text-sm leading-7 text-slate-200" }, item.negative_prompt)) : null) : null, pageType === "pack" ? /* @__PURE__ */ React.createElement("div", { className: "space-y-5" }, /* @__PURE__ */ React.createElement("p", { className: "text-sm leading-8 text-slate-200" }, item.description), /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 md:grid-cols-2" }, (item.prompts || []).map((prompt) => /* @__PURE__ */ React.createElement("div", { key: prompt.id, className: "rounded-2xl border border-white/10 bg-black/20 p-4" }, /* @__PURE__ */ React.createElement("h3", { className: "text-lg font-semibold text-white" }, prompt.title), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm leading-7 text-slate-300" }, prompt.excerpt || prompt.prompt_preview))))) : null, pageType === "challenge" ? /* @__PURE__ */ React.createElement("div", { className: "space-y-6" }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-6 md:grid-cols-2" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.22em] text-slate-400" }, "Brief"), /* @__PURE__ */ React.createElement("div", { className: "mt-3 whitespace-pre-wrap text-sm leading-8 text-slate-200" }, item.brief || item.description)), /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.22em] text-slate-400" }, "Rules"), /* @__PURE__ */ React.createElement("div", { className: "mt-3 whitespace-pre-wrap text-sm leading-8 text-slate-200" }, item.rules || "No special rules posted yet."))), (item.submissions || []).length ? /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.22em] text-slate-400" }, "Approved submissions"), /* @__PURE__ */ React.createElement("div", { className: "mt-4 grid gap-4 md:grid-cols-2" }, item.submissions.map((submission) => /* @__PURE__ */ React.createElement("div", { key: submission.id, className: "rounded-2xl border border-white/10 bg-black/20 p-4" }, /* @__PURE__ */ React.createElement("h3", { className: "text-lg font-semibold text-white" }, submission.artwork?.title || "Submission"), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm text-slate-400" }, submission.user?.name || "Unknown creator"))))) : null) : null))); } const __vite_glob_0_4 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ __proto__: null, @@ -12866,7 +13132,8 @@ const buildAdminNavGroups = (isAdmin) => [ label: "Overview", items: [ { label: "Dashboard", href: "/moderation", icon: "fa-solid fa-gauge-high", exact: true }, - { label: "Daily Activity", href: "/moderation/activity", icon: "fa-solid fa-calendar-day" } + { label: "Daily Activity", href: "/moderation/activity", icon: "fa-solid fa-calendar-day" }, + { label: "Online Users", href: "/moderation/traffic/online", icon: "fa-solid fa-user-check" } ] }, { @@ -12882,10 +13149,6 @@ const buildAdminNavGroups = (isAdmin) => [ items: [ { label: "Stories", href: "/moderation/stories", icon: "fa-solid fa-feather-pointed" }, { label: "Artworks", href: "/moderation/artworks", icon: "fa-solid fa-images" }, - { label: "Academy Dashboard", href: "/moderation/academy/dashboard", icon: "fa-solid fa-graduation-cap" }, - { label: "Academy Lessons", href: "/moderation/academy/lessons", icon: "fa-solid fa-book-open" }, - { label: "Academy Prompts", href: "/moderation/academy/prompts", icon: "fa-solid fa-wand-magic-sparkles" }, - { label: "Academy Challenges", href: "/moderation/academy/challenges", icon: "fa-solid fa-trophy" }, { label: "Featured Artworks", href: "/moderation/artworks/featured", icon: "fa-solid fa-star" }, { label: "Homepage Announcements", href: "/moderation/homepage/announcements", icon: "fa-solid fa-bullhorn" }, { label: "Upload Queue", href: "/moderation/uploads", icon: "fa-solid fa-cloud-arrow-up" }, @@ -12893,6 +13156,15 @@ const buildAdminNavGroups = (isAdmin) => [ { label: "AI Biography", href: "/moderation/ai-biography", icon: "fa-solid fa-wand-magic-sparkles" } ] }, + { + label: "Academy", + items: [ + { label: "Academy Dashboard", href: "/moderation/academy/dashboard", icon: "fa-solid fa-graduation-cap" }, + { label: "Academy Lessons", href: "/moderation/academy/lessons", icon: "fa-solid fa-book-open" }, + { label: "Academy Prompts", href: "/moderation/academy/prompts", icon: "fa-solid fa-wand-magic-sparkles" }, + { label: "Academy Challenges", href: "/moderation/academy/challenges", icon: "fa-solid fa-trophy" } + ] + }, { label: "System", items: [ @@ -12903,6 +13175,9 @@ const buildAdminNavGroups = (isAdmin) => [ ]; function NavLink$2({ item, active }) { const cls = `flex items-center gap-3 px-4 py-2.5 rounded-xl text-sm font-medium transition-all duration-200 ${active ? "bg-rose-500/20 text-rose-300 shadow-sm shadow-rose-500/10" : "text-slate-400 hover:text-white hover:bg-white/5"}`; + if (item.href === "/moderation/traffic/online") { + return /* @__PURE__ */ React.createElement("a", { href: item.href, className: cls }, /* @__PURE__ */ React.createElement("i", { className: `${item.icon} w-5 text-center text-base` }), /* @__PURE__ */ React.createElement("span", null, item.label)); + } return /* @__PURE__ */ React.createElement(xe, { href: item.href, className: cls }, /* @__PURE__ */ React.createElement("i", { className: `${item.icon} w-5 text-center text-base` }), /* @__PURE__ */ React.createElement("span", null, item.label)); } function Sidebar({ pathname, isAdmin }) { @@ -12911,7 +13186,7 @@ function Sidebar({ pathname, isAdmin }) { if (item.exact) return pathname === item.href; return pathname.startsWith(item.href.split("?")[0]); }; - return /* @__PURE__ */ React.createElement("aside", { className: "flex h-full w-64 flex-col overflow-y-auto border-r border-white/[0.07] bg-[rgba(10,14,22,0.98)] px-3 py-6" }, /* @__PURE__ */ React.createElement("div", { className: "mb-8 px-3" }, /* @__PURE__ */ React.createElement(xe, { href: "/moderation", className: "flex items-center gap-2.5" }, /* @__PURE__ */ React.createElement("span", { className: "flex h-8 w-8 items-center justify-center rounded-lg bg-rose-500/20" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-shield-halved text-sm text-rose-400" })), /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.22em] text-rose-400/80" }, "Skinbase"), /* @__PURE__ */ React.createElement("p", { className: "text-sm font-bold text-white" }, "Admin Panel")))), /* @__PURE__ */ React.createElement("nav", { className: "flex-1 space-y-6" }, adminNavGroups.map((group) => /* @__PURE__ */ React.createElement("div", { key: group.label }, /* @__PURE__ */ React.createElement("p", { className: "mb-1.5 px-4 text-[10px] font-bold uppercase tracking-[0.2em] text-slate-600" }, group.label), /* @__PURE__ */ React.createElement("div", { className: "space-y-0.5" }, group.items.map((item) => /* @__PURE__ */ React.createElement(NavLink$2, { key: item.href, item, active: isActive(item) })))))), /* @__PURE__ */ React.createElement("div", { className: "mt-6 space-y-0.5 border-t border-white/[0.06] pt-4" }, /* @__PURE__ */ React.createElement( + return /* @__PURE__ */ React.createElement("aside", { className: "nova-scrollbar flex h-full w-64 flex-col overflow-y-auto border-r border-white/[0.07] bg-[rgba(10,14,22,0.98)] px-3 py-6" }, /* @__PURE__ */ React.createElement("div", { className: "mb-8 px-3" }, /* @__PURE__ */ React.createElement(xe, { href: "/moderation", className: "flex items-center gap-2.5" }, /* @__PURE__ */ React.createElement("span", { className: "flex h-8 w-8 items-center justify-center rounded-lg bg-rose-500/20" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-shield-halved text-sm text-rose-400" })), /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.22em] text-rose-400/80" }, "Skinbase"), /* @__PURE__ */ React.createElement("p", { className: "text-sm font-bold text-white" }, "Admin Panel")))), /* @__PURE__ */ React.createElement("nav", { className: "flex-1 space-y-6" }, adminNavGroups.map((group) => /* @__PURE__ */ React.createElement("div", { key: group.label }, /* @__PURE__ */ React.createElement("p", { className: "mb-1.5 px-4 text-[10px] font-bold uppercase tracking-[0.2em] text-slate-600" }, group.label), /* @__PURE__ */ React.createElement("div", { className: "space-y-0.5" }, group.items.map((item) => /* @__PURE__ */ React.createElement(NavLink$2, { key: item.href, item, active: isActive(item) })))))), /* @__PURE__ */ React.createElement("div", { className: "mt-6 space-y-0.5 border-t border-white/[0.06] pt-4" }, /* @__PURE__ */ React.createElement( xe, { href: "/studio", @@ -12936,676 +13211,6 @@ function AdminLayout({ children, title, subtitle }) { /* @__PURE__ */ React.createElement("i", { className: mobileOpen ? "fa-solid fa-xmark" : "fa-solid fa-bars" }) )), mobileOpen && /* @__PURE__ */ React.createElement("div", { className: "fixed inset-0 z-30 lg:hidden" }, /* @__PURE__ */ React.createElement("div", { className: "absolute inset-0 bg-black/60 backdrop-blur-sm", onClick: () => setMobileOpen(false) }), /* @__PURE__ */ React.createElement("div", { className: "absolute left-0 top-0 h-full w-72 pt-14" }, /* @__PURE__ */ React.createElement(Sidebar, { pathname, isAdmin: currentUserIsAdmin }))), /* @__PURE__ */ React.createElement("div", { className: "flex flex-1 flex-col lg:pl-8" }, /* @__PURE__ */ React.createElement("main", { className: "flex-1 px-6 py-8 pt-20 lg:pt-8" }, (title || subtitle) && /* @__PURE__ */ React.createElement("div", { className: "mb-8" }, title && /* @__PURE__ */ React.createElement("h1", { className: "text-2xl font-bold text-white" }, title), subtitle && /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-sm text-slate-400" }, subtitle)), children))); } -function normalizePayload(fields, data) { - const payload = { ...data }; - fields.forEach((field) => { - if (field.type === "csv") { - payload[field.name] = String(payload[field.name] || "").split(",").map((item) => item.trim()).filter(Boolean); - } - if (field.type === "json") { - try { - payload[field.name] = payload[field.name] ? JSON.parse(payload[field.name]) : {}; - } catch { - payload[field.name] = {}; - } - } - }); - return payload; -} -function Field$4({ field, form }) { - const value = form.data[field.name]; - if (field.type === "checkbox") { - return /* @__PURE__ */ React.createElement("label", { className: "flex items-center gap-3 rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-sm text-slate-200" }, /* @__PURE__ */ React.createElement("input", { type: "checkbox", checked: Boolean(value), onChange: (event) => form.setData(field.name, event.target.checked) }), field.label); - } - if (field.type === "textarea") { - return /* @__PURE__ */ React.createElement("textarea", { value: value || "", onChange: (event) => form.setData(field.name, event.target.value), rows: 6, className: "mt-2 w-full rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-sm text-white outline-none" }); - } - if (field.type === "select") { - return /* @__PURE__ */ React.createElement( - NovaSelect, - { - value: value ?? "", - onChange: (nextValue) => form.setData(field.name, nextValue ?? ""), - options: field.options || [], - searchable: false, - className: "mt-2 rounded-2xl bg-black/20" - } - ); - } - if (field.type === "multiselect") { - return /* @__PURE__ */ React.createElement( - NovaSelect, - { - multi: true, - value: value || [], - onChange: (nextValue) => form.setData(field.name, Array.isArray(nextValue) ? nextValue : []), - options: field.options || [], - className: "mt-2 rounded-2xl bg-black/20" - } - ); - } - return /* @__PURE__ */ React.createElement("input", { type: field.type || "text", value: value ?? "", onChange: (event) => form.setData(field.name, event.target.value), className: "mt-2 w-full rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-sm text-white outline-none" }); -} -function AcademyCrudForm({ title, subtitle, fields, record, submitUrl, indexUrl, destroyUrl, method }) { - const form = G(record); - const submit = (event) => { - event.preventDefault(); - const payload = normalizePayload(fields, form.data); - if (method === "patch") { - form.transform(() => payload).patch(submitUrl); - return; - } - form.transform(() => payload).post(submitUrl); - }; - return /* @__PURE__ */ React.createElement(AdminLayout, { title, subtitle }, /* @__PURE__ */ React.createElement(Se, { title: `Admin · ${title}` }), /* @__PURE__ */ React.createElement("form", { onSubmit: submit, className: "space-y-5 rounded-[30px] border border-white/[0.08] bg-white/[0.03] p-6" }, fields.map((field) => /* @__PURE__ */ React.createElement("div", { key: field.name }, field.type !== "checkbox" ? /* @__PURE__ */ React.createElement("label", { className: "text-sm font-semibold text-white" }, field.label) : null, /* @__PURE__ */ React.createElement(Field$4, { field, form }), form.errors[field.name] ? /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm text-rose-300" }, form.errors[field.name]) : null)), /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-3" }, /* @__PURE__ */ React.createElement("button", { type: "submit", disabled: form.processing, className: "rounded-full border border-sky-300/25 bg-sky-300/12 px-5 py-3 text-sm font-semibold text-sky-100" }, form.processing ? "Saving..." : "Save"), /* @__PURE__ */ React.createElement(xe, { href: indexUrl, className: "rounded-full border border-white/10 bg-white/[0.04] px-5 py-3 text-sm font-semibold text-white" }, "Back"), destroyUrl ? /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => { - if (!window.confirm("Delete this record?")) return; - At.delete(destroyUrl); - }, className: "rounded-full border border-rose-300/20 bg-rose-300/10 px-5 py-3 text-sm font-semibold text-rose-100" }, "Delete") : null))); -} -const __vite_glob_0_5 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ - __proto__: null, - default: AcademyCrudForm -}, Symbol.toStringTag, { value: "Module" })); -function AcademyCrudIndex({ title, subtitle, items, columns, createUrl }) { - const flash = X().props.flash || {}; - return /* @__PURE__ */ React.createElement(AdminLayout, { title, subtitle }, /* @__PURE__ */ React.createElement(Se, { title: `Admin · ${title}` }), flash.success ? /* @__PURE__ */ React.createElement("div", { className: "mb-6 rounded-2xl border border-emerald-300/20 bg-emerald-300/10 px-4 py-3 text-sm text-emerald-100" }, flash.success) : null, /* @__PURE__ */ React.createElement("div", { className: "mb-6 flex items-center justify-between gap-4" }, /* @__PURE__ */ React.createElement("p", { className: "text-sm text-slate-400" }, "Manage Academy content below. Changes clear Academy cache automatically."), /* @__PURE__ */ React.createElement(xe, { href: createUrl, className: "rounded-full border border-sky-300/25 bg-sky-300/12 px-5 py-3 text-sm font-semibold text-sky-100" }, "Create record")), (items?.data || []).length === 0 ? /* @__PURE__ */ React.createElement("div", { className: "rounded-[28px] border border-white/[0.08] bg-white/[0.03] px-6 py-12 text-center text-slate-400" }, "No records exist yet.") : /* @__PURE__ */ React.createElement("div", { className: "space-y-4" }, items.data.map((item) => /* @__PURE__ */ React.createElement("div", { key: item.id, className: "rounded-[28px] border border-white/[0.08] bg-white/[0.03] p-5" }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 lg:grid-cols-[minmax(0,1fr)_auto] lg:items-center" }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-2 sm:grid-cols-2 xl:grid-cols-5" }, columns.map((column) => /* @__PURE__ */ React.createElement("div", { key: column }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.2em] text-slate-500" }, column.replaceAll("_", " ")), /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-sm text-white" }, String(item[column] ?? ""))))), /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-3 lg:justify-end" }, /* @__PURE__ */ React.createElement(xe, { href: item.edit_url, className: "rounded-full border border-white/10 bg-white/[0.04] px-4 py-2 text-sm font-semibold text-white" }, "Edit"), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => { - if (!window.confirm("Delete this record?")) return; - At.delete(item.destroy_url, { preserveScroll: true }); - }, className: "rounded-full border border-rose-300/20 bg-rose-300/10 px-4 py-2 text-sm font-semibold text-rose-100" }, "Delete"))))))); -} -const __vite_glob_0_6 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ - __proto__: null, - default: AcademyCrudIndex -}, Symbol.toStringTag, { value: "Module" })); -function StatCard$c({ label, value }) { - return /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/[0.08] bg-white/[0.04] p-5" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.2em] text-slate-500" }, label), /* @__PURE__ */ React.createElement("p", { className: "mt-3 text-3xl font-bold text-white" }, value.toLocaleString())); -} -function AcademyDashboard({ stats, links }) { - return /* @__PURE__ */ React.createElement(AdminLayout, { title: "Academy Dashboard", subtitle: "Overview of Academy content, challenge activity, and future billing placeholders." }, /* @__PURE__ */ React.createElement(Se, { title: "Admin · Academy Dashboard" }), /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 sm:grid-cols-2 xl:grid-cols-4" }, /* @__PURE__ */ React.createElement(StatCard$c, { label: "Lessons", value: stats.lessons }), /* @__PURE__ */ React.createElement(StatCard$c, { label: "Prompts", value: stats.prompts }), /* @__PURE__ */ React.createElement(StatCard$c, { label: "Prompt Packs", value: stats.packs }), /* @__PURE__ */ React.createElement(StatCard$c, { label: "Challenges", value: stats.challenges }), /* @__PURE__ */ React.createElement(StatCard$c, { label: "Submissions", value: stats.submissions }), /* @__PURE__ */ React.createElement(StatCard$c, { label: "Badges", value: stats.badges }), /* @__PURE__ */ React.createElement(StatCard$c, { label: "Creator Subscribers", value: stats.creator_subscribers }), /* @__PURE__ */ React.createElement(StatCard$c, { label: "Pro Subscribers", value: stats.pro_subscribers })), /* @__PURE__ */ React.createElement("div", { className: "mt-8 rounded-[28px] border border-white/[0.08] bg-white/[0.03] p-6" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.2em] text-slate-500" }, "Modules"), /* @__PURE__ */ React.createElement("div", { className: "mt-4 grid gap-3 md:grid-cols-2 xl:grid-cols-3" }, Object.entries(links).map(([key, href]) => /* @__PURE__ */ React.createElement(xe, { key, href, className: "rounded-2xl border border-white/[0.08] bg-black/20 px-4 py-4 text-sm font-semibold text-white transition hover:border-white/15 hover:bg-white/[0.05]" }, key.replaceAll("_", " ")))))); -} -const __vite_glob_0_7 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ - __proto__: null, - default: AcademyDashboard -}, Symbol.toStringTag, { value: "Module" })); -function AcademySubmissions({ submissions }) { - const flash = X().props.flash || {}; - return /* @__PURE__ */ React.createElement(AdminLayout, { title: "Academy Challenge Submissions", subtitle: "Approve or reject Academy challenge entries." }, /* @__PURE__ */ React.createElement(Se, { title: "Admin · Academy Challenge Submissions" }), flash.success ? /* @__PURE__ */ React.createElement("div", { className: "mb-6 rounded-2xl border border-emerald-300/20 bg-emerald-300/10 px-4 py-3 text-sm text-emerald-100" }, flash.success) : null, /* @__PURE__ */ React.createElement("div", { className: "space-y-4" }, (submissions?.data || []).map((submission) => /* @__PURE__ */ React.createElement("article", { key: submission.id, className: "rounded-[28px] border border-white/[0.08] bg-white/[0.03] p-5" }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-5 lg:grid-cols-[minmax(0,1fr)_auto] lg:items-start" }, /* @__PURE__ */ React.createElement("div", { className: "space-y-3" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center gap-3" }, /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.2em] text-white/80" }, submission.moderation_status), /* @__PURE__ */ React.createElement("span", { className: "text-sm text-slate-400" }, submission.challenge?.title || "Challenge")), /* @__PURE__ */ React.createElement("h2", { className: "text-xl font-semibold text-white" }, submission.artwork?.title || "Artwork removed"), /* @__PURE__ */ React.createElement("p", { className: "text-sm text-slate-400" }, submission.user?.name || "Unknown user", " · ", submission.ai_tool_used || "No tool noted"), submission.prompt_used ? /* @__PURE__ */ React.createElement("pre", { className: "whitespace-pre-wrap rounded-2xl border border-white/10 bg-black/20 p-4 text-sm leading-7 text-slate-200" }, submission.prompt_used) : null, submission.workflow_notes ? /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-black/20 p-4 text-sm leading-7 text-slate-300" }, submission.workflow_notes) : null), /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-3 lg:justify-end" }, /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => At.post(submission.approve_url, {}, { preserveScroll: true }), className: "rounded-full border border-emerald-300/20 bg-emerald-300/10 px-4 py-2 text-sm font-semibold text-emerald-100" }, "Approve"), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => At.post(submission.reject_url, {}, { preserveScroll: true }), className: "rounded-full border border-rose-300/20 bg-rose-300/10 px-4 py-2 text-sm font-semibold text-rose-100" }, "Reject"))))))); -} -const __vite_glob_0_8 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ - __proto__: null, - default: AcademySubmissions -}, Symbol.toStringTag, { value: "Module" })); -function getCsrfToken$f() { - if (typeof document === "undefined") return ""; - return document.querySelector('meta[name="csrf-token"]')?.getAttribute("content") || ""; -} -async function requestJson$o(url, { method = "POST", body: body2 } = {}) { - const response = await fetch(url, { - method, - credentials: "same-origin", - headers: { - Accept: "application/json", - "Content-Type": "application/json", - "X-CSRF-TOKEN": getCsrfToken$f(), - "X-Requested-With": "XMLHttpRequest" - }, - body: body2 ? JSON.stringify(body2) : void 0 - }); - const payload = await response.json().catch(() => ({})); - if (!response.ok) { - throw new Error(payload?.message || "Request failed."); - } - return payload; -} -function formatDateTime$5(value) { - if (!value) return "—"; - const date = new Date(value); - if (Number.isNaN(date.getTime())) return "—"; - return new Intl.DateTimeFormat("en", { - dateStyle: "medium", - timeStyle: "short" - }).format(date); -} -function Badge$3({ children, tone = "slate" }) { - const tones2 = { - slate: "border-white/10 bg-white/[0.06] text-slate-200", - sky: "border-sky-300/20 bg-sky-400/12 text-sky-100", - emerald: "border-emerald-300/20 bg-emerald-400/12 text-emerald-100", - amber: "border-amber-300/20 bg-amber-400/12 text-amber-100", - rose: "border-rose-300/20 bg-rose-400/12 text-rose-100" - }; - return /* @__PURE__ */ React.createElement("span", { className: `inline-flex items-center rounded-full border px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.16em] ${tones2[tone] || tones2.slate}` }, children); -} -function StatCard$b({ label, value, tone = "sky" }) { - const tones2 = { - sky: "border-sky-300/15 bg-sky-400/10 text-sky-100", - amber: "border-amber-300/15 bg-amber-400/10 text-amber-100", - emerald: "border-emerald-300/15 bg-emerald-400/10 text-emerald-100", - rose: "border-rose-300/15 bg-rose-400/10 text-rose-100", - slate: "border-white/10 bg-white/10 text-slate-100" - }; - return /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-white/[0.04] p-5 backdrop-blur-sm" }, /* @__PURE__ */ React.createElement("div", { className: `inline-flex rounded-full border px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.18em] ${tones2[tone] || tones2.sky}` }, label), /* @__PURE__ */ React.createElement("div", { className: "mt-4 text-3xl font-semibold tracking-[-0.04em] text-white" }, Number(value || 0).toLocaleString())); -} -function selectTone(record) { - if (record.last_error_code || record.status === "failed") return "rose"; - if (record.needs_review) return "amber"; - if (record.is_user_edited) return "sky"; - if (record.status === "approved") return "emerald"; - return "slate"; -} -function labelForStatus(value) { - if (!value) return "Unknown"; - return String(value).replaceAll("_", " "); -} -function AiBiographyAdmin() { - const { props } = X(); - const records = props.records || { data: [] }; - const stats = props.stats || {}; - const endpoints = props.endpoints || {}; - const filterOptions = props.filterOptions || {}; - const [filters, setFilters] = React.useState(props.filters || {}); - const [busyKey, setBusyKey] = React.useState(""); - const [notice, setNotice] = React.useState(""); - const [error, setError] = React.useState(""); - React.useEffect(() => { - setFilters(props.filters || {}); - }, [props.filters]); - function updateFilter(key, value) { - setFilters((current) => ({ ...current, [key]: value })); - } - function applyFilters(event) { - event.preventDefault(); - setError(""); - setNotice(""); - At.get(endpoints.index, filters, { - preserveState: true, - replace: true, - preserveScroll: true - }); - } - function resetFilters() { - setError(""); - setNotice(""); - At.get(endpoints.index, { - q: "", - status: "all", - scope: "all", - tier: "all", - visibility: "all", - review: "all" - }, { - preserveState: true, - replace: true, - preserveScroll: true - }); - } - async function performAction(actionKey, url) { - setBusyKey(actionKey); - setError(""); - try { - const payload = await requestJson$o(url); - setNotice(payload.message || "Action completed."); - At.reload({ - only: ["records", "stats", "filters"], - preserveScroll: true - }); - } catch (requestError) { - setError(requestError.message || "Action failed."); - } finally { - setBusyKey(""); - } - } - return /* @__PURE__ */ React.createElement("div", { className: "w-full pb-16 pt-8" }, /* @__PURE__ */ React.createElement(Se, { title: "AI Biography Review" }), /* @__PURE__ */ React.createElement("section", { className: "rounded-[32px] border border-white/10 bg-[radial-gradient(circle_at_top_left,rgba(125,211,252,0.2),transparent_32%),linear-gradient(180deg,rgba(15,23,42,0.96),rgba(2,6,23,0.9))] p-6 shadow-[0_24px_70px_rgba(2,6,23,0.32)]" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-col gap-4 lg:flex-row lg:items-end lg:justify-between" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.28em] text-sky-200/80" }, "Moderator surface"), /* @__PURE__ */ React.createElement("h1", { className: "mt-3 text-3xl font-semibold tracking-[-0.04em] text-white" }, "AI biography review"), /* @__PURE__ */ React.createElement("p", { className: "mt-2 max-w-3xl text-sm leading-relaxed text-slate-300" }, "Browse active biographies and historical generations, inspect review flags and failures, and rebuild a creator biography directly from cPad.")), /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-3 text-xs uppercase tracking-[0.16em] text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.05] px-4 py-2" }, "Page ", records.current_page || 1, " / ", records.last_page || 1), /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.05] px-4 py-2" }, Number(records.total || 0).toLocaleString(), " records"))), /* @__PURE__ */ React.createElement("div", { className: "mt-6 grid gap-4 md:grid-cols-2 xl:grid-cols-3" }, /* @__PURE__ */ React.createElement(StatCard$b, { label: "Total records", value: stats.total_records, tone: "sky" }), /* @__PURE__ */ React.createElement(StatCard$b, { label: "Active", value: stats.active_records, tone: "emerald" }), /* @__PURE__ */ React.createElement(StatCard$b, { label: "Needs review", value: stats.needs_review, tone: "amber" }), /* @__PURE__ */ React.createElement(StatCard$b, { label: "Hidden active", value: stats.hidden_active, tone: "slate" }), /* @__PURE__ */ React.createElement(StatCard$b, { label: "Failed", value: stats.failed, tone: "rose" }), /* @__PURE__ */ React.createElement(StatCard$b, { label: "User edited", value: stats.user_edited_active, tone: "sky" })), /* @__PURE__ */ React.createElement("form", { onSubmit: applyFilters, className: "mt-6 grid gap-3 lg:grid-cols-[2fr_repeat(5,minmax(0,1fr))]" }, /* @__PURE__ */ React.createElement("label", { className: "rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-400" }, "Search creator"), /* @__PURE__ */ React.createElement( - "input", - { - value: filters.q || "", - onChange: (event) => updateFilter("q", event.target.value), - placeholder: "username, name, or email", - className: "mt-2 w-full rounded-xl border border-white/10 bg-slate-950/70 px-3 py-2 text-sm text-white outline-none" - } - )), ["status", "scope", "tier", "visibility", "review"].map((key) => /* @__PURE__ */ React.createElement("div", { key, className: "rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-400" }, key.replace("_", " ")), /* @__PURE__ */ React.createElement( - NovaSelect, - { - value: filters[key] || "all", - onChange: (value) => updateFilter(key, value), - className: "mt-2", - options: (filterOptions[key] || []).map((option) => ({ value: option.value, label: option.label })), - searchable: false - } - ))), /* @__PURE__ */ React.createElement("div", { className: "lg:col-span-full flex flex-wrap gap-3" }, /* @__PURE__ */ React.createElement("button", { type: "submit", className: "inline-flex items-center gap-2 rounded-full border border-sky-300/25 bg-sky-400/12 px-5 py-2 text-xs font-semibold uppercase tracking-[0.14em] text-sky-50 transition hover:bg-sky-400/18" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-filter text-[10px]" }), "Apply filters"), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: resetFilters, className: "inline-flex items-center gap-2 rounded-full border border-white/10 bg-white/[0.05] px-5 py-2 text-xs font-semibold uppercase tracking-[0.14em] text-white transition hover:bg-white/[0.09]" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-rotate-left text-[10px]" }), "Reset")))), notice ? /* @__PURE__ */ React.createElement("div", { className: "mt-6 rounded-2xl border border-emerald-300/20 bg-emerald-400/10 px-4 py-3 text-sm text-emerald-50" }, notice) : null, error ? /* @__PURE__ */ React.createElement("div", { className: "mt-6 rounded-2xl border border-rose-300/20 bg-rose-400/10 px-4 py-3 text-sm text-rose-100" }, error) : null, /* @__PURE__ */ React.createElement("div", { className: "mt-8 space-y-4" }, (records.data || []).length === 0 ? /* @__PURE__ */ React.createElement("div", { className: "rounded-[28px] border border-white/10 bg-white/[0.04] px-6 py-12 text-center text-slate-300" }, "No AI biography records matched the current filters.") : (records.data || []).map((record) => { - const rebuildKey = `rebuild-${record.user_id}`; - const approveKey = `approve-${record.id}`; - const flagKey = `flag-${record.id}`; - const visibilityKey = `${record.is_hidden ? "show" : "hide"}-${record.id}`; - return /* @__PURE__ */ React.createElement("article", { key: record.id, className: "rounded-[28px] border border-white/10 bg-[#08111d] p-5 shadow-[0_18px_48px_rgba(2,6,23,0.2)]" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-col gap-4 xl:flex-row xl:items-start xl:justify-between" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-2" }, /* @__PURE__ */ React.createElement(Badge$3, { tone: selectTone(record) }, labelForStatus(record.status)), /* @__PURE__ */ React.createElement(Badge$3, { tone: record.is_active ? "emerald" : "slate" }, record.is_active ? "active" : "inactive"), /* @__PURE__ */ React.createElement(Badge$3, { tone: record.is_hidden ? "amber" : "sky" }, record.is_hidden ? "hidden" : "visible"), record.needs_review ? /* @__PURE__ */ React.createElement(Badge$3, { tone: "amber" }, "needs review") : null, record.is_user_edited ? /* @__PURE__ */ React.createElement(Badge$3, { tone: "sky" }, "user edited") : null, record.is_stale ? /* @__PURE__ */ React.createElement(Badge$3, { tone: "rose" }, "stale") : null, record.input_quality_tier ? /* @__PURE__ */ React.createElement(Badge$3, { tone: "slate" }, "tier: ", record.input_quality_tier) : null), /* @__PURE__ */ React.createElement("h2", { className: "mt-3 text-2xl font-semibold tracking-[-0.03em] text-white" }, record.user?.display_name || "Unknown creator"), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm text-slate-300" }, "@", record.user?.username || "unknown", record.user?.email ? ` • ${record.user.email}` : "", record.generation_reason ? ` • reason: ${labelForStatus(record.generation_reason)}` : "")), /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-2" }, record.user?.profile_url ? /* @__PURE__ */ React.createElement("a", { href: record.user.profile_url, className: "inline-flex items-center gap-2 rounded-full border border-white/10 bg-white/[0.05] px-4 py-2 text-xs font-semibold uppercase tracking-[0.14em] text-white transition hover:bg-white/[0.09]" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-user text-[10px]" }), "Open profile") : null, record.user?.gallery_url ? /* @__PURE__ */ React.createElement("a", { href: record.user.gallery_url, className: "inline-flex items-center gap-2 rounded-full border border-white/10 bg-white/[0.05] px-4 py-2 text-xs font-semibold uppercase tracking-[0.14em] text-white transition hover:bg-white/[0.09]" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-images text-[10px]" }), "Open gallery") : null, /* @__PURE__ */ React.createElement( - "button", - { - type: "button", - disabled: busyKey === rebuildKey, - onClick: () => performAction(rebuildKey, String(endpoints.rebuildPattern || "").replace("__USER__", String(record.user_id))), - className: "inline-flex items-center gap-2 rounded-full border border-sky-300/20 bg-sky-400/12 px-4 py-2 text-xs font-semibold uppercase tracking-[0.14em] text-sky-50 transition hover:bg-sky-400/18 disabled:cursor-not-allowed disabled:opacity-60" - }, - /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-rotate text-[10px]" }), - busyKey === rebuildKey ? "Rebuilding…" : "Rebuild" - ))), /* @__PURE__ */ React.createElement("div", { className: "mt-4 grid gap-4 md:grid-cols-2 xl:grid-cols-4" }, /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-400" }, "Prompt"), /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-sm text-slate-200" }, record.prompt_version || "—")), /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-400" }, "Model"), /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-sm text-slate-200" }, record.model || "—")), /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-400" }, "Generated"), /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-sm text-slate-200" }, formatDateTime$5(record.generated_at))), /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-400" }, "Last attempted"), /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-sm text-slate-200" }, formatDateTime$5(record.last_attempted_at)))), record.last_error_code || record.last_error_reason ? /* @__PURE__ */ React.createElement("div", { className: "mt-4 rounded-2xl border border-rose-300/20 bg-rose-400/10 px-4 py-3 text-sm leading-relaxed text-rose-100" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-rose-100/80" }, "Last error"), /* @__PURE__ */ React.createElement("div", { className: "mt-2" }, record.last_error_code || "generation_failed", record.last_error_reason ? ` • ${record.last_error_reason}` : "")) : null, /* @__PURE__ */ React.createElement("div", { className: "mt-4 grid gap-4 xl:grid-cols-[minmax(0,1fr)_320px]" }, /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-black/20 p-4" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-400" }, "Biography text"), /* @__PURE__ */ React.createElement("div", { className: "mt-3 max-h-[320px] overflow-y-auto whitespace-pre-wrap rounded-2xl border border-white/10 bg-slate-950/60 px-4 py-4 text-sm leading-relaxed text-slate-100" }, record.text || "No biography text stored for this record.")), /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-black/20 p-4" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-400" }, "Review actions"), /* @__PURE__ */ React.createElement("div", { className: "mt-4 grid gap-3" }, /* @__PURE__ */ React.createElement( - "button", - { - type: "button", - disabled: busyKey === approveKey, - onClick: () => performAction(approveKey, String(endpoints.approvePattern || "").replace("__BIOGRAPHY__", String(record.id))), - className: "inline-flex items-center justify-center gap-2 rounded-2xl border border-emerald-300/20 bg-emerald-400/12 px-4 py-3 text-xs font-semibold uppercase tracking-[0.14em] text-emerald-50 transition hover:bg-emerald-400/18 disabled:cursor-not-allowed disabled:opacity-60" - }, - /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-check text-[10px]" }), - busyKey === approveKey ? "Saving…" : "Mark reviewed" - ), /* @__PURE__ */ React.createElement( - "button", - { - type: "button", - disabled: busyKey === flagKey, - onClick: () => performAction(flagKey, String(endpoints.flagPattern || "").replace("__BIOGRAPHY__", String(record.id))), - className: "inline-flex items-center justify-center gap-2 rounded-2xl border border-amber-300/20 bg-amber-400/12 px-4 py-3 text-xs font-semibold uppercase tracking-[0.14em] text-amber-50 transition hover:bg-amber-400/18 disabled:cursor-not-allowed disabled:opacity-60" - }, - /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-flag text-[10px]" }), - busyKey === flagKey ? "Saving…" : "Flag for review" - ), /* @__PURE__ */ React.createElement( - "button", - { - type: "button", - disabled: !record.is_active || busyKey === visibilityKey, - onClick: () => performAction(visibilityKey, String((record.is_hidden ? endpoints.showPattern : endpoints.hidePattern) || "").replace("__BIOGRAPHY__", String(record.id))), - className: "inline-flex items-center justify-center gap-2 rounded-2xl border border-white/10 bg-white/[0.05] px-4 py-3 text-xs font-semibold uppercase tracking-[0.14em] text-white transition hover:bg-white/[0.09] disabled:cursor-not-allowed disabled:opacity-50" - }, - /* @__PURE__ */ React.createElement("i", { className: `fa-solid ${record.is_hidden ? "fa-eye" : "fa-eye-slash"} text-[10px]` }), - busyKey === visibilityKey ? "Saving…" : record.is_hidden ? "Show publicly" : "Hide publicly" - )), /* @__PURE__ */ React.createElement("div", { className: "mt-4 space-y-2 text-xs leading-relaxed text-slate-300" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("span", { className: "font-semibold text-slate-100" }, "Approved:"), " ", formatDateTime$5(record.approved_at)), /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("span", { className: "font-semibold text-slate-100" }, "Created:"), " ", formatDateTime$5(record.created_at)), /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("span", { className: "font-semibold text-slate-100" }, "Updated:"), " ", formatDateTime$5(record.updated_at)), /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("span", { className: "font-semibold text-slate-100" }, "Source hash:"), " ", record.source_hash || "—"))))); - })), records.prev_page_url || records.next_page_url ? /* @__PURE__ */ React.createElement("div", { className: "mt-8 flex items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", null, records.prev_page_url ? /* @__PURE__ */ React.createElement(xe, { href: records.prev_page_url, preserveScroll: true, className: "inline-flex items-center gap-2 rounded-full border border-white/10 bg-white/[0.05] px-4 py-2 text-xs font-semibold uppercase tracking-[0.14em] text-white transition hover:bg-white/[0.09]" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-arrow-left text-[10px]" }), "Previous") : null), /* @__PURE__ */ React.createElement("div", { className: "text-xs uppercase tracking-[0.16em] text-slate-400" }, "Showing page ", records.current_page || 1, " of ", records.last_page || 1), /* @__PURE__ */ React.createElement("div", null, records.next_page_url ? /* @__PURE__ */ React.createElement(xe, { href: records.next_page_url, preserveScroll: true, className: "inline-flex items-center gap-2 rounded-full border border-white/10 bg-white/[0.05] px-4 py-2 text-xs font-semibold uppercase tracking-[0.14em] text-white transition hover:bg-white/[0.09]" }, "Next", /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-arrow-right text-[10px]" })) : null)) : null); -} -const __vite_glob_0_94 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ - __proto__: null, - default: AiBiographyAdmin -}, Symbol.toStringTag, { value: "Module" })); -function AdminAiBiography() { - return /* @__PURE__ */ React.createElement(AdminLayout, null, /* @__PURE__ */ React.createElement(AiBiographyAdmin, null)); -} -const __vite_glob_0_9 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ - __proto__: null, - default: AdminAiBiography -}, Symbol.toStringTag, { value: "Module" })); -function AdminArtworks({ artworks }) { - const items = artworks?.data ?? []; - return /* @__PURE__ */ React.createElement(AdminLayout, { title: "Artworks", subtitle: "Browse and manage all artworks on the platform" }, /* @__PURE__ */ React.createElement(Se, { title: "Admin · Artworks" }), /* @__PURE__ */ React.createElement("div", { className: "overflow-hidden rounded-2xl border border-white/[0.07] bg-white/[0.02]" }, /* @__PURE__ */ React.createElement("div", { className: "overflow-x-auto" }, /* @__PURE__ */ React.createElement("table", { className: "w-full text-sm" }, /* @__PURE__ */ React.createElement("thead", null, /* @__PURE__ */ React.createElement("tr", { className: "border-b border-white/[0.07] text-left text-xs font-semibold uppercase tracking-wider text-slate-600" }, /* @__PURE__ */ React.createElement("th", { className: "px-5 py-3.5" }, "Artwork"), /* @__PURE__ */ React.createElement("th", { className: "px-5 py-3.5" }, "Author"), /* @__PURE__ */ React.createElement("th", { className: "px-5 py-3.5" }, "Status"), /* @__PURE__ */ React.createElement("th", { className: "px-5 py-3.5" }, "Uploaded"), /* @__PURE__ */ React.createElement("th", { className: "px-5 py-3.5 text-right" }, "Actions"))), /* @__PURE__ */ React.createElement("tbody", { className: "divide-y divide-white/[0.04]" }, items.length === 0 && /* @__PURE__ */ React.createElement("tr", null, /* @__PURE__ */ React.createElement("td", { colSpan: 5, className: "px-5 py-12 text-center text-slate-500" }, "No artworks found.")), items.map((artwork) => /* @__PURE__ */ React.createElement("tr", { key: artwork.id, className: "transition hover:bg-white/[0.025]" }, /* @__PURE__ */ React.createElement("td", { className: "px-5 py-4" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-3" }, artwork.thumb && /* @__PURE__ */ React.createElement("img", { src: artwork.thumb, alt: artwork.title, className: "h-10 w-10 rounded-lg object-cover" }), /* @__PURE__ */ React.createElement("span", { className: "font-medium text-white" }, artwork.title || /* @__PURE__ */ React.createElement("span", { className: "italic text-slate-500" }, "Untitled")))), /* @__PURE__ */ React.createElement("td", { className: "px-5 py-4 text-slate-400" }, artwork.user?.name ?? "—"), /* @__PURE__ */ React.createElement("td", { className: "px-5 py-4" }, /* @__PURE__ */ React.createElement("span", { className: `inline-flex rounded-full px-2.5 py-0.5 text-xs font-semibold capitalize ${artwork.status === "published" ? "bg-teal-500/20 text-teal-300" : artwork.status === "pending" ? "bg-amber-500/20 text-amber-300" : "bg-slate-500/20 text-slate-400"}` }, artwork.status ?? "unknown")), /* @__PURE__ */ React.createElement("td", { className: "px-5 py-4 text-slate-500" }, artwork.created_at ? new Date(artwork.created_at).toLocaleDateString("en-GB", { day: "numeric", month: "short", year: "numeric" }) : "—"), /* @__PURE__ */ React.createElement("td", { className: "px-5 py-4 text-right" }, /* @__PURE__ */ React.createElement( - "a", - { - href: `/studio/artworks/${artwork.id}/edit`, - className: "rounded-lg border border-white/10 bg-white/[0.04] px-3 py-1.5 text-xs text-white/70 transition hover:bg-white/[0.09]" - }, - "Edit" - ))))))), artworks?.last_page > 1 && /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between border-t border-white/[0.06] px-5 py-4" }, /* @__PURE__ */ React.createElement("p", { className: "text-xs text-slate-500" }, "Showing ", artworks.from, "–", artworks.to, " of ", artworks.total, " artworks"), /* @__PURE__ */ React.createElement("div", { className: "flex gap-1" }, artworks.links.map((link2, i) => link2.url ? /* @__PURE__ */ React.createElement( - "button", - { - key: i, - type: "button", - onClick: () => At.get(link2.url, {}, { preserveScroll: true }), - className: `rounded-lg px-3 py-1.5 text-xs transition ${link2.active ? "bg-rose-500/20 font-semibold text-rose-300" : "text-slate-500 hover:bg-white/[0.06] hover:text-white"}`, - dangerouslySetInnerHTML: { __html: link2.label } - } - ) : /* @__PURE__ */ React.createElement("span", { key: i, className: "rounded-lg px-3 py-1.5 text-xs text-slate-700", dangerouslySetInnerHTML: { __html: link2.label } })))))); -} -const __vite_glob_0_10 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ - __proto__: null, - default: AdminArtworks -}, Symbol.toStringTag, { value: "Module" })); -const EVENT_LABELS = { - login: "Login", - register: "Register", - forgot_password: "Forgot password", - reset_password: "Reset password" -}; -const STATUS_BADGES = { - success: "border-emerald-400/20 bg-emerald-400/10 text-emerald-200", - failed: "border-rose-400/20 bg-rose-400/10 text-rose-200" -}; -function formatTimestamp(value) { - if (!value) { - return "Unknown"; - } - return new Intl.DateTimeFormat("en-GB", { - dateStyle: "medium", - timeStyle: "medium" - }).format(new Date(value)); -} -function formatLabel(value) { - if (!value) { - return "Not recorded"; - } - return value.replaceAll("_", " ").replace(/\b\w/g, (match) => match.toUpperCase()); -} -function SummaryCard$5({ label, value, tone = "slate" }) { - const tones2 = { - slate: "border-white/[0.07] bg-white/[0.02] text-white", - rose: "border-rose-400/15 bg-rose-500/10 text-rose-100", - sky: "border-sky-400/15 bg-sky-500/10 text-sky-100" - }; - return /* @__PURE__ */ React.createElement("div", { className: `rounded-2xl border p-5 ${tones2[tone] ?? tones2.slate}` }, /* @__PURE__ */ React.createElement("p", { className: "text-xs font-semibold uppercase tracking-[0.18em] text-slate-500" }, label), /* @__PURE__ */ React.createElement("p", { className: "mt-3 text-3xl font-semibold tracking-tight" }, value)); -} -function AuthAudit({ logs, filters, eventOptions, statusOptions }) { - const items = logs?.data ?? []; - const failedCount = items.filter((entry) => entry.status === "failed").length; - const uniqueIpCount = new Set(items.map((entry) => entry.ip).filter(Boolean)).size; - const handleSearch = (event) => { - event.preventDefault(); - const search2 = event.target.elements.search.value; - At.get("/moderation/auth-audit", { - search: search2, - event: filters.event, - status: filters.status - }, { - preserveState: true, - preserveScroll: true - }); - }; - const handleFilterChange = (key, value) => { - At.get("/moderation/auth-audit", { - search: filters.search, - event: key === "event" ? value : filters.event, - status: key === "status" ? value : filters.status - }, { - preserveState: true, - preserveScroll: true - }); - }; - return /* @__PURE__ */ React.createElement(AdminLayout, { title: "Auth Audit", subtitle: "Review login, registration, forgot-password, and reset-password activity with IPs, timestamps, status, and failure reasons." }, /* @__PURE__ */ React.createElement(Se, { title: "Admin · Auth Audit" }), /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 lg:grid-cols-3" }, /* @__PURE__ */ React.createElement(SummaryCard$5, { label: "Visible records", value: items.length.toLocaleString(), tone: "slate" }), /* @__PURE__ */ React.createElement(SummaryCard$5, { label: "Failures on page", value: failedCount.toLocaleString(), tone: "rose" }), /* @__PURE__ */ React.createElement(SummaryCard$5, { label: "Unique IPs on page", value: uniqueIpCount.toLocaleString(), tone: "sky" })), /* @__PURE__ */ React.createElement("div", { className: "mt-6 rounded-[28px] border border-white/[0.07] bg-white/[0.02] p-5" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-col gap-4 xl:flex-row xl:items-end xl:justify-between" }, /* @__PURE__ */ React.createElement("form", { onSubmit: handleSearch, className: "flex flex-1 flex-col gap-3 md:flex-row" }, /* @__PURE__ */ React.createElement("label", { className: "flex-1" }, /* @__PURE__ */ React.createElement("span", { className: "mb-2 block text-xs font-semibold uppercase tracking-[0.18em] text-slate-500" }, "Search"), /* @__PURE__ */ React.createElement( - "input", - { - name: "search", - defaultValue: filters.search, - placeholder: "Email, username, IP, or failure reason", - className: "w-full rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3 text-sm text-white placeholder:text-slate-600 focus:border-white/20 focus:outline-none focus:ring-1 focus:ring-white/10" - } - )), /* @__PURE__ */ React.createElement("button", { type: "submit", className: "rounded-2xl bg-rose-500/80 px-5 py-3 text-sm font-semibold text-white transition hover:bg-rose-500" }, "Search")), /* @__PURE__ */ React.createElement("div", { className: "grid gap-3 md:grid-cols-2 xl:min-w-[26rem]" }, /* @__PURE__ */ React.createElement("label", null, /* @__PURE__ */ React.createElement("span", { className: "mb-2 block text-xs font-semibold uppercase tracking-[0.18em] text-slate-500" }, "Event"), /* @__PURE__ */ React.createElement( - "select", - { - value: filters.event, - onChange: (event) => handleFilterChange("event", event.target.value), - className: "w-full rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3 text-sm text-white focus:border-white/20 focus:outline-none focus:ring-1 focus:ring-white/10" - }, - eventOptions.map((option) => /* @__PURE__ */ React.createElement("option", { key: option.value, value: option.value, className: "bg-slate-950 text-white" }, option.label)) - )), /* @__PURE__ */ React.createElement("label", null, /* @__PURE__ */ React.createElement("span", { className: "mb-2 block text-xs font-semibold uppercase tracking-[0.18em] text-slate-500" }, "Status"), /* @__PURE__ */ React.createElement( - "select", - { - value: filters.status, - onChange: (event) => handleFilterChange("status", event.target.value), - className: "w-full rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3 text-sm text-white focus:border-white/20 focus:outline-none focus:ring-1 focus:ring-white/10" - }, - statusOptions.map((option) => /* @__PURE__ */ React.createElement("option", { key: option.value, value: option.value, className: "bg-slate-950 text-white" }, option.label)) - ))))), /* @__PURE__ */ React.createElement("div", { className: "mt-6 overflow-hidden rounded-[28px] border border-white/[0.07] bg-white/[0.02]" }, /* @__PURE__ */ React.createElement("div", { className: "overflow-x-auto" }, /* @__PURE__ */ React.createElement("table", { className: "w-full min-w-[980px] text-sm" }, /* @__PURE__ */ React.createElement("thead", null, /* @__PURE__ */ React.createElement("tr", { className: "border-b border-white/[0.07] text-left text-xs font-semibold uppercase tracking-[0.18em] text-slate-500" }, /* @__PURE__ */ React.createElement("th", { className: "px-5 py-4" }, "When"), /* @__PURE__ */ React.createElement("th", { className: "px-5 py-4" }, "Event"), /* @__PURE__ */ React.createElement("th", { className: "px-5 py-4" }, "Status"), /* @__PURE__ */ React.createElement("th", { className: "px-5 py-4" }, "Identifier"), /* @__PURE__ */ React.createElement("th", { className: "px-5 py-4" }, "User"), /* @__PURE__ */ React.createElement("th", { className: "px-5 py-4" }, "IP"), /* @__PURE__ */ React.createElement("th", { className: "px-5 py-4" }, "Reason"), /* @__PURE__ */ React.createElement("th", { className: "px-5 py-4" }, "Details"))), /* @__PURE__ */ React.createElement("tbody", { className: "divide-y divide-white/[0.05]" }, items.length === 0 ? /* @__PURE__ */ React.createElement("tr", null, /* @__PURE__ */ React.createElement("td", { colSpan: 8, className: "px-5 py-12 text-center text-slate-500" }, "No auth audit records matched the current filters.")) : items.map((entry) => /* @__PURE__ */ React.createElement("tr", { key: entry.id, className: "align-top transition hover:bg-white/[0.025]" }, /* @__PURE__ */ React.createElement("td", { className: "px-5 py-4 text-slate-300" }, formatTimestamp(entry.created_at)), /* @__PURE__ */ React.createElement("td", { className: "px-5 py-4 text-white" }, EVENT_LABELS[entry.event_type] ?? formatLabel(entry.event_type)), /* @__PURE__ */ React.createElement("td", { className: "px-5 py-4" }, /* @__PURE__ */ React.createElement("span", { className: `inline-flex rounded-full border px-2.5 py-1 text-xs font-semibold uppercase tracking-[0.16em] ${STATUS_BADGES[entry.status] ?? "border-white/10 bg-white/[0.04] text-white/70"}` }, entry.status)), /* @__PURE__ */ React.createElement("td", { className: "px-5 py-4 text-slate-300" }, entry.identifier || "Not recorded"), /* @__PURE__ */ React.createElement("td", { className: "px-5 py-4" }, entry.user ? /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "font-medium text-white" }, entry.user.name), /* @__PURE__ */ React.createElement("p", { className: "text-xs text-slate-500" }, entry.user.username ? `@${entry.user.username}` : entry.user.email)) : /* @__PURE__ */ React.createElement("span", { className: "text-slate-500" }, "Unknown user")), /* @__PURE__ */ React.createElement("td", { className: "px-5 py-4 text-slate-300" }, entry.ip || "Unknown"), /* @__PURE__ */ React.createElement("td", { className: "px-5 py-4 text-slate-300" }, formatLabel(entry.reason)), /* @__PURE__ */ React.createElement("td", { className: "px-5 py-4" }, /* @__PURE__ */ React.createElement("details", { className: "group w-72 max-w-full" }, /* @__PURE__ */ React.createElement("summary", { className: "cursor-pointer list-none text-sm font-medium text-sky-200 transition hover:text-sky-100" }, "View payload"), /* @__PURE__ */ React.createElement("div", { className: "mt-3 space-y-3 rounded-2xl border border-white/10 bg-black/20 p-4 text-xs text-slate-300" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "font-semibold uppercase tracking-[0.16em] text-slate-500" }, "User agent"), /* @__PURE__ */ React.createElement("p", { className: "mt-1 break-words leading-5 text-slate-300" }, entry.user_agent || "Not recorded")), /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Metadata"), /* @__PURE__ */ React.createElement("pre", { className: "mt-1 overflow-x-auto whitespace-pre-wrap break-words rounded-xl bg-slate-950/70 p-3 text-[11px] leading-5 text-slate-300" }, JSON.stringify(entry.metadata || {}, null, 2))))))))))), logs?.last_page > 1 ? /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between border-t border-white/[0.06] px-5 py-4" }, /* @__PURE__ */ React.createElement("p", { className: "text-xs text-slate-500" }, "Showing ", logs.from, "–", logs.to, " of ", logs.total, " audit records"), /* @__PURE__ */ React.createElement("div", { className: "flex gap-1" }, logs.links.map((link2, index2) => link2.url ? /* @__PURE__ */ React.createElement( - "button", - { - key: `${link2.label}-${index2}`, - type: "button", - onClick: () => At.get(link2.url, {}, { preserveScroll: true, preserveState: true }), - className: `rounded-lg px-3 py-1.5 text-xs transition ${link2.active ? "bg-rose-500/20 font-semibold text-rose-300" : "text-slate-500 hover:bg-white/[0.06] hover:text-white"}`, - dangerouslySetInnerHTML: { __html: link2.label } - } - ) : /* @__PURE__ */ React.createElement("span", { key: `${link2.label}-${index2}`, className: "rounded-lg px-3 py-1.5 text-xs text-slate-700", dangerouslySetInnerHTML: { __html: link2.label } })))) : null)); -} -const __vite_glob_0_11 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ - __proto__: null, - default: AuthAudit -}, Symbol.toStringTag, { value: "Module" })); -function formatDateTime$4(value) { - if (!value) return "—"; - try { - return new Intl.DateTimeFormat(void 0, { - year: "numeric", - month: "short", - day: "numeric", - hour: "2-digit", - minute: "2-digit" - }).format(new Date(value)); - } catch { - return String(value); - } -} -function StatCard$a({ icon, label, value, tone = "sky" }) { - const tones2 = { - sky: "border-sky-400/20 bg-sky-400/10 text-sky-200", - rose: "border-rose-400/20 bg-rose-400/10 text-rose-200", - amber: "border-amber-400/20 bg-amber-400/10 text-amber-200", - emerald: "border-emerald-400/20 bg-emerald-400/10 text-emerald-200" - }; - return /* @__PURE__ */ React.createElement("div", { className: `rounded-2xl border p-5 ${tones2[tone]}` }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between gap-4" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.22em] text-white/65" }, label), /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-3xl font-bold text-white" }, Number(value || 0).toLocaleString())), /* @__PURE__ */ React.createElement("div", { className: "flex h-11 w-11 items-center justify-center rounded-2xl border border-white/10 bg-black/20 text-lg text-white/80" }, /* @__PURE__ */ React.createElement("i", { className: icon })))); -} -function SectionCard$3({ title, subtitle, actionHref, actionLabel, children }) { - return /* @__PURE__ */ React.createElement("section", { className: "rounded-3xl border border-white/10 bg-white/[0.04] p-5 shadow-[0_24px_80px_rgba(2,6,23,0.35)]" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-start justify-between gap-4 border-b border-white/8 pb-4" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("h2", { className: "text-lg font-semibold text-white" }, title), subtitle ? /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-sm text-slate-400" }, subtitle) : null), actionHref ? /* @__PURE__ */ React.createElement("a", { href: actionHref, className: "inline-flex items-center gap-2 rounded-full border border-white/10 bg-white/[0.05] px-3 py-2 text-xs font-semibold uppercase tracking-[0.16em] text-slate-200 transition hover:bg-white/[0.08]" }, /* @__PURE__ */ React.createElement("span", null, actionLabel || "Open queue"), /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-arrow-up-right-from-square text-[10px]" })) : null), /* @__PURE__ */ React.createElement("div", { className: "mt-4" }, children)); -} -function EmptyState$6({ label }) { - return /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-dashed border-white/10 bg-black/10 px-4 py-6 text-sm text-slate-400" }, label); -} -function DataTable({ columns, rows, emptyLabel }) { - if (!rows?.length) { - return /* @__PURE__ */ React.createElement(EmptyState$6, { label: emptyLabel }); - } - return /* @__PURE__ */ React.createElement("div", { className: "overflow-x-auto" }, /* @__PURE__ */ React.createElement("table", { className: "min-w-full divide-y divide-white/10 text-sm text-slate-200" }, /* @__PURE__ */ React.createElement("thead", null, /* @__PURE__ */ React.createElement("tr", { className: "text-left text-[11px] uppercase tracking-[0.18em] text-slate-500" }, columns.map((column) => /* @__PURE__ */ React.createElement("th", { key: column.key, className: "px-3 py-3 font-semibold" }, column.label)))), /* @__PURE__ */ React.createElement("tbody", { className: "divide-y divide-white/6" }, rows.map((row, index2) => /* @__PURE__ */ React.createElement("tr", { key: row.id || `${index2}-${row.created_at || row.updated_at || "row"}`, className: "align-top" }, columns.map((column) => /* @__PURE__ */ React.createElement("td", { key: column.key, className: "px-3 py-3 text-slate-200/90" }, column.render ? column.render(row) : row[column.key]))))))); -} -function DailyActivity({ selectedDate, summary, queues, sections }) { - const onDateChange = (event) => { - At.get("/moderation/activity", { date: event.target.value }, { preserveState: true, replace: true }); - }; - return /* @__PURE__ */ React.createElement(AdminLayout, { title: "Daily Activity", subtitle: "A day-by-day moderation cockpit for reviewing new content, queue movement, and staff actions." }, /* @__PURE__ */ React.createElement(Se, { title: "Admin · Daily Activity" }), /* @__PURE__ */ React.createElement("div", { className: "rounded-3xl border border-white/10 bg-[linear-gradient(135deg,rgba(244,63,94,0.18),rgba(15,23,42,0.75))] p-6 shadow-[0_30px_120px_rgba(15,23,42,0.5)]" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-end justify-between gap-5" }, /* @__PURE__ */ React.createElement("div", { className: "max-w-2xl" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.26em] text-rose-200/80" }, "Moderation review"), /* @__PURE__ */ React.createElement("h2", { className: "mt-2 text-2xl font-bold text-white" }, "Selected day: ", selectedDate), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm leading-6 text-slate-200/80" }, "This view pulls together the moderation-adjacent activity for the selected day so admins can triage queues and jump into the right review surface quickly.")), /* @__PURE__ */ React.createElement("label", { className: "block" }, /* @__PURE__ */ React.createElement("span", { className: "mb-2 block text-[11px] font-semibold uppercase tracking-[0.2em] text-slate-300" }, "Day"), /* @__PURE__ */ React.createElement( - "input", - { - type: "date", - value: selectedDate, - onChange: onDateChange, - className: "rounded-2xl border border-white/10 bg-slate-950/70 px-4 py-3 text-sm text-white outline-none transition focus:border-rose-400/50" - } - )))), /* @__PURE__ */ React.createElement("div", { className: "mt-6 grid gap-4 sm:grid-cols-2 xl:grid-cols-3" }, /* @__PURE__ */ React.createElement(StatCard$a, { icon: "fa-solid fa-user-plus", label: "New Users", value: summary.new_users, tone: "sky" }), /* @__PURE__ */ React.createElement(StatCard$a, { icon: "fa-solid fa-images", label: "New Artworks", value: summary.new_artworks, tone: "rose" }), /* @__PURE__ */ React.createElement(StatCard$a, { icon: "fa-solid fa-feather-pointed", label: "New Stories", value: summary.new_stories, tone: "amber" }), /* @__PURE__ */ React.createElement(StatCard$a, { icon: "fa-solid fa-cloud-arrow-up", label: "Upload Events", value: summary.upload_events, tone: "emerald" }), /* @__PURE__ */ React.createElement(StatCard$a, { icon: "fa-solid fa-flag", label: "Report Events", value: summary.report_events, tone: "rose" }), /* @__PURE__ */ React.createElement(StatCard$a, { icon: "fa-solid fa-fingerprint", label: "Auth Events", value: summary.auth_events, tone: "sky" })), /* @__PURE__ */ React.createElement("div", { className: "mt-6 grid gap-4 lg:grid-cols-3" }, /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-white/[0.04] p-5" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.22em] text-slate-500" }, "Queues right now"), /* @__PURE__ */ React.createElement("div", { className: "mt-4 space-y-3 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between rounded-2xl border border-white/8 bg-black/10 px-4 py-3" }, /* @__PURE__ */ React.createElement("span", null, "Pending uploads"), /* @__PURE__ */ React.createElement("span", { className: "font-semibold text-white" }, queues.pending_uploads)), /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between rounded-2xl border border-white/8 bg-black/10 px-4 py-3" }, /* @__PURE__ */ React.createElement("span", null, "Open reports"), /* @__PURE__ */ React.createElement("span", { className: "font-semibold text-white" }, queues.open_reports)), /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between rounded-2xl border border-white/8 bg-black/10 px-4 py-3" }, /* @__PURE__ */ React.createElement("span", null, "Pending username requests"), /* @__PURE__ */ React.createElement("span", { className: "font-semibold text-white" }, queues.pending_username_requests)))), /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-white/[0.04] p-5 lg:col-span-2" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.22em] text-slate-500" }, "Moderation throughput on this day"), /* @__PURE__ */ React.createElement("div", { className: "mt-4 grid gap-3 sm:grid-cols-3" }, /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/8 bg-black/10 p-4" }, /* @__PURE__ */ React.createElement("div", { className: "text-xs uppercase tracking-[0.18em] text-slate-500" }, "Moderated uploads"), /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-2xl font-bold text-white" }, summary.moderated_uploads)), /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/8 bg-black/10 p-4" }, /* @__PURE__ */ React.createElement("div", { className: "text-xs uppercase tracking-[0.18em] text-slate-500" }, "Moderated reports"), /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-2xl font-bold text-white" }, summary.moderated_reports)), /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/8 bg-black/10 p-4" }, /* @__PURE__ */ React.createElement("div", { className: "text-xs uppercase tracking-[0.18em] text-slate-500" }, "Username events"), /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-2xl font-bold text-white" }, summary.username_events))))), /* @__PURE__ */ React.createElement("div", { className: "mt-6 space-y-6" }, /* @__PURE__ */ React.createElement(SectionCard$3, { title: "Uploads", subtitle: "New uploads and same-day moderation decisions.", actionHref: "/moderation/uploads", actionLabel: "Open uploads" }, /* @__PURE__ */ React.createElement( - DataTable, - { - emptyLabel: "No upload activity on this day.", - rows: sections.uploads, - columns: [ - { key: "title", label: "Upload", render: (row) => /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "font-semibold text-white" }, row.title), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-xs uppercase tracking-[0.16em] text-slate-500" }, row.type, " · ", row.status, " · ", row.processing_state)) }, - { key: "moderation_status", label: "Moderation", render: (row) => /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", null, row.moderation_status), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-xs text-slate-500" }, row.moderation_note || "No note")) }, - { key: "created_at", label: "Created", render: (row) => formatDateTime$4(row.created_at) }, - { key: "moderated_at", label: "Moderated", render: (row) => formatDateTime$4(row.moderated_at) } - ] - } - )), /* @__PURE__ */ React.createElement(SectionCard$3, { title: "Reports", subtitle: "User reports created or reviewed during the selected day." }, /* @__PURE__ */ React.createElement( - DataTable, - { - emptyLabel: "No report activity on this day.", - rows: sections.reports, - columns: [ - { key: "reason", label: "Report", render: (row) => /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "font-semibold text-white" }, row.reason), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-xs uppercase tracking-[0.16em] text-slate-500" }, row.status, " · ", row.target_type, " #", row.target_id)) }, - { key: "reporter", label: "Reporter", render: (row) => row.reporter ? `@${row.reporter.username}` : "—" }, - { key: "target", label: "Target", render: (row) => row.target?.title || row.target?.context || "Resolved via moderation target" }, - { key: "last_moderated_at", label: "Reviewed", render: (row) => /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", null, formatDateTime$4(row.last_moderated_at)), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-xs text-slate-500" }, row.last_moderated_by ? `@${row.last_moderated_by.username}` : "Unassigned")) } - ] - } - )), /* @__PURE__ */ React.createElement("div", { className: "grid gap-6 xl:grid-cols-2" }, /* @__PURE__ */ React.createElement(SectionCard$3, { title: "Username Requests", subtitle: "Requests created or reviewed on this day.", actionHref: "/moderation/usernames/moderation", actionLabel: "Open usernames" }, /* @__PURE__ */ React.createElement( - DataTable, - { - emptyLabel: "No username activity on this day.", - rows: sections.username_requests, - columns: [ - { key: "requested_username", label: "Request", render: (row) => /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "font-semibold text-white" }, row.requested_username), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-xs text-slate-500" }, "Current: ", row.current_username || row.current_name || "Unknown user")) }, - { key: "status", label: "Status" }, - { key: "created_at", label: "Created", render: (row) => formatDateTime$4(row.created_at) }, - { key: "reviewed_at", label: "Reviewed", render: (row) => formatDateTime$4(row.reviewed_at) } - ] - } - )), /* @__PURE__ */ React.createElement(SectionCard$3, { title: "Auth Audit", subtitle: "Authentication events for the selected day.", actionHref: "/moderation/auth-audit", actionLabel: "Open audit" }, /* @__PURE__ */ React.createElement( - DataTable, - { - emptyLabel: "No auth audit events on this day.", - rows: sections.auth_events, - columns: [ - { key: "event_type", label: "Event", render: (row) => /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "font-semibold text-white" }, row.event_type), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-xs text-slate-500" }, row.status, " · ", row.ip || "No IP")) }, - { key: "user", label: "User", render: (row) => row.user ? `@${row.user.username || row.user.name}` : row.identifier || "Guest" }, - { key: "reason", label: "Reason", render: (row) => row.reason || "—" }, - { key: "created_at", label: "When", render: (row) => formatDateTime$4(row.created_at) } - ] - } - ))), /* @__PURE__ */ React.createElement("div", { className: "grid gap-6 xl:grid-cols-3" }, /* @__PURE__ */ React.createElement(SectionCard$3, { title: "Users", subtitle: "Accounts created on this day.", actionHref: "/moderation/users", actionLabel: "Open users" }, /* @__PURE__ */ React.createElement( - DataTable, - { - emptyLabel: "No new users on this day.", - rows: sections.users, - columns: [ - { key: "username", label: "User", render: (row) => /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "font-semibold text-white" }, row.username ? `@${row.username}` : row.name), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-xs text-slate-500" }, row.email)) }, - { key: "role", label: "Role" }, - { key: "created_at", label: "Joined", render: (row) => formatDateTime$4(row.created_at) } - ] - } - )), /* @__PURE__ */ React.createElement(SectionCard$3, { title: "Artworks", subtitle: "Artwork records created on this day.", actionHref: "/moderation/artworks", actionLabel: "Open artworks" }, /* @__PURE__ */ React.createElement( - DataTable, - { - emptyLabel: "No artwork activity on this day.", - rows: sections.artworks, - columns: [ - { key: "title", label: "Artwork", render: (row) => /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "font-semibold text-white" }, row.title), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-xs text-slate-500" }, row.user?.username ? `@${row.user.username}` : "Unknown artist")) }, - { key: "status", label: "Status" }, - { key: "created_at", label: "Created", render: (row) => formatDateTime$4(row.created_at) } - ] - } - )), /* @__PURE__ */ React.createElement(SectionCard$3, { title: "Stories", subtitle: "Creator stories created on this day.", actionHref: "/moderation/stories", actionLabel: "Open stories" }, /* @__PURE__ */ React.createElement( - DataTable, - { - emptyLabel: "No story activity on this day.", - rows: sections.stories, - columns: [ - { key: "title", label: "Story", render: (row) => /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "font-semibold text-white" }, row.title), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-xs text-slate-500" }, row.creator?.username ? `@${row.creator.username}` : "Unknown creator")) }, - { key: "status", label: "Status" }, - { key: "created_at", label: "Created", render: (row) => formatDateTime$4(row.created_at) } - ] - } - ))))); -} -const __vite_glob_0_12 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ - __proto__: null, - default: DailyActivity -}, Symbol.toStringTag, { value: "Module" })); -function StatCard$9({ icon, label, value, color: color2 = "sky" }) { - const colors = { - sky: "from-sky-500/20 to-sky-500/5 border-sky-500/20 text-sky-400", - rose: "from-rose-500/20 to-rose-500/5 border-rose-500/20 text-rose-400", - amber: "from-amber-500/20 to-amber-500/5 border-amber-500/20 text-amber-400", - violet: "from-violet-500/20 to-violet-500/5 border-violet-500/20 text-violet-400" - }; - return /* @__PURE__ */ React.createElement("div", { className: `rounded-2xl border bg-gradient-to-br p-6 ${colors[color2]}` }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-xs font-semibold uppercase tracking-wider text-slate-400" }, label), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-3xl font-bold text-white" }, value.toLocaleString())), /* @__PURE__ */ React.createElement("div", { className: `flex h-12 w-12 items-center justify-center rounded-xl bg-white/5` }, /* @__PURE__ */ React.createElement("i", { className: `${icon} text-xl ${colors[color2].split(" ").at(-1)}` })))); -} -function Dashboard({ stats }) { - return /* @__PURE__ */ React.createElement(AdminLayout, { title: "Dashboard", subtitle: "Overview of your Skinbase platform" }, /* @__PURE__ */ React.createElement(Se, { title: "Admin Dashboard" }), /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 sm:grid-cols-2 lg:grid-cols-4" }, /* @__PURE__ */ React.createElement(StatCard$9, { icon: "fa-solid fa-users", label: "Total Users", value: stats.total_users, color: "sky" }), /* @__PURE__ */ React.createElement(StatCard$9, { icon: "fa-solid fa-user-plus", label: "New Today", value: stats.new_users_today, color: "violet" }), /* @__PURE__ */ React.createElement(StatCard$9, { icon: "fa-solid fa-shield-halved", label: "Staff Members", value: stats.staff_count, color: "rose" }), /* @__PURE__ */ React.createElement(StatCard$9, { icon: "fa-solid fa-user-shield", label: "Moderators", value: stats.moderator_count, color: "amber" })), /* @__PURE__ */ React.createElement("div", { className: "mt-10" }, /* @__PURE__ */ React.createElement("h2", { className: "mb-4 text-sm font-semibold uppercase tracking-wider text-slate-500" }, "Quick Actions"), /* @__PURE__ */ React.createElement("div", { className: "grid gap-3 sm:grid-cols-2 lg:grid-cols-3" }, [ - { label: "Daily Activity", href: "/moderation/activity", icon: "fa-solid fa-calendar-day", desc: "Review everything created or moderated on a selected day" }, - { label: "Manage Users", href: "/moderation/users", icon: "fa-solid fa-users", desc: "Search, promote or demote users" }, - { label: "Staff Roles", href: "/moderation/users?role=admin", icon: "fa-solid fa-shield-halved", desc: "View all admins, managers and editorial staff" }, - { label: "Username Queue", href: "/moderation/usernames/moderation", icon: "fa-solid fa-id-badge", desc: "Review pending username requests" }, - { label: "Upload Queue", href: "/moderation/uploads", icon: "fa-solid fa-cloud-arrow-up", desc: "Moderate pending artwork submissions" }, - { label: "Stories", href: "/moderation/stories", icon: "fa-solid fa-feather-pointed", desc: "Browse all creator stories" }, - { label: "Artworks", href: "/moderation/artworks", icon: "fa-solid fa-images", desc: "Browse all uploaded artworks" }, - { label: "Featured Artworks", href: "/moderation/artworks/featured", icon: "fa-solid fa-star", desc: "Curate the homepage featured artwork lineup" }, - { label: "AI Biography", href: "/moderation/ai-biography", icon: "fa-solid fa-wand-magic-sparkles", desc: "Review generated creator biographies and moderation flags" } - ].map((item) => /* @__PURE__ */ React.createElement( - "a", - { - key: item.href, - href: item.href, - className: "group flex items-start gap-4 rounded-2xl border border-white/[0.07] bg-white/[0.03] p-5 transition hover:border-white/15 hover:bg-white/[0.06]" - }, - /* @__PURE__ */ React.createElement("div", { className: "mt-0.5 flex h-10 w-10 flex-shrink-0 items-center justify-center rounded-xl bg-rose-500/10" }, /* @__PURE__ */ React.createElement("i", { className: `${item.icon} text-rose-400` })), - /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "font-semibold text-white group-hover:text-rose-300 transition" }, item.label), /* @__PURE__ */ React.createElement("p", { className: "mt-0.5 text-xs text-slate-500" }, item.desc)) - ))))); -} -const __vite_glob_0_13 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ - __proto__: null, - default: Dashboard -}, Symbol.toStringTag, { value: "Module" })); -const variantStyles = { - accent: { checked: "#E07A21", ring: "rgba(224,122,33,0.45)" }, - emerald: { checked: "#10b981", ring: "rgba(16,185,129,0.45)" }, - sky: { checked: "#0ea5e9", ring: "rgba(14,165,233,0.45)" } -}; -const Checkbox = reactExports.forwardRef(function Checkbox2({ label, hint, error, size = 18, variant = "accent", id, className = "", checked, disabled, onChange, ...rest }, ref2) { - const dim = typeof size === "number" ? `${size}px` : size; - const numSize = typeof size === "number" ? size : parseInt(size, 10); - const inputId = id ?? (label ? `cb-${label.toLowerCase().replace(/\s+/g, "-")}` : void 0); - const colors = variantStyles[variant] ?? variantStyles.accent; - const tickInset = Math.round(numSize * 0.18); - const strokeWidth = Math.max(1.5, numSize * 0.1); - return /* @__PURE__ */ React.createElement("div", { className: "flex flex-col gap-1" }, /* @__PURE__ */ React.createElement( - "label", - { - className: [ - "inline-flex items-start gap-2.5 select-none", - disabled ? "opacity-50 cursor-not-allowed" : "cursor-pointer" - ].join(" ") - }, - /* @__PURE__ */ React.createElement( - "input", - { - type: "checkbox", - id: inputId, - ref: ref2, - checked, - disabled, - onChange, - className: "sr-only", - "aria-invalid": !!error, - ...rest - } - ), - /* @__PURE__ */ React.createElement( - "span", - { - "aria-hidden": "true", - style: { - width: dim, - height: dim, - minWidth: dim, - minHeight: dim, - aspectRatio: "1 / 1", - marginTop: label ? "1px" : void 0, - backgroundColor: checked ? colors.checked : "rgba(255,255,255,0.06)", - borderColor: checked ? colors.checked : "rgba(255,255,255,0.25)", - boxShadow: checked ? `0 0 0 0px ${colors.ring}` : void 0, - transition: "background-color 150ms, border-color 150ms" - }, - className: [ - "shrink-0 inline-flex items-center justify-center", - "rounded-md border", - className - ].join(" ") - }, - /* @__PURE__ */ React.createElement( - "svg", - { - viewBox: "0 0 12 12", - fill: "none", - style: { - width: numSize - tickInset * 2, - height: numSize - tickInset * 2, - opacity: checked ? 1 : 0, - transition: "opacity 100ms" - }, - "aria-hidden": "true" - }, - /* @__PURE__ */ React.createElement( - "path", - { - d: "M1.5 6l3 3 6-6", - stroke: "white", - strokeWidth, - strokeLinecap: "round", - strokeLinejoin: "round" - } - ) - ) - ), - (label || hint) && /* @__PURE__ */ React.createElement("span", { className: "flex flex-col gap-0.5" }, label && /* @__PURE__ */ React.createElement("span", { className: "text-sm text-white/90 leading-snug" }, label), hint && /* @__PURE__ */ React.createElement("span", { className: "text-xs text-slate-500" }, hint)) - ), error && /* @__PURE__ */ React.createElement("p", { role: "alert", className: "text-xs text-red-400", style: { paddingLeft: `calc(${dim} + 0.625rem)` } }, error)); -}); const MONTH_NAMES = [ "January", "February", @@ -13982,6 +13587,4304 @@ function DateTimePicker({ document.body )); } +const MentionList = reactExports.forwardRef(function MentionList2({ items, command }, ref2) { + const [selectedIndex, setSelectedIndex] = reactExports.useState(0); + reactExports.useEffect(() => setSelectedIndex(0), [items]); + reactExports.useImperativeHandle(ref2, () => ({ + onKeyDown: ({ event }) => { + if (event.key === "ArrowUp") { + setSelectedIndex((i) => (i + items.length - 1) % items.length); + return true; + } + if (event.key === "ArrowDown") { + setSelectedIndex((i) => (i + 1) % items.length); + return true; + } + if (event.key === "Enter") { + selectItem(selectedIndex); + return true; + } + return false; + } + })); + const selectItem = (index2) => { + const item = items[index2]; + if (item) { + command({ id: item.username, label: item.username }); + } + }; + if (!items.length) { + return /* @__PURE__ */ React.createElement("div", { className: "rounded-xl border border-white/[0.08] bg-nova-800 p-3 shadow-xl backdrop-blur" }, /* @__PURE__ */ React.createElement("p", { className: "text-xs text-zinc-500" }, "No users found")); + } + return /* @__PURE__ */ React.createElement("div", { className: "min-w-[200px] overflow-hidden rounded-xl border border-white/[0.08] bg-nova-800 shadow-xl backdrop-blur" }, items.map((item, index2) => /* @__PURE__ */ React.createElement( + "button", + { + key: item.id, + type: "button", + onClick: () => selectItem(index2), + className: [ + "flex w-full items-center gap-2.5 px-3 py-2 text-left text-sm transition-colors", + index2 === selectedIndex ? "bg-sky-600/20 text-white" : "text-zinc-300 hover:bg-white/[0.04]" + ].join(" ") + }, + /* @__PURE__ */ React.createElement( + "img", + { + src: item.avatar_url, + alt: "", + className: "h-6 w-6 rounded-full border border-white/10 object-cover" + } + ), + /* @__PURE__ */ React.createElement("span", { className: "truncate font-medium" }, "@", item.username), + item.name && item.name !== item.username && /* @__PURE__ */ React.createElement("span", { className: "truncate text-xs text-zinc-500" }, item.name) + ))); +}); +const mentionSuggestion = { + items: async ({ query }) => { + if (!query || query.length < 2) return []; + try { + const res = await fetch(`/api/search/users?q=${encodeURIComponent(query)}&per_page=6`); + if (!res.ok) return []; + const json = await res.json(); + return json.data ?? []; + } catch { + return []; + } + }, + render: () => { + let component; + let popup; + return { + onStart: (props) => { + component = new ReactRenderer(MentionList, { + props, + editor: props.editor + }); + if (!props.clientRect) return; + popup = tippy("body", { + getReferenceClientRect: props.clientRect, + appendTo: () => document.body, + content: component.element, + showOnCreate: true, + interactive: true, + trigger: "manual", + placement: "bottom-start", + theme: "mention", + arrow: false, + offset: [0, 8] + }); + }, + onUpdate: (props) => { + component?.updateProps(props); + if (!props.clientRect) return; + popup?.[0]?.setProps({ + getReferenceClientRect: props.clientRect + }); + }, + onKeyDown: (props) => { + if (props.event.key === "Escape") { + popup?.[0]?.hide(); + return true; + } + return component?.ref?.onKeyDown(props) ?? false; + }, + onExit: () => { + popup?.[0]?.destroy(); + component?.destroy(); + } + }; + } +}; +let emojiMartPromise = null; +function ensureEmojiMart() { + if (!emojiMartPromise) { + emojiMartPromise = import("./assets/emoji-ui-C_DZUNyP.js"); + } + return emojiMartPromise; +} +function EmojiMartPicker({ + data, + onEmojiSelect, + onClickOutside, + theme = "auto", + previewPosition = "bottom", + skinTonePosition = "preview", + maxFrequentRows = 4, + perLine = 9, + navPosition = "top", + set = "native", + locale = "en", + autoFocus = false, + searchPosition, + dynamicWidth, + noCountryFlags, + className = "" +}) { + const hostRef = reactExports.useRef(null); + const pickerRef = reactExports.useRef(null); + const onEmojiSelectRef = reactExports.useRef(onEmojiSelect); + const onClickOutsideRef = reactExports.useRef(onClickOutside); + onEmojiSelectRef.current = onEmojiSelect; + onClickOutsideRef.current = onClickOutside; + const stableOnEmojiSelect = reactExports.useCallback((emoji) => { + onEmojiSelectRef.current?.(emoji); + }, []); + const stableOnClickOutside = reactExports.useCallback((e) => { + onClickOutsideRef.current?.(e); + }, []); + reactExports.useEffect(() => { + let cancelled = false; + ensureEmojiMart().then(({ Picker }) => { + if (cancelled || !hostRef.current) return; + if (!pickerRef.current) { + const pickerProps = { + data, + onEmojiSelect: stableOnEmojiSelect, + onClickOutside: stableOnClickOutside, + theme, + previewPosition, + skinTonePosition, + maxFrequentRows, + perLine, + navPosition, + set, + locale, + autoFocus + }; + if (searchPosition !== void 0) pickerProps.searchPosition = searchPosition; + if (dynamicWidth !== void 0) pickerProps.dynamicWidth = dynamicWidth; + if (noCountryFlags !== void 0) pickerProps.noCountryFlags = noCountryFlags; + const el = new Picker(pickerProps); + pickerRef.current = el; + hostRef.current.replaceChildren(el); + } + }); + return () => { + cancelled = true; + }; + }, []); + reactExports.useEffect(() => { + return () => { + if (hostRef.current) { + hostRef.current.replaceChildren(); + } + pickerRef.current = null; + }; + }, []); + return /* @__PURE__ */ React.createElement("div", { ref: hostRef, className }); +} +function extractNativeEmoji(selection) { + if (typeof selection === "string") { + return selection; + } + const detail = selection?.detail ?? null; + return selection?.native ?? selection?.emoji ?? selection?.unicode ?? selection?.skins?.[0]?.native ?? detail?.native ?? detail?.emoji ?? detail?.unicode ?? detail?.skins?.[0]?.native ?? ""; +} +function isEventWithinNode(event, node2) { + if (!event || !node2) { + return false; + } + if (typeof event.composedPath === "function") { + return event.composedPath().includes(node2); + } + return node2.contains(event.target); +} +let emojiMartDataPromise = null; +function loadEmojiMartData() { + if (!emojiMartDataPromise) { + emojiMartDataPromise = import("./assets/emoji-data-4xGXbtDn.js").then((module) => module.default); + } + return emojiMartDataPromise; +} +function EmojiPicker({ onSelect, editor }) { + const [open, setOpen] = reactExports.useState(false); + const [pickerData, setPickerData] = reactExports.useState(null); + const [panelStyle, setPanelStyle] = reactExports.useState({}); + const panelRef = reactExports.useRef(null); + const buttonRef = reactExports.useRef(null); + reactExports.useEffect(() => { + if (!open || pickerData) return; + let cancelled = false; + loadEmojiMartData().then((data) => { + if (!cancelled) { + setPickerData(data); + } + }); + return () => { + cancelled = true; + }; + }, [open, pickerData]); + reactExports.useEffect(() => { + if (!open || !buttonRef.current) return; + const rect = buttonRef.current.getBoundingClientRect(); + const panelWidth = 352; + const panelHeight = 435; + const spaceAbove = rect.top; + const openAbove = spaceAbove > panelHeight + 8; + setPanelStyle({ + position: "fixed", + zIndex: 9999, + left: Math.max(8, Math.min(rect.right - panelWidth, window.innerWidth - panelWidth - 8)), + ...openAbove ? { bottom: window.innerHeight - rect.top + 6 } : { top: rect.bottom + 6 } + }); + }, [open]); + reactExports.useEffect(() => { + if (!open) return; + const handler = (e) => { + if (!isEventWithinNode(e, panelRef.current) && !isEventWithinNode(e, buttonRef.current)) { + setOpen(false); + } + }; + document.addEventListener("mousedown", handler); + return () => document.removeEventListener("mousedown", handler); + }, [open]); + reactExports.useEffect(() => { + if (!open) return; + const handler = (e) => { + if (e.key === "Escape") setOpen(false); + }; + document.addEventListener("keydown", handler); + return () => document.removeEventListener("keydown", handler); + }, [open]); + const handleSelect = reactExports.useCallback((emoji) => { + const native = extractNativeEmoji(emoji); + if (!native) { + setOpen(false); + return; + } + onSelect?.(native); + if (editor) { + editor.chain().focus().insertContent(native).run(); + } + setOpen(false); + }, [onSelect, editor]); + const panel = open ? reactDomExports.createPortal( + /* @__PURE__ */ React.createElement( + "div", + { + ref: panelRef, + style: panelStyle, + className: "rounded-xl shadow-2xl overflow-hidden" + }, + pickerData ? /* @__PURE__ */ React.createElement( + EmojiMartPicker, + { + data: pickerData, + onEmojiSelect: handleSelect, + theme: "dark", + previewPosition: "none", + skinTonePosition: "search", + maxFrequentRows: 2, + perLine: 9 + } + ) : /* @__PURE__ */ React.createElement("div", { className: "flex h-24 w-[352px] items-center justify-center bg-zinc-900 px-4 text-sm text-zinc-300" }, "Loading emojis...") + ), + document.body + ) : null; + return /* @__PURE__ */ React.createElement("div", { className: "relative" }, /* @__PURE__ */ React.createElement( + "button", + { + ref: buttonRef, + type: "button", + onClick: () => setOpen((v) => !v), + title: "Insert emoji", + "aria-label": "Open emoji picker", + "aria-expanded": open, + className: [ + "inline-flex h-8 w-8 items-center justify-center rounded-lg text-sm transition-colors", + "focus:outline-none focus-visible:ring-2 focus-visible:ring-sky-400", + open ? "bg-sky-600/25 text-sky-300" : "text-zinc-400 hover:bg-white/[0.06] hover:text-zinc-200" + ].join(" ") + }, + /* @__PURE__ */ React.createElement("span", { className: "text-[15px]" }, "😊") + ), panel); +} +function clamp$1(value, min2, max2) { + return Math.min(max2, Math.max(min2, value)); +} +function parsePixelValue(rawValue) { + const normalized = String(rawValue || "").trim(); + if (!normalized) { + return null; + } + const parsed = Number.parseFloat(normalized.replace(/px$/i, "")); + return Number.isFinite(parsed) ? Math.round(parsed) : null; +} +function readImageAttrs$1(element2) { + const imageElement = element2.tagName?.toLowerCase() === "img" ? element2 : element2.querySelector?.("img"); + const captionElement = element2.querySelector?.("figcaption"); + return { + src: imageElement?.getAttribute("src") || "", + alt: imageElement?.getAttribute("alt") || "", + title: imageElement?.getAttribute("title") || "", + caption: captionElement?.textContent?.trim() || "", + width: parsePixelValue( + element2.getAttribute?.("data-width") || element2.getAttribute?.("width") || imageElement?.getAttribute("width") || element2.style?.width || "" + ) + }; +} +function RichImageNodeView({ editor, node: node2, selected, updateAttributes, deleteNode, getPos }) { + const imageRef = reactExports.useRef(null); + const cleanupResizeRef = reactExports.useRef(null); + reactExports.useEffect(() => () => { + if (typeof cleanupResizeRef.current === "function") { + cleanupResizeRef.current(); + } + }, []); + const selectNode = reactExports.useCallback(() => { + if (!editor || typeof getPos !== "function") { + return; + } + editor.chain().focus().setNodeSelection(getPos()).run(); + }, [editor, getPos]); + const startResize = reactExports.useCallback((event) => { + if (!imageRef.current || event.button !== 0) { + return; + } + event.preventDefault(); + event.stopPropagation(); + selectNode(); + const imageElement = imageRef.current; + const parentWidth = imageElement.parentElement?.getBoundingClientRect().width || imageElement.getBoundingClientRect().width || 0; + const startX = event.clientX; + const startWidth = node2.attrs.width || Math.round(imageElement.getBoundingClientRect().width) || 0; + const minWidth = 180; + const maxWidth = Math.max(minWidth, Math.round(parentWidth || 1280)); + const handleMove = (moveEvent) => { + const nextWidth = clamp$1(Math.round(startWidth + (moveEvent.clientX - startX)), minWidth, maxWidth); + updateAttributes({ width: nextWidth }); + }; + const handleUp = () => { + window.removeEventListener("pointermove", handleMove); + window.removeEventListener("pointerup", handleUp); + cleanupResizeRef.current = null; + }; + cleanupResizeRef.current = handleUp; + window.addEventListener("pointermove", handleMove); + window.addEventListener("pointerup", handleUp); + }, [node2.attrs.width, selectNode, updateAttributes]); + const width = Number.isFinite(Number(node2.attrs.width)) && Number(node2.attrs.width) > 0 ? Number(node2.attrs.width) : null; + return /* @__PURE__ */ React.createElement( + NodeViewWrapper, + { + as: "figure", + className: [ + "rich-image-node", + selected ? "is-selected" : "" + ].filter(Boolean).join(" "), + "data-rich-image": "true", + onMouseDown: (event) => { + if (event.target instanceof HTMLElement && event.target.closest("input, textarea, button, select, label")) { + return; + } + selectNode(); + } + }, + /* @__PURE__ */ React.createElement("div", { className: "rich-image-node__frame" }, /* @__PURE__ */ React.createElement( + "img", + { + ref: imageRef, + src: node2.attrs.src, + alt: node2.attrs.alt || "", + title: node2.attrs.title || "", + className: "rich-image-node__img", + style: width ? { width: `${width}px` } : void 0 + } + ), selected ? /* @__PURE__ */ React.createElement( + "button", + { + type: "button", + "data-drag-handle": true, + className: "rich-image-node__drag-handle", + title: "Drag to move image", + onMouseDown: selectNode + }, + /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-grip-lines" }) + ) : null, selected ? /* @__PURE__ */ React.createElement( + "button", + { + type: "button", + className: "rich-image-node__resize-handle", + title: "Resize image", + onPointerDown: startResize + }, + /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-up-right-and-down-left-from-center" }) + ) : null), + !selected && node2.attrs.caption ? /* @__PURE__ */ React.createElement("figcaption", { className: "rich-image-node__caption" }, node2.attrs.caption) : null, + selected ? /* @__PURE__ */ React.createElement("div", { className: "rich-image-node__editor", contentEditable: false }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-3 md:grid-cols-2" }, /* @__PURE__ */ React.createElement("label", { className: "grid gap-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Alt text"), /* @__PURE__ */ React.createElement( + "input", + { + value: node2.attrs.alt || "", + onChange: (event) => updateAttributes({ alt: event.target.value }), + placeholder: "Describe the image for screen readers", + className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white outline-none" + } + )), /* @__PURE__ */ React.createElement("label", { className: "grid gap-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Caption"), /* @__PURE__ */ React.createElement( + "input", + { + value: node2.attrs.caption || "", + onChange: (event) => updateAttributes({ caption: event.target.value }), + placeholder: "Visible caption below the image", + className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white outline-none" + } + ))), /* @__PURE__ */ React.createElement("div", { className: "grid gap-3 md:grid-cols-[minmax(0,1fr)_auto_auto] md:items-end" }, /* @__PURE__ */ React.createElement("label", { className: "grid gap-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Width"), /* @__PURE__ */ React.createElement( + "input", + { + type: "number", + min: "180", + max: "2400", + value: width || "", + onChange: (event) => { + const nextValue = Number.parseInt(event.target.value, 10); + updateAttributes({ width: Number.isFinite(nextValue) ? nextValue : null }); + }, + placeholder: "Auto", + className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white outline-none" + } + )), /* @__PURE__ */ React.createElement( + "button", + { + type: "button", + onClick: () => updateAttributes({ width: null }), + className: "rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3 text-sm font-semibold text-white transition hover:bg-white/[0.08]" + }, + "Fit" + ), /* @__PURE__ */ React.createElement( + "button", + { + type: "button", + onClick: deleteNode, + className: "rounded-2xl border border-rose-300/20 bg-rose-400/10 px-4 py-3 text-sm font-semibold text-rose-100 transition hover:bg-rose-400/15" + }, + "Remove" + ))) : null + ); +} +const RichImage = index_default.extend({ + addOptions() { + return { + ...this.parent?.(), + HTMLAttributes: { + class: "rich-image-node" + } + }; + }, + addAttributes() { + return { + ...this.parent?.(), + alt: { + default: "" + }, + title: { + default: "" + }, + caption: { + default: "" + }, + width: { + default: null, + parseHTML: (element2) => parsePixelValue( + element2.getAttribute?.("data-width") || element2.getAttribute?.("width") || element2.style?.width || "" + ), + renderHTML: (attributes) => { + const width = Number(attributes.width); + if (!Number.isFinite(width) || width <= 0) { + return {}; + } + return { + "data-width": String(Math.round(width)), + style: `width:${Math.round(width)}px;max-width:100%;` + }; + } + } + }; + }, + parseHTML() { + return [ + { + tag: "figure[data-rich-image]", + getAttrs: (element2) => readImageAttrs$1(element2) + }, + { + tag: "img[src]", + getAttrs: (element2) => readImageAttrs$1(element2) + } + ]; + }, + renderHTML({ node: node2, HTMLAttributes }) { + const { + src: _src, + alt: _alt, + title: _title, + caption: _caption, + width: _width, + "data-width": _dataWidth, + ...figureHTMLAttributes + } = HTMLAttributes; + const figureAttributes = mergeAttributes(this.options.HTMLAttributes, figureHTMLAttributes, { + "data-rich-image": "true" + }); + const imageAttributes = { + src: node2.attrs.src, + alt: node2.attrs.alt || "", + title: node2.attrs.title || "", + loading: "lazy", + decoding: "async" + }; + if (Number.isFinite(Number(node2.attrs.width)) && Number(node2.attrs.width) > 0) { + const width = Math.round(Number(node2.attrs.width)); + imageAttributes.style = `width:${width}px;max-width:100%;`; + imageAttributes["data-width"] = String(width); + } + const children = [ + ["img", imageAttributes] + ]; + if (node2.attrs.caption) { + children.push(["figcaption", { class: "rich-image-node__caption" }, node2.attrs.caption]); + } + return ["figure", figureAttributes, ...children]; + }, + addNodeView() { + return ReactNodeViewRenderer(RichImageNodeView); + } +}); +function readImageAttrs(element2) { + const imageElements = Array.from(element2.querySelectorAll?.("img") || []); + const subtitleElement = element2.querySelector?.("figcaption"); + return { + leftSrc: imageElements[0]?.getAttribute("src") || "", + leftAlt: imageElements[0]?.getAttribute("alt") || "", + rightSrc: imageElements[1]?.getAttribute("src") || "", + rightAlt: imageElements[1]?.getAttribute("alt") || "", + subtitle: subtitleElement?.textContent?.trim() || "" + }; +} +function RichCompareNodeView({ editor, node: node2, selected, updateAttributes, deleteNode, getPos }) { + const selectNode = reactExports.useCallback(() => { + if (!editor || typeof getPos !== "function") { + return; + } + editor.chain().focus().setNodeSelection(getPos()).run(); + }, [editor, getPos]); + return /* @__PURE__ */ React.createElement( + NodeViewWrapper, + { + as: "figure", + className: ["rich-compare-node", selected ? "is-selected" : ""].filter(Boolean).join(" "), + "data-rich-compare": "true", + onMouseDown: (event) => { + if (event.target instanceof HTMLElement && event.target.closest("input, textarea, button, select, label")) { + return; + } + selectNode(); + } + }, + /* @__PURE__ */ React.createElement("div", { className: "rich-compare-node__grid" }, /* @__PURE__ */ React.createElement("div", { className: "rich-compare-node__tile" }, /* @__PURE__ */ React.createElement("span", { className: "rich-compare-node__badge" }, "Left"), /* @__PURE__ */ React.createElement( + "img", + { + src: node2.attrs.leftSrc, + alt: node2.attrs.leftAlt || "", + className: "rich-compare-node__img", + loading: "lazy", + decoding: "async" + } + )), /* @__PURE__ */ React.createElement("div", { className: "rich-compare-node__tile" }, /* @__PURE__ */ React.createElement("span", { className: "rich-compare-node__badge" }, "Right"), /* @__PURE__ */ React.createElement( + "img", + { + src: node2.attrs.rightSrc, + alt: node2.attrs.rightAlt || "", + className: "rich-compare-node__img", + loading: "lazy", + decoding: "async" + } + ))), + !selected && node2.attrs.subtitle ? /* @__PURE__ */ React.createElement("figcaption", { className: "rich-compare-node__subtitle" }, node2.attrs.subtitle) : null, + selected ? /* @__PURE__ */ React.createElement("div", { className: "rich-compare-node__editor", contentEditable: false }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-3 md:grid-cols-2" }, /* @__PURE__ */ React.createElement("label", { className: "grid gap-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Left alt text"), /* @__PURE__ */ React.createElement( + "input", + { + value: node2.attrs.leftAlt || "", + onChange: (event) => updateAttributes({ leftAlt: event.target.value }), + placeholder: "Describe the left image", + className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white outline-none" + } + )), /* @__PURE__ */ React.createElement("label", { className: "grid gap-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Right alt text"), /* @__PURE__ */ React.createElement( + "input", + { + value: node2.attrs.rightAlt || "", + onChange: (event) => updateAttributes({ rightAlt: event.target.value }), + placeholder: "Describe the right image", + className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white outline-none" + } + ))), /* @__PURE__ */ React.createElement("label", { className: "grid gap-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Subtitle"), /* @__PURE__ */ React.createElement( + "input", + { + value: node2.attrs.subtitle || "", + onChange: (event) => updateAttributes({ subtitle: event.target.value }), + placeholder: "Visible caption below the comparison", + className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white outline-none" + } + )), /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-2" }, /* @__PURE__ */ React.createElement( + "button", + { + type: "button", + onClick: selectNode, + className: "rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3 text-sm font-semibold text-white transition hover:bg-white/[0.08]" + }, + "Keep selected" + ), /* @__PURE__ */ React.createElement( + "button", + { + type: "button", + onClick: deleteNode, + className: "rounded-2xl border border-rose-300/20 bg-rose-400/10 px-4 py-3 text-sm font-semibold text-rose-100 transition hover:bg-rose-400/15" + }, + "Remove comparison" + ))) : null + ); +} +const RichCompare = Node3.create({ + name: "imageCompare", + group: "block", + atom: true, + addAttributes() { + return { + leftSrc: { default: "" }, + leftAlt: { default: "" }, + rightSrc: { default: "" }, + rightAlt: { default: "" }, + subtitle: { default: "" } + }; + }, + parseHTML() { + return [ + { + tag: "figure[data-rich-compare]", + getAttrs: (element2) => readImageAttrs(element2) + } + ]; + }, + renderHTML({ node: node2, HTMLAttributes }) { + const { + leftSrc: _leftSrc, + leftAlt: _leftAlt, + rightSrc: _rightSrc, + rightAlt: _rightAlt, + subtitle: _subtitle, + ...figureHTMLAttributes + } = HTMLAttributes; + const leftImageAttributes = { + src: node2.attrs.leftSrc, + alt: node2.attrs.leftAlt || "", + loading: "lazy", + decoding: "async", + class: "rich-compare-node__img" + }; + const rightImageAttributes = { + src: node2.attrs.rightSrc, + alt: node2.attrs.rightAlt || "", + loading: "lazy", + decoding: "async", + class: "rich-compare-node__img" + }; + return [ + "figure", + mergeAttributes(this.options.HTMLAttributes, figureHTMLAttributes, { + "data-rich-compare": "true" + }), + [ + "div", + { class: "rich-compare-node__grid" }, + ["div", { class: "rich-compare-node__tile" }, ["img", leftImageAttributes]], + ["div", { class: "rich-compare-node__tile" }, ["img", rightImageAttributes]] + ], + ...node2.attrs.subtitle ? [["figcaption", { class: "rich-compare-node__subtitle" }, node2.attrs.subtitle]] : [] + ]; + }, + addNodeView() { + return ReactNodeViewRenderer(RichCompareNodeView); + } +}); +function TableButton({ onClick, active = false, disabled = false, title, children }) { + return /* @__PURE__ */ React.createElement( + "button", + { + type: "button", + onMouseDown: (event) => { + event.preventDefault(); + }, + onClick, + disabled, + title, + className: [ + "inline-flex h-8 items-center justify-center rounded-lg px-2.5 text-[11px] font-semibold uppercase tracking-[0.14em] transition-colors", + "focus:outline-none focus-visible:ring-2 focus-visible:ring-sky-400", + active ? "bg-sky-600/25 text-sky-300" : "text-zinc-400 hover:bg-white/[0.06] hover:text-zinc-200", + disabled && "pointer-events-none opacity-30" + ].filter(Boolean).join(" ") + }, + children + ); +} +function TableInsertDialog({ + open, + rows, + cols, + withHeaderRow, + withHeaderColumn, + onRowsChange, + onColsChange, + onHeaderRowChange, + onHeaderColumnChange, + onClose, + onInsert +}) { + if (!open) return null; + return /* @__PURE__ */ React.createElement( + "div", + { + className: "fixed inset-0 z-[9999] flex items-center justify-center bg-[#04070dcc] px-4 backdrop-blur-md", + onClick: (event) => { + if (event.target === event.currentTarget) { + onClose?.(); + } + }, + role: "presentation" + }, + /* @__PURE__ */ React.createElement("div", { className: "w-full max-w-2xl overflow-hidden rounded-3xl border border-white/10 bg-[linear-gradient(180deg,rgba(16,22,34,0.98),rgba(8,12,19,0.98))] shadow-[0_30px_80px_rgba(0,0,0,0.55)]" }, /* @__PURE__ */ React.createElement("div", { className: "border-b border-white/[0.06] px-6 py-5" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.24em] text-white/35" }, "Table"), /* @__PURE__ */ React.createElement("h3", { className: "mt-2 text-lg font-semibold text-white" }, "Insert table"), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm leading-6 text-white/65" }, "Create a table and edit rows and columns directly in the editor.")), /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 px-6 py-5 md:grid-cols-2" }, /* @__PURE__ */ React.createElement("label", { className: "grid gap-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Rows"), /* @__PURE__ */ React.createElement( + "input", + { + type: "number", + min: "1", + max: "12", + value: rows, + onChange: (event) => onRowsChange?.(Number.parseInt(event.target.value, 10) || 1), + className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white outline-none" + } + )), /* @__PURE__ */ React.createElement("label", { className: "grid gap-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Columns"), /* @__PURE__ */ React.createElement( + "input", + { + type: "number", + min: "1", + max: "12", + value: cols, + onChange: (event) => onColsChange?.(Number.parseInt(event.target.value, 10) || 1), + className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white outline-none" + } + )), /* @__PURE__ */ React.createElement("label", { className: "flex items-start gap-3 rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-sm text-slate-200 md:col-span-2" }, /* @__PURE__ */ React.createElement( + "input", + { + type: "checkbox", + checked: withHeaderRow, + onChange: (event) => onHeaderRowChange?.(event.target.checked), + className: "mt-1" + } + ), /* @__PURE__ */ React.createElement("span", null, /* @__PURE__ */ React.createElement("span", { className: "block font-semibold text-white" }, "Header row"), /* @__PURE__ */ React.createElement("span", { className: "mt-1 block text-xs leading-5 text-slate-400" }, "Use a header row for column labels."))), /* @__PURE__ */ React.createElement("label", { className: "flex items-start gap-3 rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-sm text-slate-200 md:col-span-2" }, /* @__PURE__ */ React.createElement( + "input", + { + type: "checkbox", + checked: withHeaderColumn, + onChange: (event) => onHeaderColumnChange?.(event.target.checked), + className: "mt-1" + } + ), /* @__PURE__ */ React.createElement("span", null, /* @__PURE__ */ React.createElement("span", { className: "block font-semibold text-white" }, "Header column"), /* @__PURE__ */ React.createElement("span", { className: "mt-1 block text-xs leading-5 text-slate-400" }, "Use a header column for row labels.")))), /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-end gap-3 border-t border-white/[0.06] px-6 py-4" }, /* @__PURE__ */ React.createElement("button", { type: "button", onClick: onClose, className: "rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-2.5 text-sm font-semibold text-white transition hover:bg-white/[0.08]" }, "Cancel"), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: onInsert, className: "rounded-2xl border border-sky-300/20 bg-sky-400/10 px-4 py-2.5 text-sm font-semibold text-sky-100 transition hover:bg-sky-400/15" }, "Insert table"))) + ); +} +function RichTableControls({ editor }) { + const isTableActive = Boolean(editor?.isActive("table")); + const canRun = reactExports.useCallback((commandName) => { + if (!editor) return false; + try { + const chain = editor.can().chain().focus(); + const next = typeof chain[commandName] === "function" ? chain[commandName]() : null; + return Boolean(next?.run?.()); + } catch { + return false; + } + }, [editor]); + const runCommand = reactExports.useCallback((commandName) => { + if (!editor) return; + const chain = editor.chain().focus(); + if (typeof chain[commandName] !== "function") return; + chain[commandName]().run(); + }, [editor]); + const deleteTable = reactExports.useCallback(() => { + if (!editor) return; + editor.chain().focus().deleteTable().run(); + }, [editor]); + const getActiveTable = reactExports.useCallback(() => { + if (!editor) return null; + const { state } = editor; + const { $from } = state.selection; + for (let depth = $from.depth; depth >= 0; depth -= 1) { + const node2 = $from.node(depth); + if (node2?.type?.name !== "table") { + continue; + } + return { + node: node2, + depth, + pos: $from.before(depth) + }; + } + return null; + }, [editor]); + const moveTable = reactExports.useCallback((direction) => { + if (!editor) return; + const tableInfo = getActiveTable(); + if (!tableInfo) return; + const { state, view } = editor; + const { doc } = state; + const tableNode = tableInfo.node; + const tablePos = tableInfo.pos; + const tableSize = tableNode.nodeSize; + let childPos = 1; + let previous2 = null; + let current = null; + let next = null; + for (let index2 = 0; index2 < doc.childCount; index2 += 1) { + const child = doc.child(index2); + if (childPos === tablePos) { + current = { node: child, pos: childPos }; + next = index2 + 1 < doc.childCount ? { node: doc.child(index2 + 1), pos: childPos + child.nodeSize } : null; + break; + } + previous2 = { node: child, pos: childPos }; + childPos += child.nodeSize; + } + if (!current) return; + const tr = state.tr.delete(tablePos, tablePos + tableSize); + let insertPos = tablePos; + if (direction === "up") { + if (!previous2) return; + insertPos = previous2.pos; + } else if (direction === "down") { + if (!next) return; + insertPos = next.pos + next.node.nodeSize - tableSize; + } else { + return; + } + tr.insert(insertPos, tableNode.type.create(tableNode.attrs, tableNode.content, tableNode.marks)); + view.dispatch(tr); + editor.chain().focus().setNodeSelection(insertPos).run(); + }, [editor, getActiveTable]); + if (!editor) return null; + return /* @__PURE__ */ React.createElement( + BubbleMenu, + { + editor, + shouldShow: ({ editor: bubbleEditor }) => Boolean(bubbleEditor?.isActive("table")), + tippyOptions: { + placement: "top-start", + offset: [0, 12], + duration: 100 + }, + className: "rich-table-toolbar" + }, + /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center gap-2 rounded-2xl border border-sky-300/25 bg-[linear-gradient(180deg,rgba(12,18,29,0.98),rgba(6,10,16,0.98))] px-3 py-2 text-xs text-slate-400 shadow-[0_18px_50px_rgba(0,0,0,0.35)]" }, /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-1 font-semibold uppercase tracking-[0.16em] text-slate-300" }, "Table tools"), /* @__PURE__ */ React.createElement(TableButton, { onClick: () => runCommand("addRowBefore"), disabled: !canRun("addRowBefore"), title: "Add row before" }, "Row +"), /* @__PURE__ */ React.createElement(TableButton, { onClick: () => runCommand("addRowAfter"), disabled: !canRun("addRowAfter"), title: "Add row after" }, "Row +"), /* @__PURE__ */ React.createElement(TableButton, { onClick: () => runCommand("deleteRow"), disabled: !canRun("deleteRow"), title: "Delete row" }, "Del row"), /* @__PURE__ */ React.createElement(TableButton, { onClick: () => runCommand("addColumnBefore"), disabled: !canRun("addColumnBefore"), title: "Add column before" }, "Col +"), /* @__PURE__ */ React.createElement(TableButton, { onClick: () => runCommand("addColumnAfter"), disabled: !canRun("addColumnAfter"), title: "Add column after" }, "Col +"), /* @__PURE__ */ React.createElement(TableButton, { onClick: () => runCommand("deleteColumn"), disabled: !canRun("deleteColumn"), title: "Delete column" }, "Del col"), /* @__PURE__ */ React.createElement(TableButton, { onClick: () => runCommand("mergeCells"), disabled: !canRun("mergeCells"), title: "Merge selected cells" }, "Merge"), /* @__PURE__ */ React.createElement(TableButton, { onClick: () => runCommand("splitCell"), disabled: !canRun("splitCell"), title: "Split selected cell" }, "Split"), /* @__PURE__ */ React.createElement(TableButton, { onClick: () => runCommand("toggleHeaderRow"), disabled: !canRun("toggleHeaderRow"), active: isTableActive, title: "Toggle header row" }, "Header row"), /* @__PURE__ */ React.createElement(TableButton, { onClick: () => runCommand("toggleHeaderColumn"), disabled: !canRun("toggleHeaderColumn"), active: isTableActive, title: "Toggle header column" }, "Header col"), /* @__PURE__ */ React.createElement(TableButton, { onClick: () => moveTable("up"), disabled: !getActiveTable(), title: "Move table up" }, "Move up"), /* @__PURE__ */ React.createElement(TableButton, { onClick: () => moveTable("down"), disabled: !getActiveTable(), title: "Move table down" }, "Move down"), /* @__PURE__ */ React.createElement(TableButton, { onClick: deleteTable, title: "Delete table" }, "Delete table")) + ); +} +function ToolbarBtn$2({ onClick, active, disabled, title, children, className = "" }) { + return /* @__PURE__ */ React.createElement( + "button", + { + type: "button", + onMouseDown: (event) => { + event.preventDefault(); + }, + onClick, + disabled, + title, + className: [ + "inline-flex h-8 w-8 items-center justify-center rounded-lg text-sm transition-colors", + "focus:outline-none focus-visible:ring-2 focus-visible:ring-sky-400", + active ? "bg-sky-600/25 text-sky-300" : "text-zinc-400 hover:bg-white/[0.06] hover:text-zinc-200", + disabled && "pointer-events-none opacity-30", + className + ].filter(Boolean).join(" ") + }, + children + ); +} +function Divider$1() { + return /* @__PURE__ */ React.createElement("div", { className: "mx-1 h-5 w-px bg-white/10" }); +} +function normalizeHttpUrl(rawValue) { + const trimmed = String(rawValue || "").trim(); + if (trimmed === "") { + return null; + } + const withProtocol = /^[a-z][a-z0-9+.-]*:\/\//i.test(trimmed) ? trimmed : `https://${trimmed.replace(/^\/+/, "")}`; + try { + const parsed = new URL(withProtocol); + if (!["http:", "https:"].includes(parsed.protocol)) { + return null; + } + return parsed.toString(); + } catch { + return null; + } +} +function normalizeVideoEmbedUrl(rawValue) { + const normalized = normalizeHttpUrl(rawValue); + if (!normalized) { + return null; + } + const parsed = new URL(normalized); + const host = parsed.hostname.replace(/^www\./i, "").toLowerCase(); + const path = parsed.pathname; + if (host === "youtu.be") { + const videoId = path.replace(/^\//, "").split("/")[0]; + return videoId ? `https://www.youtube.com/embed/${videoId}` : normalized; + } + if (host === "youtube.com" || host === "m.youtube.com") { + if (path === "/watch") { + const videoId = parsed.searchParams.get("v"); + return videoId ? `https://www.youtube.com/embed/${videoId}` : normalized; + } + const pathMatch = path.match(/^\/(embed|shorts|live)\/([^/?#]+)/i); + if (pathMatch?.[2]) { + return `https://www.youtube.com/embed/${pathMatch[2]}`; + } + } + return normalized; +} +function detectSocialPlatform(rawUrl) { + const normalized = normalizeHttpUrl(rawUrl); + if (!normalized) { + return { platform: "social", label: "Social post", url: null }; + } + const host = new URL(normalized).hostname.replace(/^www\./i, "").toLowerCase(); + if (host.includes("instagram.")) return { platform: "instagram", label: "Instagram post", url: normalized }; + if (host.includes("facebook.")) return { platform: "facebook", label: "Facebook post", url: normalized }; + if (host.includes("tiktok.")) return { platform: "tiktok", label: "TikTok post", url: normalized }; + if (host.includes("twitter.") || host.includes("x.com")) return { platform: "x", label: "X post", url: normalized }; + if (host.includes("linkedin.")) return { platform: "linkedin", label: "LinkedIn post", url: normalized }; + if (host.includes("threads.")) return { platform: "threads", label: "Threads post", url: normalized }; + if (host.includes("pinterest.")) return { platform: "pinterest", label: "Pinterest pin", url: normalized }; + return { platform: "social", label: "Social post", url: normalized }; +} +const ArtworkEmbed = Node3.create({ + name: "artworkEmbed", + group: "block", + atom: true, + addAttributes() { + return { + title: { default: "Artwork" }, + url: { default: "" }, + thumb: { default: "" } + }; + }, + parseHTML() { + return [{ tag: "figure[data-artwork-embed]" }]; + }, + renderHTML({ HTMLAttributes }) { + const preview = []; + if (HTMLAttributes.thumb) { + preview.push([ + "img", + { + src: HTMLAttributes.thumb, + alt: HTMLAttributes.title || "Artwork", + class: "block h-auto w-full object-cover", + loading: "lazy" + } + ]); + } + preview.push([ + "figcaption", + { class: "news-embed-caption" }, + HTMLAttributes.title || "Artwork" + ]); + return [ + "figure", + mergeAttributes(HTMLAttributes, { + "data-artwork-embed": "true", + class: "news-embed news-embed-artwork" + }), + [ + "a", + { + href: HTMLAttributes.url || "#", + class: "news-embed-link", + rel: "noopener noreferrer nofollow", + target: "_blank" + }, + ...preview + ] + ]; + } +}); +const VideoEmbed = Node3.create({ + name: "videoEmbed", + group: "block", + atom: true, + addAttributes() { + return { + src: { default: "" }, + url: { default: "" }, + title: { default: "Embedded video" } + }; + }, + parseHTML() { + return [{ tag: "figure[data-video-embed]" }]; + }, + renderHTML({ HTMLAttributes }) { + return [ + "figure", + mergeAttributes(HTMLAttributes, { + "data-video-embed": "true", + class: "news-embed news-embed-video w-full" + }), + [ + "iframe", + { + src: HTMLAttributes.src || "", + title: HTMLAttributes.title || "Embedded video", + loading: "lazy", + frameborder: "0", + allow: "accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share", + allowfullscreen: "true", + referrerpolicy: "strict-origin-when-cross-origin" + } + ] + ]; + } +}); +const SocialEmbed = Node3.create({ + name: "socialEmbed", + group: "block", + atom: true, + addAttributes() { + return { + url: { default: "" }, + platform: { default: "social" }, + label: { default: "Social post" } + }; + }, + parseHTML() { + return [{ tag: "figure[data-social-embed]" }]; + }, + renderHTML({ HTMLAttributes }) { + const platform2 = String(HTMLAttributes.platform || "social"); + const url = HTMLAttributes.url || "#"; + const label = HTMLAttributes.label || "Social post"; + if (platform2 === "instagram") { + return [ + "figure", + mergeAttributes(HTMLAttributes, { + "data-social-embed": "true", + "data-platform": platform2, + class: "news-embed news-embed-social" + }), + [ + "blockquote", + { + class: "instagram-media", + "data-instgrm-captioned": "true", + "data-instgrm-permalink": url, + "data-instgrm-version": "14" + }, + [ + "a", + { href: url, rel: "noopener noreferrer nofollow", target: "_blank" }, + label + ] + ] + ]; + } + if (platform2 === "facebook") { + return [ + "figure", + mergeAttributes(HTMLAttributes, { + "data-social-embed": "true", + "data-platform": platform2, + class: "news-embed news-embed-social" + }), + [ + "div", + { class: "fb-post", "data-href": url, "data-show-text": "true" }, + [ + "blockquote", + { cite: url, class: "fb-xfbml-parse-ignore" }, + [ + "a", + { href: url, rel: "noopener noreferrer nofollow", target: "_blank" }, + label + ] + ] + ] + ]; + } + if (platform2 === "tiktok") { + return [ + "figure", + mergeAttributes(HTMLAttributes, { + "data-social-embed": "true", + "data-platform": platform2, + class: "news-embed news-embed-social" + }), + [ + "blockquote", + { class: "tiktok-embed", cite: url }, + [ + "section", + null, + [ + "a", + { href: url, rel: "noopener noreferrer nofollow", target: "_blank" }, + label + ] + ] + ] + ]; + } + if (platform2 === "x") { + return [ + "figure", + mergeAttributes(HTMLAttributes, { + "data-social-embed": "true", + "data-platform": platform2, + class: "news-embed news-embed-social" + }), + [ + "blockquote", + { class: "twitter-tweet" }, + [ + "a", + { href: url, rel: "noopener noreferrer nofollow", target: "_blank" }, + label + ] + ] + ]; + } + return [ + "figure", + mergeAttributes(HTMLAttributes, { + "data-social-embed": "true", + "data-platform": platform2, + class: "news-embed news-embed-social" + }), + [ + "a", + { + href: url, + class: "news-embed-link", + rel: "noopener noreferrer nofollow", + target: "_blank" + }, + ["span", { class: "news-embed-badge" }, label], + ["span", { class: "news-embed-url" }, url] + ] + ]; + } +}); +function ArtworkPickerDialog({ + open, + query, + items, + loading, + onQueryChange, + onClose, + onSearch, + onSelect +}) { + if (!open) return null; + return reactDomExports.createPortal( + /* @__PURE__ */ React.createElement( + "div", + { + className: "fixed inset-0 z-[9999] flex items-center justify-center bg-[#04070dcc] px-4 backdrop-blur-md", + onClick: (event) => { + if (event.target === event.currentTarget) { + onClose?.(); + } + }, + role: "presentation" + }, + /* @__PURE__ */ React.createElement("div", { className: "w-full max-w-3xl overflow-hidden rounded-3xl border border-white/10 bg-[linear-gradient(180deg,rgba(16,22,34,0.98),rgba(8,12,19,0.98))] shadow-[0_30px_80px_rgba(0,0,0,0.55)]" }, /* @__PURE__ */ React.createElement("div", { className: "border-b border-white/[0.06] px-6 py-5" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.24em] text-white/35" }, "Artwork embed"), /* @__PURE__ */ React.createElement("h3", { className: "mt-2 text-lg font-semibold text-white" }, "Choose artwork"), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm leading-6 text-white/65" }, "Search existing artworks and insert a linked artwork card into the News article body.")), /* @__PURE__ */ React.createElement("div", { className: "border-b border-white/[0.06] px-6 py-4" }, /* @__PURE__ */ React.createElement("div", { className: "flex gap-3" }, /* @__PURE__ */ React.createElement( + "input", + { + value: query, + onChange: (event) => onQueryChange?.(event.target.value), + onKeyDown: (event) => { + if (event.key === "Enter") { + event.preventDefault(); + onSearch?.(); + } + }, + placeholder: "Search by title, slug, or creator", + className: "min-w-0 flex-1 rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white outline-none" + } + ), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: onSearch, className: "rounded-2xl border border-sky-300/20 bg-sky-400/10 px-4 py-3 text-sm font-semibold text-sky-100 transition hover:bg-sky-400/15" }, "Search"))), /* @__PURE__ */ React.createElement("div", { className: "nova-scrollbar max-h-[60vh] overflow-y-auto px-6 py-5" }, loading ? /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-black/20 p-4 text-sm text-slate-300" }, "Searching artworks…") : null, !loading && (!Array.isArray(items) || items.length === 0) ? /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-dashed border-white/10 bg-white/[0.02] p-4 text-sm text-slate-400" }, "No artworks found yet. Try a broader title or creator search.") : null, !loading && Array.isArray(items) && items.length > 0 ? /* @__PURE__ */ React.createElement("div", { className: "grid gap-3" }, items.map((item) => { + const previewImage = item.image || item.avatar || ""; + return /* @__PURE__ */ React.createElement( + "button", + { + key: `${item.entity_type || "artwork"}-${item.id}`, + type: "button", + onClick: () => onSelect?.(item), + className: "flex items-center gap-4 rounded-[24px] border border-white/10 bg-black/20 p-3 text-left transition hover:border-white/20 hover:bg-white/[0.04]" + }, + /* @__PURE__ */ React.createElement("div", { className: "h-20 w-28 shrink-0 overflow-hidden rounded-2xl border border-white/10 bg-white/[0.03]" }, previewImage ? /* @__PURE__ */ React.createElement("img", { src: previewImage, alt: item.title, className: "h-full w-full object-cover" }) : /* @__PURE__ */ React.createElement("div", { className: "flex h-full items-center justify-center text-xs uppercase tracking-[0.18em] text-slate-500" }, "No thumb")), + /* @__PURE__ */ React.createElement("div", { className: "min-w-0 flex-1" }, /* @__PURE__ */ React.createElement("div", { className: "text-sm font-semibold text-white" }, item.title), item.subtitle ? /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-xs uppercase tracking-[0.14em] text-slate-500" }, item.subtitle) : null, item.description ? /* @__PURE__ */ React.createElement("div", { className: "mt-2 line-clamp-2 text-xs leading-5 text-slate-400" }, item.description) : null) + ); + })) : null), /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-end gap-3 border-t border-white/[0.06] px-6 py-4" }, /* @__PURE__ */ React.createElement("button", { type: "button", onClick: onClose, className: "rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-2.5 text-sm font-semibold text-white transition hover:bg-white/[0.08]" }, "Cancel"))) + ), + document.body + ); +} +function MediaImageDialog({ + open, + uploading, + error, + previewUrl, + imageUrl, + altText, + uploadLabel, + helperText, + allowUpload, + onClose, + onImageUrlChange, + onAltTextChange, + onPickFile, + onBrowseAssets, + onInsert, + onClearUploaded +}) { + const inputRef = reactExports.useRef(null); + if (!open) return null; + return reactDomExports.createPortal( + /* @__PURE__ */ React.createElement( + "div", + { + className: "fixed inset-0 z-[9999] flex items-center justify-center bg-[#04070dcc] px-4 backdrop-blur-md", + onClick: (event) => { + if (event.target === event.currentTarget) { + onClose?.(); + } + }, + role: "presentation" + }, + /* @__PURE__ */ React.createElement("div", { className: "w-full max-w-4xl overflow-hidden rounded-3xl border border-white/10 bg-[linear-gradient(180deg,rgba(16,22,34,0.98),rgba(8,12,19,0.98))] shadow-[0_30px_80px_rgba(0,0,0,0.55)]" }, /* @__PURE__ */ React.createElement("div", { className: "border-b border-white/[0.06] px-6 py-5" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.24em] text-white/35" }, "Media"), /* @__PURE__ */ React.createElement("h3", { className: "mt-2 text-lg font-semibold text-white" }, "Add image"), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm leading-6 text-white/65" }, "Upload, drag, paste, or link an image without leaving the editor.")), /* @__PURE__ */ React.createElement("div", { className: "grid gap-6 px-6 py-5 lg:grid-cols-[minmax(0,1fr)_320px]" }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-4" }, allowUpload ? /* @__PURE__ */ React.createElement( + "div", + { + role: "button", + tabIndex: 0, + onClick: () => !uploading && inputRef.current?.click(), + onKeyDown: (event) => { + if (uploading) return; + if (event.key === "Enter" || event.key === " ") { + event.preventDefault(); + inputRef.current?.click(); + } + }, + onDragOver: (event) => { + event.preventDefault(); + }, + onDrop: (event) => { + event.preventDefault(); + void onPickFile?.(event.dataTransfer?.files?.[0] || null); + }, + className: [ + "rounded-[24px] border border-dashed px-5 py-5 transition outline-none", + uploading ? "cursor-progress border-sky-300/35 bg-sky-400/10" : "cursor-pointer border-white/10 bg-black/20 hover:border-white/20 hover:bg-white/[0.04]" + ].join(" ") + }, + /* @__PURE__ */ React.createElement("div", { className: "flex items-start gap-4" }, /* @__PURE__ */ React.createElement("div", { className: "flex h-12 w-12 shrink-0 items-center justify-center rounded-2xl border border-sky-300/20 bg-sky-400/10 text-sky-100" }, /* @__PURE__ */ React.createElement("i", { className: `fa-solid ${uploading ? "fa-circle-notch fa-spin" : "fa-cloud-arrow-up"}` })), /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "text-sm font-semibold text-white" }, uploading ? "Uploading image…" : uploadLabel || "Drop image here or browse"), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-xs leading-5 text-slate-400" }, helperText), /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-xs leading-5 text-slate-500" }, "You can also paste an image directly into the editor or drag one into the writing area."))), + /* @__PURE__ */ React.createElement( + "input", + { + ref: inputRef, + type: "file", + accept: "image/jpeg,image/png,image/webp", + className: "hidden", + onChange: (event) => { + void onPickFile?.(event.target.files?.[0] || null); + event.target.value = ""; + } + } + ) + ) : null, /* @__PURE__ */ React.createElement("label", { className: "grid gap-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Image URL"), /* @__PURE__ */ React.createElement( + "input", + { + value: imageUrl, + onChange: (event) => onImageUrlChange?.(event.target.value), + placeholder: "https://files.skinbase.org/...", + className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white outline-none" + } + )), /* @__PURE__ */ React.createElement("label", { className: "grid gap-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Alt text"), /* @__PURE__ */ React.createElement( + "input", + { + value: altText, + onChange: (event) => onAltTextChange?.(event.target.value), + placeholder: "Describe what the image shows", + className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white outline-none" + } + )), error ? /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-rose-300/20 bg-rose-400/10 px-4 py-3 text-sm text-rose-100" }, error) : null), /* @__PURE__ */ React.createElement("div", { className: "grid gap-4" }, /* @__PURE__ */ React.createElement("div", { className: "overflow-hidden rounded-[24px] border border-white/10 bg-slate-950" }, previewUrl ? /* @__PURE__ */ React.createElement("img", { src: previewUrl, alt: "Media preview", className: "h-64 w-full object-cover" }) : /* @__PURE__ */ React.createElement("div", { className: "flex h-64 items-center justify-center px-6 text-center text-sm text-slate-500" }, "No media selected yet.")), /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-2" }, allowUpload ? /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => inputRef.current?.click(), className: "rounded-full border border-white/10 bg-white/[0.04] px-4 py-2 text-sm font-semibold text-white transition hover:bg-white/[0.08]" }, "Browse") : null, onBrowseAssets ? /* @__PURE__ */ React.createElement("button", { type: "button", onClick: onBrowseAssets, className: "rounded-full border border-white/10 bg-white/[0.04] px-4 py-2 text-sm font-semibold text-white transition hover:bg-white/[0.08]" }, "Choose from assets") : null, previewUrl ? /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => onClearUploaded?.(), className: "rounded-full border border-white/10 bg-transparent px-4 py-2 text-sm font-semibold text-slate-300 transition hover:bg-white/[0.04]" }, "Clear") : null))), /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-end gap-3 border-t border-white/[0.06] px-6 py-4" }, /* @__PURE__ */ React.createElement("button", { type: "button", onClick: onClose, className: "rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-2.5 text-sm font-semibold text-white transition hover:bg-white/[0.08]" }, "Cancel"), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: onInsert, disabled: !previewUrl || uploading, className: "rounded-2xl border border-sky-300/20 bg-sky-400/10 px-4 py-2.5 text-sm font-semibold text-sky-100 transition hover:bg-sky-400/15 disabled:cursor-not-allowed disabled:opacity-40" }, "Insert image"))) + ), + document.body + ); +} +function CompareImageDialog({ + open, + uploading, + error, + subtitle, + leftImage, + rightImage, + allowUpload, + onClose, + onSubtitleChange, + onLeftAltTextChange, + onRightAltTextChange, + onLeftPickFile, + onRightPickFile, + onLeftBrowseAssets, + onRightBrowseAssets, + onLeftClear, + onRightClear, + onInsert +}) { + const leftInputRef = reactExports.useRef(null); + const rightInputRef = reactExports.useRef(null); + if (!open) return null; + const renderSide = (sideLabel, image2, inputRef, onPickFile, onClear, onAltTextChange, onBrowseAssets) => /* @__PURE__ */ React.createElement( + "div", + { + role: "button", + tabIndex: 0, + onClick: (event) => { + if (event.target !== event.currentTarget) { + return; + } + if (!uploading && allowUpload) { + inputRef.current?.click(); + } + }, + onKeyDown: (event) => { + if (event.target !== event.currentTarget) { + return; + } + if (uploading || !allowUpload) return; + if (event.key === "Enter" || event.key === " ") { + event.preventDefault(); + inputRef.current?.click(); + } + }, + onDragOver: (event) => { + event.preventDefault(); + }, + onDrop: (event) => { + event.preventDefault(); + void onPickFile?.(event.dataTransfer?.files?.[0] || null); + }, + className: [ + "grid gap-4 rounded-[24px] border border-dashed px-5 py-5 transition outline-none", + uploading ? "cursor-progress border-sky-300/35 bg-sky-400/10" : "cursor-pointer border-white/10 bg-black/20 hover:border-white/20 hover:bg-white/[0.04]" + ].join(" ") + }, + /* @__PURE__ */ React.createElement("div", { className: "flex items-start gap-4" }, /* @__PURE__ */ React.createElement("div", { className: "flex h-12 w-12 shrink-0 items-center justify-center rounded-2xl border border-sky-300/20 bg-sky-400/10 text-sky-100" }, /* @__PURE__ */ React.createElement("i", { className: `fa-solid ${uploading ? "fa-circle-notch fa-spin" : "fa-images"}` })), /* @__PURE__ */ React.createElement("div", { className: "min-w-0 flex-1" }, /* @__PURE__ */ React.createElement("div", { className: "text-sm font-semibold text-white" }, sideLabel), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-xs leading-5 text-slate-400" }, "Upload the image for this side of the comparison."))), + /* @__PURE__ */ React.createElement("div", { className: "overflow-hidden rounded-[20px] border border-white/10 bg-slate-950" }, image2.previewUrl ? /* @__PURE__ */ React.createElement("img", { src: image2.previewUrl, alt: `${sideLabel} preview`, className: "h-56 w-full object-cover" }) : /* @__PURE__ */ React.createElement("div", { className: "flex h-56 items-center justify-center px-6 text-center text-sm text-slate-500" }, "No image selected yet.")), + /* @__PURE__ */ React.createElement("label", { className: "grid gap-2 text-sm text-slate-300", onClick: (event) => event.stopPropagation() }, /* @__PURE__ */ React.createElement("span", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Alt text"), /* @__PURE__ */ React.createElement( + "input", + { + value: image2.altText, + onChange: (event) => onAltTextChange?.(event.target.value), + placeholder: `Describe the ${sideLabel.toLowerCase()} image`, + className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white outline-none" + } + )), + /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-2", onClick: (event) => event.stopPropagation() }, allowUpload ? /* @__PURE__ */ React.createElement( + "button", + { + type: "button", + onClick: (event) => { + event.stopPropagation(); + inputRef.current?.click(); + }, + className: "rounded-full border border-white/10 bg-white/[0.04] px-4 py-2 text-sm font-semibold text-white transition hover:bg-white/[0.08]" + }, + "Browse" + ) : null, onBrowseAssets ? /* @__PURE__ */ React.createElement( + "button", + { + type: "button", + onClick: (event) => { + event.stopPropagation(); + onBrowseAssets(); + }, + className: "rounded-full border border-white/10 bg-white/[0.04] px-4 py-2 text-sm font-semibold text-white transition hover:bg-white/[0.08]" + }, + "Choose from assets" + ) : null, image2.previewUrl ? /* @__PURE__ */ React.createElement( + "button", + { + type: "button", + onClick: (event) => { + event.stopPropagation(); + onClear?.(); + }, + className: "rounded-full border border-white/10 bg-transparent px-4 py-2 text-sm font-semibold text-slate-300 transition hover:bg-white/[0.04]" + }, + "Clear" + ) : null), + /* @__PURE__ */ React.createElement( + "input", + { + ref: inputRef, + type: "file", + accept: "image/jpeg,image/png,image/webp", + className: "hidden", + onChange: (event) => { + void onPickFile?.(event.target.files?.[0] || null); + event.target.value = ""; + } + } + ) + ); + return reactDomExports.createPortal( + /* @__PURE__ */ React.createElement( + "div", + { + className: "fixed inset-0 z-[9999] flex items-center justify-center bg-[#04070dcc] px-4 backdrop-blur-md", + onClick: (event) => { + if (event.target === event.currentTarget) { + onClose?.(); + } + }, + role: "presentation" + }, + /* @__PURE__ */ React.createElement("div", { className: "w-full max-w-6xl overflow-hidden rounded-3xl border border-white/10 bg-[linear-gradient(180deg,rgba(16,22,34,0.98),rgba(8,12,19,0.98))] shadow-[0_30px_80px_rgba(0,0,0,0.55)]" }, /* @__PURE__ */ React.createElement("div", { className: "border-b border-white/[0.06] px-6 py-5" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.24em] text-white/35" }, "Image comparison"), /* @__PURE__ */ React.createElement("h3", { className: "mt-2 text-lg font-semibold text-white" }, "Add side-by-side images"), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm leading-6 text-white/65" }, "Upload two images, add alt text for each, and include a subtitle under the comparison.")), /* @__PURE__ */ React.createElement("div", { className: "grid gap-6 px-6 py-5 xl:grid-cols-2" }, renderSide("Left image", leftImage, leftInputRef, onLeftPickFile, onLeftClear, onLeftAltTextChange, onLeftBrowseAssets), renderSide("Right image", rightImage, rightInputRef, onRightPickFile, onRightClear, onRightAltTextChange, onRightBrowseAssets)), /* @__PURE__ */ React.createElement("div", { className: "border-t border-white/[0.06] px-6 py-5" }, /* @__PURE__ */ React.createElement("label", { className: "grid gap-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Subtitle"), /* @__PURE__ */ React.createElement( + "input", + { + value: subtitle, + onChange: (event) => onSubtitleChange?.(event.target.value), + placeholder: "Visible subtitle below the comparison", + className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white outline-none" + } + )), error ? /* @__PURE__ */ React.createElement("div", { className: "mt-4 rounded-2xl border border-rose-300/20 bg-rose-400/10 px-4 py-3 text-sm text-rose-100" }, error) : null), /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-end gap-3 border-t border-white/[0.06] px-6 py-4" }, /* @__PURE__ */ React.createElement("button", { type: "button", onClick: onClose, className: "rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-2.5 text-sm font-semibold text-white transition hover:bg-white/[0.08]" }, "Cancel"), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: onInsert, disabled: !leftImage.previewUrl || !rightImage.previewUrl || uploading, className: "rounded-2xl border border-sky-300/20 bg-sky-400/10 px-4 py-2.5 text-sm font-semibold text-sky-100 transition hover:bg-sky-400/15 disabled:cursor-not-allowed disabled:opacity-40" }, "Insert comparison"))) + ), + document.body + ); +} +function AssetPickerDialog({ + open, + searchQuery, + assets, + loading, + error, + pagination, + onClose, + onRefresh, + onSearchQueryChange, + onSearch, + onPreviousPage, + onNextPage, + onSelect +}) { + if (!open) return null; + return reactDomExports.createPortal( + /* @__PURE__ */ React.createElement( + "div", + { + className: "fixed inset-0 z-[9999] flex items-center justify-center bg-[#04070dcc] px-4 backdrop-blur-md", + onClick: (event) => { + if (event.target === event.currentTarget) { + onClose?.(); + } + }, + role: "presentation" + }, + /* @__PURE__ */ React.createElement("div", { className: "w-full max-w-6xl overflow-hidden rounded-3xl border border-white/10 bg-[linear-gradient(180deg,rgba(16,22,34,0.98),rgba(8,12,19,0.98))] shadow-[0_30px_80px_rgba(0,0,0,0.55)]" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-start justify-between gap-4 border-b border-white/[0.06] px-6 py-5" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.24em] text-white/35" }, "Academy assets"), /* @__PURE__ */ React.createElement("h3", { className: "mt-2 text-lg font-semibold text-white" }, "Choose an uploaded image"), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm leading-6 text-white/65" }, "Pick from previously uploaded Academy lesson images instead of uploading a new file.")), /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center gap-2" }, /* @__PURE__ */ React.createElement("button", { type: "button", onClick: onRefresh, className: "rounded-full border border-white/10 bg-white/[0.04] px-4 py-2 text-sm font-semibold text-white transition hover:bg-white/[0.08]" }, "Refresh"))), /* @__PURE__ */ React.createElement("div", { className: "border-b border-white/[0.06] px-6 py-4" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-col gap-3 lg:flex-row lg:items-center" }, /* @__PURE__ */ React.createElement( + "input", + { + value: searchQuery, + onChange: (event) => onSearchQueryChange?.(event.target.value), + onKeyDown: (event) => { + if (event.key === "Enter") { + event.preventDefault(); + onSearch?.(); + } + }, + placeholder: "Search academy assets", + className: "min-w-0 flex-1 rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white outline-none" + } + ), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: onSearch, className: "rounded-2xl border border-sky-300/20 bg-sky-400/10 px-4 py-3 text-sm font-semibold text-sky-100 transition hover:bg-sky-400/15" }, "Search"))), /* @__PURE__ */ React.createElement("div", { className: "nova-scrollbar max-h-[68vh] overflow-y-auto px-6 py-5" }, loading ? /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-black/20 p-4 text-sm text-slate-300" }, "Loading academy assets…") : null, error ? /* @__PURE__ */ React.createElement("div", { className: "mb-4 rounded-2xl border border-rose-300/20 bg-rose-400/10 px-4 py-3 text-sm text-rose-100" }, error) : null, !loading && (!Array.isArray(assets) || assets.length === 0) ? /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-dashed border-white/10 bg-white/[0.02] p-4 text-sm text-slate-400" }, "No academy images found yet. Upload one first.") : null, !loading && Array.isArray(assets) && assets.length > 0 ? /* @__PURE__ */ React.createElement("div", { className: "grid gap-3 sm:grid-cols-2 xl:grid-cols-3" }, assets.map((asset) => /* @__PURE__ */ React.createElement( + "button", + { + key: asset.path, + type: "button", + onClick: () => onSelect?.(asset), + className: "group overflow-hidden rounded-[24px] border border-white/10 bg-black/20 text-left transition hover:border-sky-300/30 hover:bg-white/[0.04]" + }, + /* @__PURE__ */ React.createElement("div", { className: "aspect-[4/3] overflow-hidden bg-slate-950" }, /* @__PURE__ */ React.createElement("img", { src: asset.url, alt: asset.name || "Academy asset", className: "h-full w-full object-cover transition duration-300 group-hover:scale-[1.02]", loading: "lazy" })), + /* @__PURE__ */ React.createElement("div", { className: "space-y-2 p-4" }, /* @__PURE__ */ React.createElement("div", { className: "text-sm font-semibold text-white" }, asset.name || "Academy image"), /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-2 text-[11px] font-semibold uppercase tracking-[0.14em] text-slate-500" }, asset.slot ? /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.04] px-2.5 py-1" }, asset.slot) : null, asset.modified_at ? /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.04] px-2.5 py-1" }, new Date(asset.modified_at).toLocaleDateString()) : null)) + ))) : null), /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center justify-between gap-3 border-t border-white/[0.06] px-6 py-4" }, /* @__PURE__ */ React.createElement("div", { className: "text-xs font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Page ", pagination?.page || 1, " of ", pagination?.last_page || 1, typeof pagination?.total === "number" ? ` · ${pagination.total} assets` : ""), /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-2" }, /* @__PURE__ */ React.createElement( + "button", + { + type: "button", + onClick: onPreviousPage, + disabled: (pagination?.page || 1) <= 1 || loading, + className: "rounded-full border border-white/10 bg-white/[0.04] px-4 py-2 text-sm font-semibold text-white transition hover:bg-white/[0.08] disabled:cursor-not-allowed disabled:opacity-40" + }, + "Previous" + ), /* @__PURE__ */ React.createElement( + "button", + { + type: "button", + onClick: onNextPage, + disabled: !pagination?.has_more || loading, + className: "rounded-full border border-white/10 bg-white/[0.04] px-4 py-2 text-sm font-semibold text-white transition hover:bg-white/[0.08] disabled:cursor-not-allowed disabled:opacity-40" + }, + "Next" + ))), /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-end gap-3 border-t border-white/[0.06] px-6 py-4" }, /* @__PURE__ */ React.createElement("button", { type: "button", onClick: onClose, className: "rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-2.5 text-sm font-semibold text-white transition hover:bg-white/[0.08]" }, "Cancel"))) + ), + document.body + ); +} +function Toolbar$1({ + editor, + advancedNews = false, + sourceMode = false, + showStructureOutlines = false, + showComparisonTool = false, + onToggleSourceMode, + onToggleStructureOutlines, + onInsertArtwork, + onInsertImage, + onInsertComparison, + onInsertTable, + onInsertSocialEmbed, + onInsertVideoEmbed, + onInsertHashtag, + editorViewportHeight, + onIncreaseEditorViewportHeight, + onDecreaseEditorViewportHeight, + onResetEditorViewportHeight +}) { + if (!editor) return null; + const addLink = reactExports.useCallback(() => { + const prev = editor.getAttributes("link").href; + const url = window.prompt("URL", prev ?? "https://"); + if (url === null) return; + if (url === "") { + editor.chain().focus().extendMarkRange("link").unsetLink().run(); + } else { + editor.chain().focus().extendMarkRange("link").setLink({ href: url }).run(); + } + }, [editor]); + return /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center gap-0.5 border-b border-white/[0.06] px-2.5 py-2" }, /* @__PURE__ */ React.createElement(ToolbarBtn$2, { onClick: () => editor.chain().focus().toggleBold().run(), active: editor.isActive("bold"), title: "Bold (Ctrl+B)" }, /* @__PURE__ */ React.createElement("svg", { width: "15", height: "15", viewBox: "0 0 24 24", fill: "currentColor" }, /* @__PURE__ */ React.createElement("path", { d: "M6 4h8a4 4 0 014 4 4 4 0 01-4 4H6zm0 8h9a4 4 0 014 4 4 4 0 01-4 4H6z" }))), /* @__PURE__ */ React.createElement(ToolbarBtn$2, { onClick: () => editor.chain().focus().toggleItalic().run(), active: editor.isActive("italic"), title: "Italic (Ctrl+I)" }, /* @__PURE__ */ React.createElement("svg", { width: "15", height: "15", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "2" }, /* @__PURE__ */ React.createElement("line", { x1: "19", y1: "4", x2: "10", y2: "4" }), /* @__PURE__ */ React.createElement("line", { x1: "14", y1: "20", x2: "5", y2: "20" }), /* @__PURE__ */ React.createElement("line", { x1: "15", y1: "4", x2: "9", y2: "20" }))), /* @__PURE__ */ React.createElement(ToolbarBtn$2, { onClick: () => editor.chain().focus().toggleUnderline().run(), active: editor.isActive("underline"), title: "Underline (Ctrl+U)" }, /* @__PURE__ */ React.createElement("svg", { width: "15", height: "15", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "2" }, /* @__PURE__ */ React.createElement("path", { d: "M6 3v7a6 6 0 006 6 6 6 0 006-6V3" }), /* @__PURE__ */ React.createElement("line", { x1: "4", y1: "21", x2: "20", y2: "21" }))), /* @__PURE__ */ React.createElement(ToolbarBtn$2, { onClick: () => editor.chain().focus().toggleStrike().run(), active: editor.isActive("strike"), title: "Strikethrough" }, /* @__PURE__ */ React.createElement("svg", { width: "15", height: "15", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "2" }, /* @__PURE__ */ React.createElement("line", { x1: "4", y1: "12", x2: "20", y2: "12" }), /* @__PURE__ */ React.createElement("path", { d: "M17.5 7.5c0-2-1.5-3.5-5.5-3.5S6.5 5.5 6.5 7.5c0 4 11 4 11 8 0 2-1.5 3.5-5.5 3.5s-5.5-1.5-5.5-3.5" }))), /* @__PURE__ */ React.createElement(Divider$1, null), /* @__PURE__ */ React.createElement(ToolbarBtn$2, { onClick: () => editor.chain().focus().toggleHeading({ level: 2 }).run(), active: editor.isActive("heading", { level: 2 }), title: "Heading 2" }, /* @__PURE__ */ React.createElement("span", { className: "text-xs font-bold" }, "H2")), /* @__PURE__ */ React.createElement(ToolbarBtn$2, { onClick: () => editor.chain().focus().toggleHeading({ level: 3 }).run(), active: editor.isActive("heading", { level: 3 }), title: "Heading 3" }, /* @__PURE__ */ React.createElement("span", { className: "text-xs font-bold" }, "H3")), /* @__PURE__ */ React.createElement(Divider$1, null), /* @__PURE__ */ React.createElement(ToolbarBtn$2, { onClick: () => editor.chain().focus().toggleBulletList().run(), active: editor.isActive("bulletList"), title: "Bullet list" }, /* @__PURE__ */ React.createElement("svg", { width: "15", height: "15", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "2" }, /* @__PURE__ */ React.createElement("line", { x1: "9", y1: "6", x2: "20", y2: "6" }), /* @__PURE__ */ React.createElement("line", { x1: "9", y1: "12", x2: "20", y2: "12" }), /* @__PURE__ */ React.createElement("line", { x1: "9", y1: "18", x2: "20", y2: "18" }), /* @__PURE__ */ React.createElement("circle", { cx: "4.5", cy: "6", r: "1", fill: "currentColor" }), /* @__PURE__ */ React.createElement("circle", { cx: "4.5", cy: "12", r: "1", fill: "currentColor" }), /* @__PURE__ */ React.createElement("circle", { cx: "4.5", cy: "18", r: "1", fill: "currentColor" }))), /* @__PURE__ */ React.createElement(ToolbarBtn$2, { onClick: () => editor.chain().focus().toggleOrderedList().run(), active: editor.isActive("orderedList"), title: "Numbered list" }, /* @__PURE__ */ React.createElement("svg", { width: "15", height: "15", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "2" }, /* @__PURE__ */ React.createElement("line", { x1: "10", y1: "6", x2: "21", y2: "6" }), /* @__PURE__ */ React.createElement("line", { x1: "10", y1: "12", x2: "21", y2: "12" }), /* @__PURE__ */ React.createElement("line", { x1: "10", y1: "18", x2: "21", y2: "18" }), /* @__PURE__ */ React.createElement("text", { x: "3", y: "8", fontSize: "7", fill: "currentColor", stroke: "none", fontFamily: "sans-serif" }, "1"), /* @__PURE__ */ React.createElement("text", { x: "3", y: "14", fontSize: "7", fill: "currentColor", stroke: "none", fontFamily: "sans-serif" }, "2"), /* @__PURE__ */ React.createElement("text", { x: "3", y: "20", fontSize: "7", fill: "currentColor", stroke: "none", fontFamily: "sans-serif" }, "3"))), /* @__PURE__ */ React.createElement(Divider$1, null), /* @__PURE__ */ React.createElement(ToolbarBtn$2, { onClick: () => editor.chain().focus().toggleBlockquote().run(), active: editor.isActive("blockquote"), title: "Quote" }, /* @__PURE__ */ React.createElement("svg", { width: "15", height: "15", viewBox: "0 0 24 24", fill: "currentColor" }, /* @__PURE__ */ React.createElement("path", { d: "M4.583 17.321C3.553 16.227 3 15 3 13.011c0-3.5 2.457-6.637 6.03-8.188l.893 1.378c-3.335 1.804-3.987 4.145-4.247 5.621.537-.278 1.24-.375 1.929-.311C9.591 11.68 11 13.24 11 15.14c0 .94-.36 1.84-1.001 2.503A3.34 3.34 0 017.559 18.6a3.77 3.77 0 01-2.976-.879zm10.4 0C13.953 16.227 13.4 15 13.4 13.011c0-3.5 2.457-6.637 6.03-8.188l.893 1.378c-3.335 1.804-3.987 4.145-4.247 5.621.537-.278 1.24-.375 1.929-.311 1.986.169 3.395 1.729 3.395 3.629 0 .94-.36 1.84-1.001 2.503a3.34 3.34 0 01-2.44.957 3.77 3.77 0 01-2.976-.879z" }))), /* @__PURE__ */ React.createElement(ToolbarBtn$2, { onClick: () => editor.chain().focus().toggleCodeBlock().run(), active: editor.isActive("codeBlock"), title: "Code block" }, /* @__PURE__ */ React.createElement("svg", { width: "15", height: "15", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "2", strokeLinecap: "round", strokeLinejoin: "round" }, /* @__PURE__ */ React.createElement("polyline", { points: "16 18 22 12 16 6" }), /* @__PURE__ */ React.createElement("polyline", { points: "8 6 2 12 8 18" }))), /* @__PURE__ */ React.createElement(ToolbarBtn$2, { onClick: () => editor.chain().focus().toggleCode().run(), active: editor.isActive("code"), title: "Inline code" }, /* @__PURE__ */ React.createElement("span", { className: "font-mono text-[11px] font-bold" }, "{}")), /* @__PURE__ */ React.createElement(Divider$1, null), /* @__PURE__ */ React.createElement(ToolbarBtn$2, { onClick: addLink, active: editor.isActive("link"), title: "Link" }, /* @__PURE__ */ React.createElement("svg", { width: "15", height: "15", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "2", strokeLinecap: "round", strokeLinejoin: "round" }, /* @__PURE__ */ React.createElement("path", { d: "M10 13a5 5 0 007.54.54l3-3a5 5 0 00-7.07-7.07l-1.72 1.71" }), /* @__PURE__ */ React.createElement("path", { d: "M14 11a5 5 0 00-7.54-.54l-3 3a5 5 0 007.07 7.07l1.71-1.71" }))), /* @__PURE__ */ React.createElement(ToolbarBtn$2, { onClick: onInsertImage, title: "Insert image" }, /* @__PURE__ */ React.createElement("svg", { width: "15", height: "15", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "2", strokeLinecap: "round", strokeLinejoin: "round" }, /* @__PURE__ */ React.createElement("rect", { x: "3", y: "3", width: "18", height: "18", rx: "2", ry: "2" }), /* @__PURE__ */ React.createElement("circle", { cx: "8.5", cy: "8.5", r: "1.5" }), /* @__PURE__ */ React.createElement("polyline", { points: "21 15 16 10 5 21" }))), showComparisonTool ? /* @__PURE__ */ React.createElement(ToolbarBtn$2, { onClick: onInsertComparison, title: "Insert image comparison" }, /* @__PURE__ */ React.createElement("svg", { width: "15", height: "15", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "2", strokeLinecap: "round", strokeLinejoin: "round" }, /* @__PURE__ */ React.createElement("rect", { x: "3", y: "4", width: "8", height: "16", rx: "1.5" }), /* @__PURE__ */ React.createElement("rect", { x: "13", y: "4", width: "8", height: "16", rx: "1.5" }), /* @__PURE__ */ React.createElement("path", { d: "M9 8h1M14 8h1M9 16h1M14 16h1" }))) : null, /* @__PURE__ */ React.createElement(ToolbarBtn$2, { onClick: onInsertTable, title: "Insert table" }, /* @__PURE__ */ React.createElement("svg", { width: "15", height: "15", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "2", strokeLinecap: "round", strokeLinejoin: "round" }, /* @__PURE__ */ React.createElement("rect", { x: "3", y: "3", width: "18", height: "18", rx: "2" }), /* @__PURE__ */ React.createElement("path", { d: "M3 9h18M3 15h18M9 3v18M15 3v18" }))), /* @__PURE__ */ React.createElement(Divider$1, null), /* @__PURE__ */ React.createElement(ToolbarBtn$2, { onClick: () => editor.chain().focus().setHorizontalRule().run(), title: "Horizontal rule" }, /* @__PURE__ */ React.createElement("svg", { width: "15", height: "15", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "2" }, /* @__PURE__ */ React.createElement("line", { x1: "3", y1: "12", x2: "21", y2: "12" }))), /* @__PURE__ */ React.createElement(EmojiPicker, { editor }), /* @__PURE__ */ React.createElement(ToolbarBtn$2, { onClick: () => editor.chain().focus().insertContent("@").run(), title: "Mention a user (type @username)" }, /* @__PURE__ */ React.createElement("span", { className: "text-xs font-bold" }, "@")), advancedNews ? /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement(Divider$1, null), /* @__PURE__ */ React.createElement(ToolbarBtn$2, { onClick: onToggleSourceMode, active: sourceMode, title: "View or edit source HTML", className: "w-auto px-2.5" }, /* @__PURE__ */ React.createElement("span", { className: "text-[11px] font-bold uppercase tracking-[0.14em]" }, "HTML")), /* @__PURE__ */ React.createElement(ToolbarBtn$2, { onClick: onToggleStructureOutlines, active: showStructureOutlines, title: "Outline blocks (p, div, figure, list)", className: "w-auto px-2.5" }, /* @__PURE__ */ React.createElement("span", { className: "text-[11px] font-bold uppercase tracking-[0.14em]" }, "DOM")), /* @__PURE__ */ React.createElement(ToolbarBtn$2, { onClick: onInsertArtwork, title: "Embed artwork", className: "w-auto px-2.5" }, /* @__PURE__ */ React.createElement("span", { className: "text-[11px] font-bold uppercase tracking-[0.14em]" }, "Art")), /* @__PURE__ */ React.createElement(ToolbarBtn$2, { onClick: onInsertSocialEmbed, title: "Embed social post", className: "w-auto px-2.5" }, /* @__PURE__ */ React.createElement("span", { className: "text-[11px] font-bold uppercase tracking-[0.14em]" }, "Social")), /* @__PURE__ */ React.createElement(ToolbarBtn$2, { onClick: onInsertVideoEmbed, title: "Embed YouTube", className: "w-auto px-2.5" }, /* @__PURE__ */ React.createElement("span", { className: "text-[11px] font-bold uppercase tracking-[0.14em]" }, "YT")), /* @__PURE__ */ React.createElement(ToolbarBtn$2, { onClick: onInsertHashtag, title: "Insert hashtag", className: "w-auto px-2.5" }, /* @__PURE__ */ React.createElement("span", { className: "text-xs font-bold" }, "#"))) : null, /* @__PURE__ */ React.createElement("div", { className: "ml-auto flex items-center gap-0.5" }, /* @__PURE__ */ React.createElement(ToolbarBtn$2, { onClick: onDecreaseEditorViewportHeight, title: "Shorter editor", className: "w-auto px-2.5" }, /* @__PURE__ */ React.createElement("span", { className: "text-[11px] font-bold uppercase tracking-[0.14em]" }, "A-")), /* @__PURE__ */ React.createElement("div", { className: "mx-1 flex min-w-[5.25rem] items-center justify-center rounded-lg border border-white/10 bg-white/[0.04] px-2.5 py-1 text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-400" }, editorViewportHeight, "rem"), /* @__PURE__ */ React.createElement(ToolbarBtn$2, { onClick: onIncreaseEditorViewportHeight, title: "Taller editor", className: "w-auto px-2.5" }, /* @__PURE__ */ React.createElement("span", { className: "text-[11px] font-bold uppercase tracking-[0.14em]" }, "A+")), /* @__PURE__ */ React.createElement(ToolbarBtn$2, { onClick: onResetEditorViewportHeight, title: "Reset editor height", className: "w-auto px-2.5" }, /* @__PURE__ */ React.createElement("span", { className: "text-[11px] font-bold uppercase tracking-[0.14em]" }, "Fit")), /* @__PURE__ */ React.createElement(ToolbarBtn$2, { onClick: () => editor.chain().focus().undo().run(), disabled: !editor.can().undo(), title: "Undo (Ctrl+Z)" }, /* @__PURE__ */ React.createElement("svg", { width: "15", height: "15", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "2", strokeLinecap: "round", strokeLinejoin: "round" }, /* @__PURE__ */ React.createElement("polyline", { points: "1 4 1 10 7 10" }), /* @__PURE__ */ React.createElement("path", { d: "M3.51 15a9 9 0 102.13-9.36L1 10" }))), /* @__PURE__ */ React.createElement(ToolbarBtn$2, { onClick: () => editor.chain().focus().redo().run(), disabled: !editor.can().redo(), title: "Redo (Ctrl+Shift+Z)" }, /* @__PURE__ */ React.createElement("svg", { width: "15", height: "15", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "2", strokeLinecap: "round", strokeLinejoin: "round" }, /* @__PURE__ */ React.createElement("polyline", { points: "23 4 23 10 17 10" }), /* @__PURE__ */ React.createElement("path", { d: "M20.49 15a9 9 0 11-2.13-9.36L23 10" }))))); +} +function RichTextEditor({ + content: content2 = "", + onChange, + placeholder = "Write something…", + error, + minHeight = 12, + autofocus = false, + advancedNews = false, + searchEntities = null, + mediaSupport = null +}) { + const viewportStorageKey = "rich-text-editor.viewport-height"; + const viewportMinHeight = Math.max(minHeight + 6, 18); + const viewportMaxHeight = 42; + const viewportStep = 4; + const [sourceMode, setSourceMode] = reactExports.useState(false); + const [sourceValue, setSourceValue] = reactExports.useState(String(content2 || "")); + const [showStructureOutlines, setShowStructureOutlines] = reactExports.useState(false); + const [helperMessage, setHelperMessage] = reactExports.useState(""); + const [artworkPickerOpen, setArtworkPickerOpen] = reactExports.useState(false); + const [artworkQuery, setArtworkQuery] = reactExports.useState(""); + const [artworkResults, setArtworkResults] = reactExports.useState([]); + const [artworkLoading, setArtworkLoading] = reactExports.useState(false); + const [mediaDialogOpen, setMediaDialogOpen] = reactExports.useState(false); + const [mediaUploading, setMediaUploading] = reactExports.useState(false); + const [mediaError, setMediaError] = reactExports.useState(""); + const [mediaUrlValue, setMediaUrlValue] = reactExports.useState(""); + const [mediaPreviewUrl, setMediaPreviewUrl] = reactExports.useState(""); + const [mediaAltText, setMediaAltText] = reactExports.useState(""); + const [mediaUploadedPath, setMediaUploadedPath] = reactExports.useState(""); + const [academyAssetsOpen, setAcademyAssetsOpen] = reactExports.useState(false); + const [academyAssetsQuery, setAcademyAssetsQuery] = reactExports.useState(""); + const [academyAssetsSearch, setAcademyAssetsSearch] = reactExports.useState(""); + const [academyAssetsPage, setAcademyAssetsPage] = reactExports.useState(1); + const [academyAssetsPagination, setAcademyAssetsPagination] = reactExports.useState({ + page: 1, + per_page: 24, + total: 0, + last_page: 1, + has_more: false + }); + const [academyAssetsLoading, setAcademyAssetsLoading] = reactExports.useState(false); + const [academyAssetsError, setAcademyAssetsError] = reactExports.useState(""); + const [academyAssets, setAcademyAssets] = reactExports.useState([]); + const [academyAssetsTarget, setAcademyAssetsTarget] = reactExports.useState(null); + const [compareDialogOpen, setCompareDialogOpen] = reactExports.useState(false); + const [compareUploading, setCompareUploading] = reactExports.useState(false); + const [compareError, setCompareError] = reactExports.useState(""); + const [compareSubtitle, setCompareSubtitle] = reactExports.useState(""); + const [compareLeftImage, setCompareLeftImage] = reactExports.useState({ previewUrl: "", altText: "", uploadedPath: "" }); + const [compareRightImage, setCompareRightImage] = reactExports.useState({ previewUrl: "", altText: "", uploadedPath: "" }); + const [tableInsertOpen, setTableInsertOpen] = reactExports.useState(false); + const [tableRows, setTableRows] = reactExports.useState(3); + const [tableCols, setTableCols] = reactExports.useState(3); + const [tableHeaderRow, setTableHeaderRow] = reactExports.useState(true); + const [tableHeaderColumn, setTableHeaderColumn] = reactExports.useState(false); + const [editorViewportHeight, setEditorViewportHeight] = reactExports.useState(() => { + if (typeof window === "undefined") { + return Math.min(viewportMaxHeight, viewportMinHeight); + } + const storedValue = Number(window.localStorage.getItem(viewportStorageKey)); + if (Number.isFinite(storedValue)) { + return Math.min(viewportMaxHeight, Math.max(viewportMinHeight, storedValue)); + } + return Math.min(viewportMaxHeight, viewportMinHeight); + }); + const editorRef = reactExports.useRef(null); + const csrfToken2 = reactExports.useMemo(() => { + if (typeof document === "undefined") { + return ""; + } + return document.querySelector('meta[name="csrf-token"]')?.getAttribute("content") || ""; + }, []); + const deleteTemporaryMedia = reactExports.useCallback(async (path) => { + if (!mediaSupport?.deleteUrl || !path) return; + const response = await fetch(mediaSupport.deleteUrl, { + method: "DELETE", + headers: { + "Content-Type": "application/json", + "X-CSRF-TOKEN": csrfToken2, + Accept: "application/json" + }, + credentials: "same-origin", + body: JSON.stringify({ path }) + }); + const payload = await response.json().catch(() => ({})); + if (!response.ok) { + throw new Error(payload?.message || payload?.error || "Could not remove uploaded media."); + } + }, [csrfToken2, mediaSupport]); + const resetMediaState = reactExports.useCallback(() => { + setMediaUploading(false); + setMediaError(""); + setMediaUrlValue(""); + setMediaPreviewUrl(""); + setMediaAltText(""); + setMediaUploadedPath(""); + }, []); + const insertImageIntoEditor = reactExports.useCallback((src2, alt = "") => { + if (!src2 || !editorRef.current) return false; + editorRef.current.chain().focus().insertContent({ + type: "image", + attrs: { + src: src2, + alt: alt || "", + title: alt || "", + caption: "", + width: null + } + }).run(); + return true; + }, []); + const uploadMediaFile = reactExports.useCallback(async (file, previousPath = "") => { + if (!file || !mediaSupport?.uploadUrl) { + return null; + } + if (!String(file.type || "").startsWith("image/")) { + throw new Error("Use an image file to insert media."); + } + setMediaUploading(true); + setMediaError(""); + try { + if (previousPath) { + await deleteTemporaryMedia(previousPath); + } + const body2 = new FormData(); + body2.append("image", file); + body2.append("slot", mediaSupport.slot || "body"); + const response = await fetch(mediaSupport.uploadUrl, { + method: "POST", + headers: { + "X-CSRF-TOKEN": csrfToken2, + Accept: "application/json" + }, + credentials: "same-origin", + body: body2 + }); + const payload = await response.json().catch(() => ({})); + if (!response.ok) { + throw new Error(payload?.message || payload?.error || "Image upload failed."); + } + return payload; + } finally { + setMediaUploading(false); + } + }, [csrfToken2, deleteTemporaryMedia, mediaSupport]); + const loadAcademyAssets = reactExports.useCallback(async ({ page = academyAssetsPage, query = academyAssetsSearch } = {}) => { + if (!mediaSupport?.assetsUrl) { + setAcademyAssets([]); + setAcademyAssetsPagination({ page: 1, per_page: 24, total: 0, last_page: 1, has_more: false }); + return; + } + setAcademyAssetsLoading(true); + setAcademyAssetsError(""); + try { + const params = new URLSearchParams(); + params.set("limit", "24"); + params.set("page", String(Math.max(1, page))); + if (String(query || "").trim() !== "") { + params.set("q", String(query).trim()); + } + const requestUrl = new URL(mediaSupport.assetsUrl, window.location.origin); + requestUrl.search = params.toString(); + const response = await fetch(requestUrl.toString(), { + headers: { + "X-CSRF-TOKEN": csrfToken2, + Accept: "application/json" + }, + credentials: "same-origin", + cache: "no-store" + }); + const payload = await response.json().catch(() => ({})); + if (!response.ok) { + throw new Error(payload?.message || "Could not load academy assets."); + } + setAcademyAssets(Array.isArray(payload?.items) ? payload.items : []); + setAcademyAssetsPagination({ + page: Number(payload?.pagination?.page) || 1, + per_page: Number(payload?.pagination?.per_page) || 24, + total: Number(payload?.pagination?.total) || 0, + last_page: Number(payload?.pagination?.last_page) || 1, + has_more: Boolean(payload?.pagination?.has_more) + }); + } catch (loadError) { + setAcademyAssets([]); + setAcademyAssetsPagination({ page: 1, per_page: 24, total: 0, last_page: 1, has_more: false }); + setAcademyAssetsError(loadError?.message || "Could not load academy assets."); + } finally { + setAcademyAssetsLoading(false); + } + }, [academyAssetsPage, academyAssetsSearch, csrfToken2, mediaSupport?.assetsUrl]); + const openAcademyAssets = reactExports.useCallback((target) => { + setAcademyAssetsTarget(target); + setAcademyAssetsQuery(""); + setAcademyAssetsSearch(""); + setAcademyAssetsPage(1); + setAcademyAssetsOpen(true); + }, []); + const submitAcademyAssetSearch = reactExports.useCallback(() => { + setAcademyAssetsPage(1); + setAcademyAssetsSearch(academyAssetsQuery.trim()); + }, [academyAssetsQuery]); + const goToNextAcademyAssetsPage = reactExports.useCallback(() => { + setAcademyAssetsPage((current) => Math.min(current + 1, academyAssetsPagination.last_page || current + 1)); + }, [academyAssetsPagination.last_page]); + const goToPreviousAcademyAssetsPage = reactExports.useCallback(() => { + setAcademyAssetsPage((current) => Math.max(1, current - 1)); + }, []); + const closeAcademyAssets = reactExports.useCallback(() => { + setAcademyAssetsOpen(false); + setAcademyAssetsTarget(null); + setAcademyAssetsError(""); + setAcademyAssetsQuery(""); + setAcademyAssetsSearch(""); + setAcademyAssetsPage(1); + }, []); + const chooseAcademyAsset = reactExports.useCallback((asset) => { + if (!asset?.url) { + return; + } + const target = academyAssetsTarget || { type: "media" }; + if (target.type === "compare-left") { + if (compareLeftImage.uploadedPath) { + void deleteTemporaryMedia(compareLeftImage.uploadedPath).catch(() => { + }); + } + setCompareLeftImage({ + previewUrl: asset.url, + altText: compareLeftImage.altText || asset.name || "", + uploadedPath: "" + }); + } else if (target.type === "compare-right") { + if (compareRightImage.uploadedPath) { + void deleteTemporaryMedia(compareRightImage.uploadedPath).catch(() => { + }); + } + setCompareRightImage({ + previewUrl: asset.url, + altText: compareRightImage.altText || asset.name || "", + uploadedPath: "" + }); + } else { + if (mediaUploadedPath) { + void deleteTemporaryMedia(mediaUploadedPath).catch(() => { + }); + } + setMediaUploadedPath(""); + setMediaPreviewUrl(asset.url); + setMediaUrlValue(asset.url); + setMediaAltText((current) => current || asset.name || ""); + setMediaError(""); + } + closeAcademyAssets(); + }, [academyAssetsTarget, closeAcademyAssets, compareLeftImage, compareRightImage, deleteTemporaryMedia, mediaUploadedPath]); + const handleEditorImageFile = reactExports.useCallback(async (file) => { + if (!file) return false; + if (!mediaSupport?.uploadUrl) { + setHelperMessage("Image uploads are not configured for this editor."); + return false; + } + try { + setHelperMessage("Uploading image..."); + const payload = await uploadMediaFile(file, mediaUploadedPath); + if (!payload?.url) { + setHelperMessage("Image upload failed."); + return false; + } + setMediaUploadedPath(payload?.path || ""); + setMediaPreviewUrl(payload?.url || ""); + setMediaUrlValue(payload?.url || ""); + insertImageIntoEditor(payload.url, file.name?.replace(/\.[^.]+$/, "") || ""); + setHelperMessage("Image uploaded."); + resetMediaState(); + return true; + } catch (uploadError) { + setMediaError(uploadError?.message || "Image upload failed."); + setHelperMessage("Image upload failed."); + return false; + } + }, [insertImageIntoEditor, mediaSupport, mediaUploadedPath, resetMediaState, uploadMediaFile]); + const extensions = reactExports.useMemo(() => { + const base = [ + index_default$2.configure({ + link: false, + underline: false, + heading: { levels: [2, 3] }, + codeBlock: { + HTMLAttributes: { class: "forum-code-block" } + } + }), + index_default$1, + index_default$3.configure({ + openOnClick: false, + HTMLAttributes: { + class: "text-sky-300 underline hover:text-sky-200", + rel: "noopener noreferrer nofollow" + } + }), + RichImage.configure({ + HTMLAttributes: { class: "rich-image-node" } + }), + RichCompare.configure({ + HTMLAttributes: { class: "rich-compare-node" } + }), + Table.configure({ + resizable: true, + allowTableNodeSelection: true, + HTMLAttributes: { + class: "rich-table" + } + }), + TableRow, + TableHeader.configure({ + HTMLAttributes: { + class: "rich-table__header" + } + }), + TableCell.configure({ + HTMLAttributes: { + class: "rich-table__cell" + } + }), + index_default$4.configure({ placeholder }), + index_default$5.configure({ + HTMLAttributes: { + class: "mention" + }, + suggestion: mentionSuggestion + }) + ]; + if (advancedNews) { + base.push(ArtworkEmbed, VideoEmbed, SocialEmbed); + } + return base; + }, [advancedNews, placeholder]); + const editor = useEditor({ + extensions, + immediatelyRender: false, + content: content2, + autofocus, + editorProps: { + attributes: { + class: [ + "prose prose-invert prose-base max-w-none", + "focus:outline-none", + "px-4 py-3", + "prose-headings:text-white prose-headings:font-bold", + "prose-p:text-zinc-200 prose-p:leading-relaxed prose-p:mb-5", + "prose-h2:mb-5 prose-h3:mb-4 prose-hr:my-8", + "prose-a:text-sky-300 prose-a:no-underline hover:prose-a:text-sky-200", + "prose-blockquote:border-l-sky-500/50 prose-blockquote:text-zinc-400", + "prose-code:text-amber-300 prose-code:bg-white/[0.06] prose-code:rounded prose-code:px-1.5 prose-code:py-0.5 prose-code:text-xs", + "prose-pre:bg-white/[0.04] prose-pre:border prose-pre:border-white/[0.06] prose-pre:rounded-xl", + "prose-img:rounded-xl", + "prose-hr:border-white/10" + ].join(" "), + style: `min-height: ${minHeight}rem` + }, + handleDrop: (_view, event) => { + const file = event.dataTransfer?.files?.[0]; + if (!file || !String(file.type || "").startsWith("image/")) return false; + event.preventDefault(); + void handleEditorImageFile(file); + return true; + }, + handlePaste: (_view, event) => { + const file = event.clipboardData?.files?.[0]; + if (!file || !String(file.type || "").startsWith("image/")) return false; + event.preventDefault(); + void handleEditorImageFile(file); + return true; + } + }, + onUpdate: ({ editor: currentEditor }) => { + if (!sourceMode) { + onChange?.(currentEditor.getHTML()); + } + } + }); + reactExports.useEffect(() => { + editorRef.current = editor; + }, [editor]); + reactExports.useEffect(() => { + if (!helperMessage) { + return void 0; + } + const timeout = window.setTimeout(() => setHelperMessage(""), 2200); + return () => window.clearTimeout(timeout); + }, [helperMessage]); + reactExports.useEffect(() => { + if (!academyAssetsOpen) { + return; + } + void loadAcademyAssets({ page: academyAssetsPage, query: academyAssetsSearch }); + }, [academyAssetsOpen, academyAssetsPage, academyAssetsSearch, loadAcademyAssets]); + reactExports.useEffect(() => { + if (!editor) return; + if (sourceMode) return; + if ((content2 || "") === editor.getHTML()) return; + editor.commands.setContent(content2 || "", false); + const normalizedHtml = editor.getHTML(); + if (normalizedHtml !== (content2 || "")) { + onChange?.(normalizedHtml); + } + }, [content2, editor, onChange, sourceMode]); + reactExports.useEffect(() => { + if (sourceMode) { + setSourceValue(String(content2 || editor?.getHTML() || "")); + } + }, [content2, editor, sourceMode]); + reactExports.useEffect(() => { + if (typeof window === "undefined") { + return; + } + window.localStorage.setItem(viewportStorageKey, String(editorViewportHeight)); + }, [editorViewportHeight]); + const decreaseEditorViewportHeight = reactExports.useCallback(() => { + setEditorViewportHeight((current) => Math.max(viewportMinHeight, Number((current - viewportStep).toFixed(1)))); + }, [viewportMinHeight, viewportStep]); + const increaseEditorViewportHeight = reactExports.useCallback(() => { + setEditorViewportHeight((current) => Math.min(viewportMaxHeight, Number((current + viewportStep).toFixed(1)))); + }, [viewportMaxHeight, viewportStep]); + const resetEditorViewportHeight = reactExports.useCallback(() => { + setEditorViewportHeight(Math.min(viewportMaxHeight, viewportMinHeight)); + }, [viewportMaxHeight, viewportMinHeight]); + const pushHelperMessage = reactExports.useCallback((message) => { + setHelperMessage(message); + }, []); + const handleToggleSourceMode = reactExports.useCallback(() => { + if (sourceMode) { + setSourceMode(false); + if (editor) { + editor.commands.setContent(sourceValue || "", false); + } + pushHelperMessage("Returned to visual editor."); + return; + } + setSourceValue(editor?.getHTML() || String(content2 || "")); + setSourceMode(true); + }, [content2, editor, pushHelperMessage, sourceMode, sourceValue]); + const insertArtworkEmbed = reactExports.useCallback((item) => { + if (!editor || !item) return; + editor.chain().focus().insertContent({ + type: "artworkEmbed", + attrs: { + title: item.title || "Embedded artwork", + url: item.url || "#", + thumb: item.image || item.avatar || "" + } + }).run(); + }, [editor]); + const runArtworkSearch = reactExports.useCallback(async () => { + if (typeof searchEntities !== "function") { + return; + } + setArtworkLoading(true); + try { + const items = await searchEntities("artwork", artworkQuery); + setArtworkResults(Array.isArray(items) ? items : []); + } finally { + setArtworkLoading(false); + } + }, [artworkQuery, searchEntities]); + reactExports.useEffect(() => { + if (!artworkPickerOpen || typeof searchEntities !== "function") { + return; + } + runArtworkSearch(); + }, [artworkPickerOpen, runArtworkSearch, searchEntities]); + const handleInsertArtwork = reactExports.useCallback(() => { + if (!editor) return; + if (typeof searchEntities === "function") { + setArtworkPickerOpen(true); + return; + } + const url = normalizeHttpUrl(window.prompt("Artwork URL", "https://skinbase.org/art/") || ""); + if (!url) { + pushHelperMessage("Artwork URL is required."); + return; + } + const title = window.prompt("Artwork title", "Embedded artwork"); + if (title === null) return; + const thumb = normalizeHttpUrl(window.prompt("Artwork thumbnail URL (optional)", "") || "") || ""; + insertArtworkEmbed({ + title: title || "Embedded artwork", + url, + image: thumb + }); + }, [editor, insertArtworkEmbed, pushHelperMessage, searchEntities]); + const handleInsertImage = reactExports.useCallback(() => { + setMediaDialogOpen(true); + setMediaError(""); + }, []); + const handleInsertTable = reactExports.useCallback(() => { + setTableInsertOpen(true); + }, []); + const handleTableInsert = reactExports.useCallback(() => { + if (!editor) return; + editor.chain().focus().insertTable({ + rows: Math.max(1, tableRows), + cols: Math.max(1, tableCols), + withHeaderRow: tableHeaderRow, + withHeaderColumn: tableHeaderColumn + }).run(); + setTableInsertOpen(false); + }, [editor, tableCols, tableHeaderColumn, tableHeaderRow, tableRows]); + const handleMediaDialogClose = reactExports.useCallback(() => { + const uploadedPath = mediaUploadedPath; + setMediaDialogOpen(false); + resetMediaState(); + if (uploadedPath) { + void deleteTemporaryMedia(uploadedPath).catch(() => { + }); + } + }, [deleteTemporaryMedia, mediaUploadedPath, resetMediaState]); + const handleMediaInsert = reactExports.useCallback(() => { + const normalizedUrl = normalizeHttpUrl(mediaUrlValue) || mediaUrlValue.trim(); + if (!normalizedUrl) { + setMediaError("Choose or upload an image first."); + return; + } + if (!insertImageIntoEditor(normalizedUrl, mediaAltText.trim())) { + setMediaError("Editor is not ready yet."); + return; + } + setMediaDialogOpen(false); + resetMediaState(); + pushHelperMessage("Image inserted."); + }, [insertImageIntoEditor, mediaAltText, mediaUrlValue, pushHelperMessage, resetMediaState]); + const handleMediaPickFile = reactExports.useCallback(async (file) => { + if (!file) return; + try { + const payload = await uploadMediaFile(file, mediaUploadedPath); + if (!payload?.url) { + throw new Error("Image upload failed."); + } + setMediaUploadedPath(payload?.path || ""); + setMediaPreviewUrl(payload?.url || ""); + setMediaUrlValue(payload?.url || ""); + setMediaError(""); + } catch (uploadError) { + setMediaError(uploadError?.message || "Image upload failed."); + } + }, [mediaUploadedPath, uploadMediaFile]); + const handleMediaClear = reactExports.useCallback(() => { + const uploadedPath = mediaUploadedPath; + resetMediaState(); + if (uploadedPath) { + void deleteTemporaryMedia(uploadedPath).catch((deleteError) => { + setMediaError(deleteError?.message || "Could not remove uploaded media."); + }); + } + }, [deleteTemporaryMedia, mediaUploadedPath, resetMediaState]); + const handleInsertComparison = reactExports.useCallback(() => { + setCompareDialogOpen(true); + setCompareError(""); + }, []); + const resetCompareState = reactExports.useCallback(() => { + setCompareUploading(false); + setCompareError(""); + setCompareSubtitle(""); + setCompareLeftImage({ previewUrl: "", altText: "", uploadedPath: "" }); + setCompareRightImage({ previewUrl: "", altText: "", uploadedPath: "" }); + }, []); + const handleComparisonDialogClose = reactExports.useCallback(() => { + const uploadedPaths = [compareLeftImage.uploadedPath, compareRightImage.uploadedPath].filter(Boolean); + setCompareDialogOpen(false); + resetCompareState(); + uploadedPaths.forEach((path) => { + void deleteTemporaryMedia(path).catch(() => { + }); + }); + }, [compareLeftImage.uploadedPath, compareRightImage.uploadedPath, deleteTemporaryMedia, resetCompareState]); + const handleComparisonSidePick = reactExports.useCallback(async (side, file) => { + if (!file) return; + if (!mediaSupport?.uploadUrl) { + setCompareError("Image uploads are not configured for this editor."); + return; + } + const currentImage = side === "left" ? compareLeftImage : compareRightImage; + try { + setCompareUploading(true); + setCompareError(""); + const payload = await uploadMediaFile(file, currentImage.uploadedPath); + if (!payload?.url) { + throw new Error("Image upload failed."); + } + const nextImage = { + previewUrl: payload.url || "", + altText: currentImage.altText || file.name?.replace(/\.[^.]+$/, "") || "", + uploadedPath: payload.path || "" + }; + if (side === "left") { + setCompareLeftImage(nextImage); + } else { + setCompareRightImage(nextImage); + } + } catch (uploadError) { + setCompareError(uploadError?.message || "Image upload failed."); + } finally { + setCompareUploading(false); + } + }, [compareLeftImage, compareRightImage, mediaSupport, uploadMediaFile]); + const handleComparisonSideClear = reactExports.useCallback((side) => { + const currentImage = side === "left" ? compareLeftImage : compareRightImage; + if (currentImage.uploadedPath) { + void deleteTemporaryMedia(currentImage.uploadedPath).catch(() => { + }); + } + const nextImage = { previewUrl: "", altText: "", uploadedPath: "" }; + if (side === "left") { + setCompareLeftImage(nextImage); + } else { + setCompareRightImage(nextImage); + } + }, [compareLeftImage, compareRightImage, deleteTemporaryMedia]); + const handleComparisonInsert = reactExports.useCallback(() => { + if (!editor) return; + if (!compareLeftImage.previewUrl || !compareRightImage.previewUrl) { + setCompareError("Upload both images before inserting the comparison."); + return; + } + editor.chain().focus().insertContent({ + type: "imageCompare", + attrs: { + leftSrc: compareLeftImage.previewUrl, + leftAlt: compareLeftImage.altText.trim(), + rightSrc: compareRightImage.previewUrl, + rightAlt: compareRightImage.altText.trim(), + subtitle: compareSubtitle.trim() + } + }).run(); + setCompareDialogOpen(false); + resetCompareState(); + pushHelperMessage("Comparison inserted."); + }, [compareLeftImage, compareRightImage, compareSubtitle, editor, pushHelperMessage, resetCompareState]); + const handleInsertSocialEmbed = reactExports.useCallback(() => { + if (!editor) return; + const detected = detectSocialPlatform(window.prompt("Social post URL", "https://") || ""); + if (!detected.url) { + pushHelperMessage("Social post URL is required."); + return; + } + const label = window.prompt("Label (optional)", detected.label); + if (label === null) return; + editor.chain().focus().insertContent({ + type: "socialEmbed", + attrs: { + url: detected.url, + platform: detected.platform, + label: label || detected.label + } + }).run(); + }, [editor, pushHelperMessage]); + const handleInsertVideoEmbed = reactExports.useCallback(() => { + if (!editor) return; + const rawUrl = window.prompt("YouTube URL", "https://www.youtube.com/watch?v=") || ""; + const embedUrl = normalizeVideoEmbedUrl(rawUrl); + const sourceUrl = normalizeHttpUrl(rawUrl); + if (!embedUrl || !sourceUrl) { + pushHelperMessage("A valid YouTube URL is required."); + return; + } + const title = window.prompt("Video title (optional)", "Embedded YouTube video"); + if (title === null) return; + editor.chain().focus().insertContent({ + type: "videoEmbed", + attrs: { + src: embedUrl, + url: sourceUrl, + title: title.trim() || "Embedded video" + } + }).run(); + }, [editor, pushHelperMessage]); + const handleInsertHashtag = reactExports.useCallback(() => { + if (!editor) return; + const value = String(window.prompt("Hashtag", "release") || "").trim().replace(/^#+/, "").replace(/\s+/g, "-"); + if (!value) return; + editor.chain().focus().insertContent(`#${value}`).run(); + }, [editor]); + return /* @__PURE__ */ React.createElement("div", { className: "flex w-full min-w-0 flex-col gap-1.5" }, /* @__PURE__ */ React.createElement( + "div", + { + className: [ + "news-rich-text-editor w-full min-w-0 overflow-hidden rounded-xl border bg-white/[0.04] transition-colors", + error ? "border-red-500/60 focus-within:border-red-500/70 focus-within:ring-2 focus-within:ring-red-500/30" : "border-white/12 hover:border-white/20 focus-within:border-sky-500/50 focus-within:ring-2 focus-within:ring-sky-500/20" + ].join(" ") + }, + /* @__PURE__ */ React.createElement( + Toolbar$1, + { + editor, + advancedNews, + sourceMode, + showStructureOutlines, + showComparisonTool: Boolean(mediaSupport?.uploadUrl), + onToggleSourceMode: handleToggleSourceMode, + onToggleStructureOutlines: () => setShowStructureOutlines((current) => !current), + onInsertArtwork: handleInsertArtwork, + onInsertImage: handleInsertImage, + onInsertComparison: handleInsertComparison, + onInsertTable: handleInsertTable, + onInsertSocialEmbed: handleInsertSocialEmbed, + onInsertVideoEmbed: handleInsertVideoEmbed, + onInsertHashtag: handleInsertHashtag, + editorViewportHeight, + onIncreaseEditorViewportHeight: increaseEditorViewportHeight, + onDecreaseEditorViewportHeight: decreaseEditorViewportHeight, + onResetEditorViewportHeight: resetEditorViewportHeight + } + ), + advancedNews && sourceMode ? /* @__PURE__ */ React.createElement("div", { className: "border-t border-white/[0.04] bg-black/10 px-4 py-3" }, /* @__PURE__ */ React.createElement("div", { className: "mb-2 flex items-center justify-between gap-3 text-xs text-slate-400" }, /* @__PURE__ */ React.createElement("span", null, "Edit the stored article HTML directly. Saving while in this mode keeps the HTML exactly as written here."), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: handleToggleSourceMode, className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-1.5 font-semibold text-white transition hover:bg-white/[0.08]" }, "Back to visual")), /* @__PURE__ */ React.createElement( + "textarea", + { + value: sourceValue, + onChange: (event) => { + const nextValue = event.target.value; + setSourceValue(nextValue); + onChange?.(nextValue); + }, + spellCheck: false, + className: "nova-scrollbar min-h-[20rem] w-full rounded-xl border border-white/10 bg-slate-950/85 px-4 py-3 font-mono text-sm leading-6 text-slate-100 outline-none", + style: { minHeight: `${Math.max(minHeight, 20)}rem` } + } + )) : /* @__PURE__ */ React.createElement("div", { className: [ + "rich-text-editor-viewport nova-scrollbar w-full min-w-0 border-t border-white/[0.04] bg-black/15", + advancedNews && showStructureOutlines ? "news-editor-outline" : "" + ].filter(Boolean).join(" "), style: { maxHeight: `${editorViewportHeight}rem` } }, /* @__PURE__ */ React.createElement(EditorContent, { editor })) + ), advancedNews && helperMessage ? /* @__PURE__ */ React.createElement("p", { className: "text-xs text-sky-300" }, helperMessage) : null, !sourceMode ? /* @__PURE__ */ React.createElement(RichTableControls, { editor }) : null, error ? /* @__PURE__ */ React.createElement("p", { role: "alert", className: "text-xs text-red-400" }, error) : null, /* @__PURE__ */ React.createElement( + ArtworkPickerDialog, + { + open: artworkPickerOpen, + query: artworkQuery, + items: artworkResults, + loading: artworkLoading, + onQueryChange: setArtworkQuery, + onClose: () => setArtworkPickerOpen(false), + onSearch: runArtworkSearch, + onSelect: (item) => { + insertArtworkEmbed(item); + setArtworkPickerOpen(false); + pushHelperMessage(`Embedded artwork: ${item.title || "Artwork"}.`); + } + } + ), /* @__PURE__ */ React.createElement( + MediaImageDialog, + { + open: mediaDialogOpen, + uploading: mediaUploading, + error: mediaError, + previewUrl: mediaPreviewUrl || normalizeHttpUrl(mediaUrlValue) || mediaUrlValue, + imageUrl: mediaUrlValue, + altText: mediaAltText, + uploadLabel: "Drop image here or browse", + helperText: "Upload media directly to lesson storage or paste a CDN URL when you already have one.", + allowUpload: Boolean(mediaSupport?.uploadUrl), + onClose: handleMediaDialogClose, + onImageUrlChange: (nextValue) => { + setMediaUrlValue(nextValue); + setMediaPreviewUrl(normalizeHttpUrl(nextValue) || nextValue); + setMediaError(""); + }, + onAltTextChange: setMediaAltText, + onPickFile: handleMediaPickFile, + onBrowseAssets: mediaSupport?.assetsUrl ? () => openAcademyAssets({ type: "media" }) : null, + onInsert: handleMediaInsert, + onClearUploaded: handleMediaClear + } + ), /* @__PURE__ */ React.createElement( + CompareImageDialog, + { + open: compareDialogOpen, + uploading: compareUploading, + error: compareError, + subtitle: compareSubtitle, + leftImage: compareLeftImage, + rightImage: compareRightImage, + allowUpload: Boolean(mediaSupport?.uploadUrl), + onClose: handleComparisonDialogClose, + onSubtitleChange: setCompareSubtitle, + onLeftAltTextChange: (nextValue) => setCompareLeftImage((current) => ({ ...current, altText: nextValue })), + onRightAltTextChange: (nextValue) => setCompareRightImage((current) => ({ ...current, altText: nextValue })), + onLeftPickFile: (file) => handleComparisonSidePick("left", file), + onRightPickFile: (file) => handleComparisonSidePick("right", file), + onLeftBrowseAssets: mediaSupport?.assetsUrl ? () => openAcademyAssets({ type: "compare-left" }) : null, + onRightBrowseAssets: mediaSupport?.assetsUrl ? () => openAcademyAssets({ type: "compare-right" }) : null, + onLeftClear: () => handleComparisonSideClear("left"), + onRightClear: () => handleComparisonSideClear("right"), + onInsert: handleComparisonInsert + } + ), /* @__PURE__ */ React.createElement( + AssetPickerDialog, + { + open: academyAssetsOpen, + searchQuery: academyAssetsQuery, + assets: academyAssets, + loading: academyAssetsLoading, + error: academyAssetsError, + pagination: academyAssetsPagination, + onClose: closeAcademyAssets, + onRefresh: () => loadAcademyAssets({ page: academyAssetsPage, query: academyAssetsSearch }), + onSearchQueryChange: setAcademyAssetsQuery, + onSearch: submitAcademyAssetSearch, + onPreviousPage: goToPreviousAcademyAssetsPage, + onNextPage: goToNextAcademyAssetsPage, + onSelect: chooseAcademyAsset + } + ), /* @__PURE__ */ React.createElement( + TableInsertDialog, + { + open: tableInsertOpen, + rows: tableRows, + cols: tableCols, + withHeaderRow: tableHeaderRow, + withHeaderColumn: tableHeaderColumn, + onRowsChange: setTableRows, + onColsChange: setTableCols, + onHeaderRowChange: setTableHeaderRow, + onHeaderColumnChange: setTableHeaderColumn, + onClose: () => setTableInsertOpen(false), + onInsert: handleTableInsert + } + )); +} +function formatBytes$2(bytes) { + const value = Number(bytes || 0); + if (!Number.isFinite(value) || value <= 0) return null; + if (value < 1024 * 1024) return `${Math.round(value / 1024)} KB`; + return `${(value / (1024 * 1024)).toFixed(1)} MB`; +} +function WorldMediaUploadField({ + label, + slot, + value, + previewUrl, + emptyLabel, + helperText, + uploadUrl, + deleteUrl, + worldId = null, + onChange, + isTemporaryValue = false, + accept = "image/jpeg,image/png,image/webp", + maxFileSizeMb = 6 +}) { + const inputRef = reactExports.useRef(null); + const [dragging, setDragging] = reactExports.useState(false); + const [uploading, setUploading] = reactExports.useState(false); + const [error, setError] = reactExports.useState(""); + const [meta, setMeta] = reactExports.useState(null); + const csrfToken2 = reactExports.useMemo(() => { + if (typeof document === "undefined") { + return ""; + } + return document.querySelector('meta[name="csrf-token"]')?.getAttribute("content") || ""; + }, []); + const deleteTemporaryUpload = async (path) => { + if (!deleteUrl || !path) return; + const response = await fetch(deleteUrl, { + method: "DELETE", + headers: { + "Content-Type": "application/json", + "X-CSRF-TOKEN": csrfToken2, + Accept: "application/json" + }, + credentials: "same-origin", + body: JSON.stringify({ + path, + world_id: worldId || void 0 + }) + }); + const payload = await response.json().catch(() => ({})); + if (!response.ok) { + throw new Error(payload?.message || payload?.error || "Could not remove uploaded image."); + } + }; + const handleFile = async (file) => { + if (!file || uploading) return; + const allowed = ["image/jpeg", "image/png", "image/webp"]; + if (!allowed.includes(String(file.type || "").toLowerCase())) { + setError("Use a JPG, PNG, or WEBP image."); + return; + } + if (file.size > maxFileSizeMb * 1024 * 1024) { + setError(`Image is too large. Maximum allowed size is ${maxFileSizeMb} MB.`); + return; + } + setUploading(true); + setError(""); + try { + if (value && isTemporaryValue) { + await deleteTemporaryUpload(value); + } + const body2 = new FormData(); + body2.append("slot", slot); + body2.append("image", file); + if (worldId) { + body2.append("world_id", String(worldId)); + } + const response = await fetch(uploadUrl, { + method: "POST", + headers: { + "X-CSRF-TOKEN": csrfToken2, + Accept: "application/json" + }, + credentials: "same-origin", + body: body2 + }); + const payload = await response.json().catch(() => ({})); + if (!response.ok) { + throw new Error(payload?.message || payload?.error || "Upload failed."); + } + setMeta({ + width: payload?.width || null, + height: payload?.height || null, + size: formatBytes$2(payload?.size_bytes) + }); + onChange?.({ path: payload?.path || "", url: payload?.url || "" }); + } catch (uploadError) { + setError(uploadError?.message || "Upload failed."); + } finally { + setUploading(false); + if (inputRef.current) { + inputRef.current.value = ""; + } + } + }; + return /* @__PURE__ */ React.createElement("div", { className: "grid gap-3 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("span", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, label), value ? /* @__PURE__ */ React.createElement( + "button", + { + type: "button", + onClick: async (event) => { + event.stopPropagation(); + setError(""); + setMeta(null); + try { + if (value && isTemporaryValue) { + setUploading(true); + await deleteTemporaryUpload(value); + } + onChange?.({ path: "", url: "" }); + } catch (deleteError) { + setError(deleteError?.message || "Could not remove uploaded image."); + } finally { + setUploading(false); + } + }, + disabled: uploading, + className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.14em] text-white" + }, + "Clear" + ) : null), /* @__PURE__ */ React.createElement( + "div", + { + role: "button", + tabIndex: 0, + onClick: () => !uploading && inputRef.current?.click(), + onKeyDown: (event) => { + if (uploading) return; + if (event.key === "Enter" || event.key === " ") { + event.preventDefault(); + inputRef.current?.click(); + } + }, + onDragOver: (event) => { + event.preventDefault(); + if (!uploading) setDragging(true); + }, + onDragEnter: (event) => { + event.preventDefault(); + if (!uploading) setDragging(true); + }, + onDragLeave: (event) => { + event.preventDefault(); + setDragging(false); + }, + onDrop: (event) => { + event.preventDefault(); + setDragging(false); + void handleFile(event.dataTransfer?.files?.[0]); + }, + className: [ + "rounded-[24px] border border-dashed px-5 py-5 transition outline-none", + uploading ? "cursor-progress border-sky-300/35 bg-sky-400/10" : dragging ? "cursor-pointer border-sky-300/50 bg-sky-400/12" : "cursor-pointer border-white/10 bg-black/20 hover:border-white/20 hover:bg-white/[0.04]" + ].join(" ") + }, + /* @__PURE__ */ React.createElement("div", { className: "flex flex-col gap-4 lg:flex-row lg:items-center lg:justify-between" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-start gap-4" }, /* @__PURE__ */ React.createElement("div", { className: "flex h-12 w-12 shrink-0 items-center justify-center rounded-2xl border border-sky-300/20 bg-sky-400/10 text-sky-100" }, /* @__PURE__ */ React.createElement("i", { className: `fa-solid ${uploading ? "fa-circle-notch fa-spin" : "fa-cloud-arrow-up"}` })), /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "text-sm font-semibold text-white" }, uploading ? "Uploading image…" : "Drop image here or browse"), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-xs leading-5 text-slate-400" }, helperText), /* @__PURE__ */ React.createElement("div", { className: "mt-2 flex flex-wrap gap-2 text-[11px] text-slate-400" }, /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.04] px-2.5 py-1" }, "JPG"), /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.04] px-2.5 py-1" }, "PNG"), /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.04] px-2.5 py-1" }, "WEBP"), /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.04] px-2.5 py-1" }, "Max ", maxFileSizeMb, " MB")))), /* @__PURE__ */ React.createElement("div", { className: "h-28 w-full overflow-hidden rounded-[20px] border border-white/10 bg-slate-950 lg:w-44" }, previewUrl ? /* @__PURE__ */ React.createElement("img", { src: previewUrl, alt: "", className: "h-full w-full object-cover" }) : /* @__PURE__ */ React.createElement("div", { className: "flex h-full items-center justify-center px-4 text-center text-sm text-slate-500" }, emptyLabel))), + value ? /* @__PURE__ */ React.createElement("div", { className: "mt-4 truncate rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-xs text-slate-400" }, "Stored path: ", /* @__PURE__ */ React.createElement("span", { className: "text-slate-200" }, value)) : null, + meta ? /* @__PURE__ */ React.createElement("div", { className: "mt-3 text-xs text-slate-400" }, "Optimized to ", meta.width, "×", meta.height, meta.size ? ` • ${meta.size}` : "") : null, + error ? /* @__PURE__ */ React.createElement("div", { className: "mt-3 rounded-2xl border border-rose-300/20 bg-rose-400/10 px-4 py-3 text-sm text-rose-100" }, error) : null, + /* @__PURE__ */ React.createElement( + "input", + { + ref: inputRef, + type: "file", + accept, + className: "hidden", + disabled: uploading, + onChange: (event) => { + void handleFile(event.target.files?.[0]); + } + } + ) + )); +} +function getField$1(fields, name2) { + return fields.find((field) => field.name === name2) || null; +} +const LESSON_SECTION_NAV_ITEMS = [ + { id: "lesson-story-setup", label: "Story setup" }, + { id: "lesson-body-editor", label: "Main article" }, + { id: "lesson-ai-comparisons", label: "AI comparisons" }, + { id: "lesson-publishing", label: "Publishing" }, + { id: "lesson-seo", label: "SEO" }, + { id: "lesson-categories", label: "Categories" }, + { id: "lesson-cover", label: "Cover image" }, + { id: "lesson-preview", label: "Preview" } +]; +let comparisonEditorSequence = 0; +function nextComparisonEditorKey(prefix) { + comparisonEditorSequence += 1; + return `${prefix}-${comparisonEditorSequence}`; +} +function FieldError$2({ message }) { + if (!message) return null; + return /* @__PURE__ */ React.createElement("p", { className: "text-xs text-rose-300" }, message); +} +function SectionCard$5({ id, eyebrow, title, description, actions, children, tone = "default" }) { + const toneClass = tone === "feature" ? "bg-[radial-gradient(circle_at_top_left,rgba(56,189,248,0.16),transparent_38%),linear-gradient(180deg,rgba(15,23,42,0.96),rgba(2,6,23,0.92))] shadow-[0_24px_70px_rgba(2,6,23,0.28)]" : "bg-white/[0.03]"; + return /* @__PURE__ */ React.createElement("section", { id, className: `min-w-0 scroll-mt-24 rounded-[28px] border border-white/10 p-5 ${toneClass}` }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-start justify-between gap-4" }, /* @__PURE__ */ React.createElement("div", { className: "max-w-3xl" }, eyebrow ? /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.24em] text-sky-200/75" }, eyebrow) : null, /* @__PURE__ */ React.createElement("h2", { className: "mt-2 text-xl font-semibold tracking-[-0.03em] text-white" }, title), description ? /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm leading-6 text-slate-400" }, description) : null), actions ? /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-2" }, actions) : null), /* @__PURE__ */ React.createElement("div", { className: "mt-5" }, children)); +} +function SectionNav({ items }) { + return /* @__PURE__ */ React.createElement("div", { className: "sticky top-4 z-20 rounded-[24px] border border-white/10 bg-[linear-gradient(180deg,rgba(7,11,18,0.92),rgba(5,8,14,0.88))] px-3 py-3 shadow-[0_18px_50px_rgba(2,6,23,0.18)] backdrop-blur" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-3 overflow-x-auto pb-1 nova-scrollbar" }, /* @__PURE__ */ React.createElement("span", { className: "flex shrink-0 items-center gap-2 rounded-full border border-white/10 bg-white/[0.04] px-3 py-2 text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-400" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-compass text-[10px]" }), "Sections"), items.map((item) => /* @__PURE__ */ React.createElement( + "a", + { + key: item.id, + href: `#${item.id}`, + className: "shrink-0 rounded-full border border-white/10 bg-white/[0.03] px-4 py-2 text-sm font-semibold text-white/80 transition hover:border-sky-300/30 hover:bg-sky-300/10 hover:text-white" + }, + item.label + )))); +} +function TextField$2({ label, value, onChange, error, hint, ...rest }) { + return /* @__PURE__ */ React.createElement("label", { className: "grid gap-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, label), /* @__PURE__ */ React.createElement("input", { value: value ?? "", onChange, className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white outline-none", ...rest }), hint ? /* @__PURE__ */ React.createElement("span", { className: "text-xs leading-5 text-slate-500" }, hint) : null, /* @__PURE__ */ React.createElement(FieldError$2, { message: error })); +} +function TextAreaField$1({ label, value, onChange, error, rows = 4, hint }) { + return /* @__PURE__ */ React.createElement("label", { className: "grid gap-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, label), /* @__PURE__ */ React.createElement("textarea", { value: value ?? "", onChange, rows, className: "rounded-[24px] border border-white/10 bg-black/20 px-4 py-3 text-white outline-none" }), hint ? /* @__PURE__ */ React.createElement("span", { className: "text-xs leading-5 text-slate-500" }, hint) : null, /* @__PURE__ */ React.createElement(FieldError$2, { message: error })); +} +function ToggleField$2({ label, checked, onChange, help, error }) { + return /* @__PURE__ */ React.createElement("label", { className: "flex items-start gap-3 rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-sm text-slate-200" }, /* @__PURE__ */ React.createElement("input", { type: "checkbox", checked: Boolean(checked), onChange, className: "mt-1" }), /* @__PURE__ */ React.createElement("span", null, /* @__PURE__ */ React.createElement("span", { className: "block font-semibold text-white" }, label), help ? /* @__PURE__ */ React.createElement("span", { className: "mt-1 block text-xs leading-5 text-slate-400" }, help) : null, /* @__PURE__ */ React.createElement(FieldError$2, { message: error }))); +} +function slugifyLessonTitle(value) { + return String(value || "").toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 180); +} +function stripHtml$4(value) { + return String(value || "").replace(//gi, " ").replace(//gi, " ").replace(/<[^>]+>/g, " ").replace(/ /g, " ").replace(/\s+/g, " ").trim(); +} +function countWords(value) { + const text2 = stripHtml$4(value); + return text2 ? text2.split(/\s+/).length : 0; +} +function normalizeCoverPreview(value, cdnBaseUrl) { + const trimmed = String(value || "").trim(); + if (!trimmed) return ""; + if (trimmed.startsWith("http://") || trimmed.startsWith("https://") || trimmed.startsWith("/")) return trimmed; + return `${String(cdnBaseUrl || "").replace(/\/$/, "")}/${trimmed.replace(/^\//, "")}`; +} +function normalizeCategoryValue(value) { + if (value === "" || value == null) return ""; + return String(value); +} +function normalizeBoolean(value, fallback = false) { + if (typeof value === "boolean") return value; + if (typeof value === "number") return value !== 0; + const normalized = String(value || "").trim().toLowerCase(); + if (["1", "true", "yes", "on"].includes(normalized)) return true; + if (["0", "false", "no", "off"].includes(normalized)) return false; + return fallback; +} +const DEFAULT_AI_COMPARISON_TITLE = "Same Prompt, Different AI Models"; +const DEFAULT_AI_COMPARISON_PAYLOAD = { + title: DEFAULT_AI_COMPARISON_TITLE, + intro: "We used the same prompt in multiple image generators to compare composition, mood, detail, and wallpaper quality.", + prompt: "", + negative_prompt: "", + aspect_ratio: "16:9", + criteria: ["Composition", "Lighting", "Wallpaper quality", "Prompt accuracy", "Detail quality"] +}; +function normalizeCriteria(value) { + return (Array.isArray(value) ? value : []).map((criterion) => String(criterion || "").trim()).filter(Boolean); +} +function normalizeComparisonResult(result, index2, cdnBaseUrl) { + const imagePath = String(result?.image_path || ""); + const thumbPath = String(result?.thumb_path || ""); + return { + client_key: result?.client_key || nextComparisonEditorKey("comparison-result"), + id: result?.id ?? null, + provider: String(result?.provider || ""), + model_name: String(result?.model_name || ""), + image_path: imagePath, + image_url: String(result?.image_url || normalizeCoverPreview(imagePath, cdnBaseUrl) || ""), + image_temp_path: String(result?.image_temp_path || ""), + thumb_path: thumbPath, + thumb_url: String(result?.thumb_url || normalizeCoverPreview(thumbPath, cdnBaseUrl) || ""), + thumb_temp_path: String(result?.thumb_temp_path || ""), + settings: String(result?.settings || ""), + strengths: String(result?.strengths || ""), + weaknesses: String(result?.weaknesses || ""), + best_for: String(result?.best_for || ""), + score: result?.score == null || result?.score === "" ? "" : Number(result.score), + sort_order: Number(result?.sort_order ?? index2), + active: normalizeBoolean(result?.active, true) + }; +} +function createEmptyComparisonResult(sortOrder = 0) { + return normalizeComparisonResult({ sort_order: sortOrder, active: true }, sortOrder, ""); +} +function normalizeComparisonBlock(block, index2, cdnBaseUrl) { + const payload = block?.payload && typeof block.payload === "object" ? block.payload : {}; + return { + client_key: block?.client_key || nextComparisonEditorKey("comparison-block"), + id: block?.id ?? null, + type: "ai_comparison", + title: String(block?.title || payload?.title || DEFAULT_AI_COMPARISON_TITLE), + payload: { + ...DEFAULT_AI_COMPARISON_PAYLOAD, + title: String(payload?.title || block?.title || DEFAULT_AI_COMPARISON_TITLE), + intro: String(payload?.intro || ""), + prompt: String(payload?.prompt || ""), + negative_prompt: String(payload?.negative_prompt || ""), + aspect_ratio: String(payload?.aspect_ratio || DEFAULT_AI_COMPARISON_PAYLOAD.aspect_ratio), + criteria: normalizeCriteria(payload?.criteria || DEFAULT_AI_COMPARISON_PAYLOAD.criteria) + }, + sort_order: Number(block?.sort_order ?? index2), + active: normalizeBoolean(block?.active, true), + comparison_results: (Array.isArray(block?.comparison_results) ? block.comparison_results : []).map((result, resultIndex) => normalizeComparisonResult(result, resultIndex, cdnBaseUrl)) + }; +} +function createEmptyComparisonBlock(sortOrder = 0, cdnBaseUrl = "") { + return normalizeComparisonBlock({ + title: DEFAULT_AI_COMPARISON_TITLE, + payload: DEFAULT_AI_COMPARISON_PAYLOAD, + sort_order: sortOrder, + active: true, + comparison_results: [] + }, sortOrder, cdnBaseUrl); +} +function normalizeComparisonBlocks(blocks, cdnBaseUrl) { + return (Array.isArray(blocks) ? blocks : []).filter((block) => String(block?.type || "ai_comparison") === "ai_comparison").map((block, index2) => normalizeComparisonBlock(block, index2, cdnBaseUrl)); +} +function serializeComparisonBlocks(blocks) { + return (Array.isArray(blocks) ? blocks : []).map((block, index2) => ({ + id: block.id || void 0, + type: "ai_comparison", + title: String(block.title || block.payload?.title || DEFAULT_AI_COMPARISON_TITLE), + payload: { + title: String(block.payload?.title || block.title || DEFAULT_AI_COMPARISON_TITLE), + intro: String(block.payload?.intro || ""), + prompt: String(block.payload?.prompt || ""), + negative_prompt: String(block.payload?.negative_prompt || ""), + aspect_ratio: String(block.payload?.aspect_ratio || ""), + criteria: normalizeCriteria(block.payload?.criteria || []) + }, + sort_order: Number(block.sort_order ?? index2), + active: Boolean(block.active), + comparison_results: (Array.isArray(block.comparison_results) ? block.comparison_results : []).map((result, resultIndex) => ({ + id: result.id || void 0, + provider: String(result.provider || ""), + model_name: String(result.model_name || ""), + image_path: String(result.image_path || ""), + thumb_path: String(result.thumb_path || ""), + settings: String(result.settings || ""), + strengths: String(result.strengths || ""), + weaknesses: String(result.weaknesses || ""), + best_for: String(result.best_for || ""), + score: result.score === "" || result.score == null ? null : Number(result.score), + sort_order: Number(result.sort_order ?? resultIndex), + active: Boolean(result.active) + })) + })); +} +function getFormError(errors, path) { + return errors?.[path] || ""; +} +function buildLessonPayload(data) { + return { + category_id: data.category_id === "" || data.category_id == null ? null : Number(data.category_id), + title: String(data.title || ""), + slug: String(data.slug || ""), + excerpt: String(data.excerpt || ""), + content: String(data.content || ""), + difficulty: String(data.difficulty || ""), + access_level: String(data.access_level || ""), + lesson_type: String(data.lesson_type || ""), + cover_image: String(data.cover_image || ""), + video_url: String(data.video_url || ""), + reading_minutes: data.reading_minutes === "" || data.reading_minutes == null ? "" : Number(data.reading_minutes), + published_at: data.published_at || "", + seo_title: String(data.seo_title || ""), + seo_description: String(data.seo_description || ""), + featured: Boolean(data.featured), + active: Boolean(data.active), + blocks: serializeComparisonBlocks(data.blocks) + }; +} +function parseLessonImport(rawText, categoryOptions) { + let parsed; + try { + parsed = JSON.parse(String(rawText || "")); + } catch { + throw new Error("Could not parse JSON."); + } + if (!parsed || Array.isArray(parsed) || typeof parsed !== "object") { + throw new Error("Import JSON must be an object."); + } + const next = {}; + const applied = []; + const apply = (key, value) => { + next[key] = value; + applied.push(key); + }; + if (parsed.title != null) apply("title", String(parsed.title)); + if (parsed.slug != null) apply("slug", String(parsed.slug)); + if (parsed.excerpt != null) apply("excerpt", String(parsed.excerpt)); + if (parsed.content != null) apply("content", String(parsed.content)); + if (parsed.body != null && parsed.content == null) apply("content", String(parsed.body)); + if (parsed.html != null && parsed.content == null && parsed.body == null) apply("content", String(parsed.html)); + if (parsed.difficulty != null) apply("difficulty", String(parsed.difficulty)); + if (parsed.access_level != null) apply("access_level", String(parsed.access_level)); + if (parsed.access != null && parsed.access_level == null) apply("access_level", String(parsed.access)); + if (parsed.lesson_type != null) apply("lesson_type", String(parsed.lesson_type)); + if (parsed.type != null && parsed.lesson_type == null) apply("lesson_type", String(parsed.type)); + if (parsed.cover_image != null) apply("cover_image", String(parsed.cover_image)); + if (parsed.cover != null && parsed.cover_image == null) apply("cover_image", String(parsed.cover)); + if (parsed.cover_url != null && parsed.cover_image == null && parsed.cover == null) apply("cover_image", String(parsed.cover_url)); + if (parsed.video_url != null) apply("video_url", String(parsed.video_url)); + if (parsed.reading_minutes != null) apply("reading_minutes", String(parsed.reading_minutes)); + if (parsed.published_at != null) apply("published_at", String(parsed.published_at)); + if (parsed.seo_title != null) apply("seo_title", String(parsed.seo_title)); + if (parsed.seo_description != null) apply("seo_description", String(parsed.seo_description)); + if (parsed.featured != null) apply("featured", normalizeBoolean(parsed.featured)); + if (parsed.active != null) apply("active", normalizeBoolean(parsed.active, true)); + if (parsed.category_id != null || parsed.category_slug != null || parsed.category != null) { + const requested = String(parsed.category_id ?? parsed.category_slug ?? parsed.category).trim().toLowerCase(); + const match = (Array.isArray(categoryOptions) ? categoryOptions : []).find((option) => [option.id, option.value, option.slug, option.name, option.label].filter((candidate) => candidate != null).map((candidate) => String(candidate).trim().toLowerCase()).includes(requested)); + if (match) { + apply("category_id", String(match.id ?? match.value ?? "")); + } + } + if (applied.length === 0) { + throw new Error("The JSON did not contain any recognized lesson fields."); + } + return { next, applied }; +} +function JsonImportDialog$1({ open, value, error, onChange, onClose, onApply }) { + const backdropRef = reactExports.useRef(null); + reactExports.useEffect(() => { + if (!open) return void 0; + const handleKeyDown = (event) => { + if (event.key === "Escape") { + onClose?.(); + } + }; + window.addEventListener("keydown", handleKeyDown); + return () => window.removeEventListener("keydown", handleKeyDown); + }, [onClose, open]); + if (!open) return null; + return reactDomExports.createPortal( + /* @__PURE__ */ React.createElement( + "div", + { + ref: backdropRef, + className: "fixed inset-0 z-[9999] flex items-center justify-center bg-[#04070dcc] px-4 backdrop-blur-md", + onClick: (event) => { + if (event.target === backdropRef.current) { + onClose?.(); + } + }, + role: "presentation" + }, + /* @__PURE__ */ React.createElement("div", { className: "w-full max-w-3xl overflow-hidden rounded-3xl border border-white/10 bg-[linear-gradient(180deg,rgba(16,22,34,0.98),rgba(8,12,19,0.98))] shadow-[0_30px_80px_rgba(0,0,0,0.55)]" }, /* @__PURE__ */ React.createElement("div", { className: "border-b border-white/[0.06] bg-white/[0.02] px-6 py-5" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.24em] text-white/35" }, "Structured Import"), /* @__PURE__ */ React.createElement("h3", { className: "mt-2 text-lg font-semibold text-white" }, "Paste lesson JSON"), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm leading-6 text-white/65" }, "Use this to seed the lesson form with structured content before you refine it in the editor.")), /* @__PURE__ */ React.createElement("div", { className: "grid gap-5 px-6 py-5 xl:grid-cols-[minmax(0,1fr)_280px]" }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-3" }, /* @__PURE__ */ React.createElement( + "textarea", + { + value, + onChange: (event) => onChange?.(event.target.value), + rows: 16, + placeholder: '{\n "title": "Prompt engineering for cleaner scene direction",\n "excerpt": "Short summary...",\n "content": "

Rich HTML body...

",\n "category": "Prompting",\n "difficulty": "beginner"\n}', + className: "rounded-[24px] border border-white/10 bg-slate-950/80 px-4 py-4 font-mono text-sm leading-6 text-slate-100 outline-none" + } + ), error ? /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-rose-300/20 bg-rose-400/10 px-4 py-3 text-sm text-rose-100" }, error) : null), /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-white/[0.03] p-4 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Accepted keys"), /* @__PURE__ */ React.createElement("div", { className: "mt-3 space-y-2 leading-6 text-slate-400" }, /* @__PURE__ */ React.createElement("p", null, "title, slug, excerpt"), /* @__PURE__ */ React.createElement("p", null, "content, body, html"), /* @__PURE__ */ React.createElement("p", null, "category_id, category_slug, category"), /* @__PURE__ */ React.createElement("p", null, "difficulty, access_level, lesson_type"), /* @__PURE__ */ React.createElement("p", null, "cover_image, cover, cover_url, video_url"), /* @__PURE__ */ React.createElement("p", null, "reading_minutes, published_at"), /* @__PURE__ */ React.createElement("p", null, "seo_title, seo_description, featured, active")))), /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-end gap-3 border-t border-white/[0.06] px-6 py-4" }, /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => onClose?.(), className: "inline-flex items-center justify-center rounded-full border border-white/[0.08] bg-white/[0.04] px-4 py-2 text-sm font-medium text-white/70 transition hover:bg-white/[0.08] hover:text-white" }, "Cancel"), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => onApply?.(), className: "inline-flex items-center justify-center rounded-full border border-sky-300/25 bg-sky-400/90 px-4 py-2 text-sm font-semibold text-slate-950 transition hover:brightness-110" }, "Apply JSON"))) + ), + document.body + ); +} +function LessonEditor({ title, subtitle, fields, record, submitUrl, indexUrl, destroyUrl, method, editorContext = {} }) { + const cdnBaseUrl = editorContext.coverCdnBaseUrl || ""; + const form = G({ + ...record, + category_id: normalizeCategoryValue(record.category_id), + blocks: normalizeComparisonBlocks(record.blocks, cdnBaseUrl) + }); + const [coverPreviewUrl, setCoverPreviewUrl] = reactExports.useState(record.cover_image_url || normalizeCoverPreview(record.cover_image, editorContext.coverCdnBaseUrl)); + const [stagedCoverPath, setStagedCoverPath] = reactExports.useState(""); + const [categories, setCategories] = reactExports.useState(Array.isArray(editorContext.categories) ? editorContext.categories : []); + const [jsonImportOpen, setJsonImportOpen] = reactExports.useState(false); + const [jsonImportValue, setJsonImportValue] = reactExports.useState(""); + const [jsonImportError, setJsonImportError] = reactExports.useState(""); + const [categoryError, setCategoryError] = reactExports.useState(""); + const [categorySaving, setCategorySaving] = reactExports.useState(false); + const [categoryDraft, setCategoryDraft] = reactExports.useState({ type: "lesson", name: "", slug: "", description: "", order_num: 0, active: true }); + const slugTouchedRef = reactExports.useRef(Boolean(String(record.slug || "").trim())); + const difficultyField = reactExports.useMemo(() => getField$1(fields, "difficulty"), [fields]); + const accessField = reactExports.useMemo(() => getField$1(fields, "access_level"), [fields]); + const bodyWordCount = reactExports.useMemo(() => countWords(form.data.content), [form.data.content]); + const excerptLength = String(form.data.excerpt || "").length; + const csrfToken2 = reactExports.useMemo(() => { + if (typeof document === "undefined") return ""; + return document.querySelector('meta[name="csrf-token"]')?.getAttribute("content") || ""; + }, []); + reactExports.useEffect(() => { + if (slugTouchedRef.current) return; + form.setData("slug", slugifyLessonTitle(form.data.title)); + }, [form.data.title]); + const categoryOptions = reactExports.useMemo(() => { + const next = categories.map((category) => ({ value: String(category.id), label: category.name })); + return [{ value: "", label: "No category" }, ...next]; + }, [categories]); + const handleManualCoverChange = (nextValue) => { + form.setData("cover_image", nextValue); + setCoverPreviewUrl(normalizeCoverPreview(nextValue, editorContext.coverCdnBaseUrl)); + }; + const updateBlocks = (updater) => { + const currentBlocks = Array.isArray(form.data.blocks) ? form.data.blocks : []; + const nextBlocks = typeof updater === "function" ? updater(currentBlocks) : updater; + form.setData("blocks", nextBlocks); + }; + const updateBlock = (blockKey, updater) => { + updateBlocks((currentBlocks) => currentBlocks.map((block) => block.client_key === blockKey ? updater(block) : block)); + }; + const removeBlock = (blockKey) => { + updateBlocks((currentBlocks) => currentBlocks.filter((block) => block.client_key !== blockKey)); + }; + const addComparisonBlock = () => { + updateBlocks((currentBlocks) => [ + ...currentBlocks, + createEmptyComparisonBlock(currentBlocks.length, cdnBaseUrl) + ]); + }; + const addComparisonResult = (blockKey) => { + updateBlock(blockKey, (block) => ({ + ...block, + comparison_results: [ + ...Array.isArray(block.comparison_results) ? block.comparison_results : [], + createEmptyComparisonResult(Array.isArray(block.comparison_results) ? block.comparison_results.length : 0) + ] + })); + }; + const updateComparisonResult = (blockKey, resultKey, updater) => { + updateBlock(blockKey, (block) => ({ + ...block, + comparison_results: (Array.isArray(block.comparison_results) ? block.comparison_results : []).map((result) => result.client_key === resultKey ? updater(result) : result) + })); + }; + const removeComparisonResult = (blockKey, resultKey) => { + updateBlock(blockKey, (block) => ({ + ...block, + comparison_results: (Array.isArray(block.comparison_results) ? block.comparison_results : []).filter((result) => result.client_key !== resultKey) + })); + }; + const submit = (event) => { + event.preventDefault(); + const payload = buildLessonPayload(form.data); + form.transform(() => payload); + if (method === "patch") { + form.patch(submitUrl); + return; + } + form.post(submitUrl); + }; + const deleteLesson = () => { + if (!destroyUrl) return; + if (!window.confirm("Delete this lesson?")) return; + At.delete(destroyUrl); + }; + const applyJsonImport = () => { + try { + const parsed = parseLessonImport(jsonImportValue, categories); + Object.entries(parsed.next).forEach(([key, value]) => { + form.setData(key, value); + }); + if (parsed.next.cover_image != null) { + handleManualCoverChange(String(parsed.next.cover_image || "")); + } + if (parsed.next.slug != null) { + slugTouchedRef.current = true; + } + setJsonImportError(""); + setJsonImportOpen(false); + } catch (error) { + setJsonImportError(error instanceof Error ? error.message : "Could not parse JSON."); + } + }; + const createCategory = async () => { + setCategorySaving(true); + setCategoryError(""); + try { + const response = await fetch(editorContext.categoryStoreUrl, { + method: "POST", + headers: { + "Content-Type": "application/json", + "X-CSRF-TOKEN": csrfToken2, + Accept: "application/json" + }, + credentials: "same-origin", + body: JSON.stringify({ + ...categoryDraft, + order_num: Number(categoryDraft.order_num || 0), + slug: categoryDraft.slug || slugifyLessonTitle(categoryDraft.name) + }) + }); + const payload = await response.json().catch(() => ({})); + if (!response.ok) { + const firstError = payload?.errors ? Object.values(payload.errors)[0]?.[0] : null; + throw new Error(firstError || payload?.message || "Could not create category."); + } + const nextCategory = payload?.category; + if (!nextCategory?.id) { + throw new Error("Category response was incomplete."); + } + setCategories((current) => [...current, nextCategory].sort((left, right) => { + if (left.order_num !== right.order_num) return Number(left.order_num || 0) - Number(right.order_num || 0); + return String(left.name || "").localeCompare(String(right.name || "")); + })); + form.setData("category_id", String(nextCategory.id)); + setCategoryDraft({ type: "lesson", name: "", slug: "", description: "", order_num: 0, active: true }); + } catch (error) { + setCategoryError(error instanceof Error ? error.message : "Could not create category."); + } finally { + setCategorySaving(false); + } + }; + const comparisonBlocks = Array.isArray(form.data.blocks) ? form.data.blocks : []; + return /* @__PURE__ */ React.createElement(AdminLayout, { title, subtitle }, /* @__PURE__ */ React.createElement(Se, { title: `Admin · ${title}` }), /* @__PURE__ */ React.createElement("form", { onSubmit: submit, className: "space-y-6 pb-16" }, /* @__PURE__ */ React.createElement("section", { className: "overflow-hidden rounded-[28px] border border-white/10 bg-[radial-gradient(circle_at_top_left,rgba(56,189,248,0.14),transparent_34%),linear-gradient(180deg,rgba(15,23,42,0.96),rgba(2,6,23,0.94))] shadow-[0_24px_70px_rgba(2,6,23,0.34)] backdrop-blur" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-start justify-between gap-4 border-b border-white/10 px-5 py-4" }, /* @__PURE__ */ React.createElement("div", { className: "min-w-0 flex-1" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center gap-2 text-xs font-semibold uppercase tracking-[0.18em] text-slate-400" }, /* @__PURE__ */ React.createElement(xe, { href: indexUrl, className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-1.5 text-white transition hover:bg-white/[0.08]" }, "Back to lessons"), /* @__PURE__ */ React.createElement("span", null, destroyUrl ? "Edit lesson" : "New lesson")), /* @__PURE__ */ React.createElement("h1", { className: "mt-3 text-3xl font-semibold tracking-[-0.05em] text-white" }, form.data.title || "Untitled academy lesson"), /* @__PURE__ */ React.createElement("p", { className: "mt-2 max-w-3xl text-sm leading-7 text-slate-300" }, "Use the same richer writing flow as the newsroom: drag in the cover, shape the article with the rich editor, and keep publishing details in the same place.")), /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-3" }, /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => setJsonImportOpen(true), className: "rounded-2xl border border-white/10 bg-white/[0.05] px-4 py-2.5 text-sm font-semibold text-white transition hover:bg-white/[0.08]" }, "Import JSON"), /* @__PURE__ */ React.createElement("button", { type: "submit", disabled: form.processing, className: "rounded-2xl border border-sky-300/25 bg-sky-300/12 px-4 py-2.5 text-sm font-semibold text-sky-100" }, form.processing ? "Saving..." : "Save lesson")))), /* @__PURE__ */ React.createElement(SectionNav, { items: LESSON_SECTION_NAV_ITEMS }), /* @__PURE__ */ React.createElement("div", { className: "grid gap-6 xl:grid-cols-[minmax(0,1fr)_360px] xl:items-start" }, /* @__PURE__ */ React.createElement("div", { className: "min-w-0 space-y-6" }, /* @__PURE__ */ React.createElement(SectionCard$5, { id: "lesson-story-setup", eyebrow: "Story setup", title: "Headline and framing", description: "Start with the lesson identity and summary, then move into the full article body.", tone: "feature" }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 md:grid-cols-2" }, /* @__PURE__ */ React.createElement( + TextField$2, + { + label: "Title", + value: form.data.title, + onChange: (event) => form.setData("title", event.target.value), + error: form.errors.title, + maxLength: 180, + placeholder: "Prompt engineering for cleaner scene direction" + } + ), /* @__PURE__ */ React.createElement("label", { className: "grid gap-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "flex items-center justify-between gap-3 text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, /* @__PURE__ */ React.createElement("span", null, "Slug"), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => { + slugTouchedRef.current = false; + form.setData("slug", slugifyLessonTitle(form.data.title)); + }, className: "rounded-full border border-white/10 bg-white/[0.04] px-2.5 py-1 text-[10px] font-semibold text-white" }, "Sync")), /* @__PURE__ */ React.createElement( + "input", + { + value: form.data.slug, + onChange: (event) => { + slugTouchedRef.current = String(event.target.value).trim() !== ""; + form.setData("slug", event.target.value); + }, + className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white outline-none", + placeholder: "prompt-engineering-for-cleaner-scene-direction", + maxLength: 180 + } + ), /* @__PURE__ */ React.createElement("span", { className: "text-xs leading-5 text-slate-500" }, "The slug follows the title until you override it manually."), /* @__PURE__ */ React.createElement(FieldError$2, { message: form.errors.slug }))), /* @__PURE__ */ React.createElement("label", { className: "grid gap-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "flex items-center justify-between gap-3 text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, /* @__PURE__ */ React.createElement("span", null, "Excerpt"), /* @__PURE__ */ React.createElement("span", null, excerptLength, "/800")), /* @__PURE__ */ React.createElement("textarea", { value: form.data.excerpt, onChange: (event) => form.setData("excerpt", event.target.value), rows: 5, className: "rounded-[24px] border border-white/10 bg-black/20 px-4 py-3 text-white outline-none", placeholder: "Summarize what the lesson teaches, why it matters, and what a creator will walk away with." }), /* @__PURE__ */ React.createElement("span", { className: "text-xs leading-5 text-slate-500" }, "This is the short summary used in cards, internal lists, and metadata surfaces."), /* @__PURE__ */ React.createElement(FieldError$2, { message: form.errors.excerpt }))), /* @__PURE__ */ React.createElement(SectionCard$5, { id: "lesson-body-editor", eyebrow: "Main article", title: "Lesson body editor", description: "Write the tutorial in the same richer editing surface used for newsroom articles.", actions: /* @__PURE__ */ React.createElement("div", { className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-1.5 text-xs font-semibold uppercase tracking-[0.14em] text-white" }, bodyWordCount.toLocaleString(), " words") }, /* @__PURE__ */ React.createElement("div", { className: "grid min-w-0 gap-3 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement( + RichTextEditor, + { + content: form.data.content, + onChange: (nextValue) => form.setData("content", nextValue), + placeholder: "Open with the problem, explain the workflow step by step, and use headings, media, and links where the lesson needs structure.", + error: form.errors.content, + minHeight: 24, + autofocus: false, + advancedNews: true, + mediaSupport: { + uploadUrl: editorContext.bodyMediaUploadUrl, + deleteUrl: editorContext.bodyMediaDeleteUrl, + assetsUrl: editorContext.bodyMediaAssetsUrl, + slot: "body" + } + } + ), /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-black/20 px-4 py-3 text-xs leading-6 text-slate-400" }, "Tutorial workflow suggestion: define the outcome, break the process into clear steps, call out traps or quality checks, then finish with a practical next move."))), /* @__PURE__ */ React.createElement( + SectionCard$5, + { + id: "lesson-ai-comparisons", + eyebrow: "Structured blocks", + title: "AI model comparisons", + description: "Add reusable same-prompt comparison blocks without burying the data inside the lesson HTML body.", + actions: /* @__PURE__ */ React.createElement("button", { type: "button", onClick: addComparisonBlock, className: "rounded-full border border-[#ff9e8c]/25 bg-[#ff9e8c]/12 px-4 py-2 text-sm font-semibold text-[#ffd5cd]" }, "+ Add AI Comparison") + }, + /* @__PURE__ */ React.createElement("div", { className: "space-y-5" }, comparisonBlocks.length === 0 ? /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-dashed border-white/10 bg-black/20 px-5 py-6 text-sm leading-7 text-slate-400" }, "No comparison blocks yet. Add one when a lesson needs the same prompt analyzed across multiple AI image tools.") : comparisonBlocks.map((block, blockIndex) => /* @__PURE__ */ React.createElement("div", { key: block.client_key, className: "rounded-[28px] border border-white/10 bg-[radial-gradient(circle_at_top_left,rgba(255,158,140,0.12),transparent_34%),linear-gradient(180deg,rgba(15,23,42,0.82),rgba(6,10,18,0.95))] p-5 shadow-[0_24px_60px_rgba(2,6,23,0.22)]" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-start justify-between gap-3 border-b border-white/10 pb-4" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.22em] text-[#ffc0b4]" }, "AI Model Comparison"), /* @__PURE__ */ React.createElement("h3", { className: "mt-2 text-xl font-semibold tracking-[-0.03em] text-white" }, block.payload?.title || block.title || DEFAULT_AI_COMPARISON_TITLE)), /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-2" }, /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => removeBlock(block.client_key), className: "rounded-full border border-rose-300/20 bg-rose-300/10 px-3 py-1.5 text-xs font-semibold text-rose-100" }, "Remove block"))), /* @__PURE__ */ React.createElement("div", { className: "mt-5 grid gap-4 lg:grid-cols-2" }, /* @__PURE__ */ React.createElement( + TextField$2, + { + label: "Block title", + value: block.title, + onChange: (event) => updateBlock(block.client_key, (current) => ({ + ...current, + title: event.target.value, + payload: { ...current.payload, title: event.target.value } + })), + error: getFormError(form.errors, `blocks.${blockIndex}.title`) || getFormError(form.errors, `blocks.${blockIndex}.payload.title`), + placeholder: DEFAULT_AI_COMPARISON_TITLE + } + ), /* @__PURE__ */ React.createElement( + TextField$2, + { + label: "Aspect ratio", + value: block.payload?.aspect_ratio, + onChange: (event) => updateBlock(block.client_key, (current) => ({ ...current, payload: { ...current.payload, aspect_ratio: event.target.value } })), + error: getFormError(form.errors, `blocks.${blockIndex}.payload.aspect_ratio`), + placeholder: "16:9" + } + )), /* @__PURE__ */ React.createElement("div", { className: "mt-4 grid gap-4" }, /* @__PURE__ */ React.createElement( + TextAreaField$1, + { + label: "Intro", + value: block.payload?.intro, + onChange: (event) => updateBlock(block.client_key, (current) => ({ ...current, payload: { ...current.payload, intro: event.target.value } })), + error: getFormError(form.errors, `blocks.${blockIndex}.payload.intro`), + rows: 3 + } + ), /* @__PURE__ */ React.createElement( + TextAreaField$1, + { + label: "Prompt", + value: block.payload?.prompt, + onChange: (event) => updateBlock(block.client_key, (current) => ({ ...current, payload: { ...current.payload, prompt: event.target.value } })), + error: getFormError(form.errors, `blocks.${blockIndex}.payload.prompt`), + rows: 5 + } + ), /* @__PURE__ */ React.createElement( + TextAreaField$1, + { + label: "Negative prompt", + value: block.payload?.negative_prompt, + onChange: (event) => updateBlock(block.client_key, (current) => ({ ...current, payload: { ...current.payload, negative_prompt: event.target.value } })), + error: getFormError(form.errors, `blocks.${blockIndex}.payload.negative_prompt`), + rows: 3 + } + )), /* @__PURE__ */ React.createElement("div", { className: "mt-4 grid gap-4 lg:grid-cols-[minmax(0,1fr)_200px_200px]" }, /* @__PURE__ */ React.createElement( + TextAreaField$1, + { + label: "Criteria (one per line)", + value: (block.payload?.criteria || []).join("\n"), + onChange: (event) => updateBlock(block.client_key, (current) => ({ + ...current, + payload: { ...current.payload, criteria: normalizeCriteria(String(event.target.value || "").split(/\r?\n/)) } + })), + error: getFormError(form.errors, `blocks.${blockIndex}.payload.criteria`) || getFormError(form.errors, `blocks.${blockIndex}.payload.criteria.0`), + rows: 6, + hint: "Composition, lighting, wallpaper quality, and similar criteria work well here." + } + ), /* @__PURE__ */ React.createElement( + TextField$2, + { + label: "Sort order", + value: block.sort_order, + onChange: (event) => updateBlock(block.client_key, (current) => ({ ...current, sort_order: event.target.value })), + error: getFormError(form.errors, `blocks.${blockIndex}.sort_order`), + type: "number", + min: "0" + } + ), /* @__PURE__ */ React.createElement( + ToggleField$2, + { + label: "Active", + checked: Boolean(block.active), + onChange: (event) => updateBlock(block.client_key, (current) => ({ ...current, active: event.target.checked })), + error: getFormError(form.errors, `blocks.${blockIndex}.active`), + help: "Inactive comparison blocks stay stored but are hidden on the public lesson page." + } + )), /* @__PURE__ */ React.createElement("div", { className: "mt-6 rounded-[24px] border border-white/10 bg-black/20 p-4" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, "Results"), /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-sm text-slate-400" }, "Add one card per tool or model you want to compare.")), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => addComparisonResult(block.client_key), className: "rounded-full border border-sky-300/25 bg-sky-300/12 px-4 py-2 text-sm font-semibold text-sky-100" }, "+ Add model result")), /* @__PURE__ */ React.createElement("div", { className: "mt-4 space-y-4" }, (block.comparison_results || []).length === 0 ? /* @__PURE__ */ React.createElement("div", { className: "rounded-[22px] border border-dashed border-white/10 bg-white/[0.03] px-4 py-5 text-sm text-slate-500" }, "No model results yet.") : (block.comparison_results || []).map((result, resultIndex) => /* @__PURE__ */ React.createElement("div", { key: result.client_key, className: "rounded-[24px] border border-white/10 bg-slate-950/70 p-4" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-start justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "text-sm font-semibold text-white" }, result.model_name || result.provider || `Model result ${resultIndex + 1}`), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-xs uppercase tracking-[0.16em] text-slate-500" }, "Comparison card")), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => removeComparisonResult(block.client_key, result.client_key), className: "rounded-full border border-rose-300/20 bg-rose-300/10 px-3 py-1.5 text-xs font-semibold text-rose-100" }, "Remove")), /* @__PURE__ */ React.createElement("div", { className: "mt-4 grid gap-4 xl:grid-cols-2" }, /* @__PURE__ */ React.createElement( + WorldMediaUploadField, + { + label: "Generated image", + slot: "body", + value: result.image_path, + previewUrl: result.image_url, + emptyLabel: "Generated image", + helperText: "Upload the main comparison image using the same Academy lesson media pipeline.", + uploadUrl: editorContext.bodyMediaUploadUrl, + deleteUrl: editorContext.bodyMediaDeleteUrl, + isTemporaryValue: Boolean(result.image_temp_path) && result.image_temp_path === result.image_path, + onChange: ({ path, url }) => updateComparisonResult(block.client_key, result.client_key, (current) => ({ + ...current, + image_path: path || "", + image_url: url || normalizeCoverPreview(path || "", cdnBaseUrl), + image_temp_path: path || "" + })) + } + ), /* @__PURE__ */ React.createElement( + WorldMediaUploadField, + { + label: "Thumbnail image", + slot: "body", + value: result.thumb_path, + previewUrl: result.thumb_url, + emptyLabel: "Thumbnail", + helperText: "Optional smaller variant. Leave empty to reuse the main image on the public lesson page.", + uploadUrl: editorContext.bodyMediaUploadUrl, + deleteUrl: editorContext.bodyMediaDeleteUrl, + isTemporaryValue: Boolean(result.thumb_temp_path) && result.thumb_temp_path === result.thumb_path, + onChange: ({ path, url }) => updateComparisonResult(block.client_key, result.client_key, (current) => ({ + ...current, + thumb_path: path || "", + thumb_url: url || normalizeCoverPreview(path || "", cdnBaseUrl), + thumb_temp_path: path || "" + })) + } + )), /* @__PURE__ */ React.createElement("div", { className: "mt-4 grid gap-4 lg:grid-cols-2 xl:grid-cols-4" }, /* @__PURE__ */ React.createElement( + TextField$2, + { + label: "Provider", + value: result.provider, + onChange: (event) => updateComparisonResult(block.client_key, result.client_key, (current) => ({ ...current, provider: event.target.value })), + error: getFormError(form.errors, `blocks.${blockIndex}.comparison_results.${resultIndex}.provider`), + placeholder: "OpenAI" + } + ), /* @__PURE__ */ React.createElement( + TextField$2, + { + label: "Model", + value: result.model_name, + onChange: (event) => updateComparisonResult(block.client_key, result.client_key, (current) => ({ ...current, model_name: event.target.value })), + error: getFormError(form.errors, `blocks.${blockIndex}.comparison_results.${resultIndex}.model_name`), + placeholder: "ChatGPT Images" + } + ), /* @__PURE__ */ React.createElement( + TextField$2, + { + label: "Score", + value: result.score, + onChange: (event) => updateComparisonResult(block.client_key, result.client_key, (current) => ({ ...current, score: event.target.value })), + error: getFormError(form.errors, `blocks.${blockIndex}.comparison_results.${resultIndex}.score`), + type: "number", + min: "1", + max: "10" + } + ), /* @__PURE__ */ React.createElement( + TextField$2, + { + label: "Sort order", + value: result.sort_order, + onChange: (event) => updateComparisonResult(block.client_key, result.client_key, (current) => ({ ...current, sort_order: event.target.value })), + error: getFormError(form.errors, `blocks.${blockIndex}.comparison_results.${resultIndex}.sort_order`), + type: "number", + min: "0" + } + )), /* @__PURE__ */ React.createElement("div", { className: "mt-4 grid gap-4 lg:grid-cols-2" }, /* @__PURE__ */ React.createElement( + TextAreaField$1, + { + label: "Settings", + value: result.settings, + onChange: (event) => updateComparisonResult(block.client_key, result.client_key, (current) => ({ ...current, settings: event.target.value })), + error: getFormError(form.errors, `blocks.${blockIndex}.comparison_results.${resultIndex}.settings`), + rows: 3 + } + ), /* @__PURE__ */ React.createElement( + TextAreaField$1, + { + label: "Strengths", + value: result.strengths, + onChange: (event) => updateComparisonResult(block.client_key, result.client_key, (current) => ({ ...current, strengths: event.target.value })), + error: getFormError(form.errors, `blocks.${blockIndex}.comparison_results.${resultIndex}.strengths`), + rows: 3 + } + ), /* @__PURE__ */ React.createElement( + TextAreaField$1, + { + label: "Weaknesses", + value: result.weaknesses, + onChange: (event) => updateComparisonResult(block.client_key, result.client_key, (current) => ({ ...current, weaknesses: event.target.value })), + error: getFormError(form.errors, `blocks.${blockIndex}.comparison_results.${resultIndex}.weaknesses`), + rows: 3 + } + ), /* @__PURE__ */ React.createElement( + TextAreaField$1, + { + label: "Best for", + value: result.best_for, + onChange: (event) => updateComparisonResult(block.client_key, result.client_key, (current) => ({ ...current, best_for: event.target.value })), + error: getFormError(form.errors, `blocks.${blockIndex}.comparison_results.${resultIndex}.best_for`), + rows: 3 + } + )), /* @__PURE__ */ React.createElement("div", { className: "mt-4 grid gap-4 lg:grid-cols-2" }, /* @__PURE__ */ React.createElement( + TextField$2, + { + label: "Image path override", + value: result.image_path, + onChange: (event) => updateComparisonResult(block.client_key, result.client_key, (current) => ({ + ...current, + image_path: event.target.value, + image_url: normalizeCoverPreview(event.target.value, cdnBaseUrl), + image_temp_path: "" + })), + error: getFormError(form.errors, `blocks.${blockIndex}.comparison_results.${resultIndex}.image_path`), + placeholder: "academy/lessons/body/..." + } + ), /* @__PURE__ */ React.createElement( + TextField$2, + { + label: "Thumbnail path override", + value: result.thumb_path, + onChange: (event) => updateComparisonResult(block.client_key, result.client_key, (current) => ({ + ...current, + thumb_path: event.target.value, + thumb_url: normalizeCoverPreview(event.target.value, cdnBaseUrl), + thumb_temp_path: "" + })), + error: getFormError(form.errors, `blocks.${blockIndex}.comparison_results.${resultIndex}.thumb_path`), + placeholder: "Optional academy/lessons/body/..." + } + )), /* @__PURE__ */ React.createElement("div", { className: "mt-4" }, /* @__PURE__ */ React.createElement( + ToggleField$2, + { + label: "Result active", + checked: Boolean(result.active), + onChange: (event) => updateComparisonResult(block.client_key, result.client_key, (current) => ({ ...current, active: event.target.checked })), + error: getFormError(form.errors, `blocks.${blockIndex}.comparison_results.${resultIndex}.active`), + help: "Inactive results stay saved but do not render on the public lesson page." + } + ))))))))) + ), /* @__PURE__ */ React.createElement(SectionCard$5, { id: "lesson-publishing", eyebrow: "Publishing", title: "Placement and visibility", description: "Set the lesson metadata, schedule, and discovery fields before it goes live." }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 md:grid-cols-2" }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement(NovaSelect, { label: "Difficulty", value: form.data.difficulty || "", onChange: (nextValue) => form.setData("difficulty", String(nextValue || "")), options: difficultyField?.options || [], searchable: false, className: "bg-black/20", error: form.errors.difficulty })), /* @__PURE__ */ React.createElement("div", { className: "grid gap-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement(NovaSelect, { label: "Access", value: form.data.access_level || "", onChange: (nextValue) => form.setData("access_level", String(nextValue || "")), options: accessField?.options || [], searchable: false, className: "bg-black/20", error: form.errors.access_level }))), /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 md:grid-cols-2" }, /* @__PURE__ */ React.createElement(TextField$2, { label: "Lesson type", value: form.data.lesson_type, onChange: (event) => form.setData("lesson_type", event.target.value), error: form.errors.lesson_type, placeholder: "article, video, walkthrough" }), /* @__PURE__ */ React.createElement(TextField$2, { label: "Reading minutes", value: form.data.reading_minutes, onChange: (event) => form.setData("reading_minutes", event.target.value), error: form.errors.reading_minutes, type: "number", min: "1", max: "999" })), /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 md:grid-cols-2" }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement(NovaSelect, { label: "Category", value: form.data.category_id || "", onChange: (nextValue) => form.setData("category_id", String(nextValue || "")), options: categoryOptions, searchable: false, className: "bg-black/20", error: form.errors.category_id })), /* @__PURE__ */ React.createElement("div", { className: "grid gap-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Publish at"), /* @__PURE__ */ React.createElement(DateTimePicker, { value: form.data.published_at || "", onChange: (nextValue) => form.setData("published_at", nextValue || ""), clearable: true, className: "bg-black/20" }), /* @__PURE__ */ React.createElement(FieldError$2, { message: form.errors.published_at }))), /* @__PURE__ */ React.createElement("div", { className: "grid gap-3 md:grid-cols-2" }, /* @__PURE__ */ React.createElement(ToggleField$2, { label: "Featured", checked: Boolean(form.data.featured), onChange: (event) => form.setData("featured", event.target.checked), help: "Highlight this lesson in featured academy surfaces.", error: form.errors.featured }), /* @__PURE__ */ React.createElement(ToggleField$2, { label: "Active", checked: Boolean(form.data.active), onChange: (event) => form.setData("active", event.target.checked), help: "Keep inactive lessons hidden until the draft is ready.", error: form.errors.active }))), /* @__PURE__ */ React.createElement(SectionCard$5, { id: "lesson-seo", eyebrow: "SEO", title: "Search metadata", description: "Keep the lesson search-ready without stuffing the headline." }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 md:grid-cols-2" }, /* @__PURE__ */ React.createElement(TextField$2, { label: "SEO title", value: form.data.seo_title, onChange: (event) => form.setData("seo_title", event.target.value), error: form.errors.seo_title, maxLength: 180, placeholder: "Optional search title" }), /* @__PURE__ */ React.createElement(TextField$2, { label: "Video URL", value: form.data.video_url, onChange: (event) => form.setData("video_url", event.target.value), error: form.errors.video_url, placeholder: "Optional lesson video URL" })), /* @__PURE__ */ React.createElement(TextAreaField$1, { label: "SEO description", value: form.data.seo_description, onChange: (event) => form.setData("seo_description", event.target.value), error: form.errors.seo_description, rows: 4, hint: "Keep this tighter than the excerpt and focused on search intent." })), /* @__PURE__ */ React.createElement(SectionCard$5, { id: "lesson-categories", eyebrow: "Lesson categories", title: "Create category inline", description: "Add lesson categories without leaving the writing flow.", actions: /* @__PURE__ */ React.createElement("a", { href: editorContext.categoryManageUrl, className: "rounded-full border border-white/10 bg-white/[0.04] px-4 py-2 text-sm font-semibold text-white" }, "Manage all categories") }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-5 lg:grid-cols-[minmax(0,1fr)_minmax(0,1fr)]" }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-3" }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-3 md:grid-cols-2" }, /* @__PURE__ */ React.createElement("input", { value: categoryDraft.name, onChange: (event) => setCategoryDraft((current) => ({ ...current, name: event.target.value })), placeholder: "Category name", className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white outline-none" }), /* @__PURE__ */ React.createElement("input", { value: categoryDraft.slug, onChange: (event) => setCategoryDraft((current) => ({ ...current, slug: event.target.value })), placeholder: "Optional slug", className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white outline-none" })), /* @__PURE__ */ React.createElement("textarea", { value: categoryDraft.description, onChange: (event) => setCategoryDraft((current) => ({ ...current, description: event.target.value })), rows: 3, placeholder: "Description", className: "rounded-[24px] border border-white/10 bg-black/20 px-4 py-3 text-white outline-none" }), /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center gap-3" }, /* @__PURE__ */ React.createElement("input", { type: "number", value: categoryDraft.order_num, min: "0", onChange: (event) => setCategoryDraft((current) => ({ ...current, order_num: event.target.value })), className: "w-28 rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white outline-none" }), /* @__PURE__ */ React.createElement("label", { className: "flex items-center gap-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("input", { type: "checkbox", checked: categoryDraft.active, onChange: (event) => setCategoryDraft((current) => ({ ...current, active: event.target.checked })) }), " Active"), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => void createCategory(), disabled: categorySaving, className: "rounded-full border border-sky-300/20 bg-sky-400/10 px-4 py-2 text-sm font-semibold text-sky-100" }, categorySaving ? "Creating..." : "Create category")), categoryError ? /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-rose-300/20 bg-rose-400/10 px-4 py-3 text-sm text-rose-100" }, categoryError) : null), /* @__PURE__ */ React.createElement("div", { className: "grid gap-3" }, (categories || []).length === 0 ? /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-dashed border-white/10 bg-white/[0.02] p-4 text-sm text-slate-500" }, "No lesson categories yet.") : categories.map((category) => /* @__PURE__ */ React.createElement("div", { key: category.id, className: "rounded-[24px] border border-white/10 bg-black/20 p-4" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-start justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "text-sm font-semibold text-white" }, category.name), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-xs uppercase tracking-[0.14em] text-slate-500" }, category.slug), category.description ? /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm leading-6 text-slate-400" }, category.description) : null), /* @__PURE__ */ React.createElement("a", { href: category.edit_url, className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-1.5 text-xs font-semibold text-white" }, "Edit")))))))), /* @__PURE__ */ React.createElement("div", { className: "space-y-6 xl:sticky xl:top-6 xl:self-start" }, /* @__PURE__ */ React.createElement(SectionCard$5, { id: "lesson-cover", eyebrow: "Cover image", title: "Hero asset", description: "Use drag and drop for the lesson image, or paste a direct URL when you already have one." }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-4" }, /* @__PURE__ */ React.createElement( + WorldMediaUploadField, + { + label: "Lesson cover", + slot: "cover", + value: form.data.cover_image, + previewUrl: coverPreviewUrl, + emptyLabel: "Drop a lesson cover", + helperText: "Upload the hero image directly to object storage. A wide landscape image works best for academy cards, previews, and social sharing.", + uploadUrl: editorContext.coverUploadUrl, + deleteUrl: editorContext.coverDeleteUrl, + onChange: ({ path, url }) => { + setStagedCoverPath(path || ""); + form.setData("cover_image", path || ""); + setCoverPreviewUrl(url || ""); + }, + isTemporaryValue: Boolean(stagedCoverPath) && form.data.cover_image === stagedCoverPath + } + ), /* @__PURE__ */ React.createElement(FieldError$2, { message: form.errors.cover_image }), /* @__PURE__ */ React.createElement("label", { className: "grid gap-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Advanced cover path or URL"), /* @__PURE__ */ React.createElement("input", { value: form.data.cover_image, onChange: (event) => handleManualCoverChange(event.target.value), placeholder: "Optional external URL or stored object path", className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white outline-none" }), /* @__PURE__ */ React.createElement("span", { className: "text-xs leading-5 text-slate-500" }, "Keep this for migrations, imported lessons, or when you already know the exact asset path to use.")))), /* @__PURE__ */ React.createElement(SectionCard$5, { id: "lesson-preview", eyebrow: "Preview", title: "Lesson snapshot", description: "A quick view of what editors and visitors will scan first." }, /* @__PURE__ */ React.createElement("div", { className: "overflow-hidden rounded-[24px] border border-white/10 bg-black/30" }, coverPreviewUrl ? /* @__PURE__ */ React.createElement("img", { src: coverPreviewUrl, alt: "Lesson cover preview", className: "h-56 w-full object-cover" }) : /* @__PURE__ */ React.createElement("div", { className: "flex h-56 items-center justify-center px-6 text-center text-sm text-slate-500" }, "No cover image selected yet.")), /* @__PURE__ */ React.createElement("div", { className: "mt-4 rounded-[24px] border border-white/10 bg-black/20 p-4" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.22em] text-slate-400" }, "Lesson summary"), /* @__PURE__ */ React.createElement("h3", { className: "mt-3 text-2xl font-semibold tracking-[-0.04em] text-white" }, form.data.title || "Untitled lesson"), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm leading-7 text-slate-400" }, form.data.excerpt || "Add a concise excerpt to frame the lesson before someone opens it."), /* @__PURE__ */ React.createElement("dl", { className: "mt-4 grid grid-cols-2 gap-3 text-xs text-slate-400" }, /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-white/[0.03] px-3 py-2" }, /* @__PURE__ */ React.createElement("dt", { className: "uppercase tracking-[0.16em] text-slate-500" }, "Difficulty"), /* @__PURE__ */ React.createElement("dd", { className: "mt-1 text-sm text-white" }, form.data.difficulty || "—")), /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-white/[0.03] px-3 py-2" }, /* @__PURE__ */ React.createElement("dt", { className: "uppercase tracking-[0.16em] text-slate-500" }, "Access"), /* @__PURE__ */ React.createElement("dd", { className: "mt-1 text-sm text-white" }, form.data.access_level || "—")), /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-white/[0.03] px-3 py-2" }, /* @__PURE__ */ React.createElement("dt", { className: "uppercase tracking-[0.16em] text-slate-500" }, "Reading"), /* @__PURE__ */ React.createElement("dd", { className: "mt-1 text-sm text-white" }, form.data.reading_minutes || "—", " min")), /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-white/[0.03] px-3 py-2" }, /* @__PURE__ */ React.createElement("dt", { className: "uppercase tracking-[0.16em] text-slate-500" }, "Body"), /* @__PURE__ */ React.createElement("dd", { className: "mt-1 text-sm text-white" }, bodyWordCount.toLocaleString(), " words"))))))), /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-3 rounded-[28px] border border-white/10 bg-white/[0.03] p-5" }, /* @__PURE__ */ React.createElement("button", { type: "submit", disabled: form.processing, className: "rounded-full border border-sky-300/25 bg-sky-300/12 px-5 py-3 text-sm font-semibold text-sky-100" }, form.processing ? "Saving..." : "Save lesson"), /* @__PURE__ */ React.createElement(xe, { href: indexUrl, className: "rounded-full border border-white/10 bg-white/[0.04] px-5 py-3 text-sm font-semibold text-white" }, "Back"), destroyUrl ? /* @__PURE__ */ React.createElement("button", { type: "button", onClick: deleteLesson, className: "rounded-full border border-rose-300/20 bg-rose-300/10 px-5 py-3 text-sm font-semibold text-rose-100" }, "Delete") : null)), /* @__PURE__ */ React.createElement( + JsonImportDialog$1, + { + open: jsonImportOpen, + value: jsonImportValue, + error: jsonImportError, + onChange: (nextValue) => { + setJsonImportValue(nextValue); + if (jsonImportError) { + setJsonImportError(""); + } + }, + onClose: () => { + setJsonImportOpen(false); + setJsonImportError(""); + }, + onApply: applyJsonImport + } + )); +} +const __vite_glob_0_8 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ + __proto__: null, + default: LessonEditor +}, Symbol.toStringTag, { value: "Module" })); +function normalizePayload(fields, data) { + const payload = { ...data }; + fields.forEach((field) => { + if (field.type === "csv") { + payload[field.name] = String(payload[field.name] || "").split(/[,\n]/).map((item) => item.trim()).filter(Boolean); + } + if (field.type === "json") { + try { + payload[field.name] = payload[field.name] ? JSON.parse(payload[field.name]) : {}; + } catch { + payload[field.name] = {}; + } + } + }); + return payload; +} +function getField(fields, name2) { + return fields.find((field) => field.name === name2) || null; +} +function SectionCard$4({ eyebrow, title, description, children, className = "" }) { + return /* @__PURE__ */ React.createElement("section", { className: `w-full min-w-0 rounded-[32px] border border-white/10 bg-white/[0.04] p-6 shadow-[0_20px_80px_rgba(15,23,42,0.18)] ${className}`.trim() }, /* @__PURE__ */ React.createElement("div", { className: "mb-5" }, eyebrow ? /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.24em] text-sky-200/80" }, eyebrow) : null, /* @__PURE__ */ React.createElement("h2", { className: "mt-2 text-xl font-semibold tracking-[-0.04em] text-white" }, title), description ? /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm leading-7 text-slate-400" }, description) : null), /* @__PURE__ */ React.createElement("div", { className: "grid gap-5" }, children)); +} +function TextField$1({ label, value, onChange, error, ...rest }) { + return /* @__PURE__ */ React.createElement("label", { className: "grid gap-2 text-sm text-slate-200" }, /* @__PURE__ */ React.createElement("span", null, label), /* @__PURE__ */ React.createElement("input", { value: value ?? "", onChange, className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-sm text-white outline-none", ...rest }), error ? /* @__PURE__ */ React.createElement("p", { className: "text-xs text-rose-300" }, error) : null); +} +function TextAreaField({ label, value, onChange, error, rows = 6, hint }) { + return /* @__PURE__ */ React.createElement("label", { className: "grid gap-2 text-sm text-slate-200" }, /* @__PURE__ */ React.createElement("span", null, label), /* @__PURE__ */ React.createElement("textarea", { value: value ?? "", onChange, rows, className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-sm leading-7 text-white outline-none" }), hint ? /* @__PURE__ */ React.createElement("span", { className: "text-xs leading-5 text-slate-500" }, hint) : null, error ? /* @__PURE__ */ React.createElement("p", { className: "text-xs text-rose-300" }, error) : null); +} +function ToggleField$1({ label, checked, onChange, help, error }) { + return /* @__PURE__ */ React.createElement("label", { className: "flex items-start gap-3 rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-sm text-slate-200" }, /* @__PURE__ */ React.createElement("input", { type: "checkbox", checked: Boolean(checked), onChange, className: "mt-1" }), /* @__PURE__ */ React.createElement("span", null, /* @__PURE__ */ React.createElement("span", { className: "block font-semibold text-white" }, label), help ? /* @__PURE__ */ React.createElement("span", { className: "mt-1 block text-xs leading-5 text-slate-400" }, help) : null, error ? /* @__PURE__ */ React.createElement("span", { className: "mt-2 block text-xs text-rose-300" }, error) : null)); +} +function Field$4({ field, form }) { + const value = form.data[field.name]; + if (field.type === "checkbox") { + return /* @__PURE__ */ React.createElement("label", { className: "flex items-center gap-3 rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-sm text-slate-200" }, /* @__PURE__ */ React.createElement("input", { type: "checkbox", checked: Boolean(value), onChange: (event) => form.setData(field.name, event.target.checked) }), field.label); + } + if (field.type === "datetime-local") { + return /* @__PURE__ */ React.createElement( + DateTimePicker, + { + label: field.label, + value: value || "", + onChange: (nextValue) => form.setData(field.name, nextValue || ""), + error: form.errors[field.name], + clearable: true, + className: "bg-black/20" + } + ); + } + if (field.type === "textarea") { + return /* @__PURE__ */ React.createElement("label", { className: "grid gap-2 text-sm text-slate-200" }, /* @__PURE__ */ React.createElement("span", null, field.label), /* @__PURE__ */ React.createElement( + "textarea", + { + value: value || "", + onChange: (event) => form.setData(field.name, event.target.value), + rows: field.rows || 6, + className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-sm leading-7 text-white outline-none" + } + ), form.errors[field.name] ? /* @__PURE__ */ React.createElement("p", { className: "text-xs text-rose-300" }, form.errors[field.name]) : null); + } + if (field.type === "select") { + return /* @__PURE__ */ React.createElement( + NovaSelect, + { + label: field.label, + value: value ?? "", + onChange: (nextValue) => form.setData(field.name, nextValue ?? ""), + options: field.options || [], + searchable: false, + className: "rounded-2xl bg-black/20", + error: form.errors[field.name] + } + ); + } + if (field.type === "multiselect") { + return /* @__PURE__ */ React.createElement( + NovaSelect, + { + multi: true, + label: field.label, + value: value || [], + onChange: (nextValue) => form.setData(field.name, Array.isArray(nextValue) ? nextValue : []), + options: field.options || [], + className: "rounded-2xl bg-black/20", + error: form.errors[field.name] + } + ); + } + return /* @__PURE__ */ React.createElement("label", { className: "grid gap-2 text-sm text-slate-200" }, /* @__PURE__ */ React.createElement("span", null, field.label), /* @__PURE__ */ React.createElement( + "input", + { + type: field.type || "text", + value: value ?? "", + onChange: (event) => form.setData(field.name, event.target.value), + className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-sm text-white outline-none" + } + ), form.errors[field.name] ? /* @__PURE__ */ React.createElement("p", { className: "text-xs text-rose-300" }, form.errors[field.name]) : null); +} +function PromptPreviewDropzone({ form, previewUrl }) { + const inputRef = reactExports.useRef(null); + const [dragging, setDragging] = reactExports.useState(false); + const [localPreviewUrl, setLocalPreviewUrl] = reactExports.useState(""); + const [selectedFileName, setSelectedFileName] = reactExports.useState(""); + const previewSrc = localPreviewUrl || previewUrl || form.data.preview_image || ""; + reactExports.useEffect(() => () => { + if (localPreviewUrl.startsWith("blob:")) { + URL.revokeObjectURL(localPreviewUrl); + } + }, [localPreviewUrl]); + const setSelectedFile = (file) => { + if (localPreviewUrl.startsWith("blob:")) { + URL.revokeObjectURL(localPreviewUrl); + } + if (!file) { + setLocalPreviewUrl(""); + setSelectedFileName(""); + form.setData("preview_image_file", null); + form.clearErrors("preview_image_file"); + return; + } + const nextPreviewUrl = URL.createObjectURL(file); + setLocalPreviewUrl(nextPreviewUrl); + setSelectedFileName(file.name); + form.setData("preview_image_file", file); + form.clearErrors("preview_image_file"); + }; + const clearSelection = () => { + if (localPreviewUrl.startsWith("blob:")) { + URL.revokeObjectURL(localPreviewUrl); + } + setLocalPreviewUrl(""); + setSelectedFileName(""); + form.setData("preview_image_file", null); + form.clearErrors("preview_image_file"); + if (inputRef.current) { + inputRef.current.value = ""; + } + }; + return /* @__PURE__ */ React.createElement( + SectionCard$4, + { + eyebrow: "Visual preview", + title: "Preview image", + description: "Drag an image here or paste a URL. Uploaded files are converted to WebP and stored on Contabo automatically." + }, + /* @__PURE__ */ React.createElement( + "div", + { + role: "button", + tabIndex: 0, + onClick: () => inputRef.current?.click(), + onKeyDown: (event) => { + if (event.key === "Enter" || event.key === " ") { + event.preventDefault(); + inputRef.current?.click(); + } + }, + onDragOver: (event) => { + event.preventDefault(); + setDragging(true); + }, + onDragEnter: (event) => { + event.preventDefault(); + setDragging(true); + }, + onDragLeave: (event) => { + event.preventDefault(); + setDragging(false); + }, + onDrop: (event) => { + event.preventDefault(); + setDragging(false); + setSelectedFile(event.dataTransfer?.files?.[0] || null); + }, + className: [ + "w-full min-w-0 rounded-[28px] border border-dashed p-5 outline-none transition", + dragging ? "border-sky-300/50 bg-sky-400/10" : "border-white/10 bg-black/20 hover:border-white/20 hover:bg-white/[0.04]" + ].join(" ") + }, + /* @__PURE__ */ React.createElement("div", { className: "flex flex-col gap-4" }, /* @__PURE__ */ React.createElement("div", { className: "flex min-w-0 items-start gap-4" }, /* @__PURE__ */ React.createElement("div", { className: "flex h-12 w-12 shrink-0 items-center justify-center rounded-2xl border border-sky-300/20 bg-sky-400/10 text-sky-100" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-image" })), /* @__PURE__ */ React.createElement("div", { className: "min-w-0 flex-1" }, /* @__PURE__ */ React.createElement("div", { className: "text-sm font-semibold text-white" }, "Drop a preview image or browse"), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-xs leading-5 text-slate-400" }, "JPG, PNG, or WEBP. The server re-encodes the final asset to WebP before uploading it to the CDN."), /* @__PURE__ */ React.createElement("div", { className: "mt-2 flex flex-wrap gap-2 text-[11px] text-slate-400" }, /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.04] px-2.5 py-1" }, "JPG"), /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.04] px-2.5 py-1" }, "PNG"), /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.04] px-2.5 py-1" }, "WEBP"), /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.04] px-2.5 py-1" }, "Max 5 MB")))), /* @__PURE__ */ React.createElement("div", { className: "grid w-full max-w-full gap-3" }, /* @__PURE__ */ React.createElement("div", { className: "overflow-hidden rounded-[20px] border border-white/10 bg-slate-950" }, previewSrc ? /* @__PURE__ */ React.createElement("img", { src: previewSrc, alt: "Prompt preview", className: "h-40 w-full object-cover" }) : /* @__PURE__ */ React.createElement("div", { className: "flex h-40 items-center justify-center px-4 text-center text-sm text-slate-500" }, "No preview image selected")), /* @__PURE__ */ React.createElement("div", { className: "flex gap-2" }, /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => inputRef.current?.click(), className: "flex-1 rounded-full border border-white/10 bg-white/[0.04] px-4 py-2.5 text-sm font-semibold text-white transition hover:bg-white/[0.08]" }, "Browse"), selectedFileName || localPreviewUrl ? /* @__PURE__ */ React.createElement("button", { type: "button", onClick: clearSelection, className: "rounded-full border border-white/10 bg-transparent px-4 py-2.5 text-sm font-semibold text-slate-300 transition hover:bg-white/[0.04]" }, "Clear") : null))), + /* @__PURE__ */ React.createElement( + "input", + { + ref: inputRef, + type: "file", + accept: "image/jpeg,image/png,image/webp", + className: "hidden", + onChange: (event) => { + setSelectedFile(event.target.files?.[0] || null); + event.target.value = ""; + } + } + ), + /* @__PURE__ */ React.createElement("div", { className: "mt-4 grid min-w-0 gap-3 md:grid-cols-1 lg:grid-cols-[minmax(0,1fr)_minmax(0,220px)]" }, /* @__PURE__ */ React.createElement( + TextField$1, + { + label: "Preview image URL fallback", + value: form.data.preview_image || "", + onChange: (event) => form.setData("preview_image", event.target.value), + error: form.errors.preview_image, + placeholder: "Paste a URL or leave empty if you upload a file" + } + ), /* @__PURE__ */ React.createElement("div", { className: "min-w-0 rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-xs leading-6 text-slate-300" }, /* @__PURE__ */ React.createElement("div", { className: "font-semibold text-white" }, "Stored value"), /* @__PURE__ */ React.createElement("div", { className: "mt-1 break-all text-slate-400" }, form.data.preview_image_file?.name || form.data.preview_image || previewUrl || "None yet"))), + form.errors.preview_image_file ? /* @__PURE__ */ React.createElement("p", { className: "mt-3 text-sm text-rose-300" }, form.errors.preview_image_file) : null + ) + ); +} +function PromptEditor({ title, subtitle, fields, record, submitUrl, indexUrl, destroyUrl, method }) { + const form = G({ ...record, preview_image_file: null }); + const categoryField = reactExports.useMemo(() => getField(fields, "category_id"), [fields]); + const difficultyField = reactExports.useMemo(() => getField(fields, "difficulty"), [fields]); + const accessField = reactExports.useMemo(() => getField(fields, "access_level"), [fields]); + const publishedAtField = reactExports.useMemo(() => getField(fields, "published_at"), [fields]); + const featuredField = reactExports.useMemo(() => getField(fields, "featured"), [fields]); + const promptOfWeekField = reactExports.useMemo(() => getField(fields, "prompt_of_week"), [fields]); + const activeField = reactExports.useMemo(() => getField(fields, "active"), [fields]); + const seoDescriptionField = reactExports.useMemo(() => getField(fields, "seo_description"), [fields]); + const previewUrl = form.data.preview_image_url || ""; + const submit = (event) => { + event.preventDefault(); + const payload = normalizePayload(fields, form.data); + form.transform(() => payload); + if (method === "patch") { + form.patch(submitUrl); + return; + } + form.post(submitUrl); + }; + const tagCount = String(form.data.tags || "").split(/[,\n]/).map((item) => item.trim()).filter(Boolean).length; + return /* @__PURE__ */ React.createElement(AdminLayout, { title, subtitle }, /* @__PURE__ */ React.createElement(Se, { title: `Admin · ${title}` }), /* @__PURE__ */ React.createElement("form", { onSubmit: submit, className: "space-y-6" }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-6 xl:grid-cols-[minmax(0,1fr)_minmax(0,340px)]" }, /* @__PURE__ */ React.createElement("div", { className: "min-w-0 space-y-6" }, /* @__PURE__ */ React.createElement( + SectionCard$4, + { + eyebrow: "Identity", + title: "Core prompt details", + description: "Set the catalog identity first so the prompt is easy to find, sort, and preview." + }, + /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 md:grid-cols-2" }, categoryField ? /* @__PURE__ */ React.createElement(NovaSelect, { label: categoryField.label, value: form.data.category_id ?? "", onChange: (nextValue) => form.setData("category_id", nextValue ?? ""), options: categoryField.options || [], searchable: false, className: "rounded-2xl bg-black/20", error: form.errors.category_id }) : null, difficultyField ? /* @__PURE__ */ React.createElement(NovaSelect, { label: difficultyField.label, value: form.data.difficulty ?? "", onChange: (nextValue) => form.setData("difficulty", nextValue ?? ""), options: difficultyField.options || [], searchable: false, className: "rounded-2xl bg-black/20", error: form.errors.difficulty }) : null), + /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 md:grid-cols-2" }, accessField ? /* @__PURE__ */ React.createElement(NovaSelect, { label: accessField.label, value: form.data.access_level ?? "", onChange: (nextValue) => form.setData("access_level", nextValue ?? ""), options: accessField.options || [], searchable: false, className: "rounded-2xl bg-black/20", error: form.errors.access_level }) : null, /* @__PURE__ */ React.createElement(TextField$1, { label: "Aspect ratio", value: form.data.aspect_ratio || "", onChange: (event) => form.setData("aspect_ratio", event.target.value), error: form.errors.aspect_ratio, placeholder: "1:1, 16:9, 3:2" })), + /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 md:grid-cols-2" }, /* @__PURE__ */ React.createElement(TextField$1, { label: "Title", value: form.data.title || "", onChange: (event) => form.setData("title", event.target.value), error: form.errors.title, maxLength: 180 }), /* @__PURE__ */ React.createElement(TextField$1, { label: "Slug", value: form.data.slug || "", onChange: (event) => form.setData("slug", event.target.value), error: form.errors.slug, maxLength: 180, placeholder: "prompt-template-slug" })), + /* @__PURE__ */ React.createElement(TextAreaField, { label: "Excerpt", value: form.data.excerpt || "", onChange: (event) => form.setData("excerpt", event.target.value), error: form.errors.excerpt, rows: 4, hint: "Short summary shown in the library and preview cards." }), + /* @__PURE__ */ React.createElement(TextField$1, { label: "Tags", value: form.data.tags || "", onChange: (event) => form.setData("tags", event.target.value), error: form.errors.tags, placeholder: "wallpaper, cinematic, neon, portrait" }) + ), /* @__PURE__ */ React.createElement( + SectionCard$4, + { + eyebrow: "Prompt body", + title: "Prompt instructions", + description: "Write the instruction stack, guardrails, and production notes in a way that is easy to scan." + }, + /* @__PURE__ */ React.createElement(TextAreaField, { label: "Prompt", value: form.data.prompt || "", onChange: (event) => form.setData("prompt", event.target.value), error: form.errors.prompt, rows: 10, hint: "This is the main model instruction used by creators." }), + /* @__PURE__ */ React.createElement(TextAreaField, { label: "Negative prompt", value: form.data.negative_prompt || "", onChange: (event) => form.setData("negative_prompt", event.target.value), error: form.errors.negative_prompt, rows: 5, hint: "Optional exclusions, artifacts, or anti-patterns to avoid." }), + /* @__PURE__ */ React.createElement(TextAreaField, { label: "Usage notes", value: form.data.usage_notes || "", onChange: (event) => form.setData("usage_notes", event.target.value), error: form.errors.usage_notes, rows: 5, hint: "Explain how to apply the prompt in a practical workflow." }), + /* @__PURE__ */ React.createElement(TextAreaField, { label: "Workflow notes", value: form.data.workflow_notes || "", onChange: (event) => form.setData("workflow_notes", event.target.value), error: form.errors.workflow_notes, rows: 5, hint: "Internal editorial notes, camera settings, or prompt variants." }) + ), /* @__PURE__ */ React.createElement( + SectionCard$4, + { + eyebrow: "Publishing", + title: "Release controls", + description: "Choose when the prompt becomes visible and how it behaves in the academy." + }, + /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 md:grid-cols-2" }, publishedAtField ? /* @__PURE__ */ React.createElement(DateTimePicker, { label: publishedAtField.label, value: form.data.published_at || "", onChange: (nextValue) => form.setData("published_at", nextValue || ""), error: form.errors.published_at, clearable: true, className: "bg-black/20" }) : null, /* @__PURE__ */ React.createElement(TextField$1, { label: "SEO title", value: form.data.seo_title || "", onChange: (event) => form.setData("seo_title", event.target.value), error: form.errors.seo_title, maxLength: 180 })), + seoDescriptionField ? /* @__PURE__ */ React.createElement(TextAreaField, { label: seoDescriptionField.label, value: form.data.seo_description || "", onChange: (event) => form.setData("seo_description", event.target.value), error: form.errors.seo_description, rows: 4 }) : null, + /* @__PURE__ */ React.createElement("div", { className: "grid gap-3 md:grid-cols-3" }, featuredField ? /* @__PURE__ */ React.createElement(ToggleField$1, { label: featuredField.label, checked: Boolean(form.data.featured), onChange: (event) => form.setData("featured", event.target.checked), help: "Highlight this prompt in featured rails.", error: form.errors.featured }) : null, promptOfWeekField ? /* @__PURE__ */ React.createElement(ToggleField$1, { label: promptOfWeekField.label, checked: Boolean(form.data.prompt_of_week), onChange: (event) => form.setData("prompt_of_week", event.target.checked), help: "Promote this prompt as the current weekly pick.", error: form.errors.prompt_of_week }) : null, activeField ? /* @__PURE__ */ React.createElement(ToggleField$1, { label: activeField.label, checked: Boolean(form.data.active), onChange: (event) => form.setData("active", event.target.checked), help: "Keep draft prompts hidden until they are ready.", error: form.errors.active }) : null) + )), /* @__PURE__ */ React.createElement("div", { className: "min-w-0 space-y-6 xl:sticky xl:top-6 xl:self-start" }, /* @__PURE__ */ React.createElement( + SectionCard$4, + { + eyebrow: "At a glance", + title: "Prompt preview", + description: "A compact summary of what editors and visitors will see." + }, + /* @__PURE__ */ React.createElement("div", { className: "overflow-hidden rounded-[24px] border border-white/10 bg-black/30" }, previewUrl || form.data.preview_image ? /* @__PURE__ */ React.createElement("img", { src: previewUrl || form.data.preview_image, alt: "Prompt preview", className: "h-56 w-full object-cover" }) : /* @__PURE__ */ React.createElement("div", { className: "flex h-56 items-center justify-center px-6 text-center text-sm text-slate-500" }, "No preview image selected yet.")), + /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-black/20 p-4" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.22em] text-slate-400" }, "Prompt summary"), /* @__PURE__ */ React.createElement("h3", { className: "mt-3 text-2xl font-semibold tracking-[-0.04em] text-white" }, form.data.title || "Untitled prompt"), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm leading-7 text-slate-400" }, form.data.excerpt || "Add a concise excerpt to give the prompt some context in the library."), /* @__PURE__ */ React.createElement("dl", { className: "mt-4 grid grid-cols-2 gap-3 text-xs text-slate-400" }, /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-white/[0.03] px-3 py-2" }, /* @__PURE__ */ React.createElement("dt", { className: "uppercase tracking-[0.16em] text-slate-500" }, "Difficulty"), /* @__PURE__ */ React.createElement("dd", { className: "mt-1 text-sm text-white" }, form.data.difficulty || "—")), /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-white/[0.03] px-3 py-2" }, /* @__PURE__ */ React.createElement("dt", { className: "uppercase tracking-[0.16em] text-slate-500" }, "Access"), /* @__PURE__ */ React.createElement("dd", { className: "mt-1 text-sm text-white" }, form.data.access_level || "—")), /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-white/[0.03] px-3 py-2" }, /* @__PURE__ */ React.createElement("dt", { className: "uppercase tracking-[0.16em] text-slate-500" }, "Aspect"), /* @__PURE__ */ React.createElement("dd", { className: "mt-1 text-sm text-white" }, form.data.aspect_ratio || "—")), /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-white/[0.03] px-3 py-2" }, /* @__PURE__ */ React.createElement("dt", { className: "uppercase tracking-[0.16em] text-slate-500" }, "Tags"), /* @__PURE__ */ React.createElement("dd", { className: "mt-1 text-sm text-white" }, tagCount))), /* @__PURE__ */ React.createElement("p", { className: "mt-4 text-xs leading-6 text-slate-500" }, "Uploaded images are converted to WebP and stored on the Contabo S3-backed CDN before the record is saved.")) + ), /* @__PURE__ */ React.createElement(PromptPreviewDropzone, { form, previewUrl }))), /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-3 rounded-[28px] border border-white/10 bg-white/[0.03] p-5" }, /* @__PURE__ */ React.createElement("button", { type: "submit", disabled: form.processing, className: "rounded-full border border-sky-300/25 bg-sky-300/12 px-5 py-3 text-sm font-semibold text-sky-100" }, form.processing ? "Saving..." : "Save prompt"), /* @__PURE__ */ React.createElement(xe, { href: indexUrl, className: "rounded-full border border-white/10 bg-white/[0.04] px-5 py-3 text-sm font-semibold text-white" }, "Back"), destroyUrl ? /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => { + if (!window.confirm("Delete this record?")) return; + At.delete(destroyUrl); + }, className: "rounded-full border border-rose-300/20 bg-rose-300/10 px-5 py-3 text-sm font-semibold text-rose-100" }, "Delete") : null))); +} +function GenericEditor({ title, subtitle, fields, record, submitUrl, indexUrl, destroyUrl, method }) { + const form = G(record); + const submit = (event) => { + event.preventDefault(); + const payload = normalizePayload(fields, form.data); + form.transform(() => payload); + if (method === "patch") { + form.patch(submitUrl); + return; + } + form.post(submitUrl); + }; + return /* @__PURE__ */ React.createElement(AdminLayout, { title, subtitle }, /* @__PURE__ */ React.createElement(Se, { title: `Admin · ${title}` }), /* @__PURE__ */ React.createElement("form", { onSubmit: submit, className: "space-y-5 rounded-[30px] border border-white/[0.08] bg-white/[0.03] p-6" }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-5" }, fields.map((field) => /* @__PURE__ */ React.createElement(Field$4, { key: field.name, field, form }))), /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-3" }, /* @__PURE__ */ React.createElement("button", { type: "submit", disabled: form.processing, className: "rounded-full border border-sky-300/25 bg-sky-300/12 px-5 py-3 text-sm font-semibold text-sky-100" }, form.processing ? "Saving..." : "Save"), /* @__PURE__ */ React.createElement(xe, { href: indexUrl, className: "rounded-full border border-white/10 bg-white/[0.04] px-5 py-3 text-sm font-semibold text-white" }, "Back"), destroyUrl ? /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => { + if (!window.confirm("Delete this record?")) return; + At.delete(destroyUrl); + }, className: "rounded-full border border-rose-300/20 bg-rose-300/10 px-5 py-3 text-sm font-semibold text-rose-100" }, "Delete") : null))); +} +function AcademyCrudForm({ resource, title, subtitle, fields, record, submitUrl, indexUrl, destroyUrl, method, editorContext }) { + if (resource === "lessons") { + return /* @__PURE__ */ React.createElement( + LessonEditor, + { + title, + subtitle, + fields, + record, + submitUrl, + indexUrl, + destroyUrl, + method, + editorContext + } + ); + } + if (resource === "prompts") { + return /* @__PURE__ */ React.createElement( + PromptEditor, + { + title, + subtitle, + fields, + record, + submitUrl, + indexUrl, + destroyUrl, + method + } + ); + } + return /* @__PURE__ */ React.createElement( + GenericEditor, + { + title, + subtitle, + fields, + record, + submitUrl, + indexUrl, + destroyUrl, + method + } + ); +} +const __vite_glob_0_5 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ + __proto__: null, + default: AcademyCrudForm +}, Symbol.toStringTag, { value: "Module" })); +function AcademyCrudIndex({ title, subtitle, items, columns, createUrl }) { + const flash = X().props.flash || {}; + return /* @__PURE__ */ React.createElement(AdminLayout, { title, subtitle }, /* @__PURE__ */ React.createElement(Se, { title: `Admin · ${title}` }), flash.success ? /* @__PURE__ */ React.createElement("div", { className: "mb-6 rounded-2xl border border-emerald-300/20 bg-emerald-300/10 px-4 py-3 text-sm text-emerald-100" }, flash.success) : null, /* @__PURE__ */ React.createElement("div", { className: "mb-6 flex items-center justify-between gap-4" }, /* @__PURE__ */ React.createElement("p", { className: "text-sm text-slate-400" }, "Manage Academy content below. Changes clear Academy cache automatically."), /* @__PURE__ */ React.createElement(xe, { href: createUrl, className: "rounded-full border border-sky-300/25 bg-sky-300/12 px-5 py-3 text-sm font-semibold text-sky-100" }, "Create record")), (items?.data || []).length === 0 ? /* @__PURE__ */ React.createElement("div", { className: "rounded-[28px] border border-white/[0.08] bg-white/[0.03] px-6 py-12 text-center text-slate-400" }, "No records exist yet.") : /* @__PURE__ */ React.createElement("div", { className: "space-y-4" }, items.data.map((item) => /* @__PURE__ */ React.createElement("div", { key: item.id, className: "rounded-[28px] border border-white/[0.08] bg-white/[0.03] p-5" }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 lg:grid-cols-[minmax(0,1fr)_auto] lg:items-center" }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-2 sm:grid-cols-2 xl:grid-cols-5" }, columns.map((column) => /* @__PURE__ */ React.createElement("div", { key: column }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.2em] text-slate-500" }, column.replaceAll("_", " ")), /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-sm text-white" }, String(item[column] ?? ""))))), /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-3 lg:justify-end" }, /* @__PURE__ */ React.createElement(xe, { href: item.edit_url, className: "rounded-full border border-white/10 bg-white/[0.04] px-4 py-2 text-sm font-semibold text-white" }, "Edit"), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => { + if (!window.confirm("Delete this record?")) return; + At.delete(item.destroy_url, { preserveScroll: true }); + }, className: "rounded-full border border-rose-300/20 bg-rose-300/10 px-4 py-2 text-sm font-semibold text-rose-100" }, "Delete"))))))); +} +const __vite_glob_0_6 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ + __proto__: null, + default: AcademyCrudIndex +}, Symbol.toStringTag, { value: "Module" })); +function StatCard$c({ label, value }) { + return /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/[0.08] bg-white/[0.04] p-5" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.2em] text-slate-500" }, label), /* @__PURE__ */ React.createElement("p", { className: "mt-3 text-3xl font-bold text-white" }, value.toLocaleString())); +} +function AcademyDashboard({ stats, links }) { + return /* @__PURE__ */ React.createElement(AdminLayout, { title: "Academy Dashboard", subtitle: "Overview of Academy content, challenge activity, and future billing placeholders." }, /* @__PURE__ */ React.createElement(Se, { title: "Admin · Academy Dashboard" }), /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 sm:grid-cols-2 xl:grid-cols-4" }, /* @__PURE__ */ React.createElement(StatCard$c, { label: "Lessons", value: stats.lessons }), /* @__PURE__ */ React.createElement(StatCard$c, { label: "Prompts", value: stats.prompts }), /* @__PURE__ */ React.createElement(StatCard$c, { label: "Prompt Packs", value: stats.packs }), /* @__PURE__ */ React.createElement(StatCard$c, { label: "Challenges", value: stats.challenges }), /* @__PURE__ */ React.createElement(StatCard$c, { label: "Submissions", value: stats.submissions }), /* @__PURE__ */ React.createElement(StatCard$c, { label: "Badges", value: stats.badges }), /* @__PURE__ */ React.createElement(StatCard$c, { label: "Creator Subscribers", value: stats.creator_subscribers }), /* @__PURE__ */ React.createElement(StatCard$c, { label: "Pro Subscribers", value: stats.pro_subscribers })), /* @__PURE__ */ React.createElement("div", { className: "mt-8 rounded-[28px] border border-white/[0.08] bg-white/[0.03] p-6" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.2em] text-slate-500" }, "Modules"), /* @__PURE__ */ React.createElement("div", { className: "mt-4 grid gap-3 md:grid-cols-2 xl:grid-cols-3" }, Object.entries(links).map(([key, href]) => /* @__PURE__ */ React.createElement(xe, { key, href, className: "rounded-2xl border border-white/[0.08] bg-black/20 px-4 py-4 text-sm font-semibold text-white transition hover:border-white/15 hover:bg-white/[0.05]" }, key.replaceAll("_", " ")))))); +} +const __vite_glob_0_7 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ + __proto__: null, + default: AcademyDashboard +}, Symbol.toStringTag, { value: "Module" })); +function AcademySubmissions({ submissions }) { + const flash = X().props.flash || {}; + return /* @__PURE__ */ React.createElement(AdminLayout, { title: "Academy Challenge Submissions", subtitle: "Approve or reject Academy challenge entries." }, /* @__PURE__ */ React.createElement(Se, { title: "Admin · Academy Challenge Submissions" }), flash.success ? /* @__PURE__ */ React.createElement("div", { className: "mb-6 rounded-2xl border border-emerald-300/20 bg-emerald-300/10 px-4 py-3 text-sm text-emerald-100" }, flash.success) : null, /* @__PURE__ */ React.createElement("div", { className: "space-y-4" }, (submissions?.data || []).map((submission) => /* @__PURE__ */ React.createElement("article", { key: submission.id, className: "rounded-[28px] border border-white/[0.08] bg-white/[0.03] p-5" }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-5 lg:grid-cols-[minmax(0,1fr)_auto] lg:items-start" }, /* @__PURE__ */ React.createElement("div", { className: "space-y-3" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center gap-3" }, /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.2em] text-white/80" }, submission.moderation_status), /* @__PURE__ */ React.createElement("span", { className: "text-sm text-slate-400" }, submission.challenge?.title || "Challenge")), /* @__PURE__ */ React.createElement("h2", { className: "text-xl font-semibold text-white" }, submission.artwork?.title || "Artwork removed"), /* @__PURE__ */ React.createElement("p", { className: "text-sm text-slate-400" }, submission.user?.name || "Unknown user", " · ", submission.ai_tool_used || "No tool noted"), submission.prompt_used ? /* @__PURE__ */ React.createElement("pre", { className: "whitespace-pre-wrap rounded-2xl border border-white/10 bg-black/20 p-4 text-sm leading-7 text-slate-200" }, submission.prompt_used) : null, submission.workflow_notes ? /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-black/20 p-4 text-sm leading-7 text-slate-300" }, submission.workflow_notes) : null), /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-3 lg:justify-end" }, /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => At.post(submission.approve_url, {}, { preserveScroll: true }), className: "rounded-full border border-emerald-300/20 bg-emerald-300/10 px-4 py-2 text-sm font-semibold text-emerald-100" }, "Approve"), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => At.post(submission.reject_url, {}, { preserveScroll: true }), className: "rounded-full border border-rose-300/20 bg-rose-300/10 px-4 py-2 text-sm font-semibold text-rose-100" }, "Reject"))))))); +} +const __vite_glob_0_9 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ + __proto__: null, + default: AcademySubmissions +}, Symbol.toStringTag, { value: "Module" })); +function getCsrfToken$f() { + if (typeof document === "undefined") return ""; + return document.querySelector('meta[name="csrf-token"]')?.getAttribute("content") || ""; +} +async function requestJson$o(url, { method = "POST", body: body2 } = {}) { + const response = await fetch(url, { + method, + credentials: "same-origin", + headers: { + Accept: "application/json", + "Content-Type": "application/json", + "X-CSRF-TOKEN": getCsrfToken$f(), + "X-Requested-With": "XMLHttpRequest" + }, + body: body2 ? JSON.stringify(body2) : void 0 + }); + const payload = await response.json().catch(() => ({})); + if (!response.ok) { + throw new Error(payload?.message || "Request failed."); + } + return payload; +} +function formatDateTime$5(value) { + if (!value) return "—"; + const date = new Date(value); + if (Number.isNaN(date.getTime())) return "—"; + return new Intl.DateTimeFormat("en", { + dateStyle: "medium", + timeStyle: "short" + }).format(date); +} +function Badge$3({ children, tone = "slate" }) { + const tones2 = { + slate: "border-white/10 bg-white/[0.06] text-slate-200", + sky: "border-sky-300/20 bg-sky-400/12 text-sky-100", + emerald: "border-emerald-300/20 bg-emerald-400/12 text-emerald-100", + amber: "border-amber-300/20 bg-amber-400/12 text-amber-100", + rose: "border-rose-300/20 bg-rose-400/12 text-rose-100" + }; + return /* @__PURE__ */ React.createElement("span", { className: `inline-flex items-center rounded-full border px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.16em] ${tones2[tone] || tones2.slate}` }, children); +} +function StatCard$b({ label, value, tone = "sky" }) { + const tones2 = { + sky: "border-sky-300/15 bg-sky-400/10 text-sky-100", + amber: "border-amber-300/15 bg-amber-400/10 text-amber-100", + emerald: "border-emerald-300/15 bg-emerald-400/10 text-emerald-100", + rose: "border-rose-300/15 bg-rose-400/10 text-rose-100", + slate: "border-white/10 bg-white/10 text-slate-100" + }; + return /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-white/[0.04] p-5 backdrop-blur-sm" }, /* @__PURE__ */ React.createElement("div", { className: `inline-flex rounded-full border px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.18em] ${tones2[tone] || tones2.sky}` }, label), /* @__PURE__ */ React.createElement("div", { className: "mt-4 text-3xl font-semibold tracking-[-0.04em] text-white" }, Number(value || 0).toLocaleString())); +} +function selectTone(record) { + if (record.last_error_code || record.status === "failed") return "rose"; + if (record.needs_review) return "amber"; + if (record.is_user_edited) return "sky"; + if (record.status === "approved") return "emerald"; + return "slate"; +} +function labelForStatus(value) { + if (!value) return "Unknown"; + return String(value).replaceAll("_", " "); +} +function AiBiographyAdmin() { + const { props } = X(); + const records = props.records || { data: [] }; + const stats = props.stats || {}; + const endpoints = props.endpoints || {}; + const filterOptions = props.filterOptions || {}; + const [filters, setFilters] = React.useState(props.filters || {}); + const [busyKey, setBusyKey] = React.useState(""); + const [notice, setNotice] = React.useState(""); + const [error, setError] = React.useState(""); + React.useEffect(() => { + setFilters(props.filters || {}); + }, [props.filters]); + function updateFilter(key, value) { + setFilters((current) => ({ ...current, [key]: value })); + } + function applyFilters(event) { + event.preventDefault(); + setError(""); + setNotice(""); + At.get(endpoints.index, filters, { + preserveState: true, + replace: true, + preserveScroll: true + }); + } + function resetFilters() { + setError(""); + setNotice(""); + At.get(endpoints.index, { + q: "", + status: "all", + scope: "all", + tier: "all", + visibility: "all", + review: "all" + }, { + preserveState: true, + replace: true, + preserveScroll: true + }); + } + async function performAction(actionKey, url) { + setBusyKey(actionKey); + setError(""); + try { + const payload = await requestJson$o(url); + setNotice(payload.message || "Action completed."); + At.reload({ + only: ["records", "stats", "filters"], + preserveScroll: true + }); + } catch (requestError) { + setError(requestError.message || "Action failed."); + } finally { + setBusyKey(""); + } + } + return /* @__PURE__ */ React.createElement("div", { className: "w-full pb-16 pt-8" }, /* @__PURE__ */ React.createElement(Se, { title: "AI Biography Review" }), /* @__PURE__ */ React.createElement("section", { className: "rounded-[32px] border border-white/10 bg-[radial-gradient(circle_at_top_left,rgba(125,211,252,0.2),transparent_32%),linear-gradient(180deg,rgba(15,23,42,0.96),rgba(2,6,23,0.9))] p-6 shadow-[0_24px_70px_rgba(2,6,23,0.32)]" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-col gap-4 lg:flex-row lg:items-end lg:justify-between" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.28em] text-sky-200/80" }, "Moderator surface"), /* @__PURE__ */ React.createElement("h1", { className: "mt-3 text-3xl font-semibold tracking-[-0.04em] text-white" }, "AI biography review"), /* @__PURE__ */ React.createElement("p", { className: "mt-2 max-w-3xl text-sm leading-relaxed text-slate-300" }, "Browse active biographies and historical generations, inspect review flags and failures, and rebuild a creator biography directly from cPad.")), /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-3 text-xs uppercase tracking-[0.16em] text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.05] px-4 py-2" }, "Page ", records.current_page || 1, " / ", records.last_page || 1), /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.05] px-4 py-2" }, Number(records.total || 0).toLocaleString(), " records"))), /* @__PURE__ */ React.createElement("div", { className: "mt-6 grid gap-4 md:grid-cols-2 xl:grid-cols-3" }, /* @__PURE__ */ React.createElement(StatCard$b, { label: "Total records", value: stats.total_records, tone: "sky" }), /* @__PURE__ */ React.createElement(StatCard$b, { label: "Active", value: stats.active_records, tone: "emerald" }), /* @__PURE__ */ React.createElement(StatCard$b, { label: "Needs review", value: stats.needs_review, tone: "amber" }), /* @__PURE__ */ React.createElement(StatCard$b, { label: "Hidden active", value: stats.hidden_active, tone: "slate" }), /* @__PURE__ */ React.createElement(StatCard$b, { label: "Failed", value: stats.failed, tone: "rose" }), /* @__PURE__ */ React.createElement(StatCard$b, { label: "User edited", value: stats.user_edited_active, tone: "sky" })), /* @__PURE__ */ React.createElement("form", { onSubmit: applyFilters, className: "mt-6 grid gap-3 lg:grid-cols-[2fr_repeat(5,minmax(0,1fr))]" }, /* @__PURE__ */ React.createElement("label", { className: "rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-400" }, "Search creator"), /* @__PURE__ */ React.createElement( + "input", + { + value: filters.q || "", + onChange: (event) => updateFilter("q", event.target.value), + placeholder: "username, name, or email", + className: "mt-2 w-full rounded-xl border border-white/10 bg-slate-950/70 px-3 py-2 text-sm text-white outline-none" + } + )), ["status", "scope", "tier", "visibility", "review"].map((key) => /* @__PURE__ */ React.createElement("div", { key, className: "rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-400" }, key.replace("_", " ")), /* @__PURE__ */ React.createElement( + NovaSelect, + { + value: filters[key] || "all", + onChange: (value) => updateFilter(key, value), + className: "mt-2", + options: (filterOptions[key] || []).map((option) => ({ value: option.value, label: option.label })), + searchable: false + } + ))), /* @__PURE__ */ React.createElement("div", { className: "lg:col-span-full flex flex-wrap gap-3" }, /* @__PURE__ */ React.createElement("button", { type: "submit", className: "inline-flex items-center gap-2 rounded-full border border-sky-300/25 bg-sky-400/12 px-5 py-2 text-xs font-semibold uppercase tracking-[0.14em] text-sky-50 transition hover:bg-sky-400/18" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-filter text-[10px]" }), "Apply filters"), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: resetFilters, className: "inline-flex items-center gap-2 rounded-full border border-white/10 bg-white/[0.05] px-5 py-2 text-xs font-semibold uppercase tracking-[0.14em] text-white transition hover:bg-white/[0.09]" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-rotate-left text-[10px]" }), "Reset")))), notice ? /* @__PURE__ */ React.createElement("div", { className: "mt-6 rounded-2xl border border-emerald-300/20 bg-emerald-400/10 px-4 py-3 text-sm text-emerald-50" }, notice) : null, error ? /* @__PURE__ */ React.createElement("div", { className: "mt-6 rounded-2xl border border-rose-300/20 bg-rose-400/10 px-4 py-3 text-sm text-rose-100" }, error) : null, /* @__PURE__ */ React.createElement("div", { className: "mt-8 space-y-4" }, (records.data || []).length === 0 ? /* @__PURE__ */ React.createElement("div", { className: "rounded-[28px] border border-white/10 bg-white/[0.04] px-6 py-12 text-center text-slate-300" }, "No AI biography records matched the current filters.") : (records.data || []).map((record) => { + const rebuildKey = `rebuild-${record.user_id}`; + const approveKey = `approve-${record.id}`; + const flagKey = `flag-${record.id}`; + const visibilityKey = `${record.is_hidden ? "show" : "hide"}-${record.id}`; + return /* @__PURE__ */ React.createElement("article", { key: record.id, className: "rounded-[28px] border border-white/10 bg-[#08111d] p-5 shadow-[0_18px_48px_rgba(2,6,23,0.2)]" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-col gap-4 xl:flex-row xl:items-start xl:justify-between" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-2" }, /* @__PURE__ */ React.createElement(Badge$3, { tone: selectTone(record) }, labelForStatus(record.status)), /* @__PURE__ */ React.createElement(Badge$3, { tone: record.is_active ? "emerald" : "slate" }, record.is_active ? "active" : "inactive"), /* @__PURE__ */ React.createElement(Badge$3, { tone: record.is_hidden ? "amber" : "sky" }, record.is_hidden ? "hidden" : "visible"), record.needs_review ? /* @__PURE__ */ React.createElement(Badge$3, { tone: "amber" }, "needs review") : null, record.is_user_edited ? /* @__PURE__ */ React.createElement(Badge$3, { tone: "sky" }, "user edited") : null, record.is_stale ? /* @__PURE__ */ React.createElement(Badge$3, { tone: "rose" }, "stale") : null, record.input_quality_tier ? /* @__PURE__ */ React.createElement(Badge$3, { tone: "slate" }, "tier: ", record.input_quality_tier) : null), /* @__PURE__ */ React.createElement("h2", { className: "mt-3 text-2xl font-semibold tracking-[-0.03em] text-white" }, record.user?.display_name || "Unknown creator"), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm text-slate-300" }, "@", record.user?.username || "unknown", record.user?.email ? ` • ${record.user.email}` : "", record.generation_reason ? ` • reason: ${labelForStatus(record.generation_reason)}` : "")), /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-2" }, record.user?.profile_url ? /* @__PURE__ */ React.createElement("a", { href: record.user.profile_url, className: "inline-flex items-center gap-2 rounded-full border border-white/10 bg-white/[0.05] px-4 py-2 text-xs font-semibold uppercase tracking-[0.14em] text-white transition hover:bg-white/[0.09]" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-user text-[10px]" }), "Open profile") : null, record.user?.gallery_url ? /* @__PURE__ */ React.createElement("a", { href: record.user.gallery_url, className: "inline-flex items-center gap-2 rounded-full border border-white/10 bg-white/[0.05] px-4 py-2 text-xs font-semibold uppercase tracking-[0.14em] text-white transition hover:bg-white/[0.09]" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-images text-[10px]" }), "Open gallery") : null, /* @__PURE__ */ React.createElement( + "button", + { + type: "button", + disabled: busyKey === rebuildKey, + onClick: () => performAction(rebuildKey, String(endpoints.rebuildPattern || "").replace("__USER__", String(record.user_id))), + className: "inline-flex items-center gap-2 rounded-full border border-sky-300/20 bg-sky-400/12 px-4 py-2 text-xs font-semibold uppercase tracking-[0.14em] text-sky-50 transition hover:bg-sky-400/18 disabled:cursor-not-allowed disabled:opacity-60" + }, + /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-rotate text-[10px]" }), + busyKey === rebuildKey ? "Rebuilding…" : "Rebuild" + ))), /* @__PURE__ */ React.createElement("div", { className: "mt-4 grid gap-4 md:grid-cols-2 xl:grid-cols-4" }, /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-400" }, "Prompt"), /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-sm text-slate-200" }, record.prompt_version || "—")), /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-400" }, "Model"), /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-sm text-slate-200" }, record.model || "—")), /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-400" }, "Generated"), /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-sm text-slate-200" }, formatDateTime$5(record.generated_at))), /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-400" }, "Last attempted"), /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-sm text-slate-200" }, formatDateTime$5(record.last_attempted_at)))), record.last_error_code || record.last_error_reason ? /* @__PURE__ */ React.createElement("div", { className: "mt-4 rounded-2xl border border-rose-300/20 bg-rose-400/10 px-4 py-3 text-sm leading-relaxed text-rose-100" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-rose-100/80" }, "Last error"), /* @__PURE__ */ React.createElement("div", { className: "mt-2" }, record.last_error_code || "generation_failed", record.last_error_reason ? ` • ${record.last_error_reason}` : "")) : null, /* @__PURE__ */ React.createElement("div", { className: "mt-4 grid gap-4 xl:grid-cols-[minmax(0,1fr)_320px]" }, /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-black/20 p-4" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-400" }, "Biography text"), /* @__PURE__ */ React.createElement("div", { className: "mt-3 max-h-[320px] overflow-y-auto whitespace-pre-wrap rounded-2xl border border-white/10 bg-slate-950/60 px-4 py-4 text-sm leading-relaxed text-slate-100" }, record.text || "No biography text stored for this record.")), /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-black/20 p-4" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-400" }, "Review actions"), /* @__PURE__ */ React.createElement("div", { className: "mt-4 grid gap-3" }, /* @__PURE__ */ React.createElement( + "button", + { + type: "button", + disabled: busyKey === approveKey, + onClick: () => performAction(approveKey, String(endpoints.approvePattern || "").replace("__BIOGRAPHY__", String(record.id))), + className: "inline-flex items-center justify-center gap-2 rounded-2xl border border-emerald-300/20 bg-emerald-400/12 px-4 py-3 text-xs font-semibold uppercase tracking-[0.14em] text-emerald-50 transition hover:bg-emerald-400/18 disabled:cursor-not-allowed disabled:opacity-60" + }, + /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-check text-[10px]" }), + busyKey === approveKey ? "Saving…" : "Mark reviewed" + ), /* @__PURE__ */ React.createElement( + "button", + { + type: "button", + disabled: busyKey === flagKey, + onClick: () => performAction(flagKey, String(endpoints.flagPattern || "").replace("__BIOGRAPHY__", String(record.id))), + className: "inline-flex items-center justify-center gap-2 rounded-2xl border border-amber-300/20 bg-amber-400/12 px-4 py-3 text-xs font-semibold uppercase tracking-[0.14em] text-amber-50 transition hover:bg-amber-400/18 disabled:cursor-not-allowed disabled:opacity-60" + }, + /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-flag text-[10px]" }), + busyKey === flagKey ? "Saving…" : "Flag for review" + ), /* @__PURE__ */ React.createElement( + "button", + { + type: "button", + disabled: !record.is_active || busyKey === visibilityKey, + onClick: () => performAction(visibilityKey, String((record.is_hidden ? endpoints.showPattern : endpoints.hidePattern) || "").replace("__BIOGRAPHY__", String(record.id))), + className: "inline-flex items-center justify-center gap-2 rounded-2xl border border-white/10 bg-white/[0.05] px-4 py-3 text-xs font-semibold uppercase tracking-[0.14em] text-white transition hover:bg-white/[0.09] disabled:cursor-not-allowed disabled:opacity-50" + }, + /* @__PURE__ */ React.createElement("i", { className: `fa-solid ${record.is_hidden ? "fa-eye" : "fa-eye-slash"} text-[10px]` }), + busyKey === visibilityKey ? "Saving…" : record.is_hidden ? "Show publicly" : "Hide publicly" + )), /* @__PURE__ */ React.createElement("div", { className: "mt-4 space-y-2 text-xs leading-relaxed text-slate-300" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("span", { className: "font-semibold text-slate-100" }, "Approved:"), " ", formatDateTime$5(record.approved_at)), /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("span", { className: "font-semibold text-slate-100" }, "Created:"), " ", formatDateTime$5(record.created_at)), /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("span", { className: "font-semibold text-slate-100" }, "Updated:"), " ", formatDateTime$5(record.updated_at)), /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("span", { className: "font-semibold text-slate-100" }, "Source hash:"), " ", record.source_hash || "—"))))); + })), records.prev_page_url || records.next_page_url ? /* @__PURE__ */ React.createElement("div", { className: "mt-8 flex items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", null, records.prev_page_url ? /* @__PURE__ */ React.createElement(xe, { href: records.prev_page_url, preserveScroll: true, className: "inline-flex items-center gap-2 rounded-full border border-white/10 bg-white/[0.05] px-4 py-2 text-xs font-semibold uppercase tracking-[0.14em] text-white transition hover:bg-white/[0.09]" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-arrow-left text-[10px]" }), "Previous") : null), /* @__PURE__ */ React.createElement("div", { className: "text-xs uppercase tracking-[0.16em] text-slate-400" }, "Showing page ", records.current_page || 1, " of ", records.last_page || 1), /* @__PURE__ */ React.createElement("div", null, records.next_page_url ? /* @__PURE__ */ React.createElement(xe, { href: records.next_page_url, preserveScroll: true, className: "inline-flex items-center gap-2 rounded-full border border-white/10 bg-white/[0.05] px-4 py-2 text-xs font-semibold uppercase tracking-[0.14em] text-white transition hover:bg-white/[0.09]" }, "Next", /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-arrow-right text-[10px]" })) : null)) : null); +} +const __vite_glob_0_76 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ + __proto__: null, + default: AiBiographyAdmin +}, Symbol.toStringTag, { value: "Module" })); +function AdminAiBiography() { + return /* @__PURE__ */ React.createElement(AdminLayout, null, /* @__PURE__ */ React.createElement(AiBiographyAdmin, null)); +} +const __vite_glob_0_10 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ + __proto__: null, + default: AdminAiBiography +}, Symbol.toStringTag, { value: "Module" })); +function AdminArtworks({ artworks }) { + const items = artworks?.data ?? []; + return /* @__PURE__ */ React.createElement(AdminLayout, { title: "Artworks", subtitle: "Browse and manage all artworks on the platform" }, /* @__PURE__ */ React.createElement(Se, { title: "Admin · Artworks" }), /* @__PURE__ */ React.createElement("div", { className: "overflow-hidden rounded-2xl border border-white/[0.07] bg-white/[0.02]" }, /* @__PURE__ */ React.createElement("div", { className: "overflow-x-auto" }, /* @__PURE__ */ React.createElement("table", { className: "w-full text-sm" }, /* @__PURE__ */ React.createElement("thead", null, /* @__PURE__ */ React.createElement("tr", { className: "border-b border-white/[0.07] text-left text-xs font-semibold uppercase tracking-wider text-slate-600" }, /* @__PURE__ */ React.createElement("th", { className: "px-5 py-3.5" }, "Artwork"), /* @__PURE__ */ React.createElement("th", { className: "px-5 py-3.5" }, "Author"), /* @__PURE__ */ React.createElement("th", { className: "px-5 py-3.5" }, "Status"), /* @__PURE__ */ React.createElement("th", { className: "px-5 py-3.5" }, "Uploaded"), /* @__PURE__ */ React.createElement("th", { className: "px-5 py-3.5 text-right" }, "Actions"))), /* @__PURE__ */ React.createElement("tbody", { className: "divide-y divide-white/[0.04]" }, items.length === 0 && /* @__PURE__ */ React.createElement("tr", null, /* @__PURE__ */ React.createElement("td", { colSpan: 5, className: "px-5 py-12 text-center text-slate-500" }, "No artworks found.")), items.map((artwork) => /* @__PURE__ */ React.createElement("tr", { key: artwork.id, className: "transition hover:bg-white/[0.025]" }, /* @__PURE__ */ React.createElement("td", { className: "px-5 py-4" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-3" }, artwork.thumb && /* @__PURE__ */ React.createElement("img", { src: artwork.thumb, alt: artwork.title, className: "h-10 w-10 rounded-lg object-cover" }), /* @__PURE__ */ React.createElement("span", { className: "font-medium text-white" }, artwork.title || /* @__PURE__ */ React.createElement("span", { className: "italic text-slate-500" }, "Untitled")))), /* @__PURE__ */ React.createElement("td", { className: "px-5 py-4 text-slate-400" }, artwork.user?.name ?? "—"), /* @__PURE__ */ React.createElement("td", { className: "px-5 py-4" }, /* @__PURE__ */ React.createElement("span", { className: `inline-flex rounded-full px-2.5 py-0.5 text-xs font-semibold capitalize ${artwork.status === "published" ? "bg-teal-500/20 text-teal-300" : artwork.status === "pending" ? "bg-amber-500/20 text-amber-300" : "bg-slate-500/20 text-slate-400"}` }, artwork.status ?? "unknown")), /* @__PURE__ */ React.createElement("td", { className: "px-5 py-4 text-slate-500" }, artwork.created_at ? new Date(artwork.created_at).toLocaleDateString("en-GB", { day: "numeric", month: "short", year: "numeric" }) : "—"), /* @__PURE__ */ React.createElement("td", { className: "px-5 py-4 text-right" }, /* @__PURE__ */ React.createElement( + "a", + { + href: `/studio/artworks/${artwork.id}/edit`, + className: "rounded-lg border border-white/10 bg-white/[0.04] px-3 py-1.5 text-xs text-white/70 transition hover:bg-white/[0.09]" + }, + "Edit" + ))))))), artworks?.last_page > 1 && /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between border-t border-white/[0.06] px-5 py-4" }, /* @__PURE__ */ React.createElement("p", { className: "text-xs text-slate-500" }, "Showing ", artworks.from, "–", artworks.to, " of ", artworks.total, " artworks"), /* @__PURE__ */ React.createElement("div", { className: "flex gap-1" }, artworks.links.map((link2, i) => link2.url ? /* @__PURE__ */ React.createElement( + "button", + { + key: i, + type: "button", + onClick: () => At.get(link2.url, {}, { preserveScroll: true }), + className: `rounded-lg px-3 py-1.5 text-xs transition ${link2.active ? "bg-rose-500/20 font-semibold text-rose-300" : "text-slate-500 hover:bg-white/[0.06] hover:text-white"}`, + dangerouslySetInnerHTML: { __html: link2.label } + } + ) : /* @__PURE__ */ React.createElement("span", { key: i, className: "rounded-lg px-3 py-1.5 text-xs text-slate-700", dangerouslySetInnerHTML: { __html: link2.label } })))))); +} +const __vite_glob_0_11 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ + __proto__: null, + default: AdminArtworks +}, Symbol.toStringTag, { value: "Module" })); +const EVENT_LABELS = { + login: "Login", + register: "Register", + forgot_password: "Forgot password", + reset_password: "Reset password" +}; +const STATUS_BADGES = { + success: "border-emerald-400/20 bg-emerald-400/10 text-emerald-200", + failed: "border-rose-400/20 bg-rose-400/10 text-rose-200" +}; +function formatTimestamp(value) { + if (!value) { + return "Unknown"; + } + return new Intl.DateTimeFormat("en-GB", { + dateStyle: "medium", + timeStyle: "medium" + }).format(new Date(value)); +} +function formatLabel(value) { + if (!value) { + return "Not recorded"; + } + return value.replaceAll("_", " ").replace(/\b\w/g, (match) => match.toUpperCase()); +} +function SummaryCard$5({ label, value, tone = "slate" }) { + const tones2 = { + slate: "border-white/[0.07] bg-white/[0.02] text-white", + rose: "border-rose-400/15 bg-rose-500/10 text-rose-100", + sky: "border-sky-400/15 bg-sky-500/10 text-sky-100" + }; + return /* @__PURE__ */ React.createElement("div", { className: `rounded-2xl border p-5 ${tones2[tone] ?? tones2.slate}` }, /* @__PURE__ */ React.createElement("p", { className: "text-xs font-semibold uppercase tracking-[0.18em] text-slate-500" }, label), /* @__PURE__ */ React.createElement("p", { className: "mt-3 text-3xl font-semibold tracking-tight" }, value)); +} +function AuthAudit({ logs, filters, eventOptions, statusOptions }) { + const items = logs?.data ?? []; + const failedCount = items.filter((entry) => entry.status === "failed").length; + const uniqueIpCount = new Set(items.map((entry) => entry.ip).filter(Boolean)).size; + const handleSearch = (event) => { + event.preventDefault(); + const search2 = event.target.elements.search.value; + At.get("/moderation/auth-audit", { + search: search2, + event: filters.event, + status: filters.status + }, { + preserveState: true, + preserveScroll: true + }); + }; + const handleFilterChange = (key, value) => { + At.get("/moderation/auth-audit", { + search: filters.search, + event: key === "event" ? value : filters.event, + status: key === "status" ? value : filters.status + }, { + preserveState: true, + preserveScroll: true + }); + }; + return /* @__PURE__ */ React.createElement(AdminLayout, { title: "Auth Audit", subtitle: "Review login, registration, forgot-password, and reset-password activity with IPs, timestamps, status, and failure reasons." }, /* @__PURE__ */ React.createElement(Se, { title: "Admin · Auth Audit" }), /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 lg:grid-cols-3" }, /* @__PURE__ */ React.createElement(SummaryCard$5, { label: "Visible records", value: items.length.toLocaleString(), tone: "slate" }), /* @__PURE__ */ React.createElement(SummaryCard$5, { label: "Failures on page", value: failedCount.toLocaleString(), tone: "rose" }), /* @__PURE__ */ React.createElement(SummaryCard$5, { label: "Unique IPs on page", value: uniqueIpCount.toLocaleString(), tone: "sky" })), /* @__PURE__ */ React.createElement("div", { className: "mt-6 rounded-[28px] border border-white/[0.07] bg-white/[0.02] p-5" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-col gap-4 xl:flex-row xl:items-end xl:justify-between" }, /* @__PURE__ */ React.createElement("form", { onSubmit: handleSearch, className: "flex flex-1 flex-col gap-3 md:flex-row" }, /* @__PURE__ */ React.createElement("label", { className: "flex-1" }, /* @__PURE__ */ React.createElement("span", { className: "mb-2 block text-xs font-semibold uppercase tracking-[0.18em] text-slate-500" }, "Search"), /* @__PURE__ */ React.createElement( + "input", + { + name: "search", + defaultValue: filters.search, + placeholder: "Email, username, IP, or failure reason", + className: "w-full rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3 text-sm text-white placeholder:text-slate-600 focus:border-white/20 focus:outline-none focus:ring-1 focus:ring-white/10" + } + )), /* @__PURE__ */ React.createElement("button", { type: "submit", className: "rounded-2xl bg-rose-500/80 px-5 py-3 text-sm font-semibold text-white transition hover:bg-rose-500" }, "Search")), /* @__PURE__ */ React.createElement("div", { className: "grid gap-3 md:grid-cols-2 xl:min-w-[26rem]" }, /* @__PURE__ */ React.createElement("label", null, /* @__PURE__ */ React.createElement("span", { className: "mb-2 block text-xs font-semibold uppercase tracking-[0.18em] text-slate-500" }, "Event"), /* @__PURE__ */ React.createElement( + "select", + { + value: filters.event, + onChange: (event) => handleFilterChange("event", event.target.value), + className: "w-full rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3 text-sm text-white focus:border-white/20 focus:outline-none focus:ring-1 focus:ring-white/10" + }, + eventOptions.map((option) => /* @__PURE__ */ React.createElement("option", { key: option.value, value: option.value, className: "bg-slate-950 text-white" }, option.label)) + )), /* @__PURE__ */ React.createElement("label", null, /* @__PURE__ */ React.createElement("span", { className: "mb-2 block text-xs font-semibold uppercase tracking-[0.18em] text-slate-500" }, "Status"), /* @__PURE__ */ React.createElement( + "select", + { + value: filters.status, + onChange: (event) => handleFilterChange("status", event.target.value), + className: "w-full rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3 text-sm text-white focus:border-white/20 focus:outline-none focus:ring-1 focus:ring-white/10" + }, + statusOptions.map((option) => /* @__PURE__ */ React.createElement("option", { key: option.value, value: option.value, className: "bg-slate-950 text-white" }, option.label)) + ))))), /* @__PURE__ */ React.createElement("div", { className: "mt-6 overflow-hidden rounded-[28px] border border-white/[0.07] bg-white/[0.02]" }, /* @__PURE__ */ React.createElement("div", { className: "overflow-x-auto" }, /* @__PURE__ */ React.createElement("table", { className: "w-full min-w-[980px] text-sm" }, /* @__PURE__ */ React.createElement("thead", null, /* @__PURE__ */ React.createElement("tr", { className: "border-b border-white/[0.07] text-left text-xs font-semibold uppercase tracking-[0.18em] text-slate-500" }, /* @__PURE__ */ React.createElement("th", { className: "px-5 py-4" }, "When"), /* @__PURE__ */ React.createElement("th", { className: "px-5 py-4" }, "Event"), /* @__PURE__ */ React.createElement("th", { className: "px-5 py-4" }, "Status"), /* @__PURE__ */ React.createElement("th", { className: "px-5 py-4" }, "Identifier"), /* @__PURE__ */ React.createElement("th", { className: "px-5 py-4" }, "User"), /* @__PURE__ */ React.createElement("th", { className: "px-5 py-4" }, "IP"), /* @__PURE__ */ React.createElement("th", { className: "px-5 py-4" }, "Reason"), /* @__PURE__ */ React.createElement("th", { className: "px-5 py-4" }, "Details"))), /* @__PURE__ */ React.createElement("tbody", { className: "divide-y divide-white/[0.05]" }, items.length === 0 ? /* @__PURE__ */ React.createElement("tr", null, /* @__PURE__ */ React.createElement("td", { colSpan: 8, className: "px-5 py-12 text-center text-slate-500" }, "No auth audit records matched the current filters.")) : items.map((entry) => /* @__PURE__ */ React.createElement("tr", { key: entry.id, className: "align-top transition hover:bg-white/[0.025]" }, /* @__PURE__ */ React.createElement("td", { className: "px-5 py-4 text-slate-300" }, formatTimestamp(entry.created_at)), /* @__PURE__ */ React.createElement("td", { className: "px-5 py-4 text-white" }, EVENT_LABELS[entry.event_type] ?? formatLabel(entry.event_type)), /* @__PURE__ */ React.createElement("td", { className: "px-5 py-4" }, /* @__PURE__ */ React.createElement("span", { className: `inline-flex rounded-full border px-2.5 py-1 text-xs font-semibold uppercase tracking-[0.16em] ${STATUS_BADGES[entry.status] ?? "border-white/10 bg-white/[0.04] text-white/70"}` }, entry.status)), /* @__PURE__ */ React.createElement("td", { className: "px-5 py-4 text-slate-300" }, entry.identifier || "Not recorded"), /* @__PURE__ */ React.createElement("td", { className: "px-5 py-4" }, entry.user ? /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "font-medium text-white" }, entry.user.name), /* @__PURE__ */ React.createElement("p", { className: "text-xs text-slate-500" }, entry.user.username ? `@${entry.user.username}` : entry.user.email)) : /* @__PURE__ */ React.createElement("span", { className: "text-slate-500" }, "Unknown user")), /* @__PURE__ */ React.createElement("td", { className: "px-5 py-4 text-slate-300" }, entry.ip || "Unknown"), /* @__PURE__ */ React.createElement("td", { className: "px-5 py-4 text-slate-300" }, formatLabel(entry.reason)), /* @__PURE__ */ React.createElement("td", { className: "px-5 py-4" }, /* @__PURE__ */ React.createElement("details", { className: "group w-72 max-w-full" }, /* @__PURE__ */ React.createElement("summary", { className: "cursor-pointer list-none text-sm font-medium text-sky-200 transition hover:text-sky-100" }, "View payload"), /* @__PURE__ */ React.createElement("div", { className: "mt-3 space-y-3 rounded-2xl border border-white/10 bg-black/20 p-4 text-xs text-slate-300" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "font-semibold uppercase tracking-[0.16em] text-slate-500" }, "User agent"), /* @__PURE__ */ React.createElement("p", { className: "mt-1 break-words leading-5 text-slate-300" }, entry.user_agent || "Not recorded")), /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Metadata"), /* @__PURE__ */ React.createElement("pre", { className: "mt-1 overflow-x-auto whitespace-pre-wrap break-words rounded-xl bg-slate-950/70 p-3 text-[11px] leading-5 text-slate-300" }, JSON.stringify(entry.metadata || {}, null, 2))))))))))), logs?.last_page > 1 ? /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between border-t border-white/[0.06] px-5 py-4" }, /* @__PURE__ */ React.createElement("p", { className: "text-xs text-slate-500" }, "Showing ", logs.from, "–", logs.to, " of ", logs.total, " audit records"), /* @__PURE__ */ React.createElement("div", { className: "flex gap-1" }, logs.links.map((link2, index2) => link2.url ? /* @__PURE__ */ React.createElement( + "button", + { + key: `${link2.label}-${index2}`, + type: "button", + onClick: () => At.get(link2.url, {}, { preserveScroll: true, preserveState: true }), + className: `rounded-lg px-3 py-1.5 text-xs transition ${link2.active ? "bg-rose-500/20 font-semibold text-rose-300" : "text-slate-500 hover:bg-white/[0.06] hover:text-white"}`, + dangerouslySetInnerHTML: { __html: link2.label } + } + ) : /* @__PURE__ */ React.createElement("span", { key: `${link2.label}-${index2}`, className: "rounded-lg px-3 py-1.5 text-xs text-slate-700", dangerouslySetInnerHTML: { __html: link2.label } })))) : null)); +} +const __vite_glob_0_12 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ + __proto__: null, + default: AuthAudit +}, Symbol.toStringTag, { value: "Module" })); +function formatDateTime$4(value) { + if (!value) return "—"; + try { + return new Intl.DateTimeFormat(void 0, { + year: "numeric", + month: "short", + day: "numeric", + hour: "2-digit", + minute: "2-digit" + }).format(new Date(value)); + } catch { + return String(value); + } +} +function StatCard$a({ icon, label, value, tone = "sky" }) { + const tones2 = { + sky: "border-sky-400/20 bg-sky-400/10 text-sky-200", + rose: "border-rose-400/20 bg-rose-400/10 text-rose-200", + amber: "border-amber-400/20 bg-amber-400/10 text-amber-200", + emerald: "border-emerald-400/20 bg-emerald-400/10 text-emerald-200" + }; + return /* @__PURE__ */ React.createElement("div", { className: `rounded-2xl border p-5 ${tones2[tone]}` }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between gap-4" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.22em] text-white/65" }, label), /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-3xl font-bold text-white" }, Number(value || 0).toLocaleString())), /* @__PURE__ */ React.createElement("div", { className: "flex h-11 w-11 items-center justify-center rounded-2xl border border-white/10 bg-black/20 text-lg text-white/80" }, /* @__PURE__ */ React.createElement("i", { className: icon })))); +} +function SectionCard$3({ title, subtitle, actionHref, actionLabel, children }) { + return /* @__PURE__ */ React.createElement("section", { className: "rounded-3xl border border-white/10 bg-white/[0.04] p-5 shadow-[0_24px_80px_rgba(2,6,23,0.35)]" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-start justify-between gap-4 border-b border-white/8 pb-4" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("h2", { className: "text-lg font-semibold text-white" }, title), subtitle ? /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-sm text-slate-400" }, subtitle) : null), actionHref ? /* @__PURE__ */ React.createElement("a", { href: actionHref, className: "inline-flex items-center gap-2 rounded-full border border-white/10 bg-white/[0.05] px-3 py-2 text-xs font-semibold uppercase tracking-[0.16em] text-slate-200 transition hover:bg-white/[0.08]" }, /* @__PURE__ */ React.createElement("span", null, actionLabel || "Open queue"), /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-arrow-up-right-from-square text-[10px]" })) : null), /* @__PURE__ */ React.createElement("div", { className: "mt-4" }, children)); +} +function EmptyState$6({ label }) { + return /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-dashed border-white/10 bg-black/10 px-4 py-6 text-sm text-slate-400" }, label); +} +function DataTable({ columns, rows, emptyLabel }) { + if (!rows?.length) { + return /* @__PURE__ */ React.createElement(EmptyState$6, { label: emptyLabel }); + } + return /* @__PURE__ */ React.createElement("div", { className: "overflow-x-auto" }, /* @__PURE__ */ React.createElement("table", { className: "min-w-full divide-y divide-white/10 text-sm text-slate-200" }, /* @__PURE__ */ React.createElement("thead", null, /* @__PURE__ */ React.createElement("tr", { className: "text-left text-[11px] uppercase tracking-[0.18em] text-slate-500" }, columns.map((column) => /* @__PURE__ */ React.createElement("th", { key: column.key, className: "px-3 py-3 font-semibold" }, column.label)))), /* @__PURE__ */ React.createElement("tbody", { className: "divide-y divide-white/6" }, rows.map((row, index2) => /* @__PURE__ */ React.createElement("tr", { key: row.id || `${index2}-${row.created_at || row.updated_at || "row"}`, className: "align-top" }, columns.map((column) => /* @__PURE__ */ React.createElement("td", { key: column.key, className: "px-3 py-3 text-slate-200/90" }, column.render ? column.render(row) : row[column.key]))))))); +} +function DailyActivity({ selectedDate, summary, queues, sections }) { + const onDateChange = (event) => { + At.get("/moderation/activity", { date: event.target.value }, { preserveState: true, replace: true }); + }; + return /* @__PURE__ */ React.createElement(AdminLayout, { title: "Daily Activity", subtitle: "A day-by-day moderation cockpit for reviewing new content, queue movement, and staff actions." }, /* @__PURE__ */ React.createElement(Se, { title: "Admin · Daily Activity" }), /* @__PURE__ */ React.createElement("div", { className: "rounded-3xl border border-white/10 bg-[linear-gradient(135deg,rgba(244,63,94,0.18),rgba(15,23,42,0.75))] p-6 shadow-[0_30px_120px_rgba(15,23,42,0.5)]" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-end justify-between gap-5" }, /* @__PURE__ */ React.createElement("div", { className: "max-w-2xl" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.26em] text-rose-200/80" }, "Moderation review"), /* @__PURE__ */ React.createElement("h2", { className: "mt-2 text-2xl font-bold text-white" }, "Selected day: ", selectedDate), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm leading-6 text-slate-200/80" }, "This view pulls together the moderation-adjacent activity for the selected day so admins can triage queues and jump into the right review surface quickly.")), /* @__PURE__ */ React.createElement("label", { className: "block" }, /* @__PURE__ */ React.createElement("span", { className: "mb-2 block text-[11px] font-semibold uppercase tracking-[0.2em] text-slate-300" }, "Day"), /* @__PURE__ */ React.createElement( + "input", + { + type: "date", + value: selectedDate, + onChange: onDateChange, + className: "rounded-2xl border border-white/10 bg-slate-950/70 px-4 py-3 text-sm text-white outline-none transition focus:border-rose-400/50" + } + )))), /* @__PURE__ */ React.createElement("div", { className: "mt-6 grid gap-4 sm:grid-cols-2 xl:grid-cols-3" }, /* @__PURE__ */ React.createElement(StatCard$a, { icon: "fa-solid fa-user-plus", label: "New Users", value: summary.new_users, tone: "sky" }), /* @__PURE__ */ React.createElement(StatCard$a, { icon: "fa-solid fa-images", label: "New Artworks", value: summary.new_artworks, tone: "rose" }), /* @__PURE__ */ React.createElement(StatCard$a, { icon: "fa-solid fa-feather-pointed", label: "New Stories", value: summary.new_stories, tone: "amber" }), /* @__PURE__ */ React.createElement(StatCard$a, { icon: "fa-solid fa-cloud-arrow-up", label: "Upload Events", value: summary.upload_events, tone: "emerald" }), /* @__PURE__ */ React.createElement(StatCard$a, { icon: "fa-solid fa-flag", label: "Report Events", value: summary.report_events, tone: "rose" }), /* @__PURE__ */ React.createElement(StatCard$a, { icon: "fa-solid fa-fingerprint", label: "Auth Events", value: summary.auth_events, tone: "sky" })), /* @__PURE__ */ React.createElement("div", { className: "mt-6 grid gap-4 lg:grid-cols-3" }, /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-white/[0.04] p-5" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.22em] text-slate-500" }, "Queues right now"), /* @__PURE__ */ React.createElement("div", { className: "mt-4 space-y-3 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between rounded-2xl border border-white/8 bg-black/10 px-4 py-3" }, /* @__PURE__ */ React.createElement("span", null, "Pending uploads"), /* @__PURE__ */ React.createElement("span", { className: "font-semibold text-white" }, queues.pending_uploads)), /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between rounded-2xl border border-white/8 bg-black/10 px-4 py-3" }, /* @__PURE__ */ React.createElement("span", null, "Open reports"), /* @__PURE__ */ React.createElement("span", { className: "font-semibold text-white" }, queues.open_reports)), /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between rounded-2xl border border-white/8 bg-black/10 px-4 py-3" }, /* @__PURE__ */ React.createElement("span", null, "Pending username requests"), /* @__PURE__ */ React.createElement("span", { className: "font-semibold text-white" }, queues.pending_username_requests)))), /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-white/[0.04] p-5 lg:col-span-2" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.22em] text-slate-500" }, "Moderation throughput on this day"), /* @__PURE__ */ React.createElement("div", { className: "mt-4 grid gap-3 sm:grid-cols-3" }, /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/8 bg-black/10 p-4" }, /* @__PURE__ */ React.createElement("div", { className: "text-xs uppercase tracking-[0.18em] text-slate-500" }, "Moderated uploads"), /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-2xl font-bold text-white" }, summary.moderated_uploads)), /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/8 bg-black/10 p-4" }, /* @__PURE__ */ React.createElement("div", { className: "text-xs uppercase tracking-[0.18em] text-slate-500" }, "Moderated reports"), /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-2xl font-bold text-white" }, summary.moderated_reports)), /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/8 bg-black/10 p-4" }, /* @__PURE__ */ React.createElement("div", { className: "text-xs uppercase tracking-[0.18em] text-slate-500" }, "Username events"), /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-2xl font-bold text-white" }, summary.username_events))))), /* @__PURE__ */ React.createElement("div", { className: "mt-6 space-y-6" }, /* @__PURE__ */ React.createElement(SectionCard$3, { title: "Uploads", subtitle: "New uploads and same-day moderation decisions.", actionHref: "/moderation/uploads", actionLabel: "Open uploads" }, /* @__PURE__ */ React.createElement( + DataTable, + { + emptyLabel: "No upload activity on this day.", + rows: sections.uploads, + columns: [ + { key: "title", label: "Upload", render: (row) => /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "font-semibold text-white" }, row.title), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-xs uppercase tracking-[0.16em] text-slate-500" }, row.type, " · ", row.status, " · ", row.processing_state)) }, + { key: "moderation_status", label: "Moderation", render: (row) => /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", null, row.moderation_status), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-xs text-slate-500" }, row.moderation_note || "No note")) }, + { key: "created_at", label: "Created", render: (row) => formatDateTime$4(row.created_at) }, + { key: "moderated_at", label: "Moderated", render: (row) => formatDateTime$4(row.moderated_at) } + ] + } + )), /* @__PURE__ */ React.createElement(SectionCard$3, { title: "Reports", subtitle: "User reports created or reviewed during the selected day." }, /* @__PURE__ */ React.createElement( + DataTable, + { + emptyLabel: "No report activity on this day.", + rows: sections.reports, + columns: [ + { key: "reason", label: "Report", render: (row) => /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "font-semibold text-white" }, row.reason), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-xs uppercase tracking-[0.16em] text-slate-500" }, row.status, " · ", row.target_type, " #", row.target_id)) }, + { key: "reporter", label: "Reporter", render: (row) => row.reporter ? `@${row.reporter.username}` : "—" }, + { key: "target", label: "Target", render: (row) => row.target?.title || row.target?.context || "Resolved via moderation target" }, + { key: "last_moderated_at", label: "Reviewed", render: (row) => /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", null, formatDateTime$4(row.last_moderated_at)), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-xs text-slate-500" }, row.last_moderated_by ? `@${row.last_moderated_by.username}` : "Unassigned")) } + ] + } + )), /* @__PURE__ */ React.createElement("div", { className: "grid gap-6 xl:grid-cols-2" }, /* @__PURE__ */ React.createElement(SectionCard$3, { title: "Username Requests", subtitle: "Requests created or reviewed on this day.", actionHref: "/moderation/usernames/moderation", actionLabel: "Open usernames" }, /* @__PURE__ */ React.createElement( + DataTable, + { + emptyLabel: "No username activity on this day.", + rows: sections.username_requests, + columns: [ + { key: "requested_username", label: "Request", render: (row) => /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "font-semibold text-white" }, row.requested_username), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-xs text-slate-500" }, "Current: ", row.current_username || row.current_name || "Unknown user")) }, + { key: "status", label: "Status" }, + { key: "created_at", label: "Created", render: (row) => formatDateTime$4(row.created_at) }, + { key: "reviewed_at", label: "Reviewed", render: (row) => formatDateTime$4(row.reviewed_at) } + ] + } + )), /* @__PURE__ */ React.createElement(SectionCard$3, { title: "Auth Audit", subtitle: "Authentication events for the selected day.", actionHref: "/moderation/auth-audit", actionLabel: "Open audit" }, /* @__PURE__ */ React.createElement( + DataTable, + { + emptyLabel: "No auth audit events on this day.", + rows: sections.auth_events, + columns: [ + { key: "event_type", label: "Event", render: (row) => /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "font-semibold text-white" }, row.event_type), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-xs text-slate-500" }, row.status, " · ", row.ip || "No IP")) }, + { key: "user", label: "User", render: (row) => row.user ? `@${row.user.username || row.user.name}` : row.identifier || "Guest" }, + { key: "reason", label: "Reason", render: (row) => row.reason || "—" }, + { key: "created_at", label: "When", render: (row) => formatDateTime$4(row.created_at) } + ] + } + ))), /* @__PURE__ */ React.createElement("div", { className: "grid gap-6 xl:grid-cols-3" }, /* @__PURE__ */ React.createElement(SectionCard$3, { title: "Users", subtitle: "Accounts created on this day.", actionHref: "/moderation/users", actionLabel: "Open users" }, /* @__PURE__ */ React.createElement( + DataTable, + { + emptyLabel: "No new users on this day.", + rows: sections.users, + columns: [ + { key: "username", label: "User", render: (row) => /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "font-semibold text-white" }, row.username ? `@${row.username}` : row.name), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-xs text-slate-500" }, row.email)) }, + { key: "role", label: "Role" }, + { key: "created_at", label: "Joined", render: (row) => formatDateTime$4(row.created_at) } + ] + } + )), /* @__PURE__ */ React.createElement(SectionCard$3, { title: "Artworks", subtitle: "Artwork records created on this day.", actionHref: "/moderation/artworks", actionLabel: "Open artworks" }, /* @__PURE__ */ React.createElement( + DataTable, + { + emptyLabel: "No artwork activity on this day.", + rows: sections.artworks, + columns: [ + { key: "title", label: "Artwork", render: (row) => /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "font-semibold text-white" }, row.title), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-xs text-slate-500" }, row.user?.username ? `@${row.user.username}` : "Unknown artist")) }, + { key: "status", label: "Status" }, + { key: "created_at", label: "Created", render: (row) => formatDateTime$4(row.created_at) } + ] + } + )), /* @__PURE__ */ React.createElement(SectionCard$3, { title: "Stories", subtitle: "Creator stories created on this day.", actionHref: "/moderation/stories", actionLabel: "Open stories" }, /* @__PURE__ */ React.createElement( + DataTable, + { + emptyLabel: "No story activity on this day.", + rows: sections.stories, + columns: [ + { key: "title", label: "Story", render: (row) => /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "font-semibold text-white" }, row.title), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-xs text-slate-500" }, row.creator?.username ? `@${row.creator.username}` : "Unknown creator")) }, + { key: "status", label: "Status" }, + { key: "created_at", label: "Created", render: (row) => formatDateTime$4(row.created_at) } + ] + } + ))))); +} +const __vite_glob_0_13 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ + __proto__: null, + default: DailyActivity +}, Symbol.toStringTag, { value: "Module" })); +function StatCard$9({ icon, label, value, color: color2 = "sky" }) { + const colors = { + sky: "from-sky-500/20 to-sky-500/5 border-sky-500/20 text-sky-400", + rose: "from-rose-500/20 to-rose-500/5 border-rose-500/20 text-rose-400", + amber: "from-amber-500/20 to-amber-500/5 border-amber-500/20 text-amber-400", + violet: "from-violet-500/20 to-violet-500/5 border-violet-500/20 text-violet-400" + }; + return /* @__PURE__ */ React.createElement("div", { className: `rounded-2xl border bg-gradient-to-br p-6 ${colors[color2]}` }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-xs font-semibold uppercase tracking-wider text-slate-400" }, label), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-3xl font-bold text-white" }, value.toLocaleString())), /* @__PURE__ */ React.createElement("div", { className: `flex h-12 w-12 items-center justify-center rounded-xl bg-white/5` }, /* @__PURE__ */ React.createElement("i", { className: `${icon} text-xl ${colors[color2].split(" ").at(-1)}` })))); +} +function Dashboard({ stats }) { + return /* @__PURE__ */ React.createElement(AdminLayout, { title: "Dashboard", subtitle: "Overview of your Skinbase platform" }, /* @__PURE__ */ React.createElement(Se, { title: "Admin Dashboard" }), /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 sm:grid-cols-2 lg:grid-cols-4" }, /* @__PURE__ */ React.createElement(StatCard$9, { icon: "fa-solid fa-users", label: "Total Users", value: stats.total_users, color: "sky" }), /* @__PURE__ */ React.createElement(StatCard$9, { icon: "fa-solid fa-user-plus", label: "New Today", value: stats.new_users_today, color: "violet" }), /* @__PURE__ */ React.createElement(StatCard$9, { icon: "fa-solid fa-shield-halved", label: "Staff Members", value: stats.staff_count, color: "rose" }), /* @__PURE__ */ React.createElement(StatCard$9, { icon: "fa-solid fa-user-shield", label: "Moderators", value: stats.moderator_count, color: "amber" })), /* @__PURE__ */ React.createElement("div", { className: "mt-10" }, /* @__PURE__ */ React.createElement("h2", { className: "mb-4 text-sm font-semibold uppercase tracking-wider text-slate-500" }, "Quick Actions"), /* @__PURE__ */ React.createElement("div", { className: "grid gap-3 sm:grid-cols-2 lg:grid-cols-3" }, [ + { label: "Daily Activity", href: "/moderation/activity", icon: "fa-solid fa-calendar-day", desc: "Review everything created or moderated on a selected day" }, + { label: "Manage Users", href: "/moderation/users", icon: "fa-solid fa-users", desc: "Search, promote or demote users" }, + { label: "Staff Roles", href: "/moderation/users?role=admin", icon: "fa-solid fa-shield-halved", desc: "View all admins, managers and editorial staff" }, + { label: "Username Queue", href: "/moderation/usernames/moderation", icon: "fa-solid fa-id-badge", desc: "Review pending username requests" }, + { label: "Upload Queue", href: "/moderation/uploads", icon: "fa-solid fa-cloud-arrow-up", desc: "Moderate pending artwork submissions" }, + { label: "Stories", href: "/moderation/stories", icon: "fa-solid fa-feather-pointed", desc: "Browse all creator stories" }, + { label: "Artworks", href: "/moderation/artworks", icon: "fa-solid fa-images", desc: "Browse all uploaded artworks" }, + { label: "Featured Artworks", href: "/moderation/artworks/featured", icon: "fa-solid fa-star", desc: "Curate the homepage featured artwork lineup" }, + { label: "AI Biography", href: "/moderation/ai-biography", icon: "fa-solid fa-wand-magic-sparkles", desc: "Review generated creator biographies and moderation flags" } + ].map((item) => /* @__PURE__ */ React.createElement( + "a", + { + key: item.href, + href: item.href, + className: "group flex items-start gap-4 rounded-2xl border border-white/[0.07] bg-white/[0.03] p-5 transition hover:border-white/15 hover:bg-white/[0.06]" + }, + /* @__PURE__ */ React.createElement("div", { className: "mt-0.5 flex h-10 w-10 flex-shrink-0 items-center justify-center rounded-xl bg-rose-500/10" }, /* @__PURE__ */ React.createElement("i", { className: `${item.icon} text-rose-400` })), + /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "font-semibold text-white group-hover:text-rose-300 transition" }, item.label), /* @__PURE__ */ React.createElement("p", { className: "mt-0.5 text-xs text-slate-500" }, item.desc)) + ))))); +} +const __vite_glob_0_14 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ + __proto__: null, + default: Dashboard +}, Symbol.toStringTag, { value: "Module" })); +const variantStyles = { + accent: { checked: "#E07A21", ring: "rgba(224,122,33,0.45)" }, + emerald: { checked: "#10b981", ring: "rgba(16,185,129,0.45)" }, + sky: { checked: "#0ea5e9", ring: "rgba(14,165,233,0.45)" } +}; +const Checkbox = reactExports.forwardRef(function Checkbox2({ label, hint, error, size = 18, variant = "accent", id, className = "", checked, disabled, onChange, ...rest }, ref2) { + const dim = typeof size === "number" ? `${size}px` : size; + const numSize = typeof size === "number" ? size : parseInt(size, 10); + const inputId = id ?? (label ? `cb-${label.toLowerCase().replace(/\s+/g, "-")}` : void 0); + const colors = variantStyles[variant] ?? variantStyles.accent; + const tickInset = Math.round(numSize * 0.18); + const strokeWidth = Math.max(1.5, numSize * 0.1); + return /* @__PURE__ */ React.createElement("div", { className: "flex flex-col gap-1" }, /* @__PURE__ */ React.createElement( + "label", + { + className: [ + "inline-flex items-start gap-2.5 select-none", + disabled ? "opacity-50 cursor-not-allowed" : "cursor-pointer" + ].join(" ") + }, + /* @__PURE__ */ React.createElement( + "input", + { + type: "checkbox", + id: inputId, + ref: ref2, + checked, + disabled, + onChange, + className: "sr-only", + "aria-invalid": !!error, + ...rest + } + ), + /* @__PURE__ */ React.createElement( + "span", + { + "aria-hidden": "true", + style: { + width: dim, + height: dim, + minWidth: dim, + minHeight: dim, + aspectRatio: "1 / 1", + marginTop: label ? "1px" : void 0, + backgroundColor: checked ? colors.checked : "rgba(255,255,255,0.06)", + borderColor: checked ? colors.checked : "rgba(255,255,255,0.25)", + boxShadow: checked ? `0 0 0 0px ${colors.ring}` : void 0, + transition: "background-color 150ms, border-color 150ms" + }, + className: [ + "shrink-0 inline-flex items-center justify-center", + "rounded-md border", + className + ].join(" ") + }, + /* @__PURE__ */ React.createElement( + "svg", + { + viewBox: "0 0 12 12", + fill: "none", + style: { + width: numSize - tickInset * 2, + height: numSize - tickInset * 2, + opacity: checked ? 1 : 0, + transition: "opacity 100ms" + }, + "aria-hidden": "true" + }, + /* @__PURE__ */ React.createElement( + "path", + { + d: "M1.5 6l3 3 6-6", + stroke: "white", + strokeWidth, + strokeLinecap: "round", + strokeLinejoin: "round" + } + ) + ) + ), + (label || hint) && /* @__PURE__ */ React.createElement("span", { className: "flex flex-col gap-0.5" }, label && /* @__PURE__ */ React.createElement("span", { className: "text-sm text-white/90 leading-snug" }, label), hint && /* @__PURE__ */ React.createElement("span", { className: "text-xs text-slate-500" }, hint)) + ), error && /* @__PURE__ */ React.createElement("p", { role: "alert", className: "text-xs text-red-400", style: { paddingLeft: `calc(${dim} + 0.625rem)` } }, error)); +}); function getCsrfToken$e() { if (typeof document === "undefined") return ""; return document.querySelector('meta[name="csrf-token"]')?.getAttribute("content") || ""; @@ -14346,14 +18249,14 @@ function FeaturedArtworksAdmin() { } ), /* @__PURE__ */ React.createElement(NovaSelect, { value: filter2, onChange: (val) => setFilter(val), searchable: false, options: [{ value: "all", label: "All rows" }, { value: "active", label: "Active" }, { value: "inactive", label: "Inactive" }, { value: "expired", label: "Expired" }, { value: "winner", label: "Winner" }, { value: "eligible", label: "Eligible" }, { value: "ineligible", label: "Not eligible" }] }), /* @__PURE__ */ React.createElement("div", { className: "grid grid-cols-[1fr_auto] gap-3" }, /* @__PURE__ */ React.createElement(NovaSelect, { value: sortKey, onChange: (val) => setSortKey(val), searchable: false, options: [{ value: "priority", label: "Priority" }, { value: "featured_at", label: "Featured Since" }, { value: "expires_at", label: "Expires" }, { value: "score_30d", label: "Medal Score (30d)" }] }), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => setSortDirection((current) => current === "desc" ? "asc" : "desc"), className: "rounded-2xl border border-white/10 px-4 py-3 text-sm font-semibold text-slate-100 transition hover:border-white/20 hover:bg-white/5" }, sortDirection === "desc" ? "Desc" : "Asc")))), /* @__PURE__ */ React.createElement("div", { className: "mt-6 overflow-hidden rounded-[24px] border border-white/10" }, /* @__PURE__ */ React.createElement("div", { className: "hidden grid-cols-[1.2fr_1fr_0.5fr_0.9fr_0.9fr_0.7fr_1.5fr_0.9fr] gap-4 border-b border-white/10 bg-black/20 px-5 py-4 text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-400 lg:grid" }, /* @__PURE__ */ React.createElement("div", null, "Artwork"), /* @__PURE__ */ React.createElement("div", null, "Artist / Owner"), /* @__PURE__ */ React.createElement("div", null, "Priority"), /* @__PURE__ */ React.createElement("div", null, "Featured Since"), /* @__PURE__ */ React.createElement("div", null, "Expires"), /* @__PURE__ */ React.createElement("div", null, "Score (30d)"), /* @__PURE__ */ React.createElement("div", null, "Status"), /* @__PURE__ */ React.createElement("div", null, "Actions")), /* @__PURE__ */ React.createElement("div", { className: "divide-y divide-white/10" }, filteredEntries.length === 0 ? /* @__PURE__ */ React.createElement("div", { className: "px-5 py-10 text-center text-sm text-slate-400" }, "No featured entries match the current filter.") : filteredEntries.map((entry) => /* @__PURE__ */ React.createElement("div", { key: entry.id, className: "grid gap-5 bg-white/[0.02] px-5 py-5 lg:grid-cols-[1.2fr_1fr_0.5fr_0.9fr_0.9fr_0.7fr_1.5fr_0.9fr] lg:items-center" }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 sm:grid-cols-[92px_1fr]" }, /* @__PURE__ */ React.createElement("a", { href: entry.artwork?.canonical_url || "#", target: "_blank", rel: "noreferrer", className: "overflow-hidden rounded-2xl border border-white/10 bg-[#08111d]" }, /* @__PURE__ */ React.createElement("img", { src: entry.artwork?.thumbnail?.url, alt: entry.artwork?.title || "Artwork preview", className: "h-24 w-full object-cover" })), /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center gap-2" }, /* @__PURE__ */ React.createElement("span", { className: "text-sm font-semibold text-white" }, entry.artwork?.title || "Missing artwork"), /* @__PURE__ */ React.createElement("span", { className: "text-xs text-slate-400" }, "#", entry.artwork?.id || entry.artwork_id)), /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-xs leading-6 text-slate-400" }, "Visibility: ", entry.artwork?.visibility || "—", " • Published: ", entry.artwork?.published_at ? "Yes" : "No"), entry.is_winner && entry.winner_reason ? /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-xs leading-6 text-amber-100" }, entry.winner_reason) : null)), /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "text-sm font-semibold text-white" }, entry.artwork?.owner?.display_name || "Unknown"), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-xs text-slate-400" }, entry.artwork?.owner?.type === "group" ? "Group publisher" : `@${entry.artwork?.owner?.username || ""}`)), /* @__PURE__ */ React.createElement("div", { className: "text-sm font-semibold text-white" }, entry.priority), /* @__PURE__ */ React.createElement("div", { className: "text-sm text-slate-200" }, formatDateTime$3(entry.featured_at)), /* @__PURE__ */ React.createElement("div", { className: "text-sm text-slate-200" }, formatDateTime$3(entry.expires_at)), /* @__PURE__ */ React.createElement("div", { className: "text-sm font-semibold text-white" }, entry.medals?.score_30d || 0), /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-2" }, (entry.status_badges || []).map((badge, index2) => /* @__PURE__ */ React.createElement(Badge$2, { key: `${entry.id}-${badge.label}-${index2}`, label: badge.label, tone: badge.tone }))), /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-2 lg:justify-end" }, /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => editEntry(entry), className: "rounded-full border border-white/10 px-4 py-2 text-xs font-semibold uppercase tracking-[0.16em] text-slate-100 transition hover:border-white/20 hover:bg-white/5" }, "Edit"), capabilities.forceHeroEnabled ? /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => handleForceHero(entry), disabled: busy === `force-${entry.id}`, className: `rounded-full border px-4 py-2 text-xs font-semibold uppercase tracking-[0.16em] transition disabled:cursor-not-allowed disabled:opacity-60 ${entry.is_force_hero ? "border-amber-300/25 text-amber-100 hover:border-amber-300/40 hover:bg-amber-400/10" : "border-amber-300/15 text-amber-50 hover:border-amber-300/30 hover:bg-amber-400/5"}` }, busy === `force-${entry.id}` ? "Saving…" : entry.is_force_hero ? "Disable Force Hero" : "Force Hero") : null, /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => handleToggle(entry), disabled: busy === `toggle-${entry.id}`, className: "rounded-full border border-sky-300/20 px-4 py-2 text-xs font-semibold uppercase tracking-[0.16em] text-sky-100 transition hover:border-sky-300/40 hover:bg-sky-400/10 disabled:cursor-not-allowed disabled:opacity-60" }, busy === `toggle-${entry.id}` ? "Saving…" : entry.is_active ? "Deactivate" : "Activate"), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => handleDelete(entry), disabled: busy === `delete-${entry.id}`, className: "rounded-full border border-rose-300/20 px-4 py-2 text-xs font-semibold uppercase tracking-[0.16em] text-rose-100 transition hover:border-rose-300/40 hover:bg-rose-400/10 disabled:cursor-not-allowed disabled:opacity-60" }, busy === `delete-${entry.id}` ? "Deleting…" : "Delete")))))))))); } -const __vite_glob_0_34 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ +const __vite_glob_0_35 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ __proto__: null, default: FeaturedArtworksAdmin }, Symbol.toStringTag, { value: "Module" })); function AdminFeaturedArtworks() { return /* @__PURE__ */ React.createElement(AdminLayout, null, /* @__PURE__ */ React.createElement(FeaturedArtworksAdmin, null)); } -const __vite_glob_0_14 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ +const __vite_glob_0_15 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ __proto__: null, default: AdminFeaturedArtworks }, Symbol.toStringTag, { value: "Module" })); @@ -14424,7 +18327,7 @@ const PRESETS = { prose: "prose-invert prose-a:text-slate-200 prose-strong:text-white" } }; -function cx$b(...parts) { +function cx$9(...parts) { return parts.filter(Boolean).join(" "); } function readHiddenAnnouncements() { @@ -14486,7 +18389,7 @@ function HomepageAnnouncement({ announcement, mode = "live" }) { /* @__PURE__ */ React.createElement("span", null, "Show Skinbase announcement") ))); } - return /* @__PURE__ */ React.createElement("section", { className: "px-4 pt-8 sm:px-6 lg:px-8" }, /* @__PURE__ */ React.createElement("div", { className: "mx-auto max-w-7xl" }, /* @__PURE__ */ React.createElement("div", { className: cx$b("relative overflow-hidden rounded-[2rem] border shadow-[0_28px_90px_rgba(0,0,0,0.35)]", preset.shell) }, announcement.background_image_url ? /* @__PURE__ */ React.createElement("div", { className: "absolute inset-0" }, /* @__PURE__ */ React.createElement("img", { src: announcement.background_image_url, alt: "", className: "h-full w-full object-cover" }), /* @__PURE__ */ React.createElement("div", { className: "absolute inset-0 bg-slate-950", style: { opacity: overlayOpacity / 100 } })) : null, /* @__PURE__ */ React.createElement("div", { className: cx$b("pointer-events-none absolute inset-0 bg-gradient-to-br", preset.glow) }), /* @__PURE__ */ React.createElement("div", { className: "pointer-events-none absolute inset-0 bg-[linear-gradient(180deg,rgba(255,255,255,0.06),transparent_22%,rgba(2,6,23,0.15)_100%)]" }), announcement.is_dismissible && isLiveMode ? /* @__PURE__ */ React.createElement( + return /* @__PURE__ */ React.createElement("section", { className: "px-4 pt-8 sm:px-6 lg:px-8" }, /* @__PURE__ */ React.createElement("div", { className: "mx-auto max-w-7xl" }, /* @__PURE__ */ React.createElement("div", { className: cx$9("relative overflow-hidden rounded-[2rem] border shadow-[0_28px_90px_rgba(0,0,0,0.35)]", preset.shell) }, announcement.background_image_url ? /* @__PURE__ */ React.createElement("div", { className: "absolute inset-0" }, /* @__PURE__ */ React.createElement("img", { src: announcement.background_image_url, alt: "", className: "h-full w-full object-cover" }), /* @__PURE__ */ React.createElement("div", { className: "absolute inset-0 bg-slate-950", style: { opacity: overlayOpacity / 100 } })) : null, /* @__PURE__ */ React.createElement("div", { className: cx$9("pointer-events-none absolute inset-0 bg-gradient-to-br", preset.glow) }), /* @__PURE__ */ React.createElement("div", { className: "pointer-events-none absolute inset-0 bg-[linear-gradient(180deg,rgba(255,255,255,0.06),transparent_22%,rgba(2,6,23,0.15)_100%)]" }), announcement.is_dismissible && isLiveMode ? /* @__PURE__ */ React.createElement( "button", { type: "button", @@ -14496,13 +18399,13 @@ function HomepageAnnouncement({ announcement, mode = "live" }) { }, /* @__PURE__ */ React.createElement("svg", { "aria-hidden": "true", viewBox: "0 0 16 16", className: "h-3.5 w-3.5", fill: "none", stroke: "currentColor", strokeWidth: "2", strokeLinecap: "round" }, /* @__PURE__ */ React.createElement("path", { d: "M3.5 3.5 12.5 12.5" }), /* @__PURE__ */ React.createElement("path", { d: "M12.5 3.5 3.5 12.5" })), "Dismiss" - ) : null, /* @__PURE__ */ React.createElement("div", { className: cx$b( + ) : null, /* @__PURE__ */ React.createElement("div", { className: cx$9( "relative px-6 py-7 sm:px-8 lg:px-10 lg:py-10", isPreviewMode ? "flex min-h-[42rem] flex-col gap-8" : "grid gap-8 lg:grid-cols-[minmax(0,1.25fr)_auto] lg:items-end" - ) }, /* @__PURE__ */ React.createElement("div", { className: cx$b(isPreviewMode ? "w-full flex-1" : "max-w-3xl") }, announcement.badge_text ? /* @__PURE__ */ React.createElement("div", { className: cx$b("inline-flex rounded-full border px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.24em]", preset.badge) }, announcement.badge_text) : null, /* @__PURE__ */ React.createElement("h2", { className: "mt-4 text-3xl font-semibold tracking-[-0.05em] sm:text-4xl lg:text-[3.15rem]" }, announcement.title), announcement.subtitle ? /* @__PURE__ */ React.createElement("p", { className: cx$b("mt-3 text-base leading-7 text-current/80 sm:text-lg", isPreviewMode ? "w-full max-w-none" : "max-w-2xl") }, announcement.subtitle) : null, announcement.content_html ? /* @__PURE__ */ React.createElement( + ) }, /* @__PURE__ */ React.createElement("div", { className: cx$9(isPreviewMode ? "w-full flex-1" : "max-w-3xl") }, announcement.badge_text ? /* @__PURE__ */ React.createElement("div", { className: cx$9("inline-flex rounded-full border px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.24em]", preset.badge) }, announcement.badge_text) : null, /* @__PURE__ */ React.createElement("h2", { className: "mt-4 text-3xl font-semibold tracking-[-0.05em] sm:text-4xl lg:text-[3.15rem]" }, announcement.title), announcement.subtitle ? /* @__PURE__ */ React.createElement("p", { className: cx$9("mt-3 text-base leading-7 text-current/80 sm:text-lg", isPreviewMode ? "w-full max-w-none" : "max-w-2xl") }, announcement.subtitle) : null, announcement.content_html ? /* @__PURE__ */ React.createElement( "div", { - className: cx$b( + className: cx$9( "mt-5 text-sm leading-7 sm:text-base", "[&_p]:my-0 [&_p+p]:mt-6 [&_ul]:my-5 [&_ol]:my-5 [&_li+li]:mt-1.5 [&_blockquote]:my-5 [&_h2]:mb-3 [&_h2]:mt-7 [&_h3]:mb-2 [&_h3]:mt-6", preset.prose, @@ -14510,9 +18413,9 @@ function HomepageAnnouncement({ announcement, mode = "live" }) { ), dangerouslySetInnerHTML: { __html: announcement.content_html } } - ) : null), /* @__PURE__ */ React.createElement("div", { className: cx$b( + ) : null), /* @__PURE__ */ React.createElement("div", { className: cx$9( isPreviewMode ? "mt-auto flex w-full flex-col gap-4 border-t border-white/10 pt-5" : "flex flex-col items-start gap-3 lg:items-end" - ) }, /* @__PURE__ */ React.createElement("div", { className: cx$b("flex flex-wrap gap-3", isPreviewMode ? "w-full" : "lg:justify-end") }, announcement.primary_link ? /* @__PURE__ */ React.createElement("a", { href: announcement.primary_link.url, className: cx$b("inline-flex items-center justify-center rounded-full border px-5 py-3 text-sm font-semibold transition", isPreviewMode ? "min-w-[11rem]" : "", preset.primary) }, announcement.primary_link.label) : null, announcement.secondary_link ? /* @__PURE__ */ React.createElement("a", { href: announcement.secondary_link.url, className: cx$b("inline-flex items-center justify-center rounded-full border px-5 py-3 text-sm font-semibold transition", isPreviewMode ? "min-w-[11rem]" : "", preset.secondary) }, announcement.secondary_link.label) : null)))))); + ) }, /* @__PURE__ */ React.createElement("div", { className: cx$9("flex flex-wrap gap-3", isPreviewMode ? "w-full" : "lg:justify-end") }, announcement.primary_link ? /* @__PURE__ */ React.createElement("a", { href: announcement.primary_link.url, className: cx$9("inline-flex items-center justify-center rounded-full border px-5 py-3 text-sm font-semibold transition", isPreviewMode ? "min-w-[11rem]" : "", preset.primary) }, announcement.primary_link.label) : null, announcement.secondary_link ? /* @__PURE__ */ React.createElement("a", { href: announcement.secondary_link.url, className: cx$9("inline-flex items-center justify-center rounded-full border px-5 py-3 text-sm font-semibold transition", isPreviewMode ? "min-w-[11rem]" : "", preset.secondary) }, announcement.secondary_link.label) : null)))))); } function ToolbarButton({ onClick, active, disabled, title, children }) { return /* @__PURE__ */ React.createElement( @@ -14532,10 +18435,10 @@ function ToolbarButton({ onClick, active, disabled, title, children }) { children ); } -function Divider$1() { +function Divider() { return /* @__PURE__ */ React.createElement("div", { className: "mx-1 h-5 w-px bg-white/10" }); } -function Toolbar$1({ editor }) { +function Toolbar({ editor }) { if (!editor) return null; const addLink = reactExports.useCallback(() => { const previous2 = editor.getAttributes("link").href; @@ -14547,7 +18450,7 @@ function Toolbar$1({ editor }) { } editor.chain().focus().extendMarkRange("link").setLink({ href: url }).run(); }, [editor]); - return /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center gap-0.5 border-b border-white/[0.06] px-2.5 py-2" }, /* @__PURE__ */ React.createElement(ToolbarButton, { onClick: () => editor.chain().focus().toggleBold().run(), active: editor.isActive("bold"), title: "Bold" }, /* @__PURE__ */ React.createElement("svg", { width: "15", height: "15", viewBox: "0 0 24 24", fill: "currentColor" }, /* @__PURE__ */ React.createElement("path", { d: "M6 4h8a4 4 0 014 4 4 4 0 01-4 4H6zm0 8h9a4 4 0 014 4 4 4 0 01-4 4H6z" }))), /* @__PURE__ */ React.createElement(ToolbarButton, { onClick: () => editor.chain().focus().toggleItalic().run(), active: editor.isActive("italic"), title: "Italic" }, /* @__PURE__ */ React.createElement("svg", { width: "15", height: "15", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "2" }, /* @__PURE__ */ React.createElement("line", { x1: "19", y1: "4", x2: "10", y2: "4" }), /* @__PURE__ */ React.createElement("line", { x1: "14", y1: "20", x2: "5", y2: "20" }), /* @__PURE__ */ React.createElement("line", { x1: "15", y1: "4", x2: "9", y2: "20" }))), /* @__PURE__ */ React.createElement(Divider$1, null), /* @__PURE__ */ React.createElement(ToolbarButton, { onClick: () => editor.chain().focus().toggleHeading({ level: 2 }).run(), active: editor.isActive("heading", { level: 2 }), title: "Heading 2" }, /* @__PURE__ */ React.createElement("span", { className: "text-xs font-bold" }, "H2")), /* @__PURE__ */ React.createElement(ToolbarButton, { onClick: () => editor.chain().focus().toggleHeading({ level: 3 }).run(), active: editor.isActive("heading", { level: 3 }), title: "Heading 3" }, /* @__PURE__ */ React.createElement("span", { className: "text-xs font-bold" }, "H3")), /* @__PURE__ */ React.createElement(Divider$1, null), /* @__PURE__ */ React.createElement(ToolbarButton, { onClick: () => editor.chain().focus().toggleBulletList().run(), active: editor.isActive("bulletList"), title: "Bullet list" }, /* @__PURE__ */ React.createElement("svg", { width: "15", height: "15", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "2" }, /* @__PURE__ */ React.createElement("line", { x1: "9", y1: "6", x2: "20", y2: "6" }), /* @__PURE__ */ React.createElement("line", { x1: "9", y1: "12", x2: "20", y2: "12" }), /* @__PURE__ */ React.createElement("line", { x1: "9", y1: "18", x2: "20", y2: "18" }), /* @__PURE__ */ React.createElement("circle", { cx: "4.5", cy: "6", r: "1", fill: "currentColor" }), /* @__PURE__ */ React.createElement("circle", { cx: "4.5", cy: "12", r: "1", fill: "currentColor" }), /* @__PURE__ */ React.createElement("circle", { cx: "4.5", cy: "18", r: "1", fill: "currentColor" }))), /* @__PURE__ */ React.createElement(ToolbarButton, { onClick: () => editor.chain().focus().toggleOrderedList().run(), active: editor.isActive("orderedList"), title: "Numbered list" }, /* @__PURE__ */ React.createElement("svg", { width: "15", height: "15", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "2" }, /* @__PURE__ */ React.createElement("line", { x1: "10", y1: "6", x2: "21", y2: "6" }), /* @__PURE__ */ React.createElement("line", { x1: "10", y1: "12", x2: "21", y2: "12" }), /* @__PURE__ */ React.createElement("line", { x1: "10", y1: "18", x2: "21", y2: "18" }), /* @__PURE__ */ React.createElement("text", { x: "3", y: "8", fontSize: "7", fill: "currentColor", stroke: "none", fontFamily: "sans-serif" }, "1"), /* @__PURE__ */ React.createElement("text", { x: "3", y: "14", fontSize: "7", fill: "currentColor", stroke: "none", fontFamily: "sans-serif" }, "2"), /* @__PURE__ */ React.createElement("text", { x: "3", y: "20", fontSize: "7", fill: "currentColor", stroke: "none", fontFamily: "sans-serif" }, "3"))), /* @__PURE__ */ React.createElement(Divider$1, null), /* @__PURE__ */ React.createElement(ToolbarButton, { onClick: () => editor.chain().focus().toggleBlockquote().run(), active: editor.isActive("blockquote"), title: "Quote" }, /* @__PURE__ */ React.createElement("svg", { width: "15", height: "15", viewBox: "0 0 24 24", fill: "currentColor" }, /* @__PURE__ */ React.createElement("path", { d: "M4.583 17.321C3.553 16.227 3 15 3 13.011c0-3.5 2.457-6.637 6.03-8.188l.893 1.378c-3.335 1.804-3.987 4.145-4.247 5.621.537-.278 1.24-.375 1.929-.311C9.591 11.68 11 13.24 11 15.14c0 .94-.36 1.84-1.001 2.503A3.34 3.34 0 017.559 18.6a3.77 3.77 0 01-2.976-.879zm10.4 0C13.953 16.227 13.4 15 13.4 13.011c0-3.5 2.457-6.637 6.03-8.188l.893 1.378c-3.335 1.804-3.987 4.145-4.247 5.621.537-.278 1.24-.375 1.929-.311 1.986.169 3.395 1.729 3.395 3.629 0 .94-.36 1.84-1.001 2.503a3.34 3.34 0 01-2.44.957 3.77 3.77 0 01-2.976-.879z" }))), /* @__PURE__ */ React.createElement(ToolbarButton, { onClick: addLink, active: editor.isActive("link"), title: "Link" }, /* @__PURE__ */ React.createElement("svg", { width: "15", height: "15", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "2", strokeLinecap: "round", strokeLinejoin: "round" }, /* @__PURE__ */ React.createElement("path", { d: "M10 13a5 5 0 007.54.54l3-3a5 5 0 00-7.07-7.07l-1.72 1.71" }), /* @__PURE__ */ React.createElement("path", { d: "M14 11a5 5 0 00-7.54-.54l-3 3a5 5 0 007.07 7.07l1.71-1.71" }))), /* @__PURE__ */ React.createElement("div", { className: "ml-auto flex items-center gap-0.5" }, /* @__PURE__ */ React.createElement(ToolbarButton, { onClick: () => editor.chain().focus().undo().run(), disabled: !editor.can().undo(), title: "Undo" }, /* @__PURE__ */ React.createElement("svg", { width: "15", height: "15", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "2", strokeLinecap: "round", strokeLinejoin: "round" }, /* @__PURE__ */ React.createElement("polyline", { points: "1 4 1 10 7 10" }), /* @__PURE__ */ React.createElement("path", { d: "M3.51 15a9 9 0 102.13-9.36L1 10" }))), /* @__PURE__ */ React.createElement(ToolbarButton, { onClick: () => editor.chain().focus().redo().run(), disabled: !editor.can().redo(), title: "Redo" }, /* @__PURE__ */ React.createElement("svg", { width: "15", height: "15", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "2", strokeLinecap: "round", strokeLinejoin: "round" }, /* @__PURE__ */ React.createElement("polyline", { points: "23 4 23 10 17 10" }), /* @__PURE__ */ React.createElement("path", { d: "M20.49 15a9 9 0 11-2.13-9.36L23 10" }))))); + return /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center gap-0.5 border-b border-white/[0.06] px-2.5 py-2" }, /* @__PURE__ */ React.createElement(ToolbarButton, { onClick: () => editor.chain().focus().toggleBold().run(), active: editor.isActive("bold"), title: "Bold" }, /* @__PURE__ */ React.createElement("svg", { width: "15", height: "15", viewBox: "0 0 24 24", fill: "currentColor" }, /* @__PURE__ */ React.createElement("path", { d: "M6 4h8a4 4 0 014 4 4 4 0 01-4 4H6zm0 8h9a4 4 0 014 4 4 4 0 01-4 4H6z" }))), /* @__PURE__ */ React.createElement(ToolbarButton, { onClick: () => editor.chain().focus().toggleItalic().run(), active: editor.isActive("italic"), title: "Italic" }, /* @__PURE__ */ React.createElement("svg", { width: "15", height: "15", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "2" }, /* @__PURE__ */ React.createElement("line", { x1: "19", y1: "4", x2: "10", y2: "4" }), /* @__PURE__ */ React.createElement("line", { x1: "14", y1: "20", x2: "5", y2: "20" }), /* @__PURE__ */ React.createElement("line", { x1: "15", y1: "4", x2: "9", y2: "20" }))), /* @__PURE__ */ React.createElement(Divider, null), /* @__PURE__ */ React.createElement(ToolbarButton, { onClick: () => editor.chain().focus().toggleHeading({ level: 2 }).run(), active: editor.isActive("heading", { level: 2 }), title: "Heading 2" }, /* @__PURE__ */ React.createElement("span", { className: "text-xs font-bold" }, "H2")), /* @__PURE__ */ React.createElement(ToolbarButton, { onClick: () => editor.chain().focus().toggleHeading({ level: 3 }).run(), active: editor.isActive("heading", { level: 3 }), title: "Heading 3" }, /* @__PURE__ */ React.createElement("span", { className: "text-xs font-bold" }, "H3")), /* @__PURE__ */ React.createElement(Divider, null), /* @__PURE__ */ React.createElement(ToolbarButton, { onClick: () => editor.chain().focus().toggleBulletList().run(), active: editor.isActive("bulletList"), title: "Bullet list" }, /* @__PURE__ */ React.createElement("svg", { width: "15", height: "15", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "2" }, /* @__PURE__ */ React.createElement("line", { x1: "9", y1: "6", x2: "20", y2: "6" }), /* @__PURE__ */ React.createElement("line", { x1: "9", y1: "12", x2: "20", y2: "12" }), /* @__PURE__ */ React.createElement("line", { x1: "9", y1: "18", x2: "20", y2: "18" }), /* @__PURE__ */ React.createElement("circle", { cx: "4.5", cy: "6", r: "1", fill: "currentColor" }), /* @__PURE__ */ React.createElement("circle", { cx: "4.5", cy: "12", r: "1", fill: "currentColor" }), /* @__PURE__ */ React.createElement("circle", { cx: "4.5", cy: "18", r: "1", fill: "currentColor" }))), /* @__PURE__ */ React.createElement(ToolbarButton, { onClick: () => editor.chain().focus().toggleOrderedList().run(), active: editor.isActive("orderedList"), title: "Numbered list" }, /* @__PURE__ */ React.createElement("svg", { width: "15", height: "15", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "2" }, /* @__PURE__ */ React.createElement("line", { x1: "10", y1: "6", x2: "21", y2: "6" }), /* @__PURE__ */ React.createElement("line", { x1: "10", y1: "12", x2: "21", y2: "12" }), /* @__PURE__ */ React.createElement("line", { x1: "10", y1: "18", x2: "21", y2: "18" }), /* @__PURE__ */ React.createElement("text", { x: "3", y: "8", fontSize: "7", fill: "currentColor", stroke: "none", fontFamily: "sans-serif" }, "1"), /* @__PURE__ */ React.createElement("text", { x: "3", y: "14", fontSize: "7", fill: "currentColor", stroke: "none", fontFamily: "sans-serif" }, "2"), /* @__PURE__ */ React.createElement("text", { x: "3", y: "20", fontSize: "7", fill: "currentColor", stroke: "none", fontFamily: "sans-serif" }, "3"))), /* @__PURE__ */ React.createElement(Divider, null), /* @__PURE__ */ React.createElement(ToolbarButton, { onClick: () => editor.chain().focus().toggleBlockquote().run(), active: editor.isActive("blockquote"), title: "Quote" }, /* @__PURE__ */ React.createElement("svg", { width: "15", height: "15", viewBox: "0 0 24 24", fill: "currentColor" }, /* @__PURE__ */ React.createElement("path", { d: "M4.583 17.321C3.553 16.227 3 15 3 13.011c0-3.5 2.457-6.637 6.03-8.188l.893 1.378c-3.335 1.804-3.987 4.145-4.247 5.621.537-.278 1.24-.375 1.929-.311C9.591 11.68 11 13.24 11 15.14c0 .94-.36 1.84-1.001 2.503A3.34 3.34 0 017.559 18.6a3.77 3.77 0 01-2.976-.879zm10.4 0C13.953 16.227 13.4 15 13.4 13.011c0-3.5 2.457-6.637 6.03-8.188l.893 1.378c-3.335 1.804-3.987 4.145-4.247 5.621.537-.278 1.24-.375 1.929-.311 1.986.169 3.395 1.729 3.395 3.629 0 .94-.36 1.84-1.001 2.503a3.34 3.34 0 01-2.44.957 3.77 3.77 0 01-2.976-.879z" }))), /* @__PURE__ */ React.createElement(ToolbarButton, { onClick: addLink, active: editor.isActive("link"), title: "Link" }, /* @__PURE__ */ React.createElement("svg", { width: "15", height: "15", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "2", strokeLinecap: "round", strokeLinejoin: "round" }, /* @__PURE__ */ React.createElement("path", { d: "M10 13a5 5 0 007.54.54l3-3a5 5 0 00-7.07-7.07l-1.72 1.71" }), /* @__PURE__ */ React.createElement("path", { d: "M14 11a5 5 0 00-7.54-.54l-3 3a5 5 0 007.07 7.07l1.71-1.71" }))), /* @__PURE__ */ React.createElement("div", { className: "ml-auto flex items-center gap-0.5" }, /* @__PURE__ */ React.createElement(ToolbarButton, { onClick: () => editor.chain().focus().undo().run(), disabled: !editor.can().undo(), title: "Undo" }, /* @__PURE__ */ React.createElement("svg", { width: "15", height: "15", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "2", strokeLinecap: "round", strokeLinejoin: "round" }, /* @__PURE__ */ React.createElement("polyline", { points: "1 4 1 10 7 10" }), /* @__PURE__ */ React.createElement("path", { d: "M3.51 15a9 9 0 102.13-9.36L1 10" }))), /* @__PURE__ */ React.createElement(ToolbarButton, { onClick: () => editor.chain().focus().redo().run(), disabled: !editor.can().redo(), title: "Redo" }, /* @__PURE__ */ React.createElement("svg", { width: "15", height: "15", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "2", strokeLinecap: "round", strokeLinejoin: "round" }, /* @__PURE__ */ React.createElement("polyline", { points: "23 4 23 10 17 10" }), /* @__PURE__ */ React.createElement("path", { d: "M20.49 15a9 9 0 11-2.13-9.36L23 10" }))))); } function HomepageAnnouncementEditor({ content: content2 = "", @@ -14558,21 +18461,21 @@ function HomepageAnnouncementEditor({ }) { const editor = useEditor({ extensions: [ - index_default.configure({ + index_default$2.configure({ link: false, heading: { levels: [2, 3] }, code: false, codeBlock: false, horizontalRule: false }), - index_default$1.configure({ + index_default$3.configure({ openOnClick: false, HTMLAttributes: { class: "text-sky-300 underline hover:text-sky-200", rel: "noopener noreferrer nofollow" } }), - index_default$2.configure({ placeholder }) + index_default$4.configure({ placeholder }) ], immediatelyRender: false, content: content2, @@ -14609,7 +18512,7 @@ function HomepageAnnouncementEditor({ error ? "border-red-500/60 focus-within:border-red-500/70 focus-within:ring-2 focus-within:ring-red-500/30" : "border-white/12 hover:border-white/20 focus-within:border-sky-500/50 focus-within:ring-2 focus-within:ring-sky-500/20" ].join(" ") }, - /* @__PURE__ */ React.createElement(Toolbar$1, { editor }), + /* @__PURE__ */ React.createElement(Toolbar, { editor }), /* @__PURE__ */ React.createElement(EditorContent, { editor }) ), error ? /* @__PURE__ */ React.createElement("p", { role: "alert", className: "text-xs text-red-400" }, error) : null); } @@ -15086,7 +18989,7 @@ function HomepageAnnouncementForm({ announcement, previewAnnouncement, options, } }, help: "Turn this on to clear the saved background image on the next save." })) : null, activeTab === "behavior" ? /* @__PURE__ */ React.createElement(Section$1, { title: "Behavior", description: "Dismiss controls let you force a fresh surface when the message materially changes." }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 md:grid-cols-2" }, /* @__PURE__ */ React.createElement(TextField, { label: "Dismiss version", value: form.data.dismiss_version, onChange: (event) => form.setData("dismiss_version", event.target.value), error: form.errors.dismiss_version, inputMode: "numeric" }), /* @__PURE__ */ React.createElement(SelectField, { label: "Placement", value: form.data.placement, onChange: (nextValue) => form.setData("placement", nextValue), options: options.placements, error: form.errors.placement })), /* @__PURE__ */ React.createElement(ToggleField, { label: "Users can dismiss this card", checked: Boolean(form.data.is_dismissible), onChange: (event) => form.setData("is_dismissible", event.target.checked), help: "When disabled, the card remains visible and no restore pill is shown." })) : null), /* @__PURE__ */ React.createElement("aside", { className: "space-y-6 xl:sticky xl:top-[7.5rem] xl:self-start" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement(Section$1, { title: "Preview", description: "Refresh the preview to render the sanitized content and resolved CTA payload exactly as the homepage card sees it." }, /* @__PURE__ */ React.createElement("div", { className: "-mx-6 -mt-6 mb-5 border-b border-white/10 bg-slate-950/92 px-6 py-4 backdrop-blur-xl" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-3" }, /* @__PURE__ */ React.createElement("button", { type: "button", onClick: runPreview, disabled: previewBusy, className: "rounded-full border border-sky-300/20 bg-sky-300/12 px-4 py-2 text-sm font-semibold text-sky-100 transition hover:bg-sky-300/18 disabled:opacity-60" }, previewBusy ? "Refreshing preview…" : "Refresh preview"), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => submit(), className: "rounded-full border border-white/10 bg-white/[0.04] px-4 py-2 text-sm font-semibold text-white transition hover:bg-white/[0.08]" }, "Save changes")), previewError ? /* @__PURE__ */ React.createElement("p", { className: "mt-3 text-sm text-rose-300" }, previewError) : null), /* @__PURE__ */ React.createElement("div", { className: "overflow-hidden rounded-[30px] border border-white/10 bg-black/20 py-2" }, /* @__PURE__ */ React.createElement(HomepageAnnouncement, { announcement: previewWithLocalImage, mode: "preview" }))))))); } -const __vite_glob_0_15 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ +const __vite_glob_0_16 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ __proto__: null, default: HomepageAnnouncementForm }, Symbol.toStringTag, { value: "Module" })); @@ -15125,7 +19028,7 @@ function HomepageAnnouncementsIndex({ announcements, createUrl }) { } ) : /* @__PURE__ */ React.createElement("span", { key: `${link2.label}-${index2}`, className: "rounded-lg px-3 py-1.5 text-xs text-slate-600", dangerouslySetInnerHTML: { __html: link2.label } })))) : null); } -const __vite_glob_0_16 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ +const __vite_glob_0_17 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ __proto__: null, default: HomepageAnnouncementsIndex }, Symbol.toStringTag, { value: "Module" })); @@ -15165,7 +19068,7 @@ function AdminSettings({ settings = {} }) { } )))))), /* @__PURE__ */ React.createElement("p", { className: "text-xs text-slate-600" }, "Full settings management via config files and environment variables."))); } -const __vite_glob_0_17 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ +const __vite_glob_0_18 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ __proto__: null, default: AdminSettings }, Symbol.toStringTag, { value: "Module" })); @@ -15189,7 +19092,7 @@ function AdminStories({ stories }) { } ) : /* @__PURE__ */ React.createElement("span", { key: i, className: "rounded-lg px-3 py-1.5 text-xs text-slate-700", dangerouslySetInnerHTML: { __html: link2.label } })))))); } -const __vite_glob_0_18 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ +const __vite_glob_0_19 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ __proto__: null, default: AdminStories }, Symbol.toStringTag, { value: "Module" })); @@ -15255,7 +19158,7 @@ function AdminUploadQueue() { function UploadQueuePage() { return /* @__PURE__ */ React.createElement(AdminLayout, { title: "Upload Queue", subtitle: "Review and moderate pending artwork submissions" }, /* @__PURE__ */ React.createElement(Se, { title: "Admin · Upload Queue" }), /* @__PURE__ */ React.createElement(AdminUploadQueue, null)); } -const __vite_glob_0_19 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ +const __vite_glob_0_20 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ __proto__: null, default: UploadQueuePage }, Symbol.toStringTag, { value: "Module" })); @@ -15319,7 +19222,7 @@ function AdminUsernameQueue() { function UsernameQueuePage() { return /* @__PURE__ */ React.createElement(AdminLayout, { title: "Username Queue", subtitle: "Review and approve pending username change requests" }, /* @__PURE__ */ React.createElement(Se, { title: "Admin · Username Queue" }), /* @__PURE__ */ React.createElement(AdminUsernameQueue, null)); } -const __vite_glob_0_20 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ +const __vite_glob_0_21 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ __proto__: null, default: UsernameQueuePage }, Symbol.toStringTag, { value: "Module" })); @@ -15415,7 +19318,7 @@ function UsersIndex({ users, filters, roles }) { } ) : /* @__PURE__ */ React.createElement("span", { key: i, className: "rounded-lg px-3 py-1.5 text-xs text-slate-700", dangerouslySetInnerHTML: { __html: link2.label } })))))); } -const __vite_glob_0_21 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ +const __vite_glob_0_22 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ __proto__: null, default: UsersIndex }, Symbol.toStringTag, { value: "Module" })); @@ -15479,7 +19382,7 @@ function SimilarArtworksHeader({ artwork }) { artwork.content_type_name || "artworks" ))))); } -const __vite_glob_0_22 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ +const __vite_glob_0_23 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ __proto__: null, default: SimilarArtworksHeader }, Symbol.toStringTag, { value: "Module" })); @@ -27847,111 +31750,6 @@ function defaultUrlTransform(value) { } return ""; } -let emojiMartPromise = null; -function ensureEmojiMart() { - if (!emojiMartPromise) { - emojiMartPromise = import("./assets/emoji-ui-C_DZUNyP.js"); - } - return emojiMartPromise; -} -function EmojiMartPicker({ - data, - onEmojiSelect, - onClickOutside, - theme = "auto", - previewPosition = "bottom", - skinTonePosition = "preview", - maxFrequentRows = 4, - perLine = 9, - navPosition = "top", - set = "native", - locale = "en", - autoFocus = false, - searchPosition, - dynamicWidth, - noCountryFlags, - className = "" -}) { - const hostRef = reactExports.useRef(null); - const pickerRef = reactExports.useRef(null); - const onEmojiSelectRef = reactExports.useRef(onEmojiSelect); - const onClickOutsideRef = reactExports.useRef(onClickOutside); - onEmojiSelectRef.current = onEmojiSelect; - onClickOutsideRef.current = onClickOutside; - const stableOnEmojiSelect = reactExports.useCallback((emoji) => { - onEmojiSelectRef.current?.(emoji); - }, []); - const stableOnClickOutside = reactExports.useCallback((e) => { - onClickOutsideRef.current?.(e); - }, []); - reactExports.useEffect(() => { - let cancelled = false; - ensureEmojiMart().then(({ Picker }) => { - if (cancelled || !hostRef.current) return; - if (!pickerRef.current) { - const pickerProps = { - data, - onEmojiSelect: stableOnEmojiSelect, - onClickOutside: stableOnClickOutside, - theme, - previewPosition, - skinTonePosition, - maxFrequentRows, - perLine, - navPosition, - set, - locale, - autoFocus - }; - if (searchPosition !== void 0) pickerProps.searchPosition = searchPosition; - if (dynamicWidth !== void 0) pickerProps.dynamicWidth = dynamicWidth; - if (noCountryFlags !== void 0) pickerProps.noCountryFlags = noCountryFlags; - const el = new Picker(pickerProps); - pickerRef.current = el; - hostRef.current.replaceChildren(el); - } - }); - return () => { - cancelled = true; - }; - }, []); - reactExports.useEffect(() => { - return () => { - if (hostRef.current) { - hostRef.current.replaceChildren(); - } - pickerRef.current = null; - }; - }, []); - return /* @__PURE__ */ React.createElement("div", { ref: hostRef, className }); -} -const EmojiMartPicker$1 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ - __proto__: null, - default: EmojiMartPicker -}, Symbol.toStringTag, { value: "Module" })); -function extractNativeEmoji(selection) { - if (typeof selection === "string") { - return selection; - } - const detail = selection?.detail ?? null; - return selection?.native ?? selection?.emoji ?? selection?.unicode ?? selection?.skins?.[0]?.native ?? detail?.native ?? detail?.emoji ?? detail?.unicode ?? detail?.skins?.[0]?.native ?? ""; -} -function isEventWithinNode(event, node2) { - if (!event || !node2) { - return false; - } - if (typeof event.composedPath === "function") { - return event.composedPath().includes(node2); - } - return node2.contains(event.target); -} -let emojiMartDataPromise = null; -function loadEmojiMartData() { - if (!emojiMartDataPromise) { - emojiMartDataPromise = import("./assets/emoji-data-4xGXbtDn.js").then((module) => module.default); - } - return emojiMartDataPromise; -} function EmojiPickerButton({ onEmojiSelect, disabled = false, className = "" }) { const [open, setOpen] = reactExports.useState(false); const [pickerData, setPickerData] = reactExports.useState(null); @@ -28051,7 +31849,7 @@ function ListIcon$1() { function QuoteIcon$1() { return /* @__PURE__ */ React.createElement("svg", { viewBox: "0 0 24 24", fill: "currentColor", className: "h-4 w-4" }, /* @__PURE__ */ React.createElement("path", { d: "M4.583 17.321C3.553 16.227 3 15 3 13.011c0-3.5 2.457-6.637 6.03-8.188l.893 1.378c-3.335 1.804-3.987 4.145-4.247 5.621.537-.278 1.24-.375 1.929-.311C9.591 11.68 11 13.176 11 15c0 1.933-1.567 3.5-3.5 3.5-1.073 0-2.099-.456-2.917-1.179zM15.583 17.321C14.553 16.227 14 15 14 13.011c0-3.5 2.457-6.637 6.03-8.188l.893 1.378c-3.335 1.804-3.987 4.145-4.247 5.621.537-.278 1.24-.375 1.929-.311C20.591 11.68 22 13.176 22 15c0 1.933-1.567 3.5-3.5 3.5-1.073 0-2.099-.456-2.917-1.179z" })); } -function ToolbarBtn$2({ title, onClick, children }) { +function ToolbarBtn$1({ title, onClick, children }) { return /* @__PURE__ */ React.createElement( "button", { @@ -28271,7 +32069,7 @@ function CommentForm$1({ ].join(" ") }, content2.length > 0 && `${content2.length.toLocaleString()}/${maxLength.toLocaleString()}` - ), /* @__PURE__ */ React.createElement(EmojiPickerButton, { onEmojiSelect: handleEmojiSelect, disabled: submitting }))), tab2 === "write" && /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-0.5 border-b border-white/[0.04] px-3 py-1" }, /* @__PURE__ */ React.createElement(ToolbarBtn$2, { title: "Bold (Ctrl+B)", onClick: () => wrapSelection("**", "**") }, /* @__PURE__ */ React.createElement(BoldIcon$1, null)), /* @__PURE__ */ React.createElement(ToolbarBtn$2, { title: "Italic (Ctrl+I)", onClick: () => wrapSelection("*", "*") }, /* @__PURE__ */ React.createElement(ItalicIcon$1, null)), /* @__PURE__ */ React.createElement(ToolbarBtn$2, { title: "Inline code (Ctrl+E)", onClick: () => wrapSelection("`", "`") }, /* @__PURE__ */ React.createElement(CodeIcon$1, null)), /* @__PURE__ */ React.createElement(ToolbarBtn$2, { title: "Link (Ctrl+K)", onClick: insertLink }, /* @__PURE__ */ React.createElement(LinkIcon$1, null)), /* @__PURE__ */ React.createElement("div", { className: "mx-1 h-4 w-px bg-white/[0.08]" }), /* @__PURE__ */ React.createElement(ToolbarBtn$2, { title: "Bulleted list", onClick: () => prefixLines("- ") }, /* @__PURE__ */ React.createElement(ListIcon$1, null)), /* @__PURE__ */ React.createElement(ToolbarBtn$2, { title: "Quote", onClick: () => prefixLines("> ") }, /* @__PURE__ */ React.createElement(QuoteIcon$1, null))), tab2 === "write" && /* @__PURE__ */ React.createElement( + ), /* @__PURE__ */ React.createElement(EmojiPickerButton, { onEmojiSelect: handleEmojiSelect, disabled: submitting }))), tab2 === "write" && /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-0.5 border-b border-white/[0.04] px-3 py-1" }, /* @__PURE__ */ React.createElement(ToolbarBtn$1, { title: "Bold (Ctrl+B)", onClick: () => wrapSelection("**", "**") }, /* @__PURE__ */ React.createElement(BoldIcon$1, null)), /* @__PURE__ */ React.createElement(ToolbarBtn$1, { title: "Italic (Ctrl+I)", onClick: () => wrapSelection("*", "*") }, /* @__PURE__ */ React.createElement(ItalicIcon$1, null)), /* @__PURE__ */ React.createElement(ToolbarBtn$1, { title: "Inline code (Ctrl+E)", onClick: () => wrapSelection("`", "`") }, /* @__PURE__ */ React.createElement(CodeIcon$1, null)), /* @__PURE__ */ React.createElement(ToolbarBtn$1, { title: "Link (Ctrl+K)", onClick: insertLink }, /* @__PURE__ */ React.createElement(LinkIcon$1, null)), /* @__PURE__ */ React.createElement("div", { className: "mx-1 h-4 w-px bg-white/[0.08]" }), /* @__PURE__ */ React.createElement(ToolbarBtn$1, { title: "Bulleted list", onClick: () => prefixLines("- ") }, /* @__PURE__ */ React.createElement(ListIcon$1, null)), /* @__PURE__ */ React.createElement(ToolbarBtn$1, { title: "Quote", onClick: () => prefixLines("> ") }, /* @__PURE__ */ React.createElement(QuoteIcon$1, null))), tab2 === "write" && /* @__PURE__ */ React.createElement( "textarea", { ref: textareaRef, @@ -28493,7 +32291,7 @@ const TONES$3 = { 6: "border-rose-400/35 bg-rose-500/10 text-rose-100", 7: "border-violet-400/35 bg-violet-500/10 text-violet-100" }; -function cx$a(...parts) { +function cx$8(...parts) { return parts.filter(Boolean).join(" "); } function LevelBadge({ level = 1, rank = "Newbie", compact = false, className = "" }) { @@ -28502,7 +32300,7 @@ function LevelBadge({ level = 1, rank = "Newbie", compact = false, className = " return /* @__PURE__ */ React.createElement( "span", { - className: cx$a( + className: cx$8( "inline-flex items-center gap-1 rounded-full border px-2.5 py-1 font-semibold tracking-[0.08em]", compact ? "text-[10px] uppercase" : "text-[11px] uppercase", tone, @@ -28927,7 +32725,7 @@ function useWebShare({ onFallback } = {}) { ); return { canNativeShare, share }; } -const ArtworkShareModal = reactExports.lazy(() => import("./assets/ArtworkShareModal-BnRQhiXq.js")); +const ArtworkShareModal = reactExports.lazy(() => import("./assets/ArtworkShareModal-BPM8yel5.js")); function ShareIcon() { return /* @__PURE__ */ React.createElement("svg", { xmlns: "http://www.w3.org/2000/svg", fill: "none", viewBox: "0 0 24 24", strokeWidth: 1.5, stroke: "currentColor", className: "h-5 w-5" }, /* @__PURE__ */ React.createElement("path", { strokeLinecap: "round", strokeLinejoin: "round", d: "M8.684 13.342C8.886 12.938 9 12.482 9 12c0-.482-.114-.938-.316-1.342m0 2.684a3 3 0 1 1 0-2.684m0 2.684 6.632 3.316m-6.632-6 6.632-3.316m0 0a3 3 0 1 0 5.367-2.684 3 3 0 0 0-5.367 2.684Zm0 9.316a3 3 0 1 0 5.368 2.684 3 3 0 0 0-5.368-2.684Z" })); } @@ -29533,7 +33331,7 @@ function formatCount$1(value) { if (n >= 1e3) return `${(n / 1e3).toFixed(1).replace(/\.0$/, "")}k`; return NUMBER_FORMATTER$2.format(n); } -function formatDate$f(value, useRelative = true) { +function formatDate$e(value, useRelative = true) { if (!value) return "—"; try { const d2 = new Date(value); @@ -29577,7 +33375,7 @@ function ArtworkDetailsPanel({ artwork, stats }) { label: "Downloads", value: formatCount$1(stats?.downloads) } - )), /* @__PURE__ */ React.createElement("div", { className: "mt-4 divide-y divide-white/[0.05]" }, resolution ? /* @__PURE__ */ React.createElement("div", { className: "py-2" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between gap-4" }, /* @__PURE__ */ React.createElement("span", { className: "text-xs uppercase tracking-wider text-white/35" }, "Resolution"), /* @__PURE__ */ React.createElement("span", { className: "text-sm font-medium text-white/80" }, resolution)), /* @__PURE__ */ React.createElement(ArtworkFormatBadges, { width, height, className: "mt-2" })) : null, /* @__PURE__ */ React.createElement(InfoRow$1, { label: "Uploaded", value: formatDate$f(artwork?.published_at, hydrated) }))); + )), /* @__PURE__ */ React.createElement("div", { className: "mt-4 divide-y divide-white/[0.05]" }, resolution ? /* @__PURE__ */ React.createElement("div", { className: "py-2" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between gap-4" }, /* @__PURE__ */ React.createElement("span", { className: "text-xs uppercase tracking-wider text-white/35" }, "Resolution"), /* @__PURE__ */ React.createElement("span", { className: "text-sm font-medium text-white/80" }, resolution)), /* @__PURE__ */ React.createElement(ArtworkFormatBadges, { width, height, className: "mt-2" })) : null, /* @__PURE__ */ React.createElement(InfoRow$1, { label: "Uploaded", value: formatDate$e(artwork?.published_at, hydrated) }))); } function galleryUrlFor(author) { if (!author?.username) return null; @@ -29866,7 +33664,7 @@ function FollowButton({ } )); } -const AVATAR_FALLBACK$8 = "https://files.skinbase.org/default/missing_sq.webp"; +const AVATAR_FALLBACK$2 = "https://files.skinbase.org/default/missing_sq.webp"; const NUMBER_FORMATTER$1 = new Intl.NumberFormat("en-US"); function formatCount(value) { const n = Number(value || 0); @@ -29898,7 +33696,7 @@ function CreatorSpotlight({ artwork, presentSq, related = [] }) { const isOwnArtwork = Number(artwork?.viewer?.id || 0) > 0 && Number(artwork?.viewer?.id) === Number(user.id || 0); const authorName = isGroupPublisher ? publisher?.name || "Group" : user.name || user.username || "Artist"; const profileUrl = isGroupPublisher ? publisher?.profile_url || "#" : user.profile_url || (user.username ? `/@${user.username}` : "#"); - const avatar = (isGroupPublisher ? publisher?.avatar_url : user.avatar_url) || presentSq?.url || AVATAR_FALLBACK$8; + const avatar = (isGroupPublisher ? publisher?.avatar_url : user.avatar_url) || presentSq?.url || AVATAR_FALLBACK$2; const creatorItems = reactExports.useMemo(() => { const currentAuthorId = Number(user?.id || 0); const currentPublisherId = Number(publisher?.id || user?.id || 0); @@ -29923,7 +33721,7 @@ function CreatorSpotlight({ artwork, presentSq, related = [] }) { loading: "lazy", decoding: "async", onError: (event) => { - event.currentTarget.src = AVATAR_FALLBACK$8; + event.currentTarget.src = AVATAR_FALLBACK$2; } } )), /* @__PURE__ */ React.createElement("div", { className: "relative mt-3 w-full px-10 text-center" }, /* @__PURE__ */ React.createElement("a", { href: profileUrl, className: "block text-base font-bold text-white transition-colors hover:text-accent" }, authorName), !isGroupPublisher && user.username ? /* @__PURE__ */ React.createElement("p", { className: "text-xs text-white/40" }, "@", user.username) : null, isGroupPublisher && primaryAuthor ? /* @__PURE__ */ React.createElement("p", { className: "text-xs text-white/40" }, "Primary author: ", primaryAuthor.name || primaryAuthor.username) : null, bioAuthor?.username ? /* @__PURE__ */ React.createElement("span", { className: "absolute right-0 top-1/2 -translate-y-1/2" }, /* @__PURE__ */ React.createElement(AuthorBioPopover, { author: bioAuthor })) : null), /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-xs font-medium text-white/30" }, NUMBER_FORMATTER$1.format(followersCount), " Followers"), /* @__PURE__ */ React.createElement("div", { className: "mt-4 flex w-full gap-2" }, /* @__PURE__ */ React.createElement( @@ -29975,7 +33773,7 @@ function CreatorSpotlight({ artwork, presentSq, related = [] }) { ) : null)), creatorItems.length > 0 && /* @__PURE__ */ React.createElement("div", { className: "mt-5 border-t border-white/[0.06] pt-5" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between" }, /* @__PURE__ */ React.createElement("h3", { className: "text-sm font-semibold text-white/80" }, isGroupPublisher ? "More related works" : `More from ${authorName}`), /* @__PURE__ */ React.createElement("a", { href: profileUrl, "aria-label": isGroupPublisher ? "View more related works" : `View all from ${authorName}`, className: "text-white/30 transition-colors hover:text-white/60" }, /* @__PURE__ */ React.createElement("svg", { xmlns: "http://www.w3.org/2000/svg", fill: "none", viewBox: "0 0 24 24", strokeWidth: 2, stroke: "currentColor", className: "h-4 w-4" }, /* @__PURE__ */ React.createElement("path", { strokeLinecap: "round", strokeLinejoin: "round", d: "m8.25 4.5 7.5 7.5-7.5 7.5" })))), /* @__PURE__ */ React.createElement("div", { className: "mt-3 grid grid-cols-3 gap-2" }, creatorItems.slice(0, 3).map((item, idx) => /* @__PURE__ */ React.createElement("a", { key: `${item.id || item.url}-${idx}`, href: item.url, className: "group/mini relative overflow-hidden rounded-xl" }, /* @__PURE__ */ React.createElement("div", { className: "aspect-square overflow-hidden bg-deep" }, /* @__PURE__ */ React.createElement( "img", { - src: item.thumb || AVATAR_FALLBACK$8, + src: item.thumb || AVATAR_FALLBACK$2, alt: item.title || "Artwork", className: "h-full w-full object-cover transition duration-300 group-hover/mini:scale-[1.06]", loading: "lazy", @@ -29983,8 +33781,8 @@ function CreatorSpotlight({ artwork, presentSq, related = [] }) { } )), /* @__PURE__ */ React.createElement("div", { className: "pointer-events-none absolute inset-0 bg-gradient-to-t from-black/50 via-transparent to-transparent" }), /* @__PURE__ */ React.createElement("div", { className: "absolute bottom-1.5 left-1.5 right-1.5 flex items-center gap-1" }, /* @__PURE__ */ React.createElement("svg", { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 20 20", fill: "currentColor", className: "h-3 w-3 text-rose-400" }, /* @__PURE__ */ React.createElement("path", { d: "m9.653 16.915-.005-.003-.019-.01a20.759 20.759 0 0 1-1.162-.682 22.045 22.045 0 0 1-2.582-1.9C4.045 12.733 2 10.352 2 7.5a4.5 4.5 0 0 1 8-2.828A4.5 4.5 0 0 1 18 7.5c0 2.852-2.044 5.233-3.885 6.82a22.049 22.049 0 0 1-3.744 2.582l-.019.01-.005.003h-.002a.723.723 0 0 1-.69 0h-.002Z" })), /* @__PURE__ */ React.createElement("span", { className: "text-[10px] font-bold text-white drop-shadow" }, item.likes ? formatCount(item.likes) : "")))))))); } -const FALLBACK$4 = "https://files.skinbase.org/default/missing_md.webp"; -const AVATAR_FALLBACK$7 = "https://files.skinbase.org/default/avatar_default.webp"; +const FALLBACK = "https://files.skinbase.org/default/missing_md.webp"; +const AVATAR_FALLBACK$1 = "https://files.skinbase.org/default/avatar_default.webp"; function normalizeRelated(item) { if (!item?.url) return null; return { @@ -30046,7 +33844,7 @@ function RailCard({ item }) { /* @__PURE__ */ React.createElement("div", { className: "relative aspect-[4/3] overflow-hidden bg-neutral-900" }, /* @__PURE__ */ React.createElement("div", { className: "absolute inset-0 bg-gradient-to-br from-white/10 via-white/5 to-transparent pointer-events-none z-10" }), /* @__PURE__ */ React.createElement( "img", { - src: item.thumb || FALLBACK$4, + src: item.thumb || FALLBACK, srcSet: item.thumbSrcSet || void 0, sizes: "(min-width: 1280px) 210px, (min-width: 640px) 220px, 240px", alt: item.title || "Artwork", @@ -30054,17 +33852,17 @@ function RailCard({ item }) { loading: "lazy", decoding: "async", onError: (e) => { - e.currentTarget.src = FALLBACK$4; + e.currentTarget.src = FALLBACK; } } ), isMature ? /* @__PURE__ */ React.createElement("div", { className: "absolute left-3 top-3 z-20 rounded-full border border-amber-300/20 bg-black/60 px-3 py-1 text-[10px] font-semibold uppercase tracking-[0.16em] text-amber-100" }, "Mature") : null, shouldBlur ? /* @__PURE__ */ React.createElement("div", { className: "absolute inset-x-3 bottom-3 z-20 rounded-full border border-amber-300/20 bg-black/60 px-3 py-1 text-[10px] font-semibold uppercase tracking-[0.16em] text-amber-100" }, "Blurred by your settings") : null, /* @__PURE__ */ React.createElement("div", { className: "pointer-events-none absolute inset-x-0 bottom-0 z-20 bg-gradient-to-t from-black/80 via-black/40 to-transparent p-3 backdrop-blur-[2px] opacity-100 transition-opacity duration-200 md:opacity-0 md:group-hover:opacity-100 md:group-focus-visible:opacity-100" }, /* @__PURE__ */ React.createElement("div", { className: "truncate text-sm font-semibold text-white" }, item.title), /* @__PURE__ */ React.createElement("div", { className: "mt-1 flex items-center gap-2 text-xs text-white/80" }, /* @__PURE__ */ React.createElement( "img", { - src: item.authorAvatar || AVATAR_FALLBACK$7, + src: item.authorAvatar || AVATAR_FALLBACK$1, alt: item.author, className: "w-5 h-5 rounded-full object-cover shrink-0 ring-1 ring-white/20", onError: (e) => { - e.currentTarget.src = AVATAR_FALLBACK$7; + e.currentTarget.src = AVATAR_FALLBACK$1; } } ), /* @__PURE__ */ React.createElement("span", { className: "truncate" }, item.author)))), @@ -30536,7 +34334,7 @@ function ArtworkViewer({ isOpen, onClose, artwork, presentLg, presentXl }) { /* @__PURE__ */ React.createElement("span", { className: "pointer-events-none absolute bottom-5 right-5 text-xs text-white/30 select-none" }, "ESC to close") ); } -function cx$9(...parts) { +function cx$7(...parts) { return parts.filter(Boolean).join(" "); } function formatCompactNumber$3(value) { @@ -30822,7 +34620,7 @@ function ArtworkPage({ artwork: initialArtwork, related: initialRelated, present } )); } -const __vite_glob_0_23 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ +const __vite_glob_0_24 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ __proto__: null, default: ArtworkPage }, Symbol.toStringTag, { value: "Module" })); @@ -63172,7 +66970,7 @@ if (typeof document !== "undefined") { clientExports.createRoot(mountElement).render(/* @__PURE__ */ React.createElement(CategoriesPage, { ...props })); } } -const __vite_glob_0_24 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ +const __vite_glob_0_25 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ __proto__: null, default: CategoriesPage }, Symbol.toStringTag, { value: "Module" })); @@ -63194,7 +66992,7 @@ function CollectionAnalytics() { const seo = props.seo || {}; return /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement(Se, null, /* @__PURE__ */ React.createElement("title", null, seo.title || `${collection.title || "Collection"} Analytics — Skinbase`), /* @__PURE__ */ React.createElement("meta", { name: "description", content: seo.description || "Collection analytics overview." }), seo.canonical ? /* @__PURE__ */ React.createElement("link", { rel: "canonical", href: seo.canonical }) : null, /* @__PURE__ */ React.createElement("meta", { name: "robots", content: seo.robots || "noindex,follow" })), /* @__PURE__ */ React.createElement("div", { className: "relative min-h-screen overflow-hidden pb-16" }, /* @__PURE__ */ React.createElement("div", { "aria-hidden": "true", className: "pointer-events-none absolute inset-x-0 top-0 -z-10 h-[32rem] opacity-95", style: { background: "radial-gradient(circle at 14% 14%, rgba(56,189,248,0.18), transparent 26%), radial-gradient(circle at 86% 18%, rgba(16,185,129,0.16), transparent 24%), linear-gradient(180deg, #07101d 0%, #0a1220 42%, #08111f 100%)" } }), /* @__PURE__ */ React.createElement("div", { "aria-hidden": "true", className: "pointer-events-none absolute inset-0 -z-10 opacity-[0.05]", style: { backgroundImage: "url(/gfx/noise.png)", backgroundSize: "180px" } }), /* @__PURE__ */ React.createElement("div", { className: "mx-auto max-w-7xl px-4 pt-8 md:px-6" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center gap-3 text-sm text-slate-300" }, props.dashboardUrl ? /* @__PURE__ */ React.createElement("a", { href: props.dashboardUrl, className: "inline-flex items-center gap-2 rounded-full border border-white/10 bg-white/[0.04] px-4 py-2 transition hover:bg-white/[0.07] hover:text-white" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-arrow-left fa-fw text-[11px]" }), "Dashboard") : null, props.historyUrl ? /* @__PURE__ */ React.createElement("a", { href: props.historyUrl, className: "inline-flex items-center gap-2 rounded-full border border-sky-300/20 bg-sky-400/10 px-4 py-2 font-semibold text-sky-100 transition hover:bg-sky-400/15" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-timeline fa-fw text-[11px]" }), "History") : null, collection.manage_url ? /* @__PURE__ */ React.createElement("a", { href: collection.manage_url, className: "inline-flex items-center gap-2 rounded-full border border-white/10 bg-white/[0.04] px-4 py-2 transition hover:bg-white/[0.07] hover:text-white" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-pen-to-square fa-fw text-[11px]" }), "Manage") : null), /* @__PURE__ */ React.createElement("section", { className: "mt-6 rounded-[34px] border border-white/10 bg-white/[0.04] p-6 shadow-[0_30px_90px_rgba(2,6,23,0.28)] backdrop-blur-sm md:p-8" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.22em] text-sky-200/80" }, "Performance"), /* @__PURE__ */ React.createElement("h1", { className: "mt-3 text-4xl font-semibold tracking-[-0.05em] text-white md:text-5xl" }, collection.title || "Collection analytics"), /* @__PURE__ */ React.createElement("p", { className: "mt-4 max-w-3xl text-sm leading-relaxed text-slate-300 md:text-[15px]" }, "Review activity velocity, audience response, and the artworks carrying the most discovery value over the last ", range2.days || 30, " days.")), /* @__PURE__ */ React.createElement("section", { className: "mt-8 grid gap-5 md:grid-cols-2 xl:grid-cols-3" }, /* @__PURE__ */ React.createElement(MetricCard$1, { label: "Views", value: totals.views, delta: range2.views_delta, icon: "fa-eye" }), /* @__PURE__ */ React.createElement(MetricCard$1, { label: "Likes", value: totals.likes, delta: range2.likes_delta, icon: "fa-heart" }), /* @__PURE__ */ React.createElement(MetricCard$1, { label: "Follows", value: totals.follows, delta: range2.follows_delta, icon: "fa-bell" }), /* @__PURE__ */ React.createElement(MetricCard$1, { label: "Saves", value: totals.saves, delta: range2.saves_delta, icon: "fa-bookmark" }), /* @__PURE__ */ React.createElement(MetricCard$1, { label: "Comments", value: totals.comments, delta: range2.comments_delta, icon: "fa-comments" }), /* @__PURE__ */ React.createElement(MetricCard$1, { label: "Submissions", value: totals.submissions, delta: totals.submissions, icon: "fa-inbox" })), /* @__PURE__ */ React.createElement("div", { className: "mt-8 space-y-6" }, /* @__PURE__ */ React.createElement(TimelineChart, { timeline: analytics.timeline }), /* @__PURE__ */ React.createElement("section", { className: "rounded-[32px] border border-white/10 bg-white/[0.04] p-6 backdrop-blur-sm md:p-7" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.22em] text-sky-200/80" }, "Artworks"), /* @__PURE__ */ React.createElement("h2", { className: "mt-2 text-2xl font-semibold text-white" }, "Top artwork drivers")), /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-1 text-xs font-semibold text-slate-300" }, topArtworks.length)), topArtworks.length ? /* @__PURE__ */ React.createElement("div", { className: "mt-6 grid gap-4 md:grid-cols-2 xl:grid-cols-4" }, topArtworks.map((artwork) => /* @__PURE__ */ React.createElement("div", { key: artwork.id, className: "overflow-hidden rounded-[24px] border border-white/10 bg-slate-950/40" }, /* @__PURE__ */ React.createElement("div", { className: "aspect-square bg-slate-950/60" }, artwork.thumb ? /* @__PURE__ */ React.createElement("img", { src: artwork.thumb, alt: artwork.title, className: "h-full w-full object-cover" }) : /* @__PURE__ */ React.createElement("div", { className: "flex h-full w-full items-center justify-center text-slate-500" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-image text-3xl" }))), /* @__PURE__ */ React.createElement("div", { className: "space-y-2 p-4" }, /* @__PURE__ */ React.createElement("div", { className: "truncate text-sm font-semibold text-white" }, artwork.title), /* @__PURE__ */ React.createElement("div", { className: "grid grid-cols-2 gap-2 text-xs text-slate-300" }, /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-white/[0.04] px-3 py-2" }, "Views: ", Number(artwork.views || 0).toLocaleString()), /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-white/[0.04] px-3 py-2" }, "Favs: ", Number(artwork.favourites || 0).toLocaleString()), /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-white/[0.04] px-3 py-2" }, "Shares: ", Number(artwork.shares || 0).toLocaleString()), /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-white/[0.04] px-3 py-2" }, "Rank: ", Number(artwork.ranking_score || 0).toFixed(1))))))) : /* @__PURE__ */ React.createElement("div", { className: "mt-6 rounded-[24px] border border-dashed border-white/12 bg-white/[0.03] px-6 py-12 text-sm text-slate-300" }, "Attach or publish more artworks before artwork-level ranking can be surfaced here.")))))); } -const __vite_glob_0_25 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ +const __vite_glob_0_26 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ __proto__: null, default: CollectionAnalytics }, Symbol.toStringTag, { value: "Module" })); @@ -63661,7 +67459,7 @@ function CollectionDashboard() { } ), /* @__PURE__ */ React.createElement(SearchResults, { state: searchState, endpoints, selectedIds, onToggleSelected: toggleSelected })), /* @__PURE__ */ React.createElement(WarningList, { warnings: healthWarnings, endpoints }), /* @__PURE__ */ React.createElement(CollectionStrip, { title: "Top Performing", eyebrow: "Momentum", collections: topPerforming, emptyLabel: "No collections have enough activity yet to rank here.", endpoints }), /* @__PURE__ */ React.createElement(CollectionStrip, { title: "Needs Attention", eyebrow: "Quality", collections: needsAttention, emptyLabel: "No collections currently need manual intervention.", endpoints }), /* @__PURE__ */ React.createElement(CollectionStrip, { title: "Expiring Campaigns", eyebrow: "Timing", collections: expiringCampaigns, emptyLabel: "No campaigns are approaching their sunset window.", endpoints }))))); } -const __vite_glob_0_26 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ +const __vite_glob_0_27 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ __proto__: null, default: CollectionDashboard }, Symbol.toStringTag, { value: "Module" })); @@ -63857,7 +67655,7 @@ function CollectionFeaturedIndex() { } ), /* @__PURE__ */ React.createElement("div", { "aria-hidden": "true", className: "pointer-events-none absolute inset-0 -z-10 opacity-[0.05]", style: { backgroundImage: "url(/gfx/noise.png)", backgroundSize: "180px" } }), /* @__PURE__ */ React.createElement("div", { className: "mx-auto max-w-7xl px-4 pt-8 md:px-6" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center gap-3 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("a", { href: "/", className: "inline-flex items-center gap-2 rounded-full border border-white/10 bg-white/[0.04] px-4 py-2 transition hover:bg-white/[0.07] hover:text-white" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-arrow-left fa-fw text-[11px]" }), "Back to home"), /* @__PURE__ */ React.createElement("a", { href: "/collections/featured", className: "inline-flex items-center gap-2 rounded-full border border-white/10 bg-white/[0.04] px-4 py-2 transition hover:bg-white/[0.07] hover:text-white" }, "Featured"), /* @__PURE__ */ React.createElement("a", { href: "/collections/trending", className: "inline-flex items-center gap-2 rounded-full border border-white/10 bg-white/[0.04] px-4 py-2 transition hover:bg-white/[0.07] hover:text-white" }, "Trending"), /* @__PURE__ */ React.createElement("a", { href: "/collections/community", className: "inline-flex items-center gap-2 rounded-full border border-white/10 bg-white/[0.04] px-4 py-2 transition hover:bg-white/[0.07] hover:text-white" }, "Community"), /* @__PURE__ */ React.createElement("a", { href: "/collections/editorial", className: "inline-flex items-center gap-2 rounded-full border border-white/10 bg-white/[0.04] px-4 py-2 transition hover:bg-white/[0.07] hover:text-white" }, "Editorial"), /* @__PURE__ */ React.createElement("a", { href: "/collections/seasonal", className: "inline-flex items-center gap-2 rounded-full border border-white/10 bg-white/[0.04] px-4 py-2 transition hover:bg-white/[0.07] hover:text-white" }, "Seasonal")), /* @__PURE__ */ React.createElement("section", { className: "mt-6 overflow-hidden rounded-[34px] border border-white/10 bg-white/[0.04] p-6 shadow-[0_30px_90px_rgba(2,6,23,0.28)] backdrop-blur-sm md:p-8" }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-8 xl:grid-cols-[minmax(0,1.18fr)_400px] xl:items-end" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.22em] text-sky-200/80" }, eyebrow), /* @__PURE__ */ React.createElement("h1", { className: "mt-3 text-4xl font-semibold tracking-[-0.05em] text-white md:text-5xl" }, title), campaign?.badge_label ? /* @__PURE__ */ React.createElement("div", { className: "mt-4 inline-flex items-center rounded-full border border-sky-300/20 bg-sky-400/10 px-4 py-2 text-[11px] font-semibold uppercase tracking-[0.18em] text-sky-100" }, campaign.badge_label) : program?.promotion_tier ? /* @__PURE__ */ React.createElement("div", { className: "mt-4 inline-flex items-center rounded-full border border-sky-300/20 bg-sky-400/10 px-4 py-2 text-[11px] font-semibold uppercase tracking-[0.18em] text-sky-100" }, "Promotion tier: ", program.promotion_tier) : null, /* @__PURE__ */ React.createElement("p", { className: "mt-4 max-w-3xl text-sm leading-relaxed text-slate-300 md:text-[15px]" }, description), campaign ? /* @__PURE__ */ React.createElement("div", { className: "mt-5 flex flex-wrap gap-3 text-xs text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.05] px-3 py-2" }, "Campaign key: ", campaign.key), campaign.event_label ? /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.05] px-3 py-2" }, "Event: ", campaign.event_label) : null, campaign.season_key ? /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.05] px-3 py-2" }, "Season: ", campaign.season_key) : null, Array.isArray(campaign.active_surface_keys) && campaign.active_surface_keys.length ? /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.05] px-3 py-2" }, "Surfaces: ", campaign.active_surface_keys.join(", ")) : null) : program ? /* @__PURE__ */ React.createElement("div", { className: "mt-5 flex flex-wrap gap-3 text-xs text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.05] px-3 py-2" }, "Program key: ", program.key), /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.05] px-3 py-2" }, "Collections: ", program.collections_count ?? collections.length), program.trust_tier ? /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.05] px-3 py-2" }, "Trust: ", program.trust_tier) : null, Array.isArray(program.partner_labels) && program.partner_labels.length ? /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.05] px-3 py-2" }, "Partners: ", program.partner_labels.join(", ")) : null, Array.isArray(program.sponsorship_labels) && program.sponsorship_labels.length ? /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.05] px-3 py-2" }, "Sponsors: ", program.sponsorship_labels.join(", ")) : null) : null), /* @__PURE__ */ React.createElement("div", { className: "grid gap-3 sm:grid-cols-3 xl:grid-cols-1" }, /* @__PURE__ */ React.createElement(HeroStat$2, { icon: "fa-layer-group", label: "Collections", value: collections.length.toLocaleString() }), /* @__PURE__ */ React.createElement(HeroStat$2, { icon: "fa-wand-magic-sparkles", label: "Smart", value: smartCount.toLocaleString() }), /* @__PURE__ */ React.createElement(HeroStat$2, { icon: "fa-images", label: "Artworks", value: totalArtworks.toLocaleString() })))), /* @__PURE__ */ React.createElement("section", { className: "mt-8" }, /* @__PURE__ */ React.createElement(SearchPanel, { search: search2 })), /* @__PURE__ */ React.createElement("section", { className: "mt-8" }, collections.length ? /* @__PURE__ */ React.createElement("div", { className: "grid grid-cols-1 gap-5 md:grid-cols-2 xl:grid-cols-3" }, collections.map((collection) => /* @__PURE__ */ React.createElement(CollectionCard, { key: collection.id, collection, isOwner: false, saveContext: mainSave.context, saveContextMeta: mainSave.meta }))) : /* @__PURE__ */ React.createElement(EmptyState$4, null)), communityCollections.length ? /* @__PURE__ */ React.createElement("section", { className: "mt-10" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-end justify-between gap-4" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.22em] text-sky-200/80" }, "Community"), /* @__PURE__ */ React.createElement("h2", { className: "mt-2 text-2xl font-semibold text-white" }, "Collaborative picks"))), /* @__PURE__ */ React.createElement("div", { className: "mt-5 grid grid-cols-1 gap-5 md:grid-cols-2 xl:grid-cols-3" }, communityCollections.map((collection) => /* @__PURE__ */ React.createElement(CollectionCard, { key: collection.id, collection, isOwner: false, saveContext: "community_row", saveContextMeta: { surface_label: "community collections" } })))) : null, trendingCollections.length ? /* @__PURE__ */ React.createElement("section", { className: "mt-10" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.22em] text-sky-200/80" }, "Trending"), /* @__PURE__ */ React.createElement("h2", { className: "mt-2 text-2xl font-semibold text-white" }, "Momentum right now")), /* @__PURE__ */ React.createElement("div", { className: "mt-5 grid grid-cols-1 gap-5 md:grid-cols-2 xl:grid-cols-3" }, trendingCollections.map((collection) => /* @__PURE__ */ React.createElement(CollectionCard, { key: collection.id, collection, isOwner: false, saveContext: "trending_row", saveContextMeta: { surface_label: "trending collections" } })))) : null, editorialCollections.length ? /* @__PURE__ */ React.createElement("section", { className: "mt-10" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.22em] text-sky-200/80" }, "Editorial"), /* @__PURE__ */ React.createElement("h2", { className: "mt-2 text-2xl font-semibold text-white" }, "Staff and campaign collections")), /* @__PURE__ */ React.createElement("div", { className: "mt-5 grid grid-cols-1 gap-5 md:grid-cols-2 xl:grid-cols-3" }, editorialCollections.map((collection) => /* @__PURE__ */ React.createElement(CollectionCard, { key: collection.id, collection, isOwner: false, saveContext: "editorial_row", saveContextMeta: { surface_label: "editorial collections" } })))) : null, seasonalCollections.length ? /* @__PURE__ */ React.createElement("section", { className: "mt-10" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.22em] text-sky-200/80" }, "Seasonal"), /* @__PURE__ */ React.createElement("h2", { className: "mt-2 text-2xl font-semibold text-white" }, "Campaign and event spotlights")), /* @__PURE__ */ React.createElement("div", { className: "mt-5 grid grid-cols-1 gap-5 md:grid-cols-2 xl:grid-cols-3" }, seasonalCollections.map((collection) => /* @__PURE__ */ React.createElement(CollectionCard, { key: collection.id, collection, isOwner: false, saveContext: "seasonal_row", saveContextMeta: { surface_label: "seasonal collections" } })))) : null, recentCollections.length ? /* @__PURE__ */ React.createElement("section", { className: "mt-10 pb-8" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.22em] text-sky-200/80" }, "Recent"), /* @__PURE__ */ React.createElement("h2", { className: "mt-2 text-2xl font-semibold text-white" }, "Freshly published collections")), /* @__PURE__ */ React.createElement("div", { className: "mt-5 grid grid-cols-1 gap-5 md:grid-cols-2 xl:grid-cols-3" }, recentCollections.map((collection) => /* @__PURE__ */ React.createElement(CollectionCard, { key: collection.id, collection, isOwner: false, saveContext: "recent_row", saveContextMeta: { surface_label: "recent collections" } })))) : null))); } -const __vite_glob_0_27 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ +const __vite_glob_0_28 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ __proto__: null, default: CollectionFeaturedIndex }, Symbol.toStringTag, { value: "Module" })); @@ -63928,7 +67726,7 @@ function CollectionHistory() { busyId === entry.id ? "Restoring…" : "Restore" ) : null)), /* @__PURE__ */ React.createElement("div", { className: "mt-5 grid gap-4 lg:grid-cols-2" }, /* @__PURE__ */ React.createElement(FieldChanges, { label: "Before", value: entry.before }), /* @__PURE__ */ React.createElement(FieldChanges, { label: "After", value: entry.after })))) : /* @__PURE__ */ React.createElement("div", { className: "rounded-[30px] border border-dashed border-white/12 bg-white/[0.03] px-6 py-14 text-sm text-slate-300" }, "No audit entries have been recorded for this collection yet.")), Number(meta.last_page || 1) > 1 ? /* @__PURE__ */ React.createElement("div", { className: "mt-8 flex flex-wrap items-center justify-between gap-3 rounded-[28px] border border-white/10 bg-white/[0.04] px-5 py-4 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("div", null, "Page ", meta.current_page || 1, " of ", meta.last_page || 1), /* @__PURE__ */ React.createElement("div", { className: "flex gap-2" }, (meta.current_page || 1) > 1 ? /* @__PURE__ */ React.createElement("a", { href: buildPageUrl((meta.current_page || 1) - 1), className: "inline-flex items-center gap-2 rounded-full border border-white/10 bg-white/[0.04] px-4 py-2 font-semibold text-white transition hover:bg-white/[0.07]" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-arrow-left fa-fw text-[10px]" }), "Previous") : null, (meta.current_page || 1) < (meta.last_page || 1) ? /* @__PURE__ */ React.createElement("a", { href: buildPageUrl((meta.current_page || 1) + 1), className: "inline-flex items-center gap-2 rounded-full border border-white/10 bg-white/[0.04] px-4 py-2 font-semibold text-white transition hover:bg-white/[0.07]" }, "Next", /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-arrow-right fa-fw text-[10px]" })) : null)) : null))); } -const __vite_glob_0_28 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ +const __vite_glob_0_29 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ __proto__: null, default: CollectionHistory }, Symbol.toStringTag, { value: "Module" })); @@ -65888,7 +69686,7 @@ function CollectionManage() { } )), /* @__PURE__ */ React.createElement("div", { className: "mt-4 space-y-3" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between gap-3 rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3 text-sm text-white" }, /* @__PURE__ */ React.createElement("span", null, "Allow comments"), /* @__PURE__ */ React.createElement(Checkbox, { checked: form.allow_comments, onChange: (event) => handleModerationToggle("allow_comments", event.target.checked) })), /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between gap-3 rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3 text-sm text-white" }, /* @__PURE__ */ React.createElement("span", null, "Allow submissions"), /* @__PURE__ */ React.createElement(Checkbox, { checked: form.allow_submissions, onChange: (event) => handleModerationToggle("allow_submissions", event.target.checked) })), /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between gap-3 rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3 text-sm text-white" }, /* @__PURE__ */ React.createElement("span", null, "Allow saves"), /* @__PURE__ */ React.createElement(Checkbox, { checked: form.allow_saves, onChange: (event) => handleModerationToggle("allow_saves", event.target.checked) })))), /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-white/[0.04] p-5" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-400" }, "Rapid actions"), /* @__PURE__ */ React.createElement("div", { className: "mt-4 flex flex-wrap gap-3" }, /* @__PURE__ */ React.createElement("button", { type: "button", onClick: handleAdminUnfeature, className: "rounded-2xl border border-amber-300/25 bg-amber-300/10 px-4 py-3 text-sm font-semibold text-amber-100 transition hover:bg-amber-300/15" }, "Remove featured placement"), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => handleModerationStatusChange("under_review"), className: "rounded-2xl border border-white/12 bg-white/[0.05] px-4 py-3 text-sm font-semibold text-white transition hover:bg-white/[0.08]" }, "Send to review"), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => handleModerationStatusChange("restricted"), className: "rounded-2xl border border-rose-400/20 bg-rose-400/10 px-4 py-3 text-sm font-semibold text-rose-100 transition hover:bg-rose-400/15" }, "Restrict public access")), /* @__PURE__ */ React.createElement("div", { className: "mt-5 rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-4 text-sm leading-relaxed text-slate-300" }, "Current state: ", /* @__PURE__ */ React.createElement("span", { className: "font-semibold text-white" }, (collectionState?.moderation_status || "active").replace("_", " ")))))) : null))); } -const __vite_glob_0_29 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ +const __vite_glob_0_30 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ __proto__: null, default: CollectionManage }, Symbol.toStringTag, { value: "Module" })); @@ -65905,14 +69703,14 @@ function CollectionSeriesShow() { const stats = props.stats || {}; return /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement(SeoHead, { seo, title: seo.title || `${title} — Skinbase`, description: seo.description || description }), /* @__PURE__ */ React.createElement("div", { className: "relative min-h-screen overflow-hidden pb-16" }, /* @__PURE__ */ React.createElement("div", { "aria-hidden": "true", className: "pointer-events-none absolute inset-x-0 top-0 -z-10 h-[36rem] opacity-95", style: { background: "radial-gradient(circle at 10% 15%, rgba(59,130,246,0.18), transparent 28%), radial-gradient(circle at 84% 18%, rgba(34,197,94,0.16), transparent 24%), linear-gradient(180deg, #07101d 0%, #0a1220 42%, #08111f 100%)" } }), /* @__PURE__ */ React.createElement("div", { "aria-hidden": "true", className: "pointer-events-none absolute inset-0 -z-10 opacity-[0.05]", style: { backgroundImage: "url(/gfx/noise.png)", backgroundSize: "180px" } }), /* @__PURE__ */ React.createElement("div", { className: "mx-auto max-w-7xl px-4 pt-8 md:px-6" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center gap-3 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("a", { href: "/collections/featured", className: "inline-flex items-center gap-2 rounded-full border border-white/10 bg-white/[0.04] px-4 py-2 transition hover:bg-white/[0.07] hover:text-white" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-arrow-left fa-fw text-[11px]" }), "Back to collections"), leadCollection?.url ? /* @__PURE__ */ React.createElement("a", { href: leadCollection.url, className: "inline-flex items-center gap-2 rounded-full border border-white/10 bg-white/[0.04] px-4 py-2 transition hover:bg-white/[0.07] hover:text-white" }, "Lead collection") : null), /* @__PURE__ */ React.createElement("section", { className: "mt-6 overflow-hidden rounded-[34px] border border-white/10 bg-white/[0.04] p-6 shadow-[0_30px_90px_rgba(2,6,23,0.28)] backdrop-blur-sm md:p-8" }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-8 xl:grid-cols-[minmax(0,1.15fr)_400px] xl:items-end" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.22em] text-sky-200/80" }, "Series"), /* @__PURE__ */ React.createElement("h1", { className: "mt-3 text-4xl font-semibold tracking-[-0.05em] text-white md:text-5xl" }, title), /* @__PURE__ */ React.createElement("p", { className: "mt-4 max-w-3xl text-sm leading-relaxed text-slate-300 md:text-[15px]" }, description), props.seriesKey ? /* @__PURE__ */ React.createElement("div", { className: "mt-5 inline-flex rounded-full border border-white/10 bg-white/[0.05] px-4 py-2 text-xs font-semibold uppercase tracking-[0.18em] text-slate-300" }, props.seriesKey) : null), /* @__PURE__ */ React.createElement("div", { className: "grid gap-3 sm:grid-cols-3 xl:grid-cols-1" }, /* @__PURE__ */ React.createElement(StatCard$6, { icon: "fa-layer-group", label: "Collections", value: Number(stats.collections || collections.length).toLocaleString() }), /* @__PURE__ */ React.createElement(StatCard$6, { icon: "fa-user-group", label: "Creators", value: Number(stats.owners || 0).toLocaleString() }), /* @__PURE__ */ React.createElement(StatCard$6, { icon: "fa-images", label: "Artworks", value: Number(stats.artworks || 0).toLocaleString() })))), leadCollection ? /* @__PURE__ */ React.createElement("section", { className: "mt-8 rounded-[32px] border border-white/10 bg-white/[0.04] p-6 backdrop-blur-sm md:p-7" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-end justify-between gap-4" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.22em] text-sky-200/80" }, "Lead Entry"), /* @__PURE__ */ React.createElement("h2", { className: "mt-2 text-2xl font-semibold text-white" }, "Start with the opening collection")), stats.latest_activity_at ? /* @__PURE__ */ React.createElement("div", { className: "text-xs uppercase tracking-[0.16em] text-slate-400" }, "Latest activity ", new Date(stats.latest_activity_at).toLocaleDateString()) : null), /* @__PURE__ */ React.createElement("div", { className: "mt-5 max-w-xl" }, /* @__PURE__ */ React.createElement(CollectionCard, { collection: leadCollection, isOwner: false }))) : null, /* @__PURE__ */ React.createElement("section", { className: "mt-8 pb-8" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-end justify-between gap-4" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.22em] text-sky-200/80" }, "Sequence"), /* @__PURE__ */ React.createElement("h2", { className: "mt-2 text-2xl font-semibold text-white" }, "Public collections in order"))), /* @__PURE__ */ React.createElement("div", { className: "mt-5 grid grid-cols-1 gap-5 md:grid-cols-2 xl:grid-cols-3" }, collections.map((collection) => /* @__PURE__ */ React.createElement(CollectionCard, { key: collection.id, collection, isOwner: false }))))))); } -const __vite_glob_0_30 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ +const __vite_glob_0_31 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ __proto__: null, default: CollectionSeriesShow }, Symbol.toStringTag, { value: "Module" })); const IMAGE_FALLBACK = "https://files.skinbase.org/default/missing_md.webp"; -const AVATAR_FALLBACK$6 = "https://files.skinbase.org/default/avatar_default.webp"; +const AVATAR_FALLBACK = "https://files.skinbase.org/default/avatar_default.webp"; const relativeTimeFormatter = new Intl.RelativeTimeFormat("en", { numeric: "auto" }); -function cx$8(...parts) { +function cx$6(...parts) { return parts.filter(Boolean).join(" "); } function formatRelativeTime(value) { @@ -66112,7 +69910,7 @@ function BadgePill({ className = "", iconClass = "", children }) { return /* @__PURE__ */ React.createElement( "span", { - className: cx$8( + className: cx$6( "inline-flex items-center gap-1.5 rounded-full px-2.5 py-1 text-[10px] font-semibold uppercase tracking-[0.14em] backdrop-blur-sm ring-1 shadow-[0_8px_24px_rgba(2,6,23,0.28)]", className ) @@ -66219,7 +70017,7 @@ function ArtworkCard$1({ const image2 = item.image || item.thumb || item.thumb_url || item.thumbnail_url || IMAGE_FALLBACK; const responsiveImageSrcSet = imageSrcSet || item.thumb_srcset || item.thumbnail_srcset || void 0; const responsiveImageSizes = imageSizes || (variant === "embed" ? "80px" : compact ? "(max-width: 640px) 50vw, (max-width: 1024px) 33vw, 280px" : "(max-width: 640px) 50vw, (max-width: 1024px) 33vw, (max-width: 1536px) 25vw, 320px"); - const avatar = (isGroupPublisher ? publisher?.avatar_url : null) || rawAuthor?.avatar_url || rawAuthor?.avatar || item.avatar || item.author_avatar || item.avatar_url || AVATAR_FALLBACK$6; + const avatar = (isGroupPublisher ? publisher?.avatar_url : null) || rawAuthor?.avatar_url || rawAuthor?.avatar || item.avatar || item.author_avatar || item.avatar_url || AVATAR_FALLBACK; const likes = item.likes ?? item.favourites ?? 0; item.views ?? item.views_count ?? item.view_count ?? 0; item.downloads ?? item.downloads_count ?? item.download_count ?? 0; @@ -66465,7 +70263,7 @@ function ArtworkCard$1({ return /* @__PURE__ */ React.createElement( "article", { - className: cx$8("group overflow-hidden rounded-xl border border-white/[0.08] bg-black/30 transition-colors hover:border-sky-500/30", articleClassName, className), + className: cx$6("group overflow-hidden rounded-xl border border-white/[0.08] bg-black/30 transition-colors hover:border-sky-500/30", articleClassName, className), style: articleStyle, ...articleData }, @@ -66486,7 +70284,7 @@ function ArtworkCard$1({ alt: title, loading, decoding, - className: cx$8("h-full w-full object-cover transition-transform duration-300 group-hover:scale-105", shouldBlurMature ? "scale-[1.02] blur-xl" : ""), + className: cx$6("h-full w-full object-cover transition-transform duration-300 group-hover:scale-105", shouldBlurMature ? "scale-[1.02] blur-xl" : ""), onError: (event) => { swapImageToFallbackOnce(event, IMAGE_FALLBACK); } @@ -66499,11 +70297,11 @@ function ArtworkCard$1({ return /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement( "article", { - className: cx$8("group relative", articleClassName, className), + className: cx$6("group relative", articleClassName, className), style: articleStyle, ...articleData }, - /* @__PURE__ */ React.createElement("div", { className: cx$8("relative overflow-hidden rounded-[1.6rem] border border-white/8 bg-slate-950/80 shadow-[0_18px_60px_rgba(2,6,23,0.45)] transition duration-300 ease-out group-hover:-translate-y-1 group-hover:scale-[1.02] group-hover:border-white/14 group-hover:shadow-[0_24px_80px_rgba(8,47,73,0.5)] group-focus-within:-translate-y-1 group-focus-within:scale-[1.02] group-focus-within:border-sky-200/40", frameClassName) }, /* @__PURE__ */ React.createElement( + /* @__PURE__ */ React.createElement("div", { className: cx$6("relative overflow-hidden rounded-[1.6rem] border border-white/8 bg-slate-950/80 shadow-[0_18px_60px_rgba(2,6,23,0.45)] transition duration-300 ease-out group-hover:-translate-y-1 group-hover:scale-[1.02] group-hover:border-white/14 group-hover:shadow-[0_24px_80px_rgba(8,47,73,0.5)] group-focus-within:-translate-y-1 group-focus-within:scale-[1.02] group-focus-within:border-sky-200/40", frameClassName) }, /* @__PURE__ */ React.createElement( "a", { href, @@ -66512,7 +70310,7 @@ function ArtworkCard$1({ className: "absolute inset-0 z-10 rounded-[inherit] cursor-pointer focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-sky-300/80" }, /* @__PURE__ */ React.createElement("span", { className: "sr-only" }, cardLabel) - ), /* @__PURE__ */ React.createElement("div", { className: cx$8("relative overflow-hidden bg-slate-900", aspectClass, mediaClassName), style: mediaStyle }, /* @__PURE__ */ React.createElement("div", { className: "absolute inset-0 bg-[radial-gradient(circle_at_top,_rgba(148,163,184,0.28),_transparent_52%),linear-gradient(180deg,rgba(15,23,42,0.08),rgba(15,23,42,0.42))]" }), /* @__PURE__ */ React.createElement( + ), /* @__PURE__ */ React.createElement("div", { className: cx$6("relative overflow-hidden bg-slate-900", aspectClass, mediaClassName), style: mediaStyle }, /* @__PURE__ */ React.createElement("div", { className: "absolute inset-0 bg-[radial-gradient(circle_at_top,_rgba(148,163,184,0.28),_transparent_52%),linear-gradient(180deg,rgba(15,23,42,0.08),rgba(15,23,42,0.42))]" }), /* @__PURE__ */ React.createElement( "img", { src: image2, @@ -66524,15 +70322,15 @@ function ArtworkCard$1({ loading, decoding, fetchPriority: fetchPriority || void 0, - className: cx$8("h-full w-full object-cover transition duration-500 group-hover:scale-110 group-focus-within:scale-110", shouldBlurMature ? "scale-[1.02] blur-xl" : "", imageClassName), + className: cx$6("h-full w-full object-cover transition duration-500 group-hover:scale-110 group-focus-within:scale-110", shouldBlurMature ? "scale-[1.02] blur-xl" : "", imageClassName), onError: (event) => { swapImageToFallbackOnce(event, IMAGE_FALLBACK, { clearResponsive: true }); } } - ), /* @__PURE__ */ React.createElement("div", { className: "pointer-events-none absolute inset-0 bg-gradient-to-t from-black/85 via-black/38 to-transparent opacity-90 transition duration-300 md:opacity-45 md:group-hover:opacity-100 md:group-focus-within:opacity-100" }), resolvedMetricBadge?.label || relativePublishedAt ? /* @__PURE__ */ React.createElement("div", { className: "pointer-events-none absolute inset-x-0 top-0 z-20 flex items-start justify-between gap-3 p-3" }, /* @__PURE__ */ React.createElement("div", null, resolvedMetricBadge?.label ? /* @__PURE__ */ React.createElement(BadgePill, { className: resolvedMetricBadge.className || "bg-emerald-500/14 text-emerald-200 ring-emerald-400/30", iconClass: resolvedMetricBadge.iconClass }, resolvedMetricBadge.label) : null, isMatureArtwork ? /* @__PURE__ */ React.createElement(BadgePill, { className: "mt-2 bg-amber-500/16 text-amber-100 ring-amber-300/30", iconClass: "fa-solid fa-triangle-exclamation text-[10px]" }, "Mature content") : null), relativePublishedAt ? /* @__PURE__ */ React.createElement(BadgePill, { className: "bg-black/45 text-white/75 ring-white/12", iconClass: "fa-regular fa-clock text-[10px]" }, relativePublishedAt) : null) : null, showActions && /* @__PURE__ */ React.createElement("div", { className: cx$8( + ), /* @__PURE__ */ React.createElement("div", { className: "pointer-events-none absolute inset-0 bg-gradient-to-t from-black/85 via-black/38 to-transparent opacity-90 transition duration-300 md:opacity-45 md:group-hover:opacity-100 md:group-focus-within:opacity-100" }), resolvedMetricBadge?.label || relativePublishedAt ? /* @__PURE__ */ React.createElement("div", { className: "pointer-events-none absolute inset-x-0 top-0 z-20 flex items-start justify-between gap-3 p-3" }, /* @__PURE__ */ React.createElement("div", null, resolvedMetricBadge?.label ? /* @__PURE__ */ React.createElement(BadgePill, { className: resolvedMetricBadge.className || "bg-emerald-500/14 text-emerald-200 ring-emerald-400/30", iconClass: resolvedMetricBadge.iconClass }, resolvedMetricBadge.label) : null, isMatureArtwork ? /* @__PURE__ */ React.createElement(BadgePill, { className: "mt-2 bg-amber-500/16 text-amber-100 ring-amber-300/30", iconClass: "fa-solid fa-triangle-exclamation text-[10px]" }, "Mature content") : null), relativePublishedAt ? /* @__PURE__ */ React.createElement(BadgePill, { className: "bg-black/45 text-white/75 ring-white/12", iconClass: "fa-regular fa-clock text-[10px]" }, relativePublishedAt) : null) : null, showActions && /* @__PURE__ */ React.createElement("div", { className: cx$6( "absolute right-3 z-20 flex max-w-[14rem] flex-wrap justify-end translate-y-2 gap-2 opacity-100 transition duration-200 md:opacity-0 md:group-hover:translate-y-0 md:group-hover:opacity-100 md:group-focus-within:translate-y-0 md:group-focus-within:opacity-100", relativePublishedAt ? "top-12" : "top-3" - ) }, /* @__PURE__ */ React.createElement(ActionButton, { label: liked ? "Unlike artwork" : "Like artwork", onClick: handleLike }, /* @__PURE__ */ React.createElement(HeartIcon, { className: cx$8("h-4 w-4 transition-transform duration-200", liked ? "fill-current text-rose-300" : "", likeBusy ? "scale-90" : "") })), /* @__PURE__ */ React.createElement(ActionLink$1, { href: downloadHref, label: downloadBusy ? "Downloading artwork" : "Download artwork", onClick: handleDownload }, /* @__PURE__ */ React.createElement(DownloadIcon, { className: cx$8("h-4 w-4", downloadBusy ? "animate-pulse text-emerald-300" : "") })), /* @__PURE__ */ React.createElement(ActionLink$1, { href, label: "View artwork" }, /* @__PURE__ */ React.createElement(ViewIcon, { className: "h-4 w-4" })), canAddToCollection ? /* @__PURE__ */ React.createElement(ActionButton, { label: "Add artwork to collection", onClick: handleOpenCollectionPicker }, /* @__PURE__ */ React.createElement(CollectionIcon, { className: "h-4 w-4" })) : null, canHideRecommendation ? /* @__PURE__ */ React.createElement(ActionButton, { label: hideBusy ? "Hiding artwork" : "Hide artwork", onClick: handleHideArtwork }, /* @__PURE__ */ React.createElement(HideIcon, { className: cx$8("h-4 w-4", hideBusy ? "animate-pulse text-amber-200" : "text-white/90") })) : null), /* @__PURE__ */ React.createElement("div", { className: "pointer-events-none absolute inset-x-0 bottom-0 z-20 bg-gradient-to-t from-black/80 via-black/40 to-transparent p-3 backdrop-blur-[2px] opacity-100 transition-opacity duration-200 md:opacity-0 md:group-hover:opacity-100 md:group-focus-within:opacity-100" }, shouldBlurMature ? /* @__PURE__ */ React.createElement("div", { className: "mb-2 inline-flex rounded-full border border-amber-300/20 bg-black/55 px-3 py-1 text-[10px] font-semibold uppercase tracking-[0.16em] text-amber-100" }, "Blurred by your content settings") : null, /* @__PURE__ */ React.createElement("h3", { className: cx$8("truncate font-semibold text-white", titleClass) }, title), showAuthor ? /* @__PURE__ */ React.createElement("div", { className: "mt-1 flex items-start justify-between gap-3 text-xs text-white/80" }, /* @__PURE__ */ React.createElement("span", { className: "flex min-w-0 items-start gap-3" }, /* @__PURE__ */ React.createElement( + ) }, /* @__PURE__ */ React.createElement(ActionButton, { label: liked ? "Unlike artwork" : "Like artwork", onClick: handleLike }, /* @__PURE__ */ React.createElement(HeartIcon, { className: cx$6("h-4 w-4 transition-transform duration-200", liked ? "fill-current text-rose-300" : "", likeBusy ? "scale-90" : "") })), /* @__PURE__ */ React.createElement(ActionLink$1, { href: downloadHref, label: downloadBusy ? "Downloading artwork" : "Download artwork", onClick: handleDownload }, /* @__PURE__ */ React.createElement(DownloadIcon, { className: cx$6("h-4 w-4", downloadBusy ? "animate-pulse text-emerald-300" : "") })), /* @__PURE__ */ React.createElement(ActionLink$1, { href, label: "View artwork" }, /* @__PURE__ */ React.createElement(ViewIcon, { className: "h-4 w-4" })), canAddToCollection ? /* @__PURE__ */ React.createElement(ActionButton, { label: "Add artwork to collection", onClick: handleOpenCollectionPicker }, /* @__PURE__ */ React.createElement(CollectionIcon, { className: "h-4 w-4" })) : null, canHideRecommendation ? /* @__PURE__ */ React.createElement(ActionButton, { label: hideBusy ? "Hiding artwork" : "Hide artwork", onClick: handleHideArtwork }, /* @__PURE__ */ React.createElement(HideIcon, { className: cx$6("h-4 w-4", hideBusy ? "animate-pulse text-amber-200" : "text-white/90") })) : null), /* @__PURE__ */ React.createElement("div", { className: "pointer-events-none absolute inset-x-0 bottom-0 z-20 bg-gradient-to-t from-black/80 via-black/40 to-transparent p-3 backdrop-blur-[2px] opacity-100 transition-opacity duration-200 md:opacity-0 md:group-hover:opacity-100 md:group-focus-within:opacity-100" }, shouldBlurMature ? /* @__PURE__ */ React.createElement("div", { className: "mb-2 inline-flex rounded-full border border-amber-300/20 bg-black/55 px-3 py-1 text-[10px] font-semibold uppercase tracking-[0.16em] text-amber-100" }, "Blurred by your content settings") : null, /* @__PURE__ */ React.createElement("h3", { className: cx$6("truncate font-semibold text-white", titleClass) }, title), showAuthor ? /* @__PURE__ */ React.createElement("div", { className: "mt-1 flex items-start justify-between gap-3 text-xs text-white/80" }, /* @__PURE__ */ React.createElement("span", { className: "flex min-w-0 items-start gap-3" }, /* @__PURE__ */ React.createElement( "img", { src: avatar, @@ -66541,7 +70339,7 @@ function ArtworkCard$1({ decoding: "async", className: "h-9 w-9 shrink-0 rounded-full object-cover", onError: (event) => { - swapImageToFallbackOnce(event, AVATAR_FALLBACK$6); + swapImageToFallbackOnce(event, AVATAR_FALLBACK); } } ), /* @__PURE__ */ React.createElement("span", { className: "min-w-0 flex-1" }, /* @__PURE__ */ React.createElement("span", { className: "flex items-center gap-2" }, /* @__PURE__ */ React.createElement("span", { className: "block min-w-0 truncate text-sm font-medium text-white/90" }, author, username ? /* @__PURE__ */ React.createElement("span", { className: "text-[11px] text-white/60" }, " @", username) : null), authorLevel > 0 ? /* @__PURE__ */ React.createElement(LevelBadge, { level: authorLevel, rank: authorRank, compact: true, className: "shrink-0" }) : null), showStats && metadataLine && /* @__PURE__ */ React.createElement("span", { className: "mt-0.5 block truncate text-[11px] text-white/70" }, metadataLine)))) : showStats && metadataLine ? /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-[11px] text-white/70" }, metadataLine) : null, canDislikePrimaryTag ? /* @__PURE__ */ React.createElement("div", { className: "pointer-events-auto mt-2" }, /* @__PURE__ */ React.createElement( @@ -66551,7 +70349,7 @@ function ArtworkCard$1({ onClick: handleDislikePrimaryTag, className: "inline-flex items-center gap-1.5 rounded-full border border-white/12 bg-black/35 px-2.5 py-1 text-[10px] font-semibold uppercase tracking-[0.14em] text-white/80 transition hover:border-amber-200/40 hover:bg-black/55 hover:text-white focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-sky-300/80" }, - /* @__PURE__ */ React.createElement(TagIcon, { className: cx$8("h-3.5 w-3.5", dislikeBusy ? "animate-pulse text-amber-200" : "") }), + /* @__PURE__ */ React.createElement(TagIcon, { className: cx$6("h-3.5 w-3.5", dislikeBusy ? "animate-pulse text-amber-200" : "") }), dislikeBusy ? "Updating" : `Less of #${primaryTag?.slug || primaryTag?.name}` )) : null))) ), /* @__PURE__ */ React.createElement( @@ -66618,7 +70416,7 @@ async function revokeDismissSignal(entry) { } return response.json().catch(() => null); } -function cx$7(...parts) { +function cx$5(...parts) { return parts.filter(Boolean).join(" "); } function getArtworkKey(item, index2) { @@ -66719,7 +70517,7 @@ function ArtworkGallery({ setDismissedEntries((current) => current.filter((entry2) => entry2.item?.id !== dismissNotice.itemId)); setDismissNotice(null); } - return /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement("div", { className: cx$7(baseClassName, className), ...containerProps }, visibleArtworkItems.map((item, index2) => { + return /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement("div", { className: cx$5(baseClassName, className), ...containerProps }, visibleArtworkItems.map((item, index2) => { const cardProps = resolveCardProps?.(item, index2) || {}; const { className: resolvedClassName = "", ...restCardProps } = cardProps; return /* @__PURE__ */ React.createElement( @@ -66730,7 +70528,7 @@ function ArtworkGallery({ compact, showStats, showAuthor, - className: cx$7(cardClassName, resolvedClassName), + className: cx$5(cardClassName, resolvedClassName), onDismissed: handleDismissed, ...restCardProps } @@ -66755,7 +70553,7 @@ function ListIcon() { function QuoteIcon() { return /* @__PURE__ */ React.createElement("svg", { viewBox: "0 0 24 24", fill: "currentColor", className: "h-4 w-4" }, /* @__PURE__ */ React.createElement("path", { d: "M4.583 17.321C3.553 16.227 3 15 3 13.011c0-3.5 2.457-6.637 6.03-8.188l.893 1.378c-3.335 1.804-3.987 4.145-4.247 5.621.537-.278 1.24-.375 1.929-.311C9.591 11.68 11 13.176 11 15c0 1.933-1.567 3.5-3.5 3.5-1.073 0-2.099-.456-2.917-1.179zM15.583 17.321C14.553 16.227 14 15 14 13.011c0-3.5 2.457-6.637 6.03-8.188l.893 1.378c-3.335 1.804-3.987 4.145-4.247 5.621.537-.278 1.24-.375 1.929-.311C20.591 11.68 22 13.176 22 15c0 1.933-1.567 3.5-3.5 3.5-1.073 0-2.099-.456-2.917-1.179z" })); } -function ToolbarBtn$1({ title, onClick, children }) { +function ToolbarBtn({ title, onClick, children }) { return /* @__PURE__ */ React.createElement( "button", { @@ -66916,7 +70714,7 @@ function CommentForm({ placeholder = "Write a comment…", submitLabel = "Post", ].join(" ") }, content2.length > 0 && `${content2.length.toLocaleString()}/10,000` - ), /* @__PURE__ */ React.createElement(EmojiPickerButton, { onEmojiSelect: insertAtCursor, disabled: busy }))), tab2 === "write" && /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-0.5 border-b border-white/[0.04] px-3 py-1" }, /* @__PURE__ */ React.createElement(ToolbarBtn$1, { title: "Bold (Ctrl+B)", onClick: () => wrapSelection("**", "**") }, /* @__PURE__ */ React.createElement(BoldIcon, null)), /* @__PURE__ */ React.createElement(ToolbarBtn$1, { title: "Italic (Ctrl+I)", onClick: () => wrapSelection("*", "*") }, /* @__PURE__ */ React.createElement(ItalicIcon, null)), /* @__PURE__ */ React.createElement(ToolbarBtn$1, { title: "Inline code (Ctrl+E)", onClick: () => wrapSelection("`", "`") }, /* @__PURE__ */ React.createElement(CodeIcon, null)), /* @__PURE__ */ React.createElement(ToolbarBtn$1, { title: "Link (Ctrl+K)", onClick: insertLink }, /* @__PURE__ */ React.createElement(LinkIcon, null)), /* @__PURE__ */ React.createElement("div", { className: "mx-1 h-4 w-px bg-white/[0.08]" }), /* @__PURE__ */ React.createElement(ToolbarBtn$1, { title: "Bulleted list", onClick: () => prefixLines("- ") }, /* @__PURE__ */ React.createElement(ListIcon, null)), /* @__PURE__ */ React.createElement(ToolbarBtn$1, { title: "Quote", onClick: () => prefixLines("> ") }, /* @__PURE__ */ React.createElement(QuoteIcon, null))), tab2 === "write" && /* @__PURE__ */ React.createElement( + ), /* @__PURE__ */ React.createElement(EmojiPickerButton, { onEmojiSelect: insertAtCursor, disabled: busy }))), tab2 === "write" && /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-0.5 border-b border-white/[0.04] px-3 py-1" }, /* @__PURE__ */ React.createElement(ToolbarBtn, { title: "Bold (Ctrl+B)", onClick: () => wrapSelection("**", "**") }, /* @__PURE__ */ React.createElement(BoldIcon, null)), /* @__PURE__ */ React.createElement(ToolbarBtn, { title: "Italic (Ctrl+I)", onClick: () => wrapSelection("*", "*") }, /* @__PURE__ */ React.createElement(ItalicIcon, null)), /* @__PURE__ */ React.createElement(ToolbarBtn, { title: "Inline code (Ctrl+E)", onClick: () => wrapSelection("`", "`") }, /* @__PURE__ */ React.createElement(CodeIcon, null)), /* @__PURE__ */ React.createElement(ToolbarBtn, { title: "Link (Ctrl+K)", onClick: insertLink }, /* @__PURE__ */ React.createElement(LinkIcon, null)), /* @__PURE__ */ React.createElement("div", { className: "mx-1 h-4 w-px bg-white/[0.08]" }), /* @__PURE__ */ React.createElement(ToolbarBtn, { title: "Bulleted list", onClick: () => prefixLines("- ") }, /* @__PURE__ */ React.createElement(ListIcon, null)), /* @__PURE__ */ React.createElement(ToolbarBtn, { title: "Quote", onClick: () => prefixLines("> ") }, /* @__PURE__ */ React.createElement(QuoteIcon, null))), tab2 === "write" && /* @__PURE__ */ React.createElement( "textarea", { ref: textareaRef, @@ -67615,7 +71413,7 @@ function CollectionShow() { const renderedSidebarModules = enabledModules.filter((module) => module.slot === "sidebar").map(renderModule).filter(Boolean); return /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement(SeoHead, { seo, title: metaTitle, description: metaDescription, jsonLd: collectionSchema }), /* @__PURE__ */ React.createElement("div", { className: "relative min-h-screen overflow-hidden pb-16" }, /* @__PURE__ */ React.createElement("div", { "aria-hidden": "true", className: "pointer-events-none absolute inset-x-0 top-0 -z-10 h-[36rem] opacity-95", style: { background: "radial-gradient(circle at top left, rgba(56,189,248,0.18), transparent 32%), radial-gradient(circle at 82% 10%, rgba(249,115,22,0.18), transparent 26%), linear-gradient(180deg, #07101d 0%, #0a1220 42%, #08111f 100%)" } }), /* @__PURE__ */ React.createElement("div", { "aria-hidden": "true", className: "pointer-events-none absolute inset-0 -z-10 opacity-[0.05]", style: { backgroundImage: "url(/gfx/noise.png)", backgroundSize: "180px" } }), /* @__PURE__ */ React.createElement("div", { className: "mx-auto max-w-7xl px-4 pt-8 md:px-6" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center gap-3 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("a", { href: profileCollectionsUrl, className: "inline-flex items-center gap-2 rounded-full border border-white/10 bg-white/[0.04] px-4 py-2 transition hover:bg-white/[0.07] hover:text-white" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-arrow-left fa-fw text-[11px]" }), "Back to collections"), isOwner && manageUrl ? /* @__PURE__ */ React.createElement("a", { href: manageUrl, className: "inline-flex items-center gap-2 rounded-full border border-sky-300/20 bg-sky-400/10 px-4 py-2 font-semibold text-sky-100 transition hover:bg-sky-400/15" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-grip fa-fw text-[11px]" }), "Manage artworks") : null, isOwner && editUrl ? /* @__PURE__ */ React.createElement("a", { href: editUrl, className: "inline-flex items-center gap-2 rounded-full border border-white/10 bg-white/[0.04] px-4 py-2 transition hover:bg-white/[0.07] hover:text-white" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-pen-to-square fa-fw text-[11px]" }), "Edit details") : null, isOwner && analyticsUrl ? /* @__PURE__ */ React.createElement("a", { href: analyticsUrl, className: "inline-flex items-center gap-2 rounded-full border border-white/10 bg-white/[0.04] px-4 py-2 transition hover:bg-white/[0.07] hover:text-white" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-chart-column fa-fw text-[11px]" }), "Analytics") : null, isOwner && historyUrl ? /* @__PURE__ */ React.createElement("a", { href: historyUrl, className: "inline-flex items-center gap-2 rounded-full border border-white/10 bg-white/[0.04] px-4 py-2 transition hover:bg-white/[0.07] hover:text-white" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-timeline fa-fw text-[11px]" }), "History") : null), /* @__PURE__ */ React.createElement("section", { className: "mt-6 overflow-hidden rounded-[34px] border border-white/10 bg-[linear-gradient(180deg,rgba(255,255,255,0.05),rgba(255,255,255,0.02))] shadow-[0_30px_90px_rgba(2,6,23,0.32)] backdrop-blur-xl" }, /* @__PURE__ */ React.createElement("div", { className: `h-[3px] bg-gradient-to-r ${collection?.type === "editorial" ? "from-amber-400/80 via-amber-400/30 to-transparent" : collection?.type === "community" ? "from-emerald-400/80 via-emerald-400/30 to-transparent" : collection?.mode === "smart" ? "from-sky-400/80 via-sky-400/30 to-transparent" : "from-violet-400/80 via-violet-400/30 to-transparent"}` }), /* @__PURE__ */ React.createElement("div", { className: "grid items-start gap-6 p-5 md:p-7 xl:grid-cols-[minmax(0,1.2fr)_420px]" }, /* @__PURE__ */ React.createElement("div", { className: "relative self-start overflow-hidden rounded-[28px] border border-white/10 bg-slate-950/60" }, /* @__PURE__ */ React.createElement(CollectionCover, { collection }), /* @__PURE__ */ React.createElement("div", { className: "pointer-events-none absolute inset-0 bg-[linear-gradient(to_top,rgba(2,6,23,0.8),rgba(2,6,23,0.08))]" })), /* @__PURE__ */ React.createElement("div", { className: "relative overflow-hidden rounded-[30px] border border-white/10 bg-[radial-gradient(circle_at_top_left,rgba(56,189,248,0.12),transparent_28%),radial-gradient(circle_at_90%_8%,rgba(251,191,36,0.14),transparent_24%),linear-gradient(180deg,rgba(15,23,42,0.94),rgba(10,18,32,0.92))] px-5 py-6 shadow-[inset_0_1px_0_rgba(255,255,255,0.04)] md:px-6 md:py-7" }, /* @__PURE__ */ React.createElement("div", { "aria-hidden": "true", className: "pointer-events-none absolute -left-14 top-10 h-36 w-36 rounded-full bg-sky-400/10 blur-3xl" }), /* @__PURE__ */ React.createElement("div", { "aria-hidden": "true", className: "pointer-events-none absolute -right-10 bottom-8 h-32 w-32 rounded-full bg-amber-300/10 blur-3xl" }), /* @__PURE__ */ React.createElement("div", { className: "relative z-10 flex h-full flex-col justify-between" }, collection?.banner_text ? /* @__PURE__ */ React.createElement("div", { className: `mb-4 inline-flex max-w-full items-center gap-2 rounded-[22px] border px-4 py-3 text-sm font-medium shadow-[0_18px_40px_rgba(2,6,23,0.2)] ${spotlightClasses}` }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-sparkles text-[12px]" }), /* @__PURE__ */ React.createElement("span", { className: "truncate" }, collection.banner_text)) : null, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center gap-2" }, collection?.is_featured ? /* @__PURE__ */ React.createElement("span", { className: "inline-flex items-center rounded-full border border-amber-300/25 bg-amber-300/10 px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.18em] text-amber-100" }, "Featured Collection") : null, collection?.mode === "smart" ? /* @__PURE__ */ React.createElement("span", { className: "inline-flex items-center rounded-full border border-sky-300/20 bg-sky-400/10 px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.18em] text-sky-100" }, "Smart Collection") : null, /* @__PURE__ */ React.createElement(TypeBadge, { collection }), collection?.event_label ? /* @__PURE__ */ React.createElement("span", { className: "inline-flex items-center rounded-full border border-white/10 bg-white/[0.05] px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.18em] text-white" }, collection.event_label) : null, collection?.campaign_label ? /* @__PURE__ */ React.createElement("span", { className: "inline-flex items-center rounded-full border border-amber-300/20 bg-amber-300/10 px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.18em] text-amber-100" }, collection.campaign_label) : null, collection?.badge_label ? /* @__PURE__ */ React.createElement("span", { className: "inline-flex items-center rounded-full border border-white/10 bg-white/[0.05] px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.18em] text-white" }, collection.badge_label) : null, collection?.series_key ? /* @__PURE__ */ React.createElement("span", { className: "inline-flex items-center rounded-full border border-white/10 bg-white/[0.05] px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.18em] text-white" }, "Series ", collection.series_order ? `#${collection.series_order}` : "") : null, isOwner ? /* @__PURE__ */ React.createElement(CollectionVisibilityBadge, { visibility: collection?.visibility }) : null), /* @__PURE__ */ React.createElement("h1", { className: "mt-4 max-w-3xl text-4xl font-black tracking-[-0.06em] text-white md:text-5xl xl:text-[4rem] xl:leading-[0.92]" }, collection?.title), showIntroBlock ? /* @__PURE__ */ React.createElement(React.Fragment, null, collection?.subtitle ? /* @__PURE__ */ React.createElement("p", { className: "mt-3 text-lg text-slate-300 md:text-xl" }, collection.subtitle) : null, collection?.summary || collection?.description ? /* @__PURE__ */ React.createElement("p", { className: "mt-4 max-w-2xl text-sm leading-relaxed text-slate-300 md:text-[15px]" }, collection?.summary || collection?.description) : /* @__PURE__ */ React.createElement("p", { className: "mt-4 max-w-2xl text-sm leading-relaxed text-slate-400 md:text-[15px]" }, "A curated selection from @", owner?.username, ", assembled as a focused gallery rather than a simple archive."), collection?.smart_summary ? /* @__PURE__ */ React.createElement("div", { className: "mt-4 max-w-2xl rounded-[22px] border border-sky-300/15 bg-sky-400/[0.07] px-4 py-3 text-sm leading-relaxed text-sky-100/90" }, collection.smart_summary) : null, featuringCreatorsCount > 1 ? /* @__PURE__ */ React.createElement("p", { className: "mt-3 text-sm text-slate-300" }, "Featuring artworks by ", featuringCreatorsCount, " creators.") : null) : null, /* @__PURE__ */ React.createElement("div", { className: "mt-7 space-y-3" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-3" }, /* @__PURE__ */ React.createElement(CollectionHeroAction, { onClick: handleLike, disabled: state.busy || !engagement?.like_url, icon: "fa-heart", label: state.liked ? "Liked" : "Like", tone: "rose", active: state.liked }), /* @__PURE__ */ React.createElement(CollectionHeroAction, { onClick: handleFollow, disabled: state.busy || !engagement?.follow_url, icon: "fa-bell", label: state.following ? "Following" : "Follow", tone: "emerald", active: state.following }), /* @__PURE__ */ React.createElement(CollectionHeroAction, { onClick: handleSave, disabled: state.busy || !engagement?.save_url && !engagement?.unsave_url, icon: "fa-bookmark", label: state.saved ? "Saved" : "Save", tone: "violet", active: state.saved })), /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-3" }, /* @__PURE__ */ React.createElement(CollectionHeroAction, { onClick: handleShare, icon: "fa-share-nodes", label: "Share", tone: "neutral", compact: true }), featuredCollectionsUrl ? /* @__PURE__ */ React.createElement(CollectionHeroAction, { href: featuredCollectionsUrl, icon: "fa-compass", label: "Explore", tone: "sky", compact: true }) : null, reportEndpoint && !isOwner ? /* @__PURE__ */ React.createElement(CollectionHeroAction, { onClick: () => handleReport("collection", collection?.id), icon: "fa-flag", label: "Report", tone: "amber", compact: true }) : null)), state.notice ? /* @__PURE__ */ React.createElement("p", { className: "mt-3 text-sm text-sky-100" }, state.notice) : null, /* @__PURE__ */ React.createElement(OwnerCard, { owner, collectionType: collection?.type }))))), heroMetrics.length || heroSignals.length ? /* @__PURE__ */ React.createElement("section", { className: "mt-6 rounded-[30px] border border-white/10 bg-[linear-gradient(180deg,rgba(255,255,255,0.05),rgba(255,255,255,0.02))] p-5 shadow-[0_20px_70px_rgba(2,6,23,0.22)] backdrop-blur-xl md:p-6" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-start justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.22em] text-sky-200/80" }, "Collection Snapshot"), /* @__PURE__ */ React.createElement("h2", { className: "mt-2 text-2xl font-semibold text-white" }, "Stats and placement signals")), /* @__PURE__ */ React.createElement("p", { className: "max-w-xl text-sm leading-relaxed text-slate-400" }, "The engagement counters and ranking signals now live outside the hero so the header can stay focused on the artwork, title, and actions.")), /* @__PURE__ */ React.createElement("div", { className: "mt-6 grid gap-4 xl:grid-cols-[minmax(0,1.6fr)_minmax(320px,0.95fr)]" }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-3 sm:grid-cols-2 xl:grid-cols-5" }, heroMetrics.map((item) => /* @__PURE__ */ React.createElement(HeroMetricCard, { key: item.label, icon: item.icon, label: item.label, value: item.value, helper: item.helper, tone: item.tone }))), heroSignals.length ? /* @__PURE__ */ React.createElement("div", { className: "grid gap-3 md:grid-cols-2 xl:grid-cols-1" }, heroSignals.map((item) => /* @__PURE__ */ React.createElement(HeroSignalCard, { key: item.label, icon: item.icon, label: item.label, value: item.value, description: item.description, tone: item.tone }))) : null)) : null, seriesContext?.url || seriesContext?.previous || seriesContext?.next || Array.isArray(seriesContext?.siblings) && seriesContext.siblings.length ? /* @__PURE__ */ React.createElement("section", { className: "mt-8 rounded-[30px] border border-white/10 bg-white/[0.04] p-6 backdrop-blur-sm" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.22em] text-sky-200/80" }, "Series"), /* @__PURE__ */ React.createElement("h2", { className: "mt-2 text-2xl font-semibold text-white" }, seriesContext?.title || "Connected collection sequence"), seriesContext?.description ? /* @__PURE__ */ React.createElement("p", { className: "mt-3 max-w-3xl text-sm leading-relaxed text-slate-300" }, seriesContext.description) : null), /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center gap-3" }, collection?.series_key ? /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-1 text-xs font-semibold text-slate-300" }, collection.series_key) : null, seriesContext?.url ? /* @__PURE__ */ React.createElement("a", { href: seriesContext.url, className: "inline-flex items-center gap-2 rounded-full border border-white/10 bg-white/[0.04] px-4 py-2 text-xs font-semibold uppercase tracking-[0.16em] text-white transition hover:bg-white/[0.07]" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-list fa-fw text-[10px]" }), "View full series") : null)), /* @__PURE__ */ React.createElement("div", { className: "mt-6 grid gap-4 lg:grid-cols-2" }, /* @__PURE__ */ React.createElement("div", { className: "space-y-4" }, seriesContext?.previous ? /* @__PURE__ */ React.createElement("a", { href: seriesContext.previous.url, className: "flex items-center justify-between rounded-[24px] border border-white/10 bg-white/[0.04] px-5 py-4 transition hover:bg-white/[0.07]" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-400" }, "Previous"), /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-lg font-semibold text-white" }, seriesContext.previous.title)), /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-arrow-left text-slate-500" })) : null, seriesContext?.next ? /* @__PURE__ */ React.createElement("a", { href: seriesContext.next.url, className: "flex items-center justify-between rounded-[24px] border border-white/10 bg-white/[0.04] px-5 py-4 transition hover:bg-white/[0.07]" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-400" }, "Next"), /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-lg font-semibold text-white" }, seriesContext.next.title)), /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-arrow-right text-slate-500" })) : null), Array.isArray(seriesContext?.siblings) && seriesContext.siblings.length ? /* @__PURE__ */ React.createElement("div", { className: "grid gap-4" }, seriesContext.siblings.slice(0, 2).map((item) => /* @__PURE__ */ React.createElement(CollectionCard, { key: item.id, collection: item, isOwner: false }))) : null)) : null, contextSignals.length ? /* @__PURE__ */ React.createElement("section", { className: "mt-8 rounded-[30px] border border-white/10 bg-white/[0.04] p-6 backdrop-blur-sm" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-start gap-3" }, /* @__PURE__ */ React.createElement("div", { className: "flex h-10 w-10 shrink-0 items-center justify-center rounded-2xl border border-amber-300/15 bg-amber-400/10 text-amber-300" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-diagram-project text-sm" })), /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.22em] text-amber-200/80" }, "Related Context"), /* @__PURE__ */ React.createElement("h2", { className: "mt-1 text-2xl font-semibold text-white" }, "Campaign, event, and quality context"))), /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-1 text-xs font-semibold text-slate-300" }, contextSignals.length)), /* @__PURE__ */ React.createElement("div", { className: "mt-6 grid gap-4 md:grid-cols-2 xl:grid-cols-3" }, contextSignals.map((item) => /* @__PURE__ */ React.createElement(ContextSignalCard, { key: `${item.meta}-${item.title}`, item })))) : null, storyLinks.length ? /* @__PURE__ */ React.createElement("section", { className: "mt-8 rounded-[30px] border border-white/10 bg-white/[0.04] p-6 backdrop-blur-sm" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-start gap-3" }, /* @__PURE__ */ React.createElement("div", { className: "flex h-10 w-10 shrink-0 items-center justify-center rounded-2xl border border-lime-300/15 bg-lime-400/10 text-lime-300" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-book-open text-sm" })), /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.22em] text-lime-200/80" }, "Stories"), /* @__PURE__ */ React.createElement("h2", { className: "mt-1 text-2xl font-semibold text-white" }, "Stories and editorial references linked to this collection"))), /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-1 text-xs font-semibold text-slate-300" }, storyLinks.length)), /* @__PURE__ */ React.createElement("div", { className: "mt-6 grid gap-4 md:grid-cols-2 xl:grid-cols-3" }, storyLinks.map((item) => /* @__PURE__ */ React.createElement(EntityLinkCard, { key: `${item.linked_type}-${item.linked_id}-${item.id}`, item })))) : null, taxonomyLinks.length ? /* @__PURE__ */ React.createElement("section", { className: "mt-8 rounded-[30px] border border-white/10 bg-white/[0.04] p-6 backdrop-blur-sm" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-start gap-3" }, /* @__PURE__ */ React.createElement("div", { className: "flex h-10 w-10 shrink-0 items-center justify-center rounded-2xl border border-violet-300/15 bg-violet-400/10 text-violet-300" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-tags text-sm" })), /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.22em] text-violet-200/80" }, "Browse The Theme"), /* @__PURE__ */ React.createElement("h2", { className: "mt-1 text-2xl font-semibold text-white" }, "Categories and tags that anchor this collection"))), /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-1 text-xs font-semibold text-slate-300" }, taxonomyLinks.length)), /* @__PURE__ */ React.createElement("div", { className: "mt-6 grid gap-4 md:grid-cols-2 xl:grid-cols-3" }, taxonomyLinks.map((item) => /* @__PURE__ */ React.createElement(EntityLinkCard, { key: `${item.linked_type}-${item.linked_id}-${item.id}`, item })))) : null, contributorLinks.length ? /* @__PURE__ */ React.createElement("section", { className: "mt-8 rounded-[30px] border border-white/10 bg-white/[0.04] p-6 backdrop-blur-sm" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-start gap-3" }, /* @__PURE__ */ React.createElement("div", { className: "flex h-10 w-10 shrink-0 items-center justify-center rounded-2xl border border-sky-300/15 bg-sky-400/10 text-sky-300" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-user-group text-sm" })), /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.22em] text-sky-200/80" }, "Connected Creators"), /* @__PURE__ */ React.createElement("h2", { className: "mt-1 text-2xl font-semibold text-white" }, "Creators and artworks that give the set its shape"))), /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-1 text-xs font-semibold text-slate-300" }, contributorLinks.length)), /* @__PURE__ */ React.createElement("div", { className: "mt-6 grid gap-4 md:grid-cols-2 xl:grid-cols-3" }, contributorLinks.map((item) => /* @__PURE__ */ React.createElement(EntityLinkCard, { key: `${item.linked_type}-${item.linked_id}-${item.id}`, item })))) : null, renderedFullModules.length ? /* @__PURE__ */ React.createElement("div", { className: "mt-8 space-y-6" }, renderedFullModules) : null, renderedMainModules.length || renderedSidebarModules.length ? /* @__PURE__ */ React.createElement("section", { className: "mt-8 grid gap-6 xl:grid-cols-[minmax(0,1fr)_360px]" }, /* @__PURE__ */ React.createElement("div", { className: "space-y-6" }, renderedMainModules), /* @__PURE__ */ React.createElement("div", { className: "space-y-6" }, renderedSidebarModules)) : null))); } -const __vite_glob_0_31 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ +const __vite_glob_0_32 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ __proto__: null, default: CollectionShow }, Symbol.toStringTag, { value: "Module" })); @@ -68011,7 +71809,7 @@ function CollectionStaffProgramming() { return /* @__PURE__ */ React.createElement("div", { key: `merge-pending-${item.id}`, className: `rounded-[24px] border border-white/10 bg-white/[0.04] p-4 transition ${cardBusy ? "ring-1 ring-sky-300/25" : ""}` }, /* @__PURE__ */ React.createElement("div", { className: "mb-4 flex flex-wrap items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-2" }, (item.comparison?.match_reasons || []).map((reason) => /* @__PURE__ */ React.createElement("span", { key: reason, className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-1 text-[10px] font-semibold uppercase tracking-[0.14em] text-slate-300" }, titleize(reason)))), cardBusy ? /* @__PURE__ */ React.createElement("span", { className: "inline-flex items-center gap-2 rounded-full border border-sky-300/20 bg-sky-400/10 px-3 py-1 text-[10px] font-semibold uppercase tracking-[0.14em] text-sky-100" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-circle-notch fa-spin fa-fw text-[10px]" }), "Processing ", titleize(activeQueueAction)) : null), /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 lg:grid-cols-2" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "mb-2 text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-400" }, "Source"), item.source ? /* @__PURE__ */ React.createElement(CollectionCard, { collection: item.source, isOwner: true }) : null), /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "mb-2 text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-400" }, "Candidate"), item.target ? /* @__PURE__ */ React.createElement(CollectionCard, { collection: item.target, isOwner: true }) : null)), /* @__PURE__ */ React.createElement("div", { className: "mt-4 grid gap-2 md:grid-cols-3 text-xs text-slate-400" }, /* @__PURE__ */ React.createElement("div", { className: "rounded-xl border border-white/10 bg-white/[0.04] px-3 py-2" }, "Shared artworks: ", /* @__PURE__ */ React.createElement("span", { className: "font-semibold text-white" }, item.comparison?.shared_artworks_count ?? 0)), /* @__PURE__ */ React.createElement("div", { className: "rounded-xl border border-white/10 bg-white/[0.04] px-3 py-2" }, "Source count: ", /* @__PURE__ */ React.createElement("span", { className: "font-semibold text-white" }, item.comparison?.source_artworks_count ?? 0)), /* @__PURE__ */ React.createElement("div", { className: "rounded-xl border border-white/10 bg-white/[0.04] px-3 py-2" }, "Target count: ", /* @__PURE__ */ React.createElement("span", { className: "font-semibold text-white" }, item.comparison?.target_artworks_count ?? 0))), /* @__PURE__ */ React.createElement("div", { className: "mt-4 flex flex-wrap gap-2" }, item.source?.manage_url ? /* @__PURE__ */ React.createElement("a", { href: item.source.manage_url, className: "inline-flex items-center gap-2 rounded-full border border-rose-300/20 bg-rose-400/10 px-4 py-2 text-xs font-semibold text-rose-100 transition hover:bg-rose-400/15" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-code-compare fa-fw text-[10px]" }), "Review source") : null, item.target?.manage_url ? /* @__PURE__ */ React.createElement("a", { href: item.target.manage_url, className: "inline-flex items-center gap-2 rounded-full border border-white/10 bg-white/[0.04] px-4 py-2 text-xs font-semibold text-white transition hover:bg-white/[0.07]" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-arrow-up-right-from-square fa-fw text-[10px]" }), "Open target") : null, item.source?.id && historyPattern ? /* @__PURE__ */ React.createElement("a", { href: historyPattern.replace("__COLLECTION__", String(item.source.id)), className: "inline-flex items-center gap-2 rounded-full border border-white/10 bg-white/[0.04] px-4 py-2 text-xs font-semibold text-white transition hover:bg-white/[0.07]" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-timeline fa-fw text-[10px]" }), "History") : null, /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => handleQueueAction("canonicalize", item), disabled: cardBusy, className: "inline-flex items-center gap-2 rounded-full border border-sky-300/20 bg-sky-400/10 px-4 py-2 text-xs font-semibold text-sky-100 transition hover:bg-sky-400/15 disabled:opacity-60" }, /* @__PURE__ */ React.createElement("i", { className: `fa-solid ${activeQueueAction === "canonicalize" ? "fa-circle-notch fa-spin" : "fa-badge-check"} fa-fw text-[10px]` }), activeQueueAction === "canonicalize" ? "Canonicalizing..." : "Canonicalize"), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => handleQueueAction("merge", item), disabled: cardBusy, className: "inline-flex items-center gap-2 rounded-full border border-emerald-300/20 bg-emerald-400/10 px-4 py-2 text-xs font-semibold text-emerald-100 transition hover:bg-emerald-400/15 disabled:opacity-60" }, /* @__PURE__ */ React.createElement("i", { className: `fa-solid ${activeQueueAction === "merge" ? "fa-circle-notch fa-spin" : "fa-code-merge"} fa-fw text-[10px]` }), activeQueueAction === "merge" ? "Merging..." : "Merge now"), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => handleQueueAction("reject", item), disabled: cardBusy, className: "inline-flex items-center gap-2 rounded-full border border-amber-300/20 bg-amber-400/10 px-4 py-2 text-xs font-semibold text-amber-100 transition hover:bg-amber-400/15 disabled:opacity-60" }, /* @__PURE__ */ React.createElement("i", { className: `fa-solid ${activeQueueAction === "reject" ? "fa-circle-notch fa-spin" : "fa-ban"} fa-fw text-[10px]` }), activeQueueAction === "reject" ? "Rejecting..." : "Reject"))); }) : /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-dashed border-white/12 bg-white/[0.03] px-5 py-10 text-sm text-slate-300" }, "No pending merge candidates right now."))), /* @__PURE__ */ React.createElement("div", { className: "rounded-[28px] border border-white/10 bg-slate-950/40 p-5" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-sky-200/80" }, "Recent Decisions"), /* @__PURE__ */ React.createElement("h3", { className: "mt-2 text-xl font-semibold text-white" }, "Canonical, reject, and merge history")), /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-1 text-xs font-semibold text-slate-300" }, mergeQueue?.recent?.length || 0)), /* @__PURE__ */ React.createElement("div", { className: "mt-5 space-y-4" }, (mergeQueue?.recent || []).length ? mergeQueue.recent.map((item) => /* @__PURE__ */ React.createElement("div", { key: `merge-recent-${item.id}`, className: "rounded-[24px] border border-white/10 bg-white/[0.04] p-4" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-start justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("span", { className: "inline-flex rounded-full border border-white/10 bg-white/[0.04] px-3 py-1 text-[10px] font-semibold uppercase tracking-[0.16em] text-slate-300" }, titleize(item.action_type)), item.summary ? /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm text-slate-300" }, item.summary) : null, /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-xs text-slate-500" }, item.updated_at ? new Date(item.updated_at).toLocaleString() : "Unknown time", item.actor?.username ? ` • @${item.actor.username}` : ""))), /* @__PURE__ */ React.createElement("div", { className: "mt-4 grid gap-3 lg:grid-cols-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-400" }, "Source"), /* @__PURE__ */ React.createElement("div", { className: "mt-1 font-semibold text-white" }, item.source?.title || "Collection")), /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-400" }, "Target"), /* @__PURE__ */ React.createElement("div", { className: "mt-1 font-semibold text-white" }, item.target?.title || "Collection"))), /* @__PURE__ */ React.createElement("div", { className: "mt-4 flex flex-wrap gap-2" }, item.source?.manage_url ? /* @__PURE__ */ React.createElement("a", { href: item.source.manage_url, className: "inline-flex items-center gap-2 rounded-full border border-white/10 bg-white/[0.04] px-4 py-2 text-xs font-semibold text-white transition hover:bg-white/[0.07]" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-pen-to-square fa-fw text-[10px]" }), "Open source") : null, item.target?.manage_url ? /* @__PURE__ */ React.createElement("a", { href: item.target.manage_url, className: "inline-flex items-center gap-2 rounded-full border border-white/10 bg-white/[0.04] px-4 py-2 text-xs font-semibold text-white transition hover:bg-white/[0.07]" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-arrow-up-right-from-square fa-fw text-[10px]" }), "Open target") : null))) : /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-dashed border-white/12 bg-white/[0.03] px-5 py-10 text-sm text-slate-300" }, "No recent merge decisions yet."))))), /* @__PURE__ */ React.createElement("section", { className: "mt-8 grid gap-6 xl:grid-cols-[minmax(0,0.95fr)_minmax(0,1.05fr)]" }, /* @__PURE__ */ React.createElement("form", { onSubmit: handleAssignmentSubmit, className: "rounded-[32px] border border-white/10 bg-white/[0.04] p-6 backdrop-blur-sm md:p-7" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.22em] text-sky-200/80" }, "Assignment"), /* @__PURE__ */ React.createElement("h2", { className: "mt-2 text-2xl font-semibold text-white" }, "Program key and scope")), /* @__PURE__ */ React.createElement("div", { className: "mt-6 grid gap-4 md:grid-cols-2" }, /* @__PURE__ */ React.createElement(Field$1, { label: "Collection" }, /* @__PURE__ */ React.createElement(NovaSelect, { value: String(assignmentForm.collection_id || ""), onChange: (val) => setAssignmentForm((current) => ({ ...current, collection_id: val })), options: collectionOptions.map((o) => ({ value: String(o.id), label: o.title })) })), /* @__PURE__ */ React.createElement(Field$1, { label: "Program Key", help: "Use stable internal names like discover-spring or homepage-hero." }, /* @__PURE__ */ React.createElement("input", { list: "program-key-options", value: assignmentForm.program_key, onChange: (event) => setAssignmentForm((current) => ({ ...current, program_key: event.target.value })), className: "w-full rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3 text-white outline-none", maxLength: 80 })), /* @__PURE__ */ React.createElement(Field$1, { label: "Placement Scope", help: "Optional placement scope such as homepage.hero or discover.rail." }, /* @__PURE__ */ React.createElement("input", { value: assignmentForm.placement_scope, onChange: (event) => setAssignmentForm((current) => ({ ...current, placement_scope: event.target.value })), className: "w-full rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3 text-white outline-none", maxLength: 80 })), /* @__PURE__ */ React.createElement(Field$1, { label: "Campaign Key" }, /* @__PURE__ */ React.createElement("input", { value: assignmentForm.campaign_key, onChange: (event) => setAssignmentForm((current) => ({ ...current, campaign_key: event.target.value })), className: "w-full rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3 text-white outline-none", maxLength: 80 })), /* @__PURE__ */ React.createElement(Field$1, { label: "Priority" }, /* @__PURE__ */ React.createElement("input", { type: "number", min: "-100", max: "100", value: assignmentForm.priority, onChange: (event) => setAssignmentForm((current) => ({ ...current, priority: event.target.value })), className: "w-full rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3 text-white outline-none" })), /* @__PURE__ */ React.createElement(Field$1, { label: "Starts At" }, /* @__PURE__ */ React.createElement(DateTimePicker, { value: assignmentForm.starts_at, onChange: (nextValue) => setAssignmentForm((current) => ({ ...current, starts_at: nextValue })), placeholder: "Start time", clearable: true, className: "bg-white/[0.04]" })), /* @__PURE__ */ React.createElement(Field$1, { label: "Ends At" }, /* @__PURE__ */ React.createElement(DateTimePicker, { value: assignmentForm.ends_at, onChange: (nextValue) => setAssignmentForm((current) => ({ ...current, ends_at: nextValue })), placeholder: "End time", clearable: true, className: "bg-white/[0.04]" }))), /* @__PURE__ */ React.createElement(Field$1, { label: "Notes", help: "Operational note for launch timing, overrides, or review context." }, /* @__PURE__ */ React.createElement("textarea", { value: assignmentForm.notes, onChange: (event) => setAssignmentForm((current) => ({ ...current, notes: event.target.value })), className: "mt-4 min-h-[120px] w-full rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3 text-white outline-none", maxLength: 1e3 })), /* @__PURE__ */ React.createElement("div", { className: "mt-5 flex flex-wrap gap-3" }, /* @__PURE__ */ React.createElement("button", { type: "submit", disabled: busy === "assignment", className: "inline-flex items-center gap-2 rounded-2xl border border-sky-300/20 bg-sky-400/10 px-5 py-3 text-sm font-semibold text-sky-100 transition hover:bg-sky-400/15 disabled:opacity-60" }, /* @__PURE__ */ React.createElement("i", { className: `fa-solid ${busy === "assignment" ? "fa-circle-notch fa-spin" : "fa-sliders"} fa-fw` }), assignmentForm.id ? "Update Assignment" : "Save Assignment"), assignmentForm.id ? /* @__PURE__ */ React.createElement("button", { type: "button", onClick: resetAssignmentForm, className: "inline-flex items-center gap-2 rounded-2xl border border-white/10 bg-white/[0.04] px-5 py-3 text-sm font-semibold text-white transition hover:bg-white/[0.07]" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-rotate-left fa-fw" }), "Cancel Edit") : null), /* @__PURE__ */ React.createElement("datalist", { id: "program-key-options" }, programKeyOptions.map((option) => /* @__PURE__ */ React.createElement("option", { key: option, value: option })))), /* @__PURE__ */ React.createElement("div", { className: "space-y-6" }, /* @__PURE__ */ React.createElement("form", { onSubmit: handlePreview, className: "rounded-[32px] border border-white/10 bg-white/[0.04] p-6 backdrop-blur-sm md:p-7" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.22em] text-amber-200/80" }, "Preview"), /* @__PURE__ */ React.createElement("h2", { className: "mt-2 text-2xl font-semibold text-white" }, "Inspect a live program pool")), /* @__PURE__ */ React.createElement("div", { className: "mt-6 grid gap-4 md:grid-cols-[minmax(0,1fr)_140px_auto]" }, /* @__PURE__ */ React.createElement(Field$1, { label: "Program Key" }, /* @__PURE__ */ React.createElement("input", { list: "program-key-options", value: previewForm.program_key, onChange: (event) => setPreviewForm((current) => ({ ...current, program_key: event.target.value })), className: "w-full rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3 text-white outline-none", maxLength: 80 })), /* @__PURE__ */ React.createElement(Field$1, { label: "Limit" }, /* @__PURE__ */ React.createElement("input", { type: "number", min: "1", max: "24", value: previewForm.limit, onChange: (event) => setPreviewForm((current) => ({ ...current, limit: event.target.value })), className: "w-full rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3 text-white outline-none" })), /* @__PURE__ */ React.createElement("div", { className: "flex items-end" }, /* @__PURE__ */ React.createElement("button", { type: "submit", disabled: busy === "preview", className: "inline-flex h-[50px] w-full items-center justify-center gap-2 rounded-2xl border border-amber-300/20 bg-amber-400/10 px-5 text-sm font-semibold text-amber-100 transition hover:bg-amber-400/15 disabled:opacity-60" }, /* @__PURE__ */ React.createElement("i", { className: `fa-solid ${busy === "preview" ? "fa-circle-notch fa-spin" : "fa-binoculars"} fa-fw` }), "Preview"))), previewCollections.length ? /* @__PURE__ */ React.createElement("div", { className: "mt-6 grid gap-4 xl:grid-cols-2" }, previewCollections.map((collection) => /* @__PURE__ */ React.createElement("div", { key: collection.id, className: "rounded-[24px] border border-white/10 bg-slate-950/40 p-4" }, /* @__PURE__ */ React.createElement(CollectionCard, { collection, isOwner: true })))) : /* @__PURE__ */ React.createElement("div", { className: "mt-6 rounded-[24px] border border-dashed border-white/12 bg-white/[0.03] px-5 py-8 text-sm text-slate-300" }, "Run a preview to inspect which collections currently qualify for a given program key.")), /* @__PURE__ */ React.createElement("section", { className: "rounded-[32px] border border-white/10 bg-white/[0.04] p-6 backdrop-blur-sm md:p-7" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.22em] text-lime-200/80" }, "Diagnostics"), /* @__PURE__ */ React.createElement("h2", { className: "mt-2 text-2xl font-semibold text-white" }, "Eligibility, duplicate risk, and ranking refresh")), /* @__PURE__ */ React.createElement("div", { className: "mt-6 grid gap-4 xl:grid-cols-[320px_minmax(0,1fr)]" }, /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-slate-950/40 p-4 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("p", { className: "font-semibold text-white" }, "Operations summary"), /* @__PURE__ */ React.createElement("div", { className: "mt-4 grid gap-3 sm:grid-cols-2 xl:grid-cols-1" }, /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-white/[0.04] px-3 py-2" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] uppercase tracking-[0.16em] text-slate-400" }, "Stale health"), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-lg font-semibold text-white" }, Number(observabilitySummary?.counts?.stale_health || 0))), /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-white/[0.04] px-3 py-2" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] uppercase tracking-[0.16em] text-slate-400" }, "Stale recommendations"), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-lg font-semibold text-white" }, Number(observabilitySummary?.counts?.stale_recommendations || 0))), /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-white/[0.04] px-3 py-2" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] uppercase tracking-[0.16em] text-slate-400" }, "Placement blocked"), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-lg font-semibold text-white" }, Number(observabilitySummary?.counts?.placement_blocked || 0))), /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-white/[0.04] px-3 py-2" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] uppercase tracking-[0.16em] text-slate-400" }, "Duplicate risk"), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-lg font-semibold text-white" }, Number(observabilitySummary?.counts?.duplicate_risk || 0)))), observabilitySummary?.generated_at ? /* @__PURE__ */ React.createElement("p", { className: "mt-4 text-xs text-slate-400" }, "Generated ", new Date(observabilitySummary.generated_at).toLocaleString()) : null), /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-slate-950/40 p-4 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("p", { className: "font-semibold text-white" }, "Watchlist"), Array.isArray(observabilitySummary?.watchlist) && observabilitySummary.watchlist.length ? /* @__PURE__ */ React.createElement("div", { className: "mt-4 grid gap-4 xl:grid-cols-2" }, observabilitySummary.watchlist.map((collection) => /* @__PURE__ */ React.createElement("div", { key: `watch-${collection.id}`, className: "rounded-[20px] border border-white/10 bg-white/[0.04] p-3" }, /* @__PURE__ */ React.createElement(CollectionCard, { collection, isOwner: true })))) : /* @__PURE__ */ React.createElement("p", { className: "mt-3" }, "No watchlist items are currently flagged."))), /* @__PURE__ */ React.createElement("div", { className: "mt-6 grid gap-4 md:grid-cols-[minmax(0,1fr)_auto]" }, /* @__PURE__ */ React.createElement(Field$1, { label: "Target Collection", help: "Leave a selection in place to inspect one collection. Change it any time before running a diagnostic." }, /* @__PURE__ */ React.createElement(NovaSelect, { value: String(selectedCollectionId || ""), onChange: (val) => setSelectedCollectionId(val), options: collectionOptions.map((o) => ({ value: String(o.id), label: o.title })) })), /* @__PURE__ */ React.createElement("div", { className: "flex items-end gap-3" }, /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => runDiagnostic("eligibility"), disabled: busy !== "", className: "inline-flex items-center gap-2 rounded-2xl border border-lime-300/20 bg-lime-400/10 px-4 py-3 text-sm font-semibold text-lime-100 transition hover:bg-lime-400/15 disabled:opacity-60" }, /* @__PURE__ */ React.createElement("i", { className: `fa-solid ${busy === "eligibility" ? "fa-circle-notch fa-spin" : "fa-shield-check"} fa-fw` }), "Eligibility"), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => runDiagnostic("duplicates"), disabled: busy !== "", className: "inline-flex items-center gap-2 rounded-2xl border border-rose-300/20 bg-rose-400/10 px-4 py-3 text-sm font-semibold text-rose-100 transition hover:bg-rose-400/15 disabled:opacity-60" }, /* @__PURE__ */ React.createElement("i", { className: `fa-solid ${busy === "duplicates" ? "fa-circle-notch fa-spin" : "fa-id-card"} fa-fw` }), "Duplicates"), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => runDiagnostic("recommendations"), disabled: busy !== "", className: "inline-flex items-center gap-2 rounded-2xl border border-sky-300/20 bg-sky-400/10 px-4 py-3 text-sm font-semibold text-sky-100 transition hover:bg-sky-400/15 disabled:opacity-60" }, /* @__PURE__ */ React.createElement("i", { className: `fa-solid ${busy === "recommendations" ? "fa-circle-notch fa-spin" : "fa-arrows-rotate"} fa-fw` }), "Refresh"))), /* @__PURE__ */ React.createElement("div", { className: "mt-6 grid gap-4 lg:grid-cols-3" }, /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-slate-950/40 p-4 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("p", { className: "font-semibold text-white" }, "Eligibility"), diagnostics.eligibility ? /* @__PURE__ */ React.createElement("div", { className: "mt-3 space-y-2" }, /* @__PURE__ */ React.createElement("p", null, diagnostics.eligibility.status === "queued" ? `${diagnostics.eligibility.count} collection(s) queued.` : `${diagnostics.eligibility.count} collection(s) evaluated.`), diagnostics.eligibility.message ? /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-white/[0.04] px-3 py-2" }, diagnostics.eligibility.message) : null, (diagnostics.eligibility.items || []).map((item) => /* @__PURE__ */ React.createElement("div", { key: item.collection_id, className: "rounded-2xl border border-white/10 bg-white/[0.04] px-3 py-2" }, item.health_state || "unknown", " · ", item.readiness_state || "unknown", " · ", item.placement_eligibility ? "eligible" : "blocked"))) : /* @__PURE__ */ React.createElement("p", { className: "mt-3" }, "Run an eligibility refresh to verify readiness and public placement safety.")), /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-slate-950/40 p-4 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("p", { className: "font-semibold text-white" }, "Duplicate candidates"), diagnostics.duplicates ? /* @__PURE__ */ React.createElement("div", { className: "mt-3 space-y-2" }, /* @__PURE__ */ React.createElement("p", null, diagnostics.duplicates.status === "queued" ? `${diagnostics.duplicates.count} collection(s) queued.` : `${diagnostics.duplicates.count} collection(s) with candidates.`), diagnostics.duplicates.message ? /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-white/[0.04] px-3 py-2" }, diagnostics.duplicates.message) : null, (diagnostics.duplicates.items || []).map((item) => /* @__PURE__ */ React.createElement("div", { key: item.collection_id, className: "rounded-2xl border border-white/10 bg-white/[0.04] px-3 py-2" }, item.candidates?.length ? item.candidates.map((candidate) => candidate.title).join(", ") : "No candidates"))) : /* @__PURE__ */ React.createElement("p", { className: "mt-3" }, "Run duplicate scan to surface overlap before programming a collection widely.")), /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-slate-950/40 p-4 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("p", { className: "font-semibold text-white" }, "Recommendation refresh"), diagnostics.recommendations ? /* @__PURE__ */ React.createElement("div", { className: "mt-3 space-y-2" }, /* @__PURE__ */ React.createElement("p", null, diagnostics.recommendations.status === "queued" ? `${diagnostics.recommendations.count} collection(s) queued.` : `${diagnostics.recommendations.count} collection(s) refreshed.`), diagnostics.recommendations.message ? /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-white/[0.04] px-3 py-2" }, diagnostics.recommendations.message) : null, (diagnostics.recommendations.items || []).map((item) => /* @__PURE__ */ React.createElement("div", { key: item.collection_id, className: "rounded-2xl border border-white/10 bg-white/[0.04] px-3 py-2" }, titleize(item.recommendation_tier || "unknown"), " · ", titleize(item.ranking_bucket || "unknown"), " · ", titleize(item.search_boost_tier || "unknown")))) : /* @__PURE__ */ React.createElement("p", { className: "mt-3" }, "Run a recommendation refresh to update ranking and search tiers for this collection.")))), /* @__PURE__ */ React.createElement("form", { onSubmit: handleHooksSubmit, className: "rounded-[32px] border border-white/10 bg-white/[0.04] p-6 backdrop-blur-sm md:p-7" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-start justify-between gap-4" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.22em] text-fuchsia-200/80" }, "Hooks"), /* @__PURE__ */ React.createElement("h2", { className: "mt-2 text-2xl font-semibold text-white" }, "Experiment and program governance"), /* @__PURE__ */ React.createElement("p", { className: "mt-3 text-sm leading-relaxed text-slate-300" }, "Control experiment keys, promotion tiers, and staff-only program governance hooks for the selected collection without leaving the programming studio.")), selectedCollection?.program_key && endpoints.publicProgramPattern ? /* @__PURE__ */ React.createElement("a", { href: buildProgramUrl(endpoints.publicProgramPattern, selectedCollection.program_key), className: "inline-flex items-center gap-2 rounded-full border border-white/10 bg-white/[0.04] px-4 py-2 text-sm font-semibold text-white transition hover:bg-white/[0.07]" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-arrow-up-right-from-square fa-fw text-[11px]" }), "Open public program landing") : null), /* @__PURE__ */ React.createElement("div", { className: "mt-6 grid gap-4 md:grid-cols-2 xl:grid-cols-3" }, /* @__PURE__ */ React.createElement(Field$1, { label: "Experiment Key", help: "Internal test or treatment key for cross-surface collection experiments." }, /* @__PURE__ */ React.createElement("input", { value: hooksForm.experiment_key, onChange: (event) => setHooksForm((current) => ({ ...current, experiment_key: event.target.value })), className: "w-full rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3 text-white outline-none", maxLength: 80 })), /* @__PURE__ */ React.createElement(Field$1, { label: "Treatment", help: "Variant or treatment label tied to the experiment key." }, /* @__PURE__ */ React.createElement("input", { value: hooksForm.experiment_treatment, onChange: (event) => setHooksForm((current) => ({ ...current, experiment_treatment: event.target.value })), className: "w-full rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3 text-white outline-none", maxLength: 80 })), /* @__PURE__ */ React.createElement(Field$1, { label: "Placement Variant", help: "Surface-specific placement variant such as homepage_a or search_dense." }, /* @__PURE__ */ React.createElement("input", { value: hooksForm.placement_variant, onChange: (event) => setHooksForm((current) => ({ ...current, placement_variant: event.target.value })), className: "w-full rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3 text-white outline-none", maxLength: 80 })), /* @__PURE__ */ React.createElement(Field$1, { label: "Ranking Variant", help: "Override or annotate ranking mode experiments without changing the live pool logic." }, /* @__PURE__ */ React.createElement("input", { value: hooksForm.ranking_mode_variant, onChange: (event) => setHooksForm((current) => ({ ...current, ranking_mode_variant: event.target.value })), className: "w-full rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3 text-white outline-none", maxLength: 80 })), /* @__PURE__ */ React.createElement(Field$1, { label: "Pool Version", help: "Snapshot or rollout version for the collection pool definition." }, /* @__PURE__ */ React.createElement("input", { value: hooksForm.collection_pool_version, onChange: (event) => setHooksForm((current) => ({ ...current, collection_pool_version: event.target.value })), className: "w-full rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3 text-white outline-none", maxLength: 80 })), /* @__PURE__ */ React.createElement(Field$1, { label: "Test Label", help: "Human-readable campaign or experiment label for operations and diagnostics." }, /* @__PURE__ */ React.createElement("input", { value: hooksForm.test_label, onChange: (event) => setHooksForm((current) => ({ ...current, test_label: event.target.value })), className: "w-full rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3 text-white outline-none", maxLength: 120 })), /* @__PURE__ */ React.createElement(Field$1, { label: "Promotion Tier", help: "Optional internal tier for elevated or restrained programming treatment." }, /* @__PURE__ */ React.createElement("input", { value: hooksForm.promotion_tier, onChange: (event) => setHooksForm((current) => ({ ...current, promotion_tier: event.target.value })), className: "w-full rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3 text-white outline-none", maxLength: 40 })), viewer.isAdmin ? /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement(Field$1, { label: "Partner Key", help: "Admin-only internal key for trusted partner or program ownership." }, /* @__PURE__ */ React.createElement("input", { value: hooksForm.partner_key, onChange: (event) => setHooksForm((current) => ({ ...current, partner_key: event.target.value })), className: "w-full rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3 text-white outline-none", maxLength: 80 })), /* @__PURE__ */ React.createElement(Field$1, { label: "Trust Tier", help: "Admin-only trust marker used for internal partner/program review logic." }, /* @__PURE__ */ React.createElement("input", { value: hooksForm.trust_tier, onChange: (event) => setHooksForm((current) => ({ ...current, trust_tier: event.target.value })), className: "w-full rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3 text-white outline-none", maxLength: 40 })), /* @__PURE__ */ React.createElement(Field$1, { label: "Sponsorship State", help: "Admin-only state for sponsored, pending, or cleared program treatment." }, /* @__PURE__ */ React.createElement("input", { value: hooksForm.sponsorship_state, onChange: (event) => setHooksForm((current) => ({ ...current, sponsorship_state: event.target.value })), className: "w-full rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3 text-white outline-none", maxLength: 40 })), /* @__PURE__ */ React.createElement(Field$1, { label: "Ownership Domain", help: "Admin-only internal ownership domain such as editorial, partner, creator_program, or events." }, /* @__PURE__ */ React.createElement("input", { value: hooksForm.ownership_domain, onChange: (event) => setHooksForm((current) => ({ ...current, ownership_domain: event.target.value })), className: "w-full rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3 text-white outline-none", maxLength: 80 })), /* @__PURE__ */ React.createElement(Field$1, { label: "Commercial Review", help: "Admin-only commercial review status for future partner and sponsor programs." }, /* @__PURE__ */ React.createElement("input", { value: hooksForm.commercial_review_state, onChange: (event) => setHooksForm((current) => ({ ...current, commercial_review_state: event.target.value })), className: "w-full rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3 text-white outline-none", maxLength: 40 })), /* @__PURE__ */ React.createElement(Field$1, { label: "Legal Review", help: "Admin-only legal review status when collections need compliance approval before wider promotion." }, /* @__PURE__ */ React.createElement("input", { value: hooksForm.legal_review_state, onChange: (event) => setHooksForm((current) => ({ ...current, legal_review_state: event.target.value })), className: "w-full rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3 text-white outline-none", maxLength: 40 }))) : /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-dashed border-white/12 bg-white/[0.03] px-4 py-4 text-sm text-slate-300 md:col-span-2 xl:col-span-3" }, "Partner, sponsorship, ownership, and review metadata remain admin-only. Moderators can still manage experiment and promotion hooks here.")), /* @__PURE__ */ React.createElement("div", { className: "mt-4 flex items-center gap-3 rounded-[20px] border border-white/10 bg-slate-950/40 px-4 py-3 text-sm text-slate-200" }, /* @__PURE__ */ React.createElement(Checkbox, { checked: hooksForm.placement_eligibility, onChange: (event) => setHooksForm((current) => ({ ...current, placement_eligibility: event.target.checked })), label: "Placement eligible override" })), /* @__PURE__ */ React.createElement("div", { className: "mt-5 grid gap-3 sm:grid-cols-2 xl:grid-cols-3" }, /* @__PURE__ */ React.createElement("div", { className: "rounded-[22px] border border-white/10 bg-slate-950/40 px-4 py-3 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-400" }, "Experiment"), /* @__PURE__ */ React.createElement("div", { className: "mt-1 font-semibold text-white" }, hooksDiagnostics?.experiment_key || selectedCollection?.experiment_key || "Not set")), /* @__PURE__ */ React.createElement("div", { className: "rounded-[22px] border border-white/10 bg-slate-950/40 px-4 py-3 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-400" }, "Treatment"), /* @__PURE__ */ React.createElement("div", { className: "mt-1 font-semibold text-white" }, hooksDiagnostics?.experiment_treatment || selectedCollection?.experiment_treatment || "Not set")), /* @__PURE__ */ React.createElement("div", { className: "rounded-[22px] border border-white/10 bg-slate-950/40 px-4 py-3 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-400" }, "Placement Variant"), /* @__PURE__ */ React.createElement("div", { className: "mt-1 font-semibold text-white" }, hooksDiagnostics?.placement_variant || selectedCollection?.placement_variant || "Not set")), /* @__PURE__ */ React.createElement("div", { className: "rounded-[22px] border border-white/10 bg-slate-950/40 px-4 py-3 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-400" }, "Workflow"), /* @__PURE__ */ React.createElement("div", { className: "mt-1 font-semibold text-white" }, titleize(hooksDiagnostics?.workflow_state || selectedCollection?.workflow_state || "unknown"))), /* @__PURE__ */ React.createElement("div", { className: "rounded-[22px] border border-white/10 bg-slate-950/40 px-4 py-3 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-400" }, "Health"), /* @__PURE__ */ React.createElement("div", { className: "mt-1 font-semibold text-white" }, titleize(hooksDiagnostics?.health_state || selectedCollection?.health_state || "unknown"))), /* @__PURE__ */ React.createElement("div", { className: "rounded-[22px] border border-white/10 bg-slate-950/40 px-4 py-3 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-400" }, "Recommendation Tier"), /* @__PURE__ */ React.createElement("div", { className: "mt-1 font-semibold text-white" }, titleize(hooksDiagnostics?.recommendation_tier || selectedCollection?.recommendation_tier || "unknown"))), /* @__PURE__ */ React.createElement("div", { className: "rounded-[22px] border border-white/10 bg-slate-950/40 px-4 py-3 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-400" }, "Ranking Bucket"), /* @__PURE__ */ React.createElement("div", { className: "mt-1 font-semibold text-white" }, titleize(hooksDiagnostics?.ranking_bucket || selectedCollection?.ranking_bucket || "unknown"))), /* @__PURE__ */ React.createElement("div", { className: "rounded-[22px] border border-white/10 bg-slate-950/40 px-4 py-3 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-400" }, "Ranking Variant"), /* @__PURE__ */ React.createElement("div", { className: "mt-1 font-semibold text-white" }, hooksDiagnostics?.ranking_mode_variant || selectedCollection?.ranking_mode_variant || "Not set")), /* @__PURE__ */ React.createElement("div", { className: "rounded-[22px] border border-white/10 bg-slate-950/40 px-4 py-3 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-400" }, "Pool Version"), /* @__PURE__ */ React.createElement("div", { className: "mt-1 font-semibold text-white" }, hooksDiagnostics?.collection_pool_version || selectedCollection?.collection_pool_version || "Not set")), /* @__PURE__ */ React.createElement("div", { className: "rounded-[22px] border border-white/10 bg-slate-950/40 px-4 py-3 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-400" }, "Test Label"), /* @__PURE__ */ React.createElement("div", { className: "mt-1 font-semibold text-white" }, hooksDiagnostics?.test_label || selectedCollection?.test_label || "Not set")), /* @__PURE__ */ React.createElement("div", { className: "rounded-[22px] border border-white/10 bg-slate-950/40 px-4 py-3 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-400" }, "Promotion Tier"), /* @__PURE__ */ React.createElement("div", { className: "mt-1 font-semibold text-white" }, hooksDiagnostics?.promotion_tier || selectedCollection?.promotion_tier || "Not set")), /* @__PURE__ */ React.createElement("div", { className: "rounded-[22px] border border-white/10 bg-slate-950/40 px-4 py-3 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-400" }, "Partner Key"), /* @__PURE__ */ React.createElement("div", { className: "mt-1 font-semibold text-white" }, hooksDiagnostics?.partner_key || selectedCollection?.partner_key || "Not set")), /* @__PURE__ */ React.createElement("div", { className: "rounded-[22px] border border-white/10 bg-slate-950/40 px-4 py-3 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-400" }, "Trust Tier"), /* @__PURE__ */ React.createElement("div", { className: "mt-1 font-semibold text-white" }, hooksDiagnostics?.trust_tier || selectedCollection?.trust_tier || "Not set")), /* @__PURE__ */ React.createElement("div", { className: "rounded-[22px] border border-white/10 bg-slate-950/40 px-4 py-3 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-400" }, "Sponsorship State"), /* @__PURE__ */ React.createElement("div", { className: "mt-1 font-semibold text-white" }, hooksDiagnostics?.sponsorship_state || selectedCollection?.sponsorship_state || "Not set")), /* @__PURE__ */ React.createElement("div", { className: "rounded-[22px] border border-white/10 bg-slate-950/40 px-4 py-3 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-400" }, "Ownership Domain"), /* @__PURE__ */ React.createElement("div", { className: "mt-1 font-semibold text-white" }, hooksDiagnostics?.ownership_domain || selectedCollection?.ownership_domain || "Not set")), /* @__PURE__ */ React.createElement("div", { className: "rounded-[22px] border border-white/10 bg-slate-950/40 px-4 py-3 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-400" }, "Commercial Review"), /* @__PURE__ */ React.createElement("div", { className: "mt-1 font-semibold text-white" }, hooksDiagnostics?.commercial_review_state || selectedCollection?.commercial_review_state || "Not set")), /* @__PURE__ */ React.createElement("div", { className: "rounded-[22px] border border-white/10 bg-slate-950/40 px-4 py-3 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-400" }, "Legal Review"), /* @__PURE__ */ React.createElement("div", { className: "mt-1 font-semibold text-white" }, hooksDiagnostics?.legal_review_state || selectedCollection?.legal_review_state || "Not set")), /* @__PURE__ */ React.createElement("div", { className: "rounded-[22px] border border-white/10 bg-slate-950/40 px-4 py-3 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-400" }, "Last Health Check"), /* @__PURE__ */ React.createElement("div", { className: "mt-1 font-semibold text-white" }, hooksDiagnostics?.last_health_check_at ? new Date(hooksDiagnostics.last_health_check_at).toLocaleString() : "Not yet")), /* @__PURE__ */ React.createElement("div", { className: "rounded-[22px] border border-white/10 bg-slate-950/40 px-4 py-3 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-400" }, "Last Recommendation Refresh"), /* @__PURE__ */ React.createElement("div", { className: "mt-1 font-semibold text-white" }, hooksDiagnostics?.last_recommendation_refresh_at ? new Date(hooksDiagnostics.last_recommendation_refresh_at).toLocaleString() : "Not yet"))), /* @__PURE__ */ React.createElement("div", { className: "mt-5 flex flex-wrap gap-3" }, /* @__PURE__ */ React.createElement("button", { type: "submit", disabled: busy === "hooks" || !selectedCollectionId, className: "inline-flex items-center gap-2 rounded-2xl border border-fuchsia-300/20 bg-fuchsia-400/10 px-5 py-3 text-sm font-semibold text-fuchsia-100 transition hover:bg-fuchsia-400/15 disabled:opacity-60" }, /* @__PURE__ */ React.createElement("i", { className: `fa-solid ${busy === "hooks" ? "fa-circle-notch fa-spin" : "fa-flask-vial"} fa-fw` }), "Save Hooks"), selectedCollection?.manage_url ? /* @__PURE__ */ React.createElement("a", { href: selectedCollection.manage_url, className: "inline-flex items-center gap-2 rounded-2xl border border-white/10 bg-white/[0.04] px-5 py-3 text-sm font-semibold text-white transition hover:bg-white/[0.07]" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-arrow-up-right-from-square fa-fw" }), "Open collection") : null)))), /* @__PURE__ */ React.createElement("section", { className: "mt-8 rounded-[32px] border border-white/10 bg-white/[0.04] p-6 backdrop-blur-sm md:p-7" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.22em] text-sky-200/80" }, "Assignments"), /* @__PURE__ */ React.createElement("h2", { className: "mt-2 text-2xl font-semibold text-white" }, "Current programming inventory")), /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-1 text-xs font-semibold text-slate-300" }, assignments.length)), /* @__PURE__ */ React.createElement("div", { className: "mt-6 space-y-5" }, assignments.length ? assignments.map((assignment) => /* @__PURE__ */ React.createElement("div", { key: assignment.id, className: "rounded-[28px] border border-white/10 bg-slate-950/40 p-5" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center gap-2" }, /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-sky-300/20 bg-sky-400/10 px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.18em] text-sky-100" }, assignment.program_key), assignment.placement_scope ? /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-300" }, assignment.placement_scope) : null, /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-300" }, "priority ", assignment.priority)), /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-2" }, /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => hydrateAssignment(assignment), className: "inline-flex items-center gap-2 rounded-full border border-white/10 bg-white/[0.04] px-4 py-2 text-xs font-semibold text-white transition hover:bg-white/[0.07]" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-pen fa-fw text-[10px]" }), "Edit"), endpoints.managePattern ? /* @__PURE__ */ React.createElement("a", { href: endpoints.managePattern.replace("__COLLECTION__", String(assignment.collection?.id || "")), className: "inline-flex items-center gap-2 rounded-full border border-white/10 bg-white/[0.04] px-4 py-2 text-xs font-semibold text-white transition hover:bg-white/[0.07]" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-arrow-up-right-from-square fa-fw text-[10px]" }), "Manage") : null)), /* @__PURE__ */ React.createElement("div", { className: "mt-4 grid gap-5 xl:grid-cols-[minmax(0,1fr)_280px]" }, /* @__PURE__ */ React.createElement("div", null, assignment.collection ? /* @__PURE__ */ React.createElement(CollectionCard, { collection: assignment.collection, isOwner: true }) : null), /* @__PURE__ */ React.createElement("div", { className: "space-y-3 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("div", { className: "rounded-[22px] border border-white/10 bg-white/[0.04] px-4 py-3" }, "Campaign: ", assignment.campaign_key || "None"), /* @__PURE__ */ React.createElement("div", { className: "rounded-[22px] border border-white/10 bg-white/[0.04] px-4 py-3" }, "Starts: ", assignment.starts_at ? new Date(assignment.starts_at).toLocaleString() : "Immediate"), /* @__PURE__ */ React.createElement("div", { className: "rounded-[22px] border border-white/10 bg-white/[0.04] px-4 py-3" }, "Ends: ", assignment.ends_at ? new Date(assignment.ends_at).toLocaleString() : "Open-ended"), /* @__PURE__ */ React.createElement("div", { className: "rounded-[22px] border border-white/10 bg-white/[0.04] px-4 py-3" }, "Placement: ", assignment.collection?.placement_eligibility ? "Eligible" : "Blocked"), assignment.notes ? /* @__PURE__ */ React.createElement("div", { className: "rounded-[22px] border border-white/10 bg-white/[0.04] px-4 py-3" }, assignment.notes) : null)))) : /* @__PURE__ */ React.createElement("div", { className: "rounded-[26px] border border-dashed border-white/12 bg-white/[0.03] px-6 py-12 text-sm text-slate-300" }, "No programming assignments yet. Create the first one above.")))))); } -const __vite_glob_0_32 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ +const __vite_glob_0_33 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ __proto__: null, default: CollectionStaffProgramming }, Symbol.toStringTag, { value: "Module" })); @@ -68337,7 +72135,7 @@ function CollectionStaffSurfaces() { return /* @__PURE__ */ React.createElement("label", { key: option.id, className: `flex cursor-pointer items-start gap-3 rounded-[22px] border px-4 py-3 transition ${checked ? "border-lime-300/30 bg-lime-400/10" : "border-white/10 bg-white/[0.04] hover:bg-white/[0.07]"}` }, /* @__PURE__ */ React.createElement(Checkbox, { checked, onChange: () => toggleBatchCollection(option.id) }), /* @__PURE__ */ React.createElement("span", { className: "min-w-0" }, /* @__PURE__ */ React.createElement("span", { className: "block truncate text-sm font-semibold text-white" }, option.title), /* @__PURE__ */ React.createElement("span", { className: "mt-1 block text-xs text-slate-400" }, option.type || "collection", " · ", option.visibility || "public"))); }))), /* @__PURE__ */ React.createElement("div", { className: "rounded-[26px] border border-white/10 bg-slate-950/40 p-5" }, /* @__PURE__ */ React.createElement("p", { className: "text-sm font-semibold text-white" }, "Campaign metadata"), /* @__PURE__ */ React.createElement("div", { className: "mt-4 grid gap-4 md:grid-cols-2" }, /* @__PURE__ */ React.createElement(Field, { label: "Campaign Key" }, /* @__PURE__ */ React.createElement("input", { value: batchForm.campaign_key, onChange: (event) => setBatchForm((current) => ({ ...current, campaign_key: event.target.value })), className: "w-full rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3 text-white outline-none", maxLength: 80 })), /* @__PURE__ */ React.createElement(Field, { label: "Campaign Label" }, /* @__PURE__ */ React.createElement("input", { value: batchForm.campaign_label, onChange: (event) => setBatchForm((current) => ({ ...current, campaign_label: event.target.value })), className: "w-full rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3 text-white outline-none", maxLength: 120 })), /* @__PURE__ */ React.createElement(Field, { label: "Event Label" }, /* @__PURE__ */ React.createElement("input", { value: batchForm.event_label, onChange: (event) => setBatchForm((current) => ({ ...current, event_label: event.target.value })), className: "w-full rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3 text-white outline-none", maxLength: 120 })), /* @__PURE__ */ React.createElement(Field, { label: "Season Key" }, /* @__PURE__ */ React.createElement("input", { value: batchForm.season_key, onChange: (event) => setBatchForm((current) => ({ ...current, season_key: event.target.value })), className: "w-full rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3 text-white outline-none", maxLength: 80 }))), /* @__PURE__ */ React.createElement(Field, { label: "Editorial Notes", help: "Shared context recorded on each selected collection." }, /* @__PURE__ */ React.createElement("textarea", { value: batchForm.editorial_notes, onChange: (event) => setBatchForm((current) => ({ ...current, editorial_notes: event.target.value })), className: "mt-4 min-h-[120px] w-full rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3 text-white outline-none", maxLength: 4e3 })))), /* @__PURE__ */ React.createElement("div", { className: "space-y-4" }, /* @__PURE__ */ React.createElement("div", { className: "rounded-[26px] border border-white/10 bg-slate-950/40 p-5" }, /* @__PURE__ */ React.createElement("p", { className: "text-sm font-semibold text-white" }, "Optional placement plan"), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm text-slate-300" }, "If you set a surface, the preview shows which collections can safely be placed and which ones will be skipped."), /* @__PURE__ */ React.createElement("div", { className: "mt-4 grid gap-4 md:grid-cols-2" }, /* @__PURE__ */ React.createElement(Field, { label: "Surface" }, /* @__PURE__ */ React.createElement(NovaSelect, { value: batchForm.surface_key, onChange: (val) => setBatchForm((current) => ({ ...current, surface_key: val })), placeholder: "No placement", options: surfaceKeyOptions.map((o) => ({ value: o, label: o })) })), /* @__PURE__ */ React.createElement(Field, { label: "Placement Type" }, /* @__PURE__ */ React.createElement(NovaSelect, { value: batchForm.placement_type, onChange: (val) => setBatchForm((current) => ({ ...current, placement_type: val })), searchable: false, options: [{ value: "campaign", label: "Campaign" }, { value: "manual", label: "Manual" }, { value: "scheduled_override", label: "Scheduled override" }] })), /* @__PURE__ */ React.createElement(Field, { label: "Priority" }, /* @__PURE__ */ React.createElement("input", { type: "number", min: "-100", max: "100", value: batchForm.priority, onChange: (event) => setBatchForm((current) => ({ ...current, priority: event.target.value })), className: "w-full rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3 text-white outline-none" })), /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-3 rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3 text-sm text-white" }, /* @__PURE__ */ React.createElement(Checkbox, { checked: batchForm.is_active, onChange: (event) => setBatchForm((current) => ({ ...current, is_active: event.target.checked })), label: "Active placement" })), /* @__PURE__ */ React.createElement(Field, { label: "Starts At" }, /* @__PURE__ */ React.createElement(DateTimePicker, { value: batchForm.starts_at, onChange: (nextValue) => setBatchForm((current) => ({ ...current, starts_at: nextValue })), placeholder: "Start time", clearable: true, className: "bg-white/[0.04]" })), /* @__PURE__ */ React.createElement(Field, { label: "Ends At" }, /* @__PURE__ */ React.createElement(DateTimePicker, { value: batchForm.ends_at, onChange: (nextValue) => setBatchForm((current) => ({ ...current, ends_at: nextValue })), placeholder: "End time", clearable: true, className: "bg-white/[0.04]" }))), /* @__PURE__ */ React.createElement(Field, { label: "Placement Notes" }, /* @__PURE__ */ React.createElement("textarea", { value: batchForm.notes, onChange: (event) => setBatchForm((current) => ({ ...current, notes: event.target.value })), className: "mt-4 min-h-[110px] w-full rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-3 text-white outline-none", maxLength: 1e3 })), /* @__PURE__ */ React.createElement("div", { className: "mt-5 flex flex-wrap gap-3" }, /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => handleBatchEditorial("preview"), disabled: busy === "batch-preview", className: "inline-flex items-center gap-2 rounded-2xl border border-lime-300/20 bg-lime-400/10 px-5 py-3 text-sm font-semibold text-lime-100 transition hover:bg-lime-400/15 disabled:opacity-60" }, /* @__PURE__ */ React.createElement("i", { className: `fa-solid ${busy === "batch-preview" ? "fa-circle-notch fa-spin" : "fa-flask"} fa-fw` }), "Preview Batch"), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => handleBatchEditorial("apply"), disabled: busy === "batch-apply", className: "inline-flex items-center gap-2 rounded-2xl border border-amber-300/20 bg-amber-400/10 px-5 py-3 text-sm font-semibold text-amber-100 transition hover:bg-amber-400/15 disabled:opacity-60" }, /* @__PURE__ */ React.createElement("i", { className: `fa-solid ${busy === "batch-apply" ? "fa-circle-notch fa-spin" : "fa-wand-magic-sparkles"} fa-fw` }), "Apply Batch"))), batchResult ? /* @__PURE__ */ React.createElement("div", { className: "rounded-[26px] border border-white/10 bg-slate-950/40 p-5" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-sm font-semibold text-white" }, "Preview results"), /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-sm text-slate-300" }, batchResult.collections_count, " collections reviewed, ", batchResult.placement_eligible_count, " placement-ready."))), /* @__PURE__ */ React.createElement("div", { className: "mt-4 space-y-3" }, (batchResult.items || []).map((item) => /* @__PURE__ */ React.createElement("div", { key: item.collection?.id, className: "rounded-[22px] border border-white/10 bg-white/[0.04] p-4" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-sm font-semibold text-white" }, item.collection?.title), /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-xs text-slate-400" }, item.collection?.visibility, " · ", item.collection?.lifecycle_state, " · ", item.collection?.moderation_status)), item.placement ? /* @__PURE__ */ React.createElement("span", { className: `rounded-full border px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.18em] ${item.placement.eligible ? "border-lime-300/20 bg-lime-400/10 text-lime-100" : "border-rose-300/20 bg-rose-400/10 text-rose-100"}` }, item.placement.eligible ? `ready for ${item.placement.surface_key}` : "placement skipped") : /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-300" }, "metadata only")), item.eligibility?.reasons?.length ? /* @__PURE__ */ React.createElement("p", { className: "mt-3 text-xs text-amber-100/80" }, "Campaign readiness: ", item.eligibility.reasons.join(" ")) : null, item.placement?.reasons?.length ? /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-xs text-rose-100/80" }, "Placement: ", item.placement.reasons.join(" ")) : null)))) : null))), /* @__PURE__ */ React.createElement("section", { className: "mt-8 rounded-[32px] border border-white/10 bg-white/[0.04] p-6 backdrop-blur-sm md:p-7" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.22em] text-sky-200/80" }, "Definitions"), /* @__PURE__ */ React.createElement("h2", { className: "mt-2 text-2xl font-semibold text-white" }, "Registered surfaces")), /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-1 text-xs font-semibold text-slate-300" }, definitions.length)), /* @__PURE__ */ React.createElement("div", { className: "mt-6 grid gap-4 lg:grid-cols-2" }, definitions.map((definition2) => /* @__PURE__ */ React.createElement("div", { key: definition2.id, className: "rounded-[24px] border border-white/10 bg-slate-950/40 p-5" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center gap-2" }, /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-sky-300/20 bg-sky-400/10 px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.18em] text-sky-100" }, definition2.surface_key), /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-300" }, definition2.mode)), /* @__PURE__ */ React.createElement("h3", { className: "mt-4 text-lg font-semibold text-white" }, definition2.title), definition2.description ? /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm text-slate-300" }, definition2.description) : null, /* @__PURE__ */ React.createElement("div", { className: "mt-4 flex flex-wrap gap-2 text-xs text-slate-400" }, /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-1" }, definition2.ranking_mode), /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-1" }, "max ", definition2.max_items), /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-1" }, definition2.is_active ? "active" : "inactive"), definition2.starts_at ? /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-1" }, "starts ", new Date(definition2.starts_at).toLocaleString()) : null, definition2.ends_at ? /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-1" }, "ends ", new Date(definition2.ends_at).toLocaleString()) : null, definition2.fallback_surface_key ? /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-1" }, "fallback ", definition2.fallback_surface_key) : null), /* @__PURE__ */ React.createElement("div", { className: "mt-4" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-2" }, /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => hydrateDefinition(definition2), className: "inline-flex items-center gap-2 rounded-full border border-white/10 bg-white/[0.04] px-4 py-2 text-xs font-semibold text-white transition hover:bg-white/[0.07]" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-pen fa-fw text-[10px]" }), "Edit Definition"), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => handleDeleteDefinition(definition2), disabled: busy === `delete-definition-${definition2.id}`, className: "inline-flex items-center gap-2 rounded-full border border-rose-300/20 bg-rose-400/10 px-4 py-2 text-xs font-semibold text-rose-100 transition hover:bg-rose-400/15 disabled:opacity-60" }, /* @__PURE__ */ React.createElement("i", { className: `fa-solid ${busy === `delete-definition-${definition2.id}` ? "fa-circle-notch fa-spin" : "fa-trash"} fa-fw text-[10px]` }), "Delete"))))))), conflicts.length ? /* @__PURE__ */ React.createElement("section", { className: "mt-8 rounded-[32px] border border-rose-300/20 bg-rose-500/10 p-6 backdrop-blur-sm md:p-7" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.22em] text-rose-100/80" }, "Conflicts"), /* @__PURE__ */ React.createElement("h2", { className: "mt-2 text-2xl font-semibold text-white" }, "Schedule overlaps need review")), /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-rose-300/20 bg-rose-400/10 px-3 py-1 text-xs font-semibold text-rose-100" }, conflicts.length)), /* @__PURE__ */ React.createElement("div", { className: "mt-6 grid gap-4 lg:grid-cols-2" }, conflicts.map((conflict, index2) => /* @__PURE__ */ React.createElement("div", { key: `${conflict.surface_key}-${index2}`, className: "rounded-[24px] border border-rose-300/20 bg-slate-950/40 p-5" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center gap-2" }, /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-rose-300/20 bg-rose-400/10 px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.18em] text-rose-100" }, conflict.surface_key)), /* @__PURE__ */ React.createElement("p", { className: "mt-4 text-sm text-rose-50" }, conflict.summary), /* @__PURE__ */ React.createElement("p", { className: "mt-3 text-xs text-rose-100/70" }, "Window: ", conflict.window?.starts_at ? new Date(conflict.window.starts_at).toLocaleString() : "Immediate", " to ", conflict.window?.ends_at ? new Date(conflict.window.ends_at).toLocaleString() : "Open-ended"))))) : null, /* @__PURE__ */ React.createElement("section", { className: "mt-8 rounded-[32px] border border-white/10 bg-white/[0.04] p-6 backdrop-blur-sm md:p-7" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.22em] text-amber-200/80" }, "Placements"), /* @__PURE__ */ React.createElement("h2", { className: "mt-2 text-2xl font-semibold text-white" }, "Active and scheduled slots")), /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-1 text-xs font-semibold text-slate-300" }, placements.length)), /* @__PURE__ */ React.createElement("div", { className: "mt-6 space-y-5" }, placements.map((placement) => /* @__PURE__ */ React.createElement("div", { key: placement.id, className: "rounded-[28px] border border-white/10 bg-slate-950/40 p-5" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center gap-2" }, /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-amber-300/20 bg-amber-400/10 px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.18em] text-amber-100" }, placement.surface_key), /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-300" }, placement.placement_type), /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-300" }, "priority ", placement.priority), conflictPlacementIds.has(placement.id) || placement.has_conflict ? /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-rose-300/20 bg-rose-400/10 px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.18em] text-rose-100" }, "conflict") : null), /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-2" }, /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => hydratePlacement(placement), className: "inline-flex items-center gap-2 rounded-full border border-white/10 bg-white/[0.04] px-4 py-2 text-xs font-semibold text-white transition hover:bg-white/[0.07]" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-pen fa-fw text-[10px]" }), "Edit"), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => handleDeletePlacement(placement), disabled: busy === `delete-placement-${placement.id}`, className: "inline-flex items-center gap-2 rounded-full border border-rose-300/20 bg-rose-400/10 px-4 py-2 text-xs font-semibold text-rose-100 transition hover:bg-rose-400/15 disabled:opacity-60" }, /* @__PURE__ */ React.createElement("i", { className: `fa-solid ${busy === `delete-placement-${placement.id}` ? "fa-circle-notch fa-spin" : "fa-trash"} fa-fw text-[10px]` }), "Delete"))), /* @__PURE__ */ React.createElement("div", { className: "mt-4 grid gap-5 xl:grid-cols-[minmax(0,1fr)_280px]" }, /* @__PURE__ */ React.createElement("div", null, placement.collection ? /* @__PURE__ */ React.createElement(CollectionCard, { collection: placement.collection, isOwner: true }) : null), /* @__PURE__ */ React.createElement("div", { className: "space-y-3 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("div", { className: "rounded-[22px] border border-white/10 bg-white/[0.04] px-4 py-3" }, "Starts: ", placement.starts_at ? new Date(placement.starts_at).toLocaleString() : "Immediate"), /* @__PURE__ */ React.createElement("div", { className: "rounded-[22px] border border-white/10 bg-white/[0.04] px-4 py-3" }, "Ends: ", placement.ends_at ? new Date(placement.ends_at).toLocaleString() : "Open-ended"), /* @__PURE__ */ React.createElement("div", { className: "rounded-[22px] border border-white/10 bg-white/[0.04] px-4 py-3" }, "Campaign: ", placement.campaign_key || "None"), /* @__PURE__ */ React.createElement("div", { className: "rounded-[22px] border border-white/10 bg-white/[0.04] px-4 py-3" }, "Status: ", placement.is_active ? "Active" : "Inactive"), placement.notes ? /* @__PURE__ */ React.createElement("div", { className: "rounded-[22px] border border-white/10 bg-white/[0.04] px-4 py-3 text-slate-300" }, placement.notes) : null))))))))); } -const __vite_glob_0_33 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ +const __vite_glob_0_34 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ __proto__: null, default: CollectionStaffSurfaces }, Symbol.toStringTag, { value: "Module" })); @@ -68906,7 +72704,7 @@ function NovaCardsAdminIndex() { } )), /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between rounded-2xl border border-white/10 bg-white/[0.03] px-4 py-3 text-sm text-slate-200" }, /* @__PURE__ */ React.createElement("span", null, "Featured"), /* @__PURE__ */ React.createElement(Checkbox, { checked: Boolean(card.featured), onChange: (event) => updateCard(card.id, { featured: event.target.checked }) })), /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between rounded-2xl border border-white/10 bg-white/[0.03] px-4 py-3 text-sm text-slate-200" }, /* @__PURE__ */ React.createElement("span", null, "Allow remix"), /* @__PURE__ */ React.createElement(Checkbox, { checked: Boolean(card.allow_remix), onChange: (event) => updateCard(card.id, { allow_remix: event.target.checked }) }))), /* @__PURE__ */ React.createElement("div", { className: "mt-4 grid gap-3 md:grid-cols-4 text-xs text-slate-400" }, /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-white/[0.03] px-4 py-3" }, card.likes_count || 0, " likes"), /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-white/[0.03] px-4 py-3" }, card.saves_count || 0, " saves"), /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-white/[0.03] px-4 py-3" }, card.remixes_count || 0, " remixes"), /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-white/[0.03] px-4 py-3" }, card.challenge_entries_count || 0, " challenge entries")), card.moderation_reason_labels?.length ? /* @__PURE__ */ React.createElement("div", { className: "mt-4 rounded-2xl border border-amber-300/15 bg-amber-400/10 px-4 py-3 text-sm text-amber-50" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-amber-100/80" }, "Heuristic moderation flags"), /* @__PURE__ */ React.createElement("div", { className: "mt-2 flex flex-wrap gap-2" }, card.moderation_reason_labels.map((label) => /* @__PURE__ */ React.createElement("span", { key: `${card.id}-${label}`, className: "rounded-full border border-amber-200/20 bg-amber-50/10 px-3 py-1 text-[10px] font-semibold uppercase tracking-[0.14em] text-amber-50" }, label))), card.moderation_source ? /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-[11px] uppercase tracking-[0.14em] text-amber-100/70" }, "Source ", String(card.moderation_source).replaceAll("_", " ")) : null) : null, card.moderation_override ? /* @__PURE__ */ React.createElement("div", { className: "mt-4 rounded-2xl border border-sky-300/15 bg-sky-400/10 px-4 py-3 text-sm text-sky-50" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-sky-100/80" }, "Latest staff override"), /* @__PURE__ */ React.createElement("div", { className: "mt-2 flex flex-wrap gap-2 text-xs uppercase tracking-[0.14em] text-sky-100/80" }, /* @__PURE__ */ React.createElement("span", null, "Status ", card.moderation_override.moderation_status), card.moderation_override.disposition_label ? /* @__PURE__ */ React.createElement("span", null, card.moderation_override.disposition_label) : null, card.moderation_override.actor_username ? /* @__PURE__ */ React.createElement("span", null, "@", card.moderation_override.actor_username) : null, card.moderation_override.source ? /* @__PURE__ */ React.createElement("span", null, String(card.moderation_override.source).replaceAll("_", " ")) : null), card.moderation_override.note ? /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-sm leading-6 text-sky-50" }, card.moderation_override.note) : null) : null, card.moderation_override_history?.length > 1 ? /* @__PURE__ */ React.createElement("div", { className: "mt-4 rounded-2xl border border-sky-300/10 bg-sky-400/[0.08] px-4 py-3 text-sm text-sky-50" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-sky-100/75" }, "Recent override history"), /* @__PURE__ */ React.createElement("div", { className: "mt-3 space-y-2" }, renderOverrideHistoryItems(card.moderation_override_history, `card-${card.id}`))) : null))))), /* @__PURE__ */ React.createElement("div", { className: "space-y-6" }, /* @__PURE__ */ React.createElement("section", { className: "rounded-[28px] border border-white/10 bg-white/[0.04] p-5 shadow-[0_20px_50px_rgba(2,6,23,0.18)]" }, /* @__PURE__ */ React.createElement("div", { className: "mb-4 text-sm font-semibold uppercase tracking-[0.2em] text-slate-400" }, "Creator curation"), !featuredCreators.length ? /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-white/[0.03] px-4 py-4 text-sm text-slate-400" }, "No public Nova creators are available for curation yet.") : null, /* @__PURE__ */ React.createElement("div", { className: "space-y-3" }, featuredCreators.map((creator) => /* @__PURE__ */ React.createElement("div", { key: creator.id, className: "rounded-2xl border border-white/10 bg-white/[0.03] p-4" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-start justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "font-semibold text-white" }, creator.display_name), /* @__PURE__ */ React.createElement("div", { className: "text-xs uppercase tracking-[0.18em] text-slate-500" }, "@", creator.username)), creator.public_url ? /* @__PURE__ */ React.createElement("a", { href: creator.public_url, className: "text-xs font-semibold uppercase tracking-[0.16em] text-sky-300 transition hover:text-sky-200" }, "Open profile") : null), /* @__PURE__ */ React.createElement("div", { className: "mt-3 grid grid-cols-3 gap-2 text-xs text-slate-300" }, /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-[#08111f]/70 px-3 py-3" }, creator.public_cards_count || 0, " public cards"), /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-[#08111f]/70 px-3 py-3" }, creator.featured_cards_count || 0, " featured"), /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-[#08111f]/70 px-3 py-3" }, creator.total_views_count || 0, " views")), /* @__PURE__ */ React.createElement("div", { className: "mt-3 flex items-center justify-between rounded-2xl border border-white/10 bg-white/[0.03] px-4 py-3 text-sm text-slate-200" }, /* @__PURE__ */ React.createElement("span", null, "Feature on editorial page"), /* @__PURE__ */ React.createElement(Checkbox, { checked: Boolean(creator.nova_featured_creator), onChange: (event) => updateCreator(creator.id, { nova_featured_creator: event.target.checked }) })))))), /* @__PURE__ */ React.createElement("section", { className: "rounded-[28px] border border-white/10 bg-white/[0.04] p-5 shadow-[0_20px_50px_rgba(2,6,23,0.18)]" }, /* @__PURE__ */ React.createElement("div", { className: "mb-4 text-sm font-semibold uppercase tracking-[0.2em] text-slate-400" }, "Categories"), /* @__PURE__ */ React.createElement("div", { className: "space-y-3" }, categories.map((category) => /* @__PURE__ */ React.createElement("div", { key: category.id, className: "rounded-2xl border border-white/10 bg-white/[0.03] p-4" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "font-semibold text-white" }, category.name), /* @__PURE__ */ React.createElement("div", { className: "text-xs uppercase tracking-[0.18em] text-slate-500" }, category.slug, " • ", category.cards_count, " cards")), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => saveCategory(category), className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-1 text-xs font-semibold uppercase tracking-[0.16em] text-white transition hover:bg-white/[0.08]" }, "Save")))))), /* @__PURE__ */ React.createElement("section", { className: "rounded-[28px] border border-white/10 bg-white/[0.04] p-5 shadow-[0_20px_50px_rgba(2,6,23,0.18)]" }, /* @__PURE__ */ React.createElement("div", { className: "mb-4 text-sm font-semibold uppercase tracking-[0.2em] text-slate-400" }, "Add category"), /* @__PURE__ */ React.createElement("div", { className: "space-y-3" }, /* @__PURE__ */ React.createElement("input", { value: newCategory.name, onChange: (event) => setNewCategory((current) => ({ ...current, name: event.target.value })), placeholder: "Name", className: "w-full rounded-2xl border border-white/10 bg-[#0d1726] px-4 py-3 text-white" }), /* @__PURE__ */ React.createElement("input", { value: newCategory.slug, onChange: (event) => setNewCategory((current) => ({ ...current, slug: event.target.value })), placeholder: "Slug", className: "w-full rounded-2xl border border-white/10 bg-[#0d1726] px-4 py-3 text-white" }), /* @__PURE__ */ React.createElement("textarea", { value: newCategory.description, onChange: (event) => setNewCategory((current) => ({ ...current, description: event.target.value })), placeholder: "Description", rows: 3, className: "w-full rounded-2xl border border-white/10 bg-[#0d1726] px-4 py-3 text-white" }), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => saveCategory(newCategory), className: "w-full rounded-2xl border border-sky-300/20 bg-sky-400/10 px-4 py-3 text-sm font-semibold text-sky-100 transition hover:bg-sky-400/15" }, "Create category")))))); } -const __vite_glob_0_35 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ +const __vite_glob_0_36 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ __proto__: null, default: NovaCardsAdminIndex }, Symbol.toStringTag, { value: "Module" })); @@ -68969,7 +72767,7 @@ function NovaCardsAssetPackAdmin() { } }, rows: 10, className: "rounded-2xl border border-white/10 bg-[#0d1726] px-4 py-3 font-mono text-sm text-white md:col-span-2" })), /* @__PURE__ */ React.createElement("div", { className: "mt-5 flex items-center justify-between gap-3 rounded-2xl border border-white/10 bg-white/[0.03] px-4 py-3 text-sm text-slate-200" }, /* @__PURE__ */ React.createElement(Checkbox, { checked: Boolean(form.active), onChange: (event) => setForm((current) => ({ ...current, active: event.target.checked })), label: "Active" }), /* @__PURE__ */ React.createElement(Checkbox, { checked: Boolean(form.official), onChange: (event) => setForm((current) => ({ ...current, official: event.target.checked })), label: "Official" })), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: savePack, className: "mt-5 w-full rounded-2xl border border-sky-300/20 bg-sky-400/10 px-4 py-3 text-sm font-semibold text-sky-100 transition hover:bg-sky-400/15" }, selectedId ? "Update pack" : "Create pack")))); } -const __vite_glob_0_36 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ +const __vite_glob_0_37 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ __proto__: null, default: NovaCardsAssetPackAdmin }, Symbol.toStringTag, { value: "Module" })); @@ -69035,7 +72833,7 @@ function NovaCardsChallengeAdmin() { } }, rows: 10, className: "rounded-2xl border border-white/10 bg-[#0d1726] px-4 py-3 font-mono text-sm text-white md:col-span-2" })), /* @__PURE__ */ React.createElement("div", { className: "mt-5 flex items-center justify-between gap-3 rounded-2xl border border-white/10 bg-white/[0.03] px-4 py-3 text-sm text-slate-200" }, /* @__PURE__ */ React.createElement(Checkbox, { checked: Boolean(form.official), onChange: (event) => setForm((current) => ({ ...current, official: event.target.checked })), label: "Official" }), /* @__PURE__ */ React.createElement(Checkbox, { checked: Boolean(form.featured), onChange: (event) => setForm((current) => ({ ...current, featured: event.target.checked })), label: "Featured" })), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: saveChallenge, className: "mt-5 w-full rounded-2xl border border-sky-300/20 bg-sky-400/10 px-4 py-3 text-sm font-semibold text-sky-100 transition hover:bg-sky-400/15" }, selectedId ? "Update challenge" : "Create challenge")))); } -const __vite_glob_0_37 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ +const __vite_glob_0_38 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ __proto__: null, default: NovaCardsChallengeAdmin }, Symbol.toStringTag, { value: "Module" })); @@ -69120,7 +72918,7 @@ function NovaCardsCollectionAdmin() { } return /* @__PURE__ */ React.createElement("div", { className: "mx-auto max-w-7xl px-4 pb-20 pt-8 sm:px-6 lg:px-8" }, /* @__PURE__ */ React.createElement(Se, { title: "Nova Cards Collections" }), /* @__PURE__ */ React.createElement("section", { className: "rounded-[32px] border border-white/10 bg-[radial-gradient(circle_at_top_left,rgba(56,189,248,0.14),transparent_38%),linear-gradient(180deg,rgba(15,23,42,0.96),rgba(2,6,23,0.88))] p-6 shadow-[0_24px_70px_rgba(2,6,23,0.32)]" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-col gap-4 lg:flex-row lg:items-end lg:justify-between" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.28em] text-sky-200/75" }, "Editorial layer"), /* @__PURE__ */ React.createElement("h1", { className: "mt-3 text-3xl font-semibold tracking-[-0.04em] text-white" }, "Official and public card collections"), /* @__PURE__ */ React.createElement("p", { className: "mt-3 max-w-3xl text-sm leading-7 text-slate-300" }, "Create editorial collections, assign owners, and curate the public card sets that the v2 browse surface links to.")), /* @__PURE__ */ React.createElement("div", { className: "flex gap-3" }, /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => setSelectedId(null), className: "rounded-2xl border border-white/10 bg-white/[0.05] px-5 py-3 text-sm font-semibold text-white transition hover:bg-white/[0.08]" }, "New collection"), /* @__PURE__ */ React.createElement(xe, { href: endpoints.cards || "/cp/cards", className: "rounded-2xl border border-white/10 bg-white/[0.05] px-5 py-3 text-sm font-semibold text-white transition hover:bg-white/[0.08]" }, "Back to cards")))), /* @__PURE__ */ React.createElement("div", { className: "mt-8 grid gap-6 xl:grid-cols-[minmax(0,0.9fr)_minmax(0,1.1fr)]" }, /* @__PURE__ */ React.createElement("section", { className: "rounded-[28px] border border-white/10 bg-white/[0.04] p-5 shadow-[0_20px_50px_rgba(2,6,23,0.18)]" }, /* @__PURE__ */ React.createElement("div", { className: "mb-4 text-sm font-semibold uppercase tracking-[0.2em] text-slate-400" }, "Collections"), /* @__PURE__ */ React.createElement("div", { className: "space-y-3" }, collections.map((collection) => /* @__PURE__ */ React.createElement("button", { key: collection.id, type: "button", onClick: () => setSelectedId(collection.id), className: `w-full rounded-[22px] border p-4 text-left transition ${selectedId === collection.id ? "border-sky-300/35 bg-sky-400/10" : "border-white/10 bg-white/[0.03] hover:border-white/20 hover:bg-white/[0.05]"}` }, /* @__PURE__ */ React.createElement("div", { className: "flex items-start justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "text-base font-semibold tracking-[-0.03em] text-white" }, collection.name), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-xs uppercase tracking-[0.18em] text-slate-500" }, collection.featured ? "Featured • " : "", collection.official ? "Official" : "@" + (collection.owner?.username || "creator"))), /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.04] px-2.5 py-1 text-[10px] font-semibold uppercase tracking-[0.16em] text-slate-200" }, collection.cards_count, " cards")), collection.description ? /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-sm text-slate-400" }, collection.description) : null)))), /* @__PURE__ */ React.createElement("section", { className: "space-y-6" }, /* @__PURE__ */ React.createElement("div", { className: "rounded-[28px] border border-white/10 bg-white/[0.04] p-5 shadow-[0_20px_50px_rgba(2,6,23,0.18)]" }, /* @__PURE__ */ React.createElement("div", { className: "mb-4 text-sm font-semibold uppercase tracking-[0.2em] text-slate-400" }, "Collection editor"), /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 md:grid-cols-2" }, /* @__PURE__ */ React.createElement("div", { className: "text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "mb-2 block" }, "Owner"), /* @__PURE__ */ React.createElement(NovaSelect, { value: form.user_id, onChange: (val) => setForm((current) => ({ ...current, user_id: Number(val) })), options: admins.map((a) => ({ value: a.id, label: a.name || a.username })) })), /* @__PURE__ */ React.createElement("div", { className: "text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "mb-2 block" }, "Visibility"), /* @__PURE__ */ React.createElement(NovaSelect, { value: form.visibility, onChange: (val) => setForm((current) => ({ ...current, visibility: val })), searchable: false, options: [{ value: "public", label: "public" }, { value: "private", label: "private" }] })), /* @__PURE__ */ React.createElement("input", { value: form.name, onChange: (event) => setForm((current) => ({ ...current, name: event.target.value })), placeholder: "Collection name", className: "rounded-2xl border border-white/10 bg-[#0d1726] px-4 py-3 text-white" }), /* @__PURE__ */ React.createElement("input", { value: form.slug, onChange: (event) => setForm((current) => ({ ...current, slug: event.target.value })), placeholder: "Slug", className: "rounded-2xl border border-white/10 bg-[#0d1726] px-4 py-3 text-white" }), /* @__PURE__ */ React.createElement("textarea", { value: form.description, onChange: (event) => setForm((current) => ({ ...current, description: event.target.value })), placeholder: "Description", rows: 4, className: "rounded-2xl border border-white/10 bg-[#0d1726] px-4 py-3 text-white md:col-span-2" })), /* @__PURE__ */ React.createElement("div", { className: "mt-5 flex items-center justify-between gap-3 rounded-2xl border border-white/10 bg-white/[0.03] px-4 py-3 text-sm text-slate-200" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center gap-4" }, /* @__PURE__ */ React.createElement(Checkbox, { checked: Boolean(form.official), onChange: (event) => setForm((current) => ({ ...current, official: event.target.checked })), label: "Official collection" }), /* @__PURE__ */ React.createElement(Checkbox, { checked: Boolean(form.featured), onChange: (event) => setForm((current) => ({ ...current, featured: event.target.checked })), label: "Featured collection" })), selected?.public_url ? /* @__PURE__ */ React.createElement("a", { href: selected.public_url, className: "text-sky-100 transition hover:text-white", target: "_blank", rel: "noreferrer" }, "Open public page") : null), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: saveCollection, className: "mt-5 w-full rounded-2xl border border-sky-300/20 bg-sky-400/10 px-4 py-3 text-sm font-semibold text-sky-100 transition hover:bg-sky-400/15" }, selectedId ? "Update collection" : "Create collection")), /* @__PURE__ */ React.createElement("div", { className: "rounded-[28px] border border-white/10 bg-white/[0.04] p-5 shadow-[0_20px_50px_rgba(2,6,23,0.18)]" }, /* @__PURE__ */ React.createElement("div", { className: "mb-4 text-sm font-semibold uppercase tracking-[0.2em] text-slate-400" }, "Curate cards"), !selectedId ? /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-dashed border-white/12 bg-white/[0.03] px-4 py-8 text-center text-sm text-slate-400" }, "Create or select a collection first.") : /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 md:grid-cols-[minmax(0,1fr)_minmax(0,1fr)_auto]" }, /* @__PURE__ */ React.createElement(NovaSelect, { value: String(cardId || ""), onChange: (val) => setCardId(val), placeholder: "Select a card", options: cards.map((c) => ({ value: String(c.id), label: c.title })) }), /* @__PURE__ */ React.createElement("input", { value: cardNote, onChange: (event) => setCardNote(event.target.value), placeholder: "Optional curator note", className: "rounded-2xl border border-white/10 bg-[#0d1726] px-4 py-3 text-white" }), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: attachCard, className: "rounded-2xl border border-sky-300/20 bg-sky-400/10 px-4 py-3 text-sm font-semibold text-sky-100 transition hover:bg-sky-400/15" }, "Add")), /* @__PURE__ */ React.createElement("div", { className: "mt-5 space-y-3" }, (selected?.items || []).map((item) => /* @__PURE__ */ React.createElement("div", { key: item.id, className: "flex items-start justify-between gap-4 rounded-[22px] border border-white/10 bg-white/[0.03] p-4" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "text-base font-semibold text-white" }, item.card?.title), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-xs uppercase tracking-[0.18em] text-slate-500" }, "#", item.sort_order, " ", item.card?.creator?.username ? `• @${item.card.creator.username}` : ""), item.note ? /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-sm text-slate-400" }, item.note) : null), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => detachCard(selectedId, item.card.id), className: "rounded-2xl border border-rose-300/20 bg-rose-400/10 px-4 py-3 text-sm font-semibold text-rose-100 transition hover:bg-rose-400/15" }, "Remove"))))))))); } -const __vite_glob_0_38 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ +const __vite_glob_0_39 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ __proto__: null, default: NovaCardsCollectionAdmin }, Symbol.toStringTag, { value: "Module" })); @@ -69225,7 +73023,7 @@ function NovaCardsTemplateAdmin() { } return /* @__PURE__ */ React.createElement("div", { className: "mx-auto max-w-7xl px-4 pb-20 pt-8 sm:px-6 lg:px-8" }, /* @__PURE__ */ React.createElement(Se, { title: "Nova Cards Templates" }), /* @__PURE__ */ React.createElement("section", { className: "rounded-[32px] border border-white/10 bg-[radial-gradient(circle_at_top_left,rgba(56,189,248,0.14),transparent_38%),linear-gradient(180deg,rgba(15,23,42,0.96),rgba(2,6,23,0.88))] p-6 shadow-[0_24px_70px_rgba(2,6,23,0.32)]" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-col gap-4 lg:flex-row lg:items-end lg:justify-between" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.28em] text-sky-200/75" }, "Template system"), /* @__PURE__ */ React.createElement("h1", { className: "mt-3 text-3xl font-semibold tracking-[-0.04em] text-white" }, "Official Nova Cards templates"), /* @__PURE__ */ React.createElement("p", { className: "mt-3 max-w-3xl text-sm leading-7 text-slate-300" }, "Keep starter templates config-driven so the editor and render pipeline stay aligned as new card styles ship.")), /* @__PURE__ */ React.createElement("div", { className: "flex gap-3" }, /* @__PURE__ */ React.createElement("button", { type: "button", onClick: resetForm, className: "rounded-2xl border border-white/10 bg-white/[0.05] px-5 py-3 text-sm font-semibold text-white transition hover:bg-white/[0.08]" }, "New template"), /* @__PURE__ */ React.createElement(xe, { href: endpoints.cards || "/cp/cards", className: "rounded-2xl border border-white/10 bg-white/[0.05] px-5 py-3 text-sm font-semibold text-white transition hover:bg-white/[0.08]" }, "Back to cards")))), /* @__PURE__ */ React.createElement("div", { className: "mt-8 grid gap-6 xl:grid-cols-[minmax(0,1.1fr)_minmax(0,1.4fr)]" }, /* @__PURE__ */ React.createElement("section", { className: "rounded-[28px] border border-white/10 bg-white/[0.04] p-5 shadow-[0_20px_50px_rgba(2,6,23,0.18)]" }, /* @__PURE__ */ React.createElement("div", { className: "mb-4 text-sm font-semibold uppercase tracking-[0.2em] text-slate-400" }, "Existing templates"), /* @__PURE__ */ React.createElement("div", { className: "space-y-3" }, templates.map((template) => /* @__PURE__ */ React.createElement("button", { key: template.id, type: "button", onClick: () => loadTemplate(template), className: `w-full rounded-[22px] border p-4 text-left transition ${selectedId === template.id ? "border-sky-300/35 bg-sky-400/10" : "border-white/10 bg-white/[0.03] hover:border-white/20 hover:bg-white/[0.05]"}` }, /* @__PURE__ */ React.createElement("div", { className: "flex items-start justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "text-base font-semibold tracking-[-0.03em] text-white" }, template.name), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-xs uppercase tracking-[0.18em] text-slate-500" }, template.slug)), /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.04] px-2.5 py-1 text-[10px] font-semibold uppercase tracking-[0.16em] text-slate-200" }, template.supported_formats?.join(", "))), template.description ? /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-sm text-slate-400" }, template.description) : null)))), /* @__PURE__ */ React.createElement("section", { className: "rounded-[28px] border border-white/10 bg-white/[0.04] p-5 shadow-[0_20px_50px_rgba(2,6,23,0.18)]" }, /* @__PURE__ */ React.createElement("div", { className: "mb-4 text-sm font-semibold uppercase tracking-[0.2em] text-slate-400" }, "Template editor"), /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 md:grid-cols-2" }, /* @__PURE__ */ React.createElement("input", { value: form.name, onChange: (event) => setForm((current) => ({ ...current, name: event.target.value })), placeholder: "Template name", className: "rounded-2xl border border-white/10 bg-[#0d1726] px-4 py-3 text-white" }), /* @__PURE__ */ React.createElement("input", { value: form.slug, onChange: (event) => setForm((current) => ({ ...current, slug: event.target.value })), placeholder: "Slug", className: "rounded-2xl border border-white/10 bg-[#0d1726] px-4 py-3 text-white" }), /* @__PURE__ */ React.createElement("textarea", { value: form.description, onChange: (event) => setForm((current) => ({ ...current, description: event.target.value })), placeholder: "Description", rows: 3, className: "rounded-2xl border border-white/10 bg-[#0d1726] px-4 py-3 text-white md:col-span-2" }), /* @__PURE__ */ React.createElement("div", { className: "text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "mb-2 block" }, "Font preset"), /* @__PURE__ */ React.createElement(NovaSelect, { value: form.config_json?.font_preset || "modern-sans", onChange: (val) => setForm((current) => ({ ...current, config_json: { ...current.config_json, font_preset: val } })), options: fonts.map((f2) => ({ value: f2.key, label: f2.label })), searchable: false })), /* @__PURE__ */ React.createElement("div", { className: "text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "mb-2 block" }, "Gradient preset"), /* @__PURE__ */ React.createElement(NovaSelect, { value: form.config_json?.gradient_preset || "midnight-nova", onChange: (val) => setForm((current) => ({ ...current, config_json: { ...current.config_json, gradient_preset: val } })), options: gradients.map((g2) => ({ value: g2.key, label: g2.label })), searchable: false })), /* @__PURE__ */ React.createElement("div", { className: "text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "mb-2 block" }, "Layout preset"), /* @__PURE__ */ React.createElement(NovaSelect, { value: form.config_json?.layout || "quote_heavy", onChange: (val) => setForm((current) => ({ ...current, config_json: { ...current.config_json, layout: val } })), options: ["quote_heavy", "author_emphasis", "centered", "minimal"].map((v) => ({ value: v, label: v })), searchable: false })), /* @__PURE__ */ React.createElement("div", { className: "text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "mb-2 block" }, "Text alignment"), /* @__PURE__ */ React.createElement(NovaSelect, { value: form.config_json?.text_align || "center", onChange: (val) => setForm((current) => ({ ...current, config_json: { ...current.config_json, text_align: val } })), options: ["left", "center", "right"].map((v) => ({ value: v, label: v })), searchable: false })), /* @__PURE__ */ React.createElement("div", { className: "text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "mb-2 block" }, "Overlay style"), /* @__PURE__ */ React.createElement(NovaSelect, { value: form.config_json?.overlay_style || "dark-soft", onChange: (val) => setForm((current) => ({ ...current, config_json: { ...current.config_json, overlay_style: val } })), options: ["none", "dark-soft", "dark-strong", "light-soft"].map((v) => ({ value: v, label: v })), searchable: false })), /* @__PURE__ */ React.createElement("label", { className: "text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "mb-2 block" }, "Text color"), /* @__PURE__ */ React.createElement("input", { type: "color", value: form.config_json?.text_color || "#ffffff", onChange: (event) => setForm((current) => ({ ...current, config_json: { ...current.config_json, text_color: event.target.value } })), className: "h-12 w-full rounded-2xl border border-white/10 bg-[#0d1726] p-2" }))), /* @__PURE__ */ React.createElement("div", { className: "mt-5" }, /* @__PURE__ */ React.createElement("div", { className: "mb-3 text-sm font-semibold uppercase tracking-[0.18em] text-slate-400" }, "Supported formats"), /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-3" }, formats2.map((format) => /* @__PURE__ */ React.createElement("div", { key: format.key, className: "inline-flex items-center gap-2 rounded-full border border-white/10 bg-white/[0.03] px-3 py-2 text-sm text-slate-200" }, /* @__PURE__ */ React.createElement(Checkbox, { checked: form.supported_formats.includes(format.key), onChange: () => toggleFormat(format.key), label: format.label }))))), /* @__PURE__ */ React.createElement("div", { className: "mt-5 flex items-center justify-between gap-3 rounded-2xl border border-white/10 bg-white/[0.03] px-4 py-3 text-sm text-slate-200" }, /* @__PURE__ */ React.createElement(Checkbox, { checked: Boolean(form.active), onChange: (event) => setForm((current) => ({ ...current, active: event.target.checked })), label: "Active" }), /* @__PURE__ */ React.createElement(Checkbox, { checked: Boolean(form.official), onChange: (event) => setForm((current) => ({ ...current, official: event.target.checked })), label: "Official" })), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: saveTemplate, className: "mt-5 w-full rounded-2xl border border-sky-300/20 bg-sky-400/10 px-4 py-3 text-sm font-semibold text-sky-100 transition hover:bg-sky-400/15" }, selectedId ? "Update template" : "Create template")))); } -const __vite_glob_0_39 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ +const __vite_glob_0_40 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ __proto__: null, default: NovaCardsTemplateAdmin }, Symbol.toStringTag, { value: "Module" })); @@ -69511,7 +73309,7 @@ function SavedCollections() { } ))))) : activeFilters.q || activeFilters.filter !== "all" || activeFilters.sort !== "saved_desc" || activeFilters.list ? /* @__PURE__ */ React.createElement("div", { className: "rounded-[32px] border border-dashed border-white/12 bg-white/[0.03] px-6 py-16 text-center text-sm text-slate-300" }, "No saved collections match the current search or filters.") : /* @__PURE__ */ React.createElement(EmptyState$3, { browseUrl })), recommendedCollections.length ? /* @__PURE__ */ React.createElement("section", { className: "rounded-[32px] border border-white/10 bg-white/[0.04] p-6 backdrop-blur-sm md:p-7" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.22em] text-amber-200/80" }, "Recommended Next"), /* @__PURE__ */ React.createElement("h2", { className: "mt-2 text-2xl font-semibold text-white" }, "Because of what you save")), /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-1 text-xs font-semibold text-slate-300" }, recommendedCollections.length)), /* @__PURE__ */ React.createElement("div", { className: "mt-6 grid grid-cols-1 gap-5 xl:grid-cols-3" }, recommendedCollections.map((collection) => /* @__PURE__ */ React.createElement(CollectionCard, { key: collection.id, collection, isOwner: false })))) : null))))); } -const __vite_glob_0_40 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ +const __vite_glob_0_41 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ __proto__: null, default: SavedCollections }, Symbol.toStringTag, { value: "Module" })); @@ -69849,7 +73647,7 @@ if (typeof document !== "undefined") { clientExports.createRoot(mountEl).render(/* @__PURE__ */ React.createElement(CommunityActivityPage, { ...props })); } } -const __vite_glob_0_41 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ +const __vite_glob_0_42 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ __proto__: null, default: CommunityActivityPage }, Symbol.toStringTag, { value: "Module" })); @@ -70167,7 +73965,7 @@ if (typeof document !== "undefined") { clientExports.createRoot(mountEl).render(/* @__PURE__ */ React.createElement(LatestCommentsPage, { ...props })); } } -const __vite_glob_0_42 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ +const __vite_glob_0_43 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ __proto__: null, default: LatestCommentsPage }, Symbol.toStringTag, { value: "Module" })); @@ -70554,8 +74352,7 @@ function PostCard$1({ post: post2, isLoggedIn = false, viewerUsername = null, on const handleSaveEdit = async () => { setSaving(true); try { - const { default: axios2 } = await Promise.resolve().then(() => index$1); - const { data } = await axios2.patch(`/api/posts/${post2.id}`, { body: editBody }); + const { data } = await axios.patch(`/api/posts/${post2.id}`, { body: editBody }); setPostData(data.post); setEditMode(false); } catch { @@ -70566,20 +74363,18 @@ function PostCard$1({ post: post2, isLoggedIn = false, viewerUsername = null, on const handleDelete = async () => { if (!window.confirm("Delete this post?")) return; try { - const { default: axios2 } = await Promise.resolve().then(() => index$1); - await axios2.delete(`/api/posts/${post2.id}`); + await axios.delete(`/api/posts/${post2.id}`); onDelete?.(post2.id); } catch { } }; const handlePin = async () => { - const { default: axios2 } = await Promise.resolve().then(() => index$1); try { if (postData.is_pinned) { - await axios2.delete(`/api/posts/${post2.id}/pin`); + await axios.delete(`/api/posts/${post2.id}/pin`); setPostData((p) => ({ ...p, is_pinned: false, pinned_order: null })); } else { - const { data } = await axios2.post(`/api/posts/${post2.id}/pin`); + const { data } = await axios.post(`/api/posts/${post2.id}/pin`); setPostData((p) => ({ ...p, is_pinned: true, pinned_order: data.pinned_order ?? 1 })); } } catch { @@ -70589,14 +74384,13 @@ function PostCard$1({ post: post2, isLoggedIn = false, viewerUsername = null, on const handleSaveToggle = async () => { if (!isLoggedIn || saveLoading) return; setSaveLoading(true); - const { default: axios2 } = await Promise.resolve().then(() => index$1); try { if (postData.viewer_saved) { - await axios2.delete(`/api/posts/${post2.id}/save`); + await axios.delete(`/api/posts/${post2.id}/save`); setPostData((p) => ({ ...p, viewer_saved: false, saves_count: Math.max(0, (p.saves_count ?? 1) - 1) })); onUnsaved?.(post2.id); } else { - await axios2.post(`/api/posts/${post2.id}/save`); + await axios.post(`/api/posts/${post2.id}/save`); setPostData((p) => ({ ...p, viewer_saved: true, saves_count: (p.saves_count ?? 0) + 1 })); } } catch { @@ -70608,9 +74402,8 @@ function PostCard$1({ post: post2, isLoggedIn = false, viewerUsername = null, on if (!isOwn) return; setAnalyticsOpen(true); if (!analytics) { - const { default: axios2 } = await Promise.resolve().then(() => index$1); try { - const { data } = await axios2.get(`/api/posts/${post2.id}/analytics`); + const { data } = await axios.get(`/api/posts/${post2.id}/analytics`); setAnalytics(data); } catch { setAnalytics(null); @@ -70843,7 +74636,7 @@ function FollowingFeed() { loading ? /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-spinner fa-spin mr-2" }), "Loading…") : "Load more" ))))); } -const __vite_glob_0_43 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ +const __vite_glob_0_44 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ __proto__: null, default: FollowingFeed }, Symbol.toStringTag, { value: "Module" })); @@ -70903,7 +74696,7 @@ function HashtagFeed() { loading ? /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-spinner fa-spin mr-2" }), "Loading…") : "Load more" )))))); } -const __vite_glob_0_44 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ +const __vite_glob_0_45 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ __proto__: null, default: HashtagFeed }, Symbol.toStringTag, { value: "Module" })); @@ -70961,7 +74754,7 @@ function SavedFeed() { loading ? /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-spinner fa-spin mr-2" }), "Loading…") : "Load more" )))))); } -const __vite_glob_0_45 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ +const __vite_glob_0_46 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ __proto__: null, default: SavedFeed }, Symbol.toStringTag, { value: "Module" })); @@ -71086,7 +74879,7 @@ function SearchFeed() { "Load more" ))), /* @__PURE__ */ React.createElement("aside", { className: "hidden lg:block w-64 shrink-0 space-y-4 pt-14" }, /* @__PURE__ */ React.createElement(TrendingHashtagsSidebar$1, { hashtags: trendingHashtags }), /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/[0.07] bg-white/[0.03] px-4 py-4 text-center" }, /* @__PURE__ */ React.createElement("p", { className: "text-xs text-slate-500 leading-relaxed" }, "Tip: search ", /* @__PURE__ */ React.createElement("span", { className: "text-sky-400/80" }, "#hashtag"), " to find posts by topic."))))))); } -const __vite_glob_0_46 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ +const __vite_glob_0_47 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ __proto__: null, default: SearchFeed }, Symbol.toStringTag, { value: "Module" })); @@ -71148,7 +74941,7 @@ function TrendingFeed() { loading ? /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-spinner fa-spin mr-2" }), "Loading…") : "Load more" ))), /* @__PURE__ */ React.createElement("aside", { className: "hidden lg:block w-64 shrink-0 space-y-4 pt-14" }, /* @__PURE__ */ React.createElement(TrendingHashtagsSidebar, { hashtags: trendingHashtags }), /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/[0.07] bg-white/[0.03] px-4 py-4 text-center" }, /* @__PURE__ */ React.createElement("p", { className: "text-xs text-slate-500 leading-relaxed" }, "Posts are ranked by likes, comments & engagement over the last 7 days."))))))); } -const __vite_glob_0_47 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ +const __vite_glob_0_48 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ __proto__: null, default: TrendingFeed }, Symbol.toStringTag, { value: "Module" })); @@ -71175,7 +74968,7 @@ function ThreadRow({ thread, isFirst = false }) { ].filter(Boolean).join(" ") }, /* @__PURE__ */ React.createElement("div", { className: "mt-0.5 flex h-9 w-9 shrink-0 items-center justify-center rounded-lg bg-sky-500/10 text-sky-400 group-hover:bg-sky-500/15 transition-colors" }, isPinned ? /* @__PURE__ */ React.createElement("svg", { width: "16", height: "16", viewBox: "0 0 24 24", fill: "currentColor" }, /* @__PURE__ */ React.createElement("path", { d: "M16 12V4h1V2H7v2h1v8l-2 2v2h5.2v6h1.6v-6H18v-2z" })) : /* @__PURE__ */ React.createElement("svg", { width: "16", height: "16", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "2", strokeLinecap: "round", strokeLinejoin: "round" }, /* @__PURE__ */ React.createElement("path", { d: "M21 15a2 2 0 01-2 2H7l-4 4V5a2 2 0 012-2h14a2 2 0 012 2z" }))), - /* @__PURE__ */ React.createElement("div", { className: "min-w-0 flex-1" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-2" }, /* @__PURE__ */ React.createElement("h3", { className: "m-0 truncate text-sm font-semibold leading-tight text-white transition-colors group-hover:text-sky-300" }, title), isPinned && /* @__PURE__ */ React.createElement("span", { className: "shrink-0 rounded-full bg-amber-500/15 px-2 py-0.5 text-[10px] font-medium text-amber-300" }, "Pinned")), excerpt && /* @__PURE__ */ React.createElement("p", { className: "mt-0.5 truncate text-xs text-white/40" }, stripHtml$3(excerpt).slice(0, 180)), /* @__PURE__ */ React.createElement("div", { className: "mt-1.5 flex flex-wrap items-center gap-3 text-xs text-white/35" }, /* @__PURE__ */ React.createElement("span", { className: "flex items-center gap-1" }, /* @__PURE__ */ React.createElement("svg", { width: "12", height: "12", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "2", strokeLinecap: "round", strokeLinejoin: "round" }, /* @__PURE__ */ React.createElement("path", { d: "M20 21v-2a4 4 0 00-4-4H8a4 4 0 00-4 4v2" }), /* @__PURE__ */ React.createElement("circle", { cx: "12", cy: "7", r: "4" })), author), /* @__PURE__ */ React.createElement("span", { className: "flex items-center gap-1" }, /* @__PURE__ */ React.createElement("svg", { width: "12", height: "12", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "2", strokeLinecap: "round", strokeLinejoin: "round" }, /* @__PURE__ */ React.createElement("path", { d: "M21 15a2 2 0 01-2 2H7l-4 4V5a2 2 0 012-2h14a2 2 0 012 2z" })), posts, " ", posts === 1 ? "reply" : "replies"), lastUpdate && /* @__PURE__ */ React.createElement("span", { className: "flex items-center gap-1" }, /* @__PURE__ */ React.createElement("svg", { width: "12", height: "12", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "2", strokeLinecap: "round", strokeLinejoin: "round" }, /* @__PURE__ */ React.createElement("circle", { cx: "12", cy: "12", r: "10" }), /* @__PURE__ */ React.createElement("polyline", { points: "12 6 12 12 16 14" })), formatDate$e(lastUpdate)))), + /* @__PURE__ */ React.createElement("div", { className: "min-w-0 flex-1" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-2" }, /* @__PURE__ */ React.createElement("h3", { className: "m-0 truncate text-sm font-semibold leading-tight text-white transition-colors group-hover:text-sky-300" }, title), isPinned && /* @__PURE__ */ React.createElement("span", { className: "shrink-0 rounded-full bg-amber-500/15 px-2 py-0.5 text-[10px] font-medium text-amber-300" }, "Pinned")), excerpt && /* @__PURE__ */ React.createElement("p", { className: "mt-0.5 truncate text-xs text-white/40" }, stripHtml$3(excerpt).slice(0, 180)), /* @__PURE__ */ React.createElement("div", { className: "mt-1.5 flex flex-wrap items-center gap-3 text-xs text-white/35" }, /* @__PURE__ */ React.createElement("span", { className: "flex items-center gap-1" }, /* @__PURE__ */ React.createElement("svg", { width: "12", height: "12", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "2", strokeLinecap: "round", strokeLinejoin: "round" }, /* @__PURE__ */ React.createElement("path", { d: "M20 21v-2a4 4 0 00-4-4H8a4 4 0 00-4 4v2" }), /* @__PURE__ */ React.createElement("circle", { cx: "12", cy: "7", r: "4" })), author), /* @__PURE__ */ React.createElement("span", { className: "flex items-center gap-1" }, /* @__PURE__ */ React.createElement("svg", { width: "12", height: "12", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "2", strokeLinecap: "round", strokeLinejoin: "round" }, /* @__PURE__ */ React.createElement("path", { d: "M21 15a2 2 0 01-2 2H7l-4 4V5a2 2 0 012-2h14a2 2 0 012 2z" })), posts, " ", posts === 1 ? "reply" : "replies"), lastUpdate && /* @__PURE__ */ React.createElement("span", { className: "flex items-center gap-1" }, /* @__PURE__ */ React.createElement("svg", { width: "12", height: "12", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "2", strokeLinecap: "round", strokeLinejoin: "round" }, /* @__PURE__ */ React.createElement("circle", { cx: "12", cy: "12", r: "10" }), /* @__PURE__ */ React.createElement("polyline", { points: "12 6 12 12 16 14" })), formatDate$d(lastUpdate)))), /* @__PURE__ */ React.createElement("div", { className: "mt-1 shrink-0" }, /* @__PURE__ */ React.createElement("span", { className: "inline-flex min-w-[2rem] items-center justify-center rounded-full bg-white/[0.06] px-2.5 py-1 text-xs font-medium text-white/60" }, posts)) ); } @@ -71206,7 +74999,7 @@ function stripHtml$3(html2) { } return decodeEntities(html2).replace(/<[^>]*>/g, ""); } -function formatDate$e(dateStr) { +function formatDate$d(dateStr) { try { const d2 = new Date(dateStr); return d2.toLocaleDateString("en-GB", { day: "2-digit", month: "2-digit", year: "numeric" }) + " " + d2.toLocaleTimeString("en-GB", { hour: "2-digit", minute: "2-digit" }); @@ -71233,881 +75026,10 @@ function ForumCategory({ category, parentCategory = null, threads = [], paginati "New topic" ))), /* @__PURE__ */ React.createElement("section", { className: "overflow-hidden rounded-2xl border border-white/[0.06] bg-nova-800/50 backdrop-blur" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-4 border-b border-white/[0.06] px-5 py-3" }, /* @__PURE__ */ React.createElement("span", { className: "flex-1 text-xs font-semibold uppercase tracking-widest text-white/30" }, "Topics"), /* @__PURE__ */ React.createElement("span", { className: "w-16 text-center text-xs font-semibold uppercase tracking-widest text-white/30" }, "Replies")), threads.length === 0 ? /* @__PURE__ */ React.createElement("div", { className: "px-5 py-12 text-center" }, /* @__PURE__ */ React.createElement("svg", { className: "mx-auto mb-4 text-zinc-600", width: "40", height: "40", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "1.5", strokeLinecap: "round", strokeLinejoin: "round" }, /* @__PURE__ */ React.createElement("path", { d: "M21 15a2 2 0 01-2 2H7l-4 4V5a2 2 0 012-2h14a2 2 0 012 2z" })), /* @__PURE__ */ React.createElement("p", { className: "text-sm text-zinc-500" }, "No topics in this board yet."), isAuthenticated && slug && /* @__PURE__ */ React.createElement("a", { href: `/forum/${slug}/new`, className: "mt-3 inline-block text-sm text-sky-300 hover:text-sky-200" }, "Be the first to start a discussion →")) : /* @__PURE__ */ React.createElement("div", null, threads.map((thread, i) => /* @__PURE__ */ React.createElement(ThreadRow, { key: thread.topic_id ?? thread.id ?? i, thread, isFirst: i === 0 })))), pagination?.last_page > 1 && /* @__PURE__ */ React.createElement("div", { className: "mt-6" }, /* @__PURE__ */ React.createElement(Pagination$1, { meta: pagination })))); } -const __vite_glob_0_48 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ +const __vite_glob_0_49 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ __proto__: null, default: ForumCategory }, Symbol.toStringTag, { value: "Module" })); -const MentionList = reactExports.forwardRef(function MentionList2({ items, command }, ref2) { - const [selectedIndex, setSelectedIndex] = reactExports.useState(0); - reactExports.useEffect(() => setSelectedIndex(0), [items]); - reactExports.useImperativeHandle(ref2, () => ({ - onKeyDown: ({ event }) => { - if (event.key === "ArrowUp") { - setSelectedIndex((i) => (i + items.length - 1) % items.length); - return true; - } - if (event.key === "ArrowDown") { - setSelectedIndex((i) => (i + 1) % items.length); - return true; - } - if (event.key === "Enter") { - selectItem(selectedIndex); - return true; - } - return false; - } - })); - const selectItem = (index2) => { - const item = items[index2]; - if (item) { - command({ id: item.username, label: item.username }); - } - }; - if (!items.length) { - return /* @__PURE__ */ React.createElement("div", { className: "rounded-xl border border-white/[0.08] bg-nova-800 p-3 shadow-xl backdrop-blur" }, /* @__PURE__ */ React.createElement("p", { className: "text-xs text-zinc-500" }, "No users found")); - } - return /* @__PURE__ */ React.createElement("div", { className: "min-w-[200px] overflow-hidden rounded-xl border border-white/[0.08] bg-nova-800 shadow-xl backdrop-blur" }, items.map((item, index2) => /* @__PURE__ */ React.createElement( - "button", - { - key: item.id, - type: "button", - onClick: () => selectItem(index2), - className: [ - "flex w-full items-center gap-2.5 px-3 py-2 text-left text-sm transition-colors", - index2 === selectedIndex ? "bg-sky-600/20 text-white" : "text-zinc-300 hover:bg-white/[0.04]" - ].join(" ") - }, - /* @__PURE__ */ React.createElement( - "img", - { - src: item.avatar_url, - alt: "", - className: "h-6 w-6 rounded-full border border-white/10 object-cover" - } - ), - /* @__PURE__ */ React.createElement("span", { className: "truncate font-medium" }, "@", item.username), - item.name && item.name !== item.username && /* @__PURE__ */ React.createElement("span", { className: "truncate text-xs text-zinc-500" }, item.name) - ))); -}); -const mentionSuggestion = { - items: async ({ query }) => { - if (!query || query.length < 2) return []; - try { - const res = await fetch(`/api/search/users?q=${encodeURIComponent(query)}&per_page=6`); - if (!res.ok) return []; - const json = await res.json(); - return json.data ?? []; - } catch { - return []; - } - }, - render: () => { - let component; - let popup; - return { - onStart: (props) => { - component = new ReactRenderer(MentionList, { - props, - editor: props.editor - }); - if (!props.clientRect) return; - popup = tippy("body", { - getReferenceClientRect: props.clientRect, - appendTo: () => document.body, - content: component.element, - showOnCreate: true, - interactive: true, - trigger: "manual", - placement: "bottom-start", - theme: "mention", - arrow: false, - offset: [0, 8] - }); - }, - onUpdate: (props) => { - component?.updateProps(props); - if (!props.clientRect) return; - popup?.[0]?.setProps({ - getReferenceClientRect: props.clientRect - }); - }, - onKeyDown: (props) => { - if (props.event.key === "Escape") { - popup?.[0]?.hide(); - return true; - } - return component?.ref?.onKeyDown(props) ?? false; - }, - onExit: () => { - popup?.[0]?.destroy(); - component?.destroy(); - } - }; - } -}; -function EmojiPicker$1({ onSelect, editor }) { - const [open, setOpen] = reactExports.useState(false); - const [pickerData, setPickerData] = reactExports.useState(null); - const [panelStyle, setPanelStyle] = reactExports.useState({}); - const panelRef = reactExports.useRef(null); - const buttonRef = reactExports.useRef(null); - reactExports.useEffect(() => { - if (!open || pickerData) return; - let cancelled = false; - loadEmojiMartData().then((data) => { - if (!cancelled) { - setPickerData(data); - } - }); - return () => { - cancelled = true; - }; - }, [open, pickerData]); - reactExports.useEffect(() => { - if (!open || !buttonRef.current) return; - const rect = buttonRef.current.getBoundingClientRect(); - const panelWidth = 352; - const panelHeight = 435; - const spaceAbove = rect.top; - const openAbove = spaceAbove > panelHeight + 8; - setPanelStyle({ - position: "fixed", - zIndex: 9999, - left: Math.max(8, Math.min(rect.right - panelWidth, window.innerWidth - panelWidth - 8)), - ...openAbove ? { bottom: window.innerHeight - rect.top + 6 } : { top: rect.bottom + 6 } - }); - }, [open]); - reactExports.useEffect(() => { - if (!open) return; - const handler = (e) => { - if (!isEventWithinNode(e, panelRef.current) && !isEventWithinNode(e, buttonRef.current)) { - setOpen(false); - } - }; - document.addEventListener("mousedown", handler); - return () => document.removeEventListener("mousedown", handler); - }, [open]); - reactExports.useEffect(() => { - if (!open) return; - const handler = (e) => { - if (e.key === "Escape") setOpen(false); - }; - document.addEventListener("keydown", handler); - return () => document.removeEventListener("keydown", handler); - }, [open]); - const handleSelect = reactExports.useCallback((emoji) => { - const native = extractNativeEmoji(emoji); - if (!native) { - setOpen(false); - return; - } - onSelect?.(native); - if (editor) { - editor.chain().focus().insertContent(native).run(); - } - setOpen(false); - }, [onSelect, editor]); - const panel = open ? reactDomExports.createPortal( - /* @__PURE__ */ React.createElement( - "div", - { - ref: panelRef, - style: panelStyle, - className: "rounded-xl shadow-2xl overflow-hidden" - }, - pickerData ? /* @__PURE__ */ React.createElement( - EmojiMartPicker, - { - data: pickerData, - onEmojiSelect: handleSelect, - theme: "dark", - previewPosition: "none", - skinTonePosition: "search", - maxFrequentRows: 2, - perLine: 9 - } - ) : /* @__PURE__ */ React.createElement("div", { className: "flex h-24 w-[352px] items-center justify-center bg-zinc-900 px-4 text-sm text-zinc-300" }, "Loading emojis...") - ), - document.body - ) : null; - return /* @__PURE__ */ React.createElement("div", { className: "relative" }, /* @__PURE__ */ React.createElement( - "button", - { - ref: buttonRef, - type: "button", - onClick: () => setOpen((v) => !v), - title: "Insert emoji", - "aria-label": "Open emoji picker", - "aria-expanded": open, - className: [ - "inline-flex h-8 w-8 items-center justify-center rounded-lg text-sm transition-colors", - "focus:outline-none focus-visible:ring-2 focus-visible:ring-sky-400", - open ? "bg-sky-600/25 text-sky-300" : "text-zinc-400 hover:bg-white/[0.06] hover:text-zinc-200" - ].join(" ") - }, - /* @__PURE__ */ React.createElement("span", { className: "text-[15px]" }, "😊") - ), panel); -} -function ToolbarBtn({ onClick, active, disabled, title, children, className = "" }) { - return /* @__PURE__ */ React.createElement( - "button", - { - type: "button", - onMouseDown: (event) => { - event.preventDefault(); - }, - onClick, - disabled, - title, - className: [ - "inline-flex h-8 w-8 items-center justify-center rounded-lg text-sm transition-colors", - "focus:outline-none focus-visible:ring-2 focus-visible:ring-sky-400", - active ? "bg-sky-600/25 text-sky-300" : "text-zinc-400 hover:bg-white/[0.06] hover:text-zinc-200", - disabled && "pointer-events-none opacity-30", - className - ].filter(Boolean).join(" ") - }, - children - ); -} -function Divider() { - return /* @__PURE__ */ React.createElement("div", { className: "mx-1 h-5 w-px bg-white/10" }); -} -function normalizeHttpUrl(rawValue) { - const trimmed = String(rawValue || "").trim(); - if (trimmed === "") { - return null; - } - const withProtocol = /^[a-z][a-z0-9+.-]*:\/\//i.test(trimmed) ? trimmed : `https://${trimmed.replace(/^\/+/, "")}`; - try { - const parsed = new URL(withProtocol); - if (!["http:", "https:"].includes(parsed.protocol)) { - return null; - } - return parsed.toString(); - } catch { - return null; - } -} -function normalizeVideoEmbedUrl(rawValue) { - const normalized = normalizeHttpUrl(rawValue); - if (!normalized) { - return null; - } - const parsed = new URL(normalized); - const host = parsed.hostname.replace(/^www\./i, "").toLowerCase(); - const path = parsed.pathname; - if (host === "youtu.be") { - const videoId = path.replace(/^\//, "").split("/")[0]; - return videoId ? `https://www.youtube.com/embed/${videoId}` : normalized; - } - if (host === "youtube.com" || host === "m.youtube.com") { - if (path === "/watch") { - const videoId = parsed.searchParams.get("v"); - return videoId ? `https://www.youtube.com/embed/${videoId}` : normalized; - } - const pathMatch = path.match(/^\/(embed|shorts|live)\/([^/?#]+)/i); - if (pathMatch?.[2]) { - return `https://www.youtube.com/embed/${pathMatch[2]}`; - } - } - return normalized; -} -function detectSocialPlatform(rawUrl) { - const normalized = normalizeHttpUrl(rawUrl); - if (!normalized) { - return { platform: "social", label: "Social post", url: null }; - } - const host = new URL(normalized).hostname.replace(/^www\./i, "").toLowerCase(); - if (host.includes("instagram.")) return { platform: "instagram", label: "Instagram post", url: normalized }; - if (host.includes("facebook.")) return { platform: "facebook", label: "Facebook post", url: normalized }; - if (host.includes("tiktok.")) return { platform: "tiktok", label: "TikTok post", url: normalized }; - if (host.includes("twitter.") || host.includes("x.com")) return { platform: "x", label: "X post", url: normalized }; - if (host.includes("linkedin.")) return { platform: "linkedin", label: "LinkedIn post", url: normalized }; - if (host.includes("threads.")) return { platform: "threads", label: "Threads post", url: normalized }; - if (host.includes("pinterest.")) return { platform: "pinterest", label: "Pinterest pin", url: normalized }; - return { platform: "social", label: "Social post", url: normalized }; -} -const ArtworkEmbed = Node3.create({ - name: "artworkEmbed", - group: "block", - atom: true, - addAttributes() { - return { - title: { default: "Artwork" }, - url: { default: "" }, - thumb: { default: "" } - }; - }, - parseHTML() { - return [{ tag: "figure[data-artwork-embed]" }]; - }, - renderHTML({ HTMLAttributes }) { - const preview = []; - if (HTMLAttributes.thumb) { - preview.push([ - "img", - { - src: HTMLAttributes.thumb, - alt: HTMLAttributes.title || "Artwork", - class: "block h-auto w-full object-cover", - loading: "lazy" - } - ]); - } - preview.push([ - "figcaption", - { class: "news-embed-caption" }, - HTMLAttributes.title || "Artwork" - ]); - return [ - "figure", - mergeAttributes(HTMLAttributes, { - "data-artwork-embed": "true", - class: "news-embed news-embed-artwork" - }), - [ - "a", - { - href: HTMLAttributes.url || "#", - class: "news-embed-link", - rel: "noopener noreferrer nofollow", - target: "_blank" - }, - ...preview - ] - ]; - } -}); -const VideoEmbed = Node3.create({ - name: "videoEmbed", - group: "block", - atom: true, - addAttributes() { - return { - src: { default: "" }, - url: { default: "" }, - title: { default: "Embedded video" } - }; - }, - parseHTML() { - return [{ tag: "figure[data-video-embed]" }]; - }, - renderHTML({ HTMLAttributes }) { - return [ - "figure", - mergeAttributes(HTMLAttributes, { - "data-video-embed": "true", - class: "news-embed news-embed-video" - }), - [ - "iframe", - { - src: HTMLAttributes.src || "", - title: HTMLAttributes.title || "Embedded video", - loading: "lazy", - frameborder: "0", - allow: "accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share", - allowfullscreen: "true", - referrerpolicy: "strict-origin-when-cross-origin" - } - ], - [ - "figcaption", - { class: "news-embed-caption" }, - [ - "a", - { - href: HTMLAttributes.url || HTMLAttributes.src || "#", - rel: "noopener noreferrer nofollow", - target: "_blank" - }, - HTMLAttributes.title || "Watch video" - ] - ] - ]; - } -}); -const SocialEmbed = Node3.create({ - name: "socialEmbed", - group: "block", - atom: true, - addAttributes() { - return { - url: { default: "" }, - platform: { default: "social" }, - label: { default: "Social post" } - }; - }, - parseHTML() { - return [{ tag: "figure[data-social-embed]" }]; - }, - renderHTML({ HTMLAttributes }) { - const platform2 = String(HTMLAttributes.platform || "social"); - const url = HTMLAttributes.url || "#"; - const label = HTMLAttributes.label || "Social post"; - if (platform2 === "instagram") { - return [ - "figure", - mergeAttributes(HTMLAttributes, { - "data-social-embed": "true", - "data-platform": platform2, - class: "news-embed news-embed-social" - }), - [ - "blockquote", - { - class: "instagram-media", - "data-instgrm-captioned": "true", - "data-instgrm-permalink": url, - "data-instgrm-version": "14" - }, - [ - "a", - { href: url, rel: "noopener noreferrer nofollow", target: "_blank" }, - label - ] - ] - ]; - } - if (platform2 === "facebook") { - return [ - "figure", - mergeAttributes(HTMLAttributes, { - "data-social-embed": "true", - "data-platform": platform2, - class: "news-embed news-embed-social" - }), - [ - "div", - { class: "fb-post", "data-href": url, "data-show-text": "true" }, - [ - "blockquote", - { cite: url, class: "fb-xfbml-parse-ignore" }, - [ - "a", - { href: url, rel: "noopener noreferrer nofollow", target: "_blank" }, - label - ] - ] - ] - ]; - } - if (platform2 === "tiktok") { - return [ - "figure", - mergeAttributes(HTMLAttributes, { - "data-social-embed": "true", - "data-platform": platform2, - class: "news-embed news-embed-social" - }), - [ - "blockquote", - { class: "tiktok-embed", cite: url }, - [ - "section", - null, - [ - "a", - { href: url, rel: "noopener noreferrer nofollow", target: "_blank" }, - label - ] - ] - ] - ]; - } - if (platform2 === "x") { - return [ - "figure", - mergeAttributes(HTMLAttributes, { - "data-social-embed": "true", - "data-platform": platform2, - class: "news-embed news-embed-social" - }), - [ - "blockquote", - { class: "twitter-tweet" }, - [ - "a", - { href: url, rel: "noopener noreferrer nofollow", target: "_blank" }, - label - ] - ] - ]; - } - return [ - "figure", - mergeAttributes(HTMLAttributes, { - "data-social-embed": "true", - "data-platform": platform2, - class: "news-embed news-embed-social" - }), - [ - "a", - { - href: url, - class: "news-embed-link", - rel: "noopener noreferrer nofollow", - target: "_blank" - }, - ["span", { class: "news-embed-badge" }, label], - ["span", { class: "news-embed-url" }, url] - ] - ]; - } -}); -function ArtworkPickerDialog({ - open, - query, - items, - loading, - onQueryChange, - onClose, - onSearch, - onSelect -}) { - if (!open) return null; - return reactDomExports.createPortal( - /* @__PURE__ */ React.createElement( - "div", - { - className: "fixed inset-0 z-[9999] flex items-center justify-center bg-[#04070dcc] px-4 backdrop-blur-md", - onClick: (event) => { - if (event.target === event.currentTarget) { - onClose?.(); - } - }, - role: "presentation" - }, - /* @__PURE__ */ React.createElement("div", { className: "w-full max-w-3xl overflow-hidden rounded-3xl border border-white/10 bg-[linear-gradient(180deg,rgba(16,22,34,0.98),rgba(8,12,19,0.98))] shadow-[0_30px_80px_rgba(0,0,0,0.55)]" }, /* @__PURE__ */ React.createElement("div", { className: "border-b border-white/[0.06] px-6 py-5" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.24em] text-white/35" }, "Artwork embed"), /* @__PURE__ */ React.createElement("h3", { className: "mt-2 text-lg font-semibold text-white" }, "Choose artwork"), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm leading-6 text-white/65" }, "Search existing artworks and insert a linked artwork card into the News article body.")), /* @__PURE__ */ React.createElement("div", { className: "border-b border-white/[0.06] px-6 py-4" }, /* @__PURE__ */ React.createElement("div", { className: "flex gap-3" }, /* @__PURE__ */ React.createElement( - "input", - { - value: query, - onChange: (event) => onQueryChange?.(event.target.value), - onKeyDown: (event) => { - if (event.key === "Enter") { - event.preventDefault(); - onSearch?.(); - } - }, - placeholder: "Search by title, slug, or creator", - className: "min-w-0 flex-1 rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white outline-none" - } - ), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: onSearch, className: "rounded-2xl border border-sky-300/20 bg-sky-400/10 px-4 py-3 text-sm font-semibold text-sky-100 transition hover:bg-sky-400/15" }, "Search"))), /* @__PURE__ */ React.createElement("div", { className: "nova-scrollbar max-h-[60vh] overflow-y-auto px-6 py-5" }, loading ? /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-black/20 p-4 text-sm text-slate-300" }, "Searching artworks…") : null, !loading && (!Array.isArray(items) || items.length === 0) ? /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-dashed border-white/10 bg-white/[0.02] p-4 text-sm text-slate-400" }, "No artworks found yet. Try a broader title or creator search.") : null, !loading && Array.isArray(items) && items.length > 0 ? /* @__PURE__ */ React.createElement("div", { className: "grid gap-3" }, items.map((item) => { - const previewImage = item.image || item.avatar || ""; - return /* @__PURE__ */ React.createElement( - "button", - { - key: `${item.entity_type || "artwork"}-${item.id}`, - type: "button", - onClick: () => onSelect?.(item), - className: "flex items-center gap-4 rounded-[24px] border border-white/10 bg-black/20 p-3 text-left transition hover:border-white/20 hover:bg-white/[0.04]" - }, - /* @__PURE__ */ React.createElement("div", { className: "h-20 w-28 shrink-0 overflow-hidden rounded-2xl border border-white/10 bg-white/[0.03]" }, previewImage ? /* @__PURE__ */ React.createElement("img", { src: previewImage, alt: item.title, className: "h-full w-full object-cover" }) : /* @__PURE__ */ React.createElement("div", { className: "flex h-full items-center justify-center text-xs uppercase tracking-[0.18em] text-slate-500" }, "No thumb")), - /* @__PURE__ */ React.createElement("div", { className: "min-w-0 flex-1" }, /* @__PURE__ */ React.createElement("div", { className: "text-sm font-semibold text-white" }, item.title), item.subtitle ? /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-xs uppercase tracking-[0.14em] text-slate-500" }, item.subtitle) : null, item.description ? /* @__PURE__ */ React.createElement("div", { className: "mt-2 line-clamp-2 text-xs leading-5 text-slate-400" }, item.description) : null) - ); - })) : null), /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-end gap-3 border-t border-white/[0.06] px-6 py-4" }, /* @__PURE__ */ React.createElement("button", { type: "button", onClick: onClose, className: "rounded-2xl border border-white/10 bg-white/[0.04] px-4 py-2.5 text-sm font-semibold text-white transition hover:bg-white/[0.08]" }, "Cancel"))) - ), - document.body - ); -} -function Toolbar({ - editor, - advancedNews = false, - sourceMode = false, - showStructureOutlines = false, - onToggleSourceMode, - onToggleStructureOutlines, - onInsertArtwork, - onInsertSocialEmbed, - onInsertVideoEmbed, - onInsertHashtag -}) { - if (!editor) return null; - const addLink = reactExports.useCallback(() => { - const prev = editor.getAttributes("link").href; - const url = window.prompt("URL", prev ?? "https://"); - if (url === null) return; - if (url === "") { - editor.chain().focus().extendMarkRange("link").unsetLink().run(); - } else { - editor.chain().focus().extendMarkRange("link").setLink({ href: url }).run(); - } - }, [editor]); - const addImage = reactExports.useCallback(() => { - const url = window.prompt("Image URL", "https://"); - if (url) { - editor.chain().focus().setImage({ src: url }).run(); - } - }, [editor]); - return /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center gap-0.5 border-b border-white/[0.06] px-2.5 py-2" }, /* @__PURE__ */ React.createElement(ToolbarBtn, { onClick: () => editor.chain().focus().toggleBold().run(), active: editor.isActive("bold"), title: "Bold (Ctrl+B)" }, /* @__PURE__ */ React.createElement("svg", { width: "15", height: "15", viewBox: "0 0 24 24", fill: "currentColor" }, /* @__PURE__ */ React.createElement("path", { d: "M6 4h8a4 4 0 014 4 4 4 0 01-4 4H6zm0 8h9a4 4 0 014 4 4 4 0 01-4 4H6z" }))), /* @__PURE__ */ React.createElement(ToolbarBtn, { onClick: () => editor.chain().focus().toggleItalic().run(), active: editor.isActive("italic"), title: "Italic (Ctrl+I)" }, /* @__PURE__ */ React.createElement("svg", { width: "15", height: "15", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "2" }, /* @__PURE__ */ React.createElement("line", { x1: "19", y1: "4", x2: "10", y2: "4" }), /* @__PURE__ */ React.createElement("line", { x1: "14", y1: "20", x2: "5", y2: "20" }), /* @__PURE__ */ React.createElement("line", { x1: "15", y1: "4", x2: "9", y2: "20" }))), /* @__PURE__ */ React.createElement(ToolbarBtn, { onClick: () => editor.chain().focus().toggleUnderline().run(), active: editor.isActive("underline"), title: "Underline (Ctrl+U)" }, /* @__PURE__ */ React.createElement("svg", { width: "15", height: "15", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "2" }, /* @__PURE__ */ React.createElement("path", { d: "M6 3v7a6 6 0 006 6 6 6 0 006-6V3" }), /* @__PURE__ */ React.createElement("line", { x1: "4", y1: "21", x2: "20", y2: "21" }))), /* @__PURE__ */ React.createElement(ToolbarBtn, { onClick: () => editor.chain().focus().toggleStrike().run(), active: editor.isActive("strike"), title: "Strikethrough" }, /* @__PURE__ */ React.createElement("svg", { width: "15", height: "15", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "2" }, /* @__PURE__ */ React.createElement("line", { x1: "4", y1: "12", x2: "20", y2: "12" }), /* @__PURE__ */ React.createElement("path", { d: "M17.5 7.5c0-2-1.5-3.5-5.5-3.5S6.5 5.5 6.5 7.5c0 4 11 4 11 8 0 2-1.5 3.5-5.5 3.5s-5.5-1.5-5.5-3.5" }))), /* @__PURE__ */ React.createElement(Divider, null), /* @__PURE__ */ React.createElement(ToolbarBtn, { onClick: () => editor.chain().focus().toggleHeading({ level: 2 }).run(), active: editor.isActive("heading", { level: 2 }), title: "Heading 2" }, /* @__PURE__ */ React.createElement("span", { className: "text-xs font-bold" }, "H2")), /* @__PURE__ */ React.createElement(ToolbarBtn, { onClick: () => editor.chain().focus().toggleHeading({ level: 3 }).run(), active: editor.isActive("heading", { level: 3 }), title: "Heading 3" }, /* @__PURE__ */ React.createElement("span", { className: "text-xs font-bold" }, "H3")), /* @__PURE__ */ React.createElement(Divider, null), /* @__PURE__ */ React.createElement(ToolbarBtn, { onClick: () => editor.chain().focus().toggleBulletList().run(), active: editor.isActive("bulletList"), title: "Bullet list" }, /* @__PURE__ */ React.createElement("svg", { width: "15", height: "15", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "2" }, /* @__PURE__ */ React.createElement("line", { x1: "9", y1: "6", x2: "20", y2: "6" }), /* @__PURE__ */ React.createElement("line", { x1: "9", y1: "12", x2: "20", y2: "12" }), /* @__PURE__ */ React.createElement("line", { x1: "9", y1: "18", x2: "20", y2: "18" }), /* @__PURE__ */ React.createElement("circle", { cx: "4.5", cy: "6", r: "1", fill: "currentColor" }), /* @__PURE__ */ React.createElement("circle", { cx: "4.5", cy: "12", r: "1", fill: "currentColor" }), /* @__PURE__ */ React.createElement("circle", { cx: "4.5", cy: "18", r: "1", fill: "currentColor" }))), /* @__PURE__ */ React.createElement(ToolbarBtn, { onClick: () => editor.chain().focus().toggleOrderedList().run(), active: editor.isActive("orderedList"), title: "Numbered list" }, /* @__PURE__ */ React.createElement("svg", { width: "15", height: "15", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "2" }, /* @__PURE__ */ React.createElement("line", { x1: "10", y1: "6", x2: "21", y2: "6" }), /* @__PURE__ */ React.createElement("line", { x1: "10", y1: "12", x2: "21", y2: "12" }), /* @__PURE__ */ React.createElement("line", { x1: "10", y1: "18", x2: "21", y2: "18" }), /* @__PURE__ */ React.createElement("text", { x: "3", y: "8", fontSize: "7", fill: "currentColor", stroke: "none", fontFamily: "sans-serif" }, "1"), /* @__PURE__ */ React.createElement("text", { x: "3", y: "14", fontSize: "7", fill: "currentColor", stroke: "none", fontFamily: "sans-serif" }, "2"), /* @__PURE__ */ React.createElement("text", { x: "3", y: "20", fontSize: "7", fill: "currentColor", stroke: "none", fontFamily: "sans-serif" }, "3"))), /* @__PURE__ */ React.createElement(Divider, null), /* @__PURE__ */ React.createElement(ToolbarBtn, { onClick: () => editor.chain().focus().toggleBlockquote().run(), active: editor.isActive("blockquote"), title: "Quote" }, /* @__PURE__ */ React.createElement("svg", { width: "15", height: "15", viewBox: "0 0 24 24", fill: "currentColor" }, /* @__PURE__ */ React.createElement("path", { d: "M4.583 17.321C3.553 16.227 3 15 3 13.011c0-3.5 2.457-6.637 6.03-8.188l.893 1.378c-3.335 1.804-3.987 4.145-4.247 5.621.537-.278 1.24-.375 1.929-.311C9.591 11.68 11 13.24 11 15.14c0 .94-.36 1.84-1.001 2.503A3.34 3.34 0 017.559 18.6a3.77 3.77 0 01-2.976-.879zm10.4 0C13.953 16.227 13.4 15 13.4 13.011c0-3.5 2.457-6.637 6.03-8.188l.893 1.378c-3.335 1.804-3.987 4.145-4.247 5.621.537-.278 1.24-.375 1.929-.311 1.986.169 3.395 1.729 3.395 3.629 0 .94-.36 1.84-1.001 2.503a3.34 3.34 0 01-2.44.957 3.77 3.77 0 01-2.976-.879z" }))), /* @__PURE__ */ React.createElement(ToolbarBtn, { onClick: () => editor.chain().focus().toggleCodeBlock().run(), active: editor.isActive("codeBlock"), title: "Code block" }, /* @__PURE__ */ React.createElement("svg", { width: "15", height: "15", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "2", strokeLinecap: "round", strokeLinejoin: "round" }, /* @__PURE__ */ React.createElement("polyline", { points: "16 18 22 12 16 6" }), /* @__PURE__ */ React.createElement("polyline", { points: "8 6 2 12 8 18" }))), /* @__PURE__ */ React.createElement(ToolbarBtn, { onClick: () => editor.chain().focus().toggleCode().run(), active: editor.isActive("code"), title: "Inline code" }, /* @__PURE__ */ React.createElement("span", { className: "font-mono text-[11px] font-bold" }, "{}")), /* @__PURE__ */ React.createElement(Divider, null), /* @__PURE__ */ React.createElement(ToolbarBtn, { onClick: addLink, active: editor.isActive("link"), title: "Link" }, /* @__PURE__ */ React.createElement("svg", { width: "15", height: "15", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "2", strokeLinecap: "round", strokeLinejoin: "round" }, /* @__PURE__ */ React.createElement("path", { d: "M10 13a5 5 0 007.54.54l3-3a5 5 0 00-7.07-7.07l-1.72 1.71" }), /* @__PURE__ */ React.createElement("path", { d: "M14 11a5 5 0 00-7.54-.54l-3 3a5 5 0 007.07 7.07l1.71-1.71" }))), /* @__PURE__ */ React.createElement(ToolbarBtn, { onClick: addImage, title: "Insert image" }, /* @__PURE__ */ React.createElement("svg", { width: "15", height: "15", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "2", strokeLinecap: "round", strokeLinejoin: "round" }, /* @__PURE__ */ React.createElement("rect", { x: "3", y: "3", width: "18", height: "18", rx: "2", ry: "2" }), /* @__PURE__ */ React.createElement("circle", { cx: "8.5", cy: "8.5", r: "1.5" }), /* @__PURE__ */ React.createElement("polyline", { points: "21 15 16 10 5 21" }))), /* @__PURE__ */ React.createElement(Divider, null), /* @__PURE__ */ React.createElement(ToolbarBtn, { onClick: () => editor.chain().focus().setHorizontalRule().run(), title: "Horizontal rule" }, /* @__PURE__ */ React.createElement("svg", { width: "15", height: "15", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "2" }, /* @__PURE__ */ React.createElement("line", { x1: "3", y1: "12", x2: "21", y2: "12" }))), /* @__PURE__ */ React.createElement(EmojiPicker$1, { editor }), /* @__PURE__ */ React.createElement(ToolbarBtn, { onClick: () => editor.chain().focus().insertContent("@").run(), title: "Mention a user (type @username)" }, /* @__PURE__ */ React.createElement("span", { className: "text-xs font-bold" }, "@")), advancedNews ? /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement(Divider, null), /* @__PURE__ */ React.createElement(ToolbarBtn, { onClick: onToggleSourceMode, active: sourceMode, title: "View or edit source HTML", className: "w-auto px-2.5" }, /* @__PURE__ */ React.createElement("span", { className: "text-[11px] font-bold uppercase tracking-[0.14em]" }, "HTML")), /* @__PURE__ */ React.createElement(ToolbarBtn, { onClick: onToggleStructureOutlines, active: showStructureOutlines, title: "Outline blocks (p, div, figure, list)", className: "w-auto px-2.5" }, /* @__PURE__ */ React.createElement("span", { className: "text-[11px] font-bold uppercase tracking-[0.14em]" }, "DOM")), /* @__PURE__ */ React.createElement(ToolbarBtn, { onClick: onInsertArtwork, title: "Embed artwork", className: "w-auto px-2.5" }, /* @__PURE__ */ React.createElement("span", { className: "text-[11px] font-bold uppercase tracking-[0.14em]" }, "Art")), /* @__PURE__ */ React.createElement(ToolbarBtn, { onClick: onInsertSocialEmbed, title: "Embed social post", className: "w-auto px-2.5" }, /* @__PURE__ */ React.createElement("span", { className: "text-[11px] font-bold uppercase tracking-[0.14em]" }, "Social")), /* @__PURE__ */ React.createElement(ToolbarBtn, { onClick: onInsertVideoEmbed, title: "Embed YouTube", className: "w-auto px-2.5" }, /* @__PURE__ */ React.createElement("span", { className: "text-[11px] font-bold uppercase tracking-[0.14em]" }, "YT")), /* @__PURE__ */ React.createElement(ToolbarBtn, { onClick: onInsertHashtag, title: "Insert hashtag", className: "w-auto px-2.5" }, /* @__PURE__ */ React.createElement("span", { className: "text-xs font-bold" }, "#"))) : null, /* @__PURE__ */ React.createElement("div", { className: "ml-auto flex items-center gap-0.5" }, /* @__PURE__ */ React.createElement(ToolbarBtn, { onClick: () => editor.chain().focus().undo().run(), disabled: !editor.can().undo(), title: "Undo (Ctrl+Z)" }, /* @__PURE__ */ React.createElement("svg", { width: "15", height: "15", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "2", strokeLinecap: "round", strokeLinejoin: "round" }, /* @__PURE__ */ React.createElement("polyline", { points: "1 4 1 10 7 10" }), /* @__PURE__ */ React.createElement("path", { d: "M3.51 15a9 9 0 102.13-9.36L1 10" }))), /* @__PURE__ */ React.createElement(ToolbarBtn, { onClick: () => editor.chain().focus().redo().run(), disabled: !editor.can().redo(), title: "Redo (Ctrl+Shift+Z)" }, /* @__PURE__ */ React.createElement("svg", { width: "15", height: "15", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "2", strokeLinecap: "round", strokeLinejoin: "round" }, /* @__PURE__ */ React.createElement("polyline", { points: "23 4 23 10 17 10" }), /* @__PURE__ */ React.createElement("path", { d: "M20.49 15a9 9 0 11-2.13-9.36L23 10" }))))); -} -function RichTextEditor({ - content: content2 = "", - onChange, - placeholder = "Write something…", - error, - minHeight = 12, - autofocus = false, - advancedNews = false, - searchEntities = null -}) { - const [sourceMode, setSourceMode] = reactExports.useState(false); - const [sourceValue, setSourceValue] = reactExports.useState(String(content2 || "")); - const [showStructureOutlines, setShowStructureOutlines] = reactExports.useState(false); - const [helperMessage, setHelperMessage] = reactExports.useState(""); - const [artworkPickerOpen, setArtworkPickerOpen] = reactExports.useState(false); - const [artworkQuery, setArtworkQuery] = reactExports.useState(""); - const [artworkResults, setArtworkResults] = reactExports.useState([]); - const [artworkLoading, setArtworkLoading] = reactExports.useState(false); - const extensions = reactExports.useMemo(() => { - const base = [ - index_default.configure({ - link: false, - underline: false, - heading: { levels: [2, 3] }, - codeBlock: { - HTMLAttributes: { class: "forum-code-block" } - } - }), - index_default$3, - index_default$1.configure({ - openOnClick: false, - HTMLAttributes: { - class: "text-sky-300 underline hover:text-sky-200", - rel: "noopener noreferrer nofollow" - } - }), - index_default$4.configure({ - HTMLAttributes: { class: "rounded-lg max-w-full" } - }), - index_default$2.configure({ placeholder }), - index_default$5.configure({ - HTMLAttributes: { - class: "mention" - }, - suggestion: mentionSuggestion - }) - ]; - if (advancedNews) { - base.push(ArtworkEmbed, VideoEmbed, SocialEmbed); - } - return base; - }, [advancedNews, placeholder]); - const editor = useEditor({ - extensions, - immediatelyRender: false, - content: content2, - autofocus, - editorProps: { - attributes: { - class: [ - "prose prose-invert prose-sm max-w-none", - "focus:outline-none", - "px-4 py-3", - "prose-headings:text-white prose-headings:font-bold", - "prose-p:text-zinc-200 prose-p:leading-relaxed", - "prose-a:text-sky-300 prose-a:no-underline hover:prose-a:text-sky-200", - "prose-blockquote:border-l-sky-500/50 prose-blockquote:text-zinc-400", - "prose-code:text-amber-300 prose-code:bg-white/[0.06] prose-code:rounded prose-code:px-1.5 prose-code:py-0.5 prose-code:text-xs", - "prose-pre:bg-white/[0.04] prose-pre:border prose-pre:border-white/[0.06] prose-pre:rounded-xl", - "prose-img:rounded-xl", - "prose-hr:border-white/10" - ].join(" "), - style: `min-height: ${minHeight}rem` - } - }, - onUpdate: ({ editor: currentEditor }) => { - if (!sourceMode) { - onChange?.(currentEditor.getHTML()); - } - } - }); - reactExports.useEffect(() => { - if (!helperMessage) { - return void 0; - } - const timeout = window.setTimeout(() => setHelperMessage(""), 2200); - return () => window.clearTimeout(timeout); - }, [helperMessage]); - reactExports.useEffect(() => { - if (!editor) return; - if (sourceMode) return; - if ((content2 || "") === editor.getHTML()) return; - editor.commands.setContent(content2 || "", false); - const normalizedHtml = editor.getHTML(); - if (normalizedHtml !== (content2 || "")) { - onChange?.(normalizedHtml); - } - }, [content2, editor, onChange, sourceMode]); - reactExports.useEffect(() => { - if (sourceMode) { - setSourceValue(String(content2 || editor?.getHTML() || "")); - } - }, [content2, editor, sourceMode]); - const pushHelperMessage = reactExports.useCallback((message) => { - setHelperMessage(message); - }, []); - const handleToggleSourceMode = reactExports.useCallback(() => { - if (sourceMode) { - setSourceMode(false); - if (editor) { - editor.commands.setContent(sourceValue || "", false); - } - pushHelperMessage("Returned to visual editor."); - return; - } - setSourceValue(editor?.getHTML() || String(content2 || "")); - setSourceMode(true); - }, [content2, editor, pushHelperMessage, sourceMode, sourceValue]); - const insertArtworkEmbed = reactExports.useCallback((item) => { - if (!editor || !item) return; - editor.chain().focus().insertContent({ - type: "artworkEmbed", - attrs: { - title: item.title || "Embedded artwork", - url: item.url || "#", - thumb: item.image || item.avatar || "" - } - }).run(); - }, [editor]); - const runArtworkSearch = reactExports.useCallback(async () => { - if (typeof searchEntities !== "function") { - return; - } - setArtworkLoading(true); - try { - const items = await searchEntities("artwork", artworkQuery); - setArtworkResults(Array.isArray(items) ? items : []); - } finally { - setArtworkLoading(false); - } - }, [artworkQuery, searchEntities]); - reactExports.useEffect(() => { - if (!artworkPickerOpen || typeof searchEntities !== "function") { - return; - } - runArtworkSearch(); - }, [artworkPickerOpen, runArtworkSearch, searchEntities]); - const handleInsertArtwork = reactExports.useCallback(() => { - if (!editor) return; - if (typeof searchEntities === "function") { - setArtworkPickerOpen(true); - return; - } - const url = normalizeHttpUrl(window.prompt("Artwork URL", "https://skinbase.org/art/") || ""); - if (!url) { - pushHelperMessage("Artwork URL is required."); - return; - } - const title = window.prompt("Artwork title", "Embedded artwork"); - if (title === null) return; - const thumb = normalizeHttpUrl(window.prompt("Artwork thumbnail URL (optional)", "") || "") || ""; - insertArtworkEmbed({ - title: title || "Embedded artwork", - url, - image: thumb - }); - }, [editor, insertArtworkEmbed, pushHelperMessage, searchEntities]); - const handleInsertSocialEmbed = reactExports.useCallback(() => { - if (!editor) return; - const detected = detectSocialPlatform(window.prompt("Social post URL", "https://") || ""); - if (!detected.url) { - pushHelperMessage("Social post URL is required."); - return; - } - const label = window.prompt("Label (optional)", detected.label); - if (label === null) return; - editor.chain().focus().insertContent({ - type: "socialEmbed", - attrs: { - url: detected.url, - platform: detected.platform, - label: label || detected.label - } - }).run(); - }, [editor, pushHelperMessage]); - const handleInsertVideoEmbed = reactExports.useCallback(() => { - if (!editor) return; - const rawUrl = window.prompt("YouTube URL", "https://www.youtube.com/watch?v=") || ""; - const embedUrl = normalizeVideoEmbedUrl(rawUrl); - const sourceUrl = normalizeHttpUrl(rawUrl); - if (!embedUrl || !sourceUrl) { - pushHelperMessage("A valid YouTube URL is required."); - return; - } - const title = window.prompt("Video title (optional)", "Embedded YouTube video"); - if (title === null) return; - editor.chain().focus().insertContent({ - type: "videoEmbed", - attrs: { - src: embedUrl, - url: sourceUrl, - title: title || "Embedded YouTube video" - } - }).run(); - }, [editor, pushHelperMessage]); - const handleInsertHashtag = reactExports.useCallback(() => { - if (!editor) return; - const value = String(window.prompt("Hashtag", "release") || "").trim().replace(/^#+/, "").replace(/\s+/g, "-"); - if (!value) return; - editor.chain().focus().insertContent(`#${value}`).run(); - }, [editor]); - return /* @__PURE__ */ React.createElement("div", { className: "flex flex-col gap-1.5" }, /* @__PURE__ */ React.createElement( - "div", - { - className: [ - "news-rich-text-editor overflow-hidden rounded-xl border bg-white/[0.04] transition-colors", - error ? "border-red-500/60 focus-within:border-red-500/70 focus-within:ring-2 focus-within:ring-red-500/30" : "border-white/12 hover:border-white/20 focus-within:border-sky-500/50 focus-within:ring-2 focus-within:ring-sky-500/20" - ].join(" ") - }, - /* @__PURE__ */ React.createElement( - Toolbar, - { - editor, - advancedNews, - sourceMode, - showStructureOutlines, - onToggleSourceMode: handleToggleSourceMode, - onToggleStructureOutlines: () => setShowStructureOutlines((current) => !current), - onInsertArtwork: handleInsertArtwork, - onInsertSocialEmbed: handleInsertSocialEmbed, - onInsertVideoEmbed: handleInsertVideoEmbed, - onInsertHashtag: handleInsertHashtag - } - ), - advancedNews && sourceMode ? /* @__PURE__ */ React.createElement("div", { className: "border-t border-white/[0.04] bg-black/10 px-4 py-3" }, /* @__PURE__ */ React.createElement("div", { className: "mb-2 flex items-center justify-between gap-3 text-xs text-slate-400" }, /* @__PURE__ */ React.createElement("span", null, "Edit the stored article HTML directly. Saving while in this mode keeps the HTML exactly as written here."), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: handleToggleSourceMode, className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-1.5 font-semibold text-white transition hover:bg-white/[0.08]" }, "Back to visual")), /* @__PURE__ */ React.createElement( - "textarea", - { - value: sourceValue, - onChange: (event) => { - const nextValue = event.target.value; - setSourceValue(nextValue); - onChange?.(nextValue); - }, - spellCheck: false, - className: "nova-scrollbar min-h-[20rem] w-full rounded-xl border border-white/10 bg-slate-950/85 px-4 py-3 font-mono text-sm leading-6 text-slate-100 outline-none", - style: { minHeight: `${Math.max(minHeight, 20)}rem` } - } - )) : /* @__PURE__ */ React.createElement("div", { className: advancedNews && showStructureOutlines ? "news-editor-outline" : "" }, /* @__PURE__ */ React.createElement(EditorContent, { editor })) - ), advancedNews && helperMessage ? /* @__PURE__ */ React.createElement("p", { className: "text-xs text-sky-300" }, helperMessage) : null, error ? /* @__PURE__ */ React.createElement("p", { role: "alert", className: "text-xs text-red-400" }, error) : null, /* @__PURE__ */ React.createElement( - ArtworkPickerDialog, - { - open: artworkPickerOpen, - query: artworkQuery, - items: artworkResults, - loading: artworkLoading, - onQueryChange: setArtworkQuery, - onClose: () => setArtworkPickerOpen(false), - onSearch: runArtworkSearch, - onSelect: (item) => { - insertArtworkEmbed(item); - setArtworkPickerOpen(false); - pushHelperMessage(`Embedded artwork: ${item.title || "Artwork"}.`); - } - } - )); -} const providerAdapters = { turnstile: { globalName: "turnstile", @@ -72368,7 +75290,7 @@ function ForumEditPost({ post: post2, thread, csrfToken: csrfToken2, errors = {} ), /* @__PURE__ */ React.createElement(Button$1, { type: "submit", variant: "primary", size: "md", loading: submitting }, "Save changes")) ))); } -const __vite_glob_0_49 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ +const __vite_glob_0_50 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ __proto__: null, default: ForumEditPost }, Symbol.toStringTag, { value: "Module" })); @@ -72459,7 +75381,7 @@ function formatLastActivity(value) { } return `Updated ${date.toLocaleDateString("en-GB", { day: "2-digit", month: "short", year: "numeric" })}`; } -const __vite_glob_0_50 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ +const __vite_glob_0_51 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ __proto__: null, default: ForumIndex }, Symbol.toStringTag, { value: "Module" })); @@ -72580,7 +75502,7 @@ function ForumNewThread({ category, csrfToken: csrfToken2, errors = {}, oldValue /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between pt-2" }, /* @__PURE__ */ React.createElement("a", { href: `/forum/${slug}`, className: "text-sm text-zinc-500 hover:text-zinc-300 transition-colors" }, "← Cancel"), /* @__PURE__ */ React.createElement(Button$1, { type: "submit", variant: "primary", size: "md", loading: submitting }, "Publish topic")) ))); } -const __vite_glob_0_51 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ +const __vite_glob_0_52 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ __proto__: null, default: ForumNewThread }, Symbol.toStringTag, { value: "Module" })); @@ -72595,7 +75517,7 @@ function ForumSection({ category, boards = [], seo = {} }) { ]; return /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement(SeoHead, { seo }), /* @__PURE__ */ React.createElement("div", { className: "mx-auto max-w-6xl px-4 pb-20 pt-10 sm:px-6 lg:px-8" }, /* @__PURE__ */ React.createElement(Breadcrumbs, { items: breadcrumbs }), /* @__PURE__ */ React.createElement("section", { className: "mt-5 overflow-hidden rounded-3xl border border-white/10 bg-nova-800/55 shadow-xl backdrop-blur" }, /* @__PURE__ */ React.createElement("div", { className: "relative h-56 overflow-hidden sm:h-64" }, /* @__PURE__ */ React.createElement("img", { src: preview, alt: `${name2} preview`, className: "h-full w-full object-cover object-center" }), /* @__PURE__ */ React.createElement("div", { className: "absolute inset-0 bg-gradient-to-t from-black/85 via-black/35 to-transparent" }), /* @__PURE__ */ React.createElement("div", { className: "absolute inset-x-0 bottom-0 p-6 sm:p-8" }, /* @__PURE__ */ React.createElement("p", { className: "text-xs font-semibold uppercase tracking-[0.18em] text-cyan-200/85" }, "Forum Section"), /* @__PURE__ */ React.createElement("h1", { className: "mt-2 text-3xl font-black text-white sm:text-4xl" }, name2), description && /* @__PURE__ */ React.createElement("p", { className: "mt-2 max-w-3xl text-sm text-white/70 sm:text-base" }, description)))), /* @__PURE__ */ React.createElement("section", { className: "mt-8 rounded-2xl border border-white/8 bg-nova-800/45 p-5 backdrop-blur sm:p-6" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-end justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-xs font-semibold uppercase tracking-[0.16em] text-white/40" }, "Subcategories"), /* @__PURE__ */ React.createElement("h2", { className: "mt-1 text-2xl font-bold text-white" }, "Browse boards")), /* @__PURE__ */ React.createElement("p", { className: "text-xs text-white/45 sm:text-sm" }, "Select a board to open its thread list.")), boards.length === 0 ? /* @__PURE__ */ React.createElement("div", { className: "py-12 text-center text-sm text-white/45" }, "No boards are available in this section yet.") : /* @__PURE__ */ React.createElement("div", { className: "mt-5 grid gap-4 md:grid-cols-2" }, boards.map((board) => /* @__PURE__ */ React.createElement("a", { key: board.id ?? board.slug, href: `/forum/${board.slug}`, className: "rounded-2xl border border-white/8 bg-white/[0.02] p-5 transition hover:border-cyan-400/25 hover:bg-white/[0.04]" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-start justify-between gap-4" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("h3", { className: "text-lg font-semibold text-white" }, board.title), board.description && /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm text-white/55" }, board.description)), /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-cyan-300/20 bg-cyan-300/10 px-2.5 py-1 text-[11px] font-semibold uppercase tracking-[0.14em] text-cyan-200" }, "Open")), /* @__PURE__ */ React.createElement("div", { className: "mt-4 flex flex-wrap gap-4 text-xs text-white/50" }, /* @__PURE__ */ React.createElement("span", null, board.topics_count ?? 0, " topics"), /* @__PURE__ */ React.createElement("span", null, board.posts_count ?? 0, " posts"), board.latest_topic?.title && /* @__PURE__ */ React.createElement("span", null, "Latest: ", board.latest_topic.title)))))))); } -const __vite_glob_0_52 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ +const __vite_glob_0_53 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ __proto__: null, default: ForumSection }, Symbol.toStringTag, { value: "Module" })); @@ -72674,7 +75596,7 @@ function PostCard({ post: post2, thread, isOp = false, isAuthenticated = false, id: `post-${postId}`, className: "overflow-hidden rounded-2xl border border-white/[0.06] bg-nova-800/50 backdrop-blur transition-all hover:border-white/10" }, - /* @__PURE__ */ React.createElement("header", { className: "flex flex-col gap-3 border-b border-white/[0.06] px-5 py-4 sm:flex-row sm:items-center sm:justify-between" }, /* @__PURE__ */ React.createElement(AuthorBadge, { user: author }), /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-2 text-xs text-zinc-500" }, postedAt && /* @__PURE__ */ React.createElement("time", { dateTime: postedAt }, formatDate$d(postedAt)), isOp && /* @__PURE__ */ React.createElement("span", { className: "rounded-full bg-cyan-500/15 px-2.5 py-0.5 text-[11px] font-medium text-cyan-300" }, "OP"))), + /* @__PURE__ */ React.createElement("header", { className: "flex flex-col gap-3 border-b border-white/[0.06] px-5 py-4 sm:flex-row sm:items-center sm:justify-between" }, /* @__PURE__ */ React.createElement(AuthorBadge, { user: author }), /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-2 text-xs text-zinc-500" }, postedAt && /* @__PURE__ */ React.createElement("time", { dateTime: postedAt }, formatDate$c(postedAt)), isOp && /* @__PURE__ */ React.createElement("span", { className: "rounded-full bg-cyan-500/15 px-2.5 py-0.5 text-[11px] font-medium text-cyan-300" }, "OP"))), /* @__PURE__ */ React.createElement("div", { className: "px-5 py-5" }, /* @__PURE__ */ React.createElement( "div", { @@ -72739,7 +75661,7 @@ function AttachmentItem({ attachment }) { function getCsrf$1() { return document.querySelector('meta[name="csrf-token"]')?.getAttribute("content") ?? ""; } -function formatDate$d(dateStr) { +function formatDate$c(dateStr) { try { const d2 = new Date(dateStr); return d2.toLocaleDateString("en-GB", { day: "2-digit", month: "2-digit", year: "numeric" }) + " " + d2.toLocaleTimeString("en-GB", { hour: "2-digit", minute: "2-digit" }); @@ -72756,7 +75678,7 @@ function formatTimeAgo(dateStr) { if (diff < 3600) return `${Math.floor(diff / 60)}m ago`; if (diff < 86400) return `${Math.floor(diff / 3600)}h ago`; if (diff < 604800) return `${Math.floor(diff / 86400)}d ago`; - return formatDate$d(dateStr); + return formatDate$c(dateStr); } catch { return ""; } @@ -72881,7 +75803,7 @@ function ForumThread({ url.searchParams.set("sort", newSort); window.location.href = url.toString(); }, [currentSort]); - return /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement(SeoHead, { seo }), /* @__PURE__ */ React.createElement("div", { className: "px-4 pt-10 pb-20 sm:px-6 lg:px-8 max-w-5xl mx-auto space-y-5" }, /* @__PURE__ */ React.createElement(Breadcrumbs, { items: breadcrumbs }), status2 && /* @__PURE__ */ React.createElement("div", { className: "rounded-xl border border-emerald-500/20 bg-emerald-500/10 px-4 py-3 text-sm text-emerald-300" }, status2), /* @__PURE__ */ React.createElement("section", { className: "rounded-2xl border border-white/[0.06] bg-nova-800/50 p-5 backdrop-blur" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-col gap-4 sm:flex-row sm:items-start sm:justify-between" }, /* @__PURE__ */ React.createElement("div", { className: "min-w-0" }, /* @__PURE__ */ React.createElement("h1", { className: "text-2xl font-bold text-white leading-snug" }, thread?.title), thread?.description ? /* @__PURE__ */ React.createElement("p", { className: "mt-3 max-w-3xl text-sm leading-6 text-zinc-300 sm:text-[15px]" }, thread.description) : null, /* @__PURE__ */ React.createElement("div", { className: "mt-2 flex flex-wrap items-center gap-2 text-xs text-zinc-500" }, /* @__PURE__ */ React.createElement("span", null, "By ", author?.name ?? "Unknown"), /* @__PURE__ */ React.createElement("span", { className: "text-zinc-700" }, "•"), thread?.created_at && /* @__PURE__ */ React.createElement("time", { dateTime: thread.created_at }, formatDate$c(thread.created_at)))), /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center gap-2 text-xs" }, /* @__PURE__ */ React.createElement("span", { className: "rounded-full bg-sky-500/15 px-2.5 py-1 text-sky-300" }, number(thread?.views ?? 0), " views"), /* @__PURE__ */ React.createElement("span", { className: "rounded-full bg-cyan-500/15 px-2.5 py-1 text-cyan-300" }, number(replyCount), " replies"), thread?.is_pinned && /* @__PURE__ */ React.createElement("span", { className: "rounded-full bg-amber-500/15 px-2.5 py-1 text-amber-300" }, "Pinned"), thread?.is_locked && /* @__PURE__ */ React.createElement("span", { className: "rounded-full bg-red-500/15 px-2.5 py-1 text-red-300" }, "Locked"))), canModerate && /* @__PURE__ */ React.createElement("div", { className: "mt-4 flex flex-wrap items-center gap-2 border-t border-white/[0.06] pt-3" }, thread?.is_locked ? /* @__PURE__ */ React.createElement(ModForm, { action: `/forum/topic/${thread.slug}/unlock`, csrf: csrfToken2, label: "Unlock", variant: "danger" }) : /* @__PURE__ */ React.createElement(ModForm, { action: `/forum/topic/${thread.slug}/lock`, csrf: csrfToken2, label: "Lock", variant: "danger" }), thread?.is_pinned ? /* @__PURE__ */ React.createElement(ModForm, { action: `/forum/topic/${thread.slug}/unpin`, csrf: csrfToken2, label: "Unpin", variant: "warning" }) : /* @__PURE__ */ React.createElement(ModForm, { action: `/forum/topic/${thread.slug}/pin`, csrf: csrfToken2, label: "Pin", variant: "warning" }))), /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between" }, /* @__PURE__ */ React.createElement("p", { className: "text-xs text-zinc-500" }, number(replyCount), " ", replyCount === 1 ? "reply" : "replies"), /* @__PURE__ */ React.createElement( + return /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement(SeoHead, { seo }), /* @__PURE__ */ React.createElement("div", { className: "px-4 pt-10 pb-20 sm:px-6 lg:px-8 max-w-5xl mx-auto space-y-5" }, /* @__PURE__ */ React.createElement(Breadcrumbs, { items: breadcrumbs }), status2 && /* @__PURE__ */ React.createElement("div", { className: "rounded-xl border border-emerald-500/20 bg-emerald-500/10 px-4 py-3 text-sm text-emerald-300" }, status2), /* @__PURE__ */ React.createElement("section", { className: "rounded-2xl border border-white/[0.06] bg-nova-800/50 p-5 backdrop-blur" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-col gap-4 sm:flex-row sm:items-start sm:justify-between" }, /* @__PURE__ */ React.createElement("div", { className: "min-w-0" }, /* @__PURE__ */ React.createElement("h1", { className: "text-2xl font-bold text-white leading-snug" }, thread?.title), thread?.description ? /* @__PURE__ */ React.createElement("p", { className: "mt-3 max-w-3xl text-sm leading-6 text-zinc-300 sm:text-[15px]" }, thread.description) : null, /* @__PURE__ */ React.createElement("div", { className: "mt-2 flex flex-wrap items-center gap-2 text-xs text-zinc-500" }, /* @__PURE__ */ React.createElement("span", null, "By ", author?.name ?? "Unknown"), /* @__PURE__ */ React.createElement("span", { className: "text-zinc-700" }, "•"), thread?.created_at && /* @__PURE__ */ React.createElement("time", { dateTime: thread.created_at }, formatDate$b(thread.created_at)))), /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center gap-2 text-xs" }, /* @__PURE__ */ React.createElement("span", { className: "rounded-full bg-sky-500/15 px-2.5 py-1 text-sky-300" }, number(thread?.views ?? 0), " views"), /* @__PURE__ */ React.createElement("span", { className: "rounded-full bg-cyan-500/15 px-2.5 py-1 text-cyan-300" }, number(replyCount), " replies"), thread?.is_pinned && /* @__PURE__ */ React.createElement("span", { className: "rounded-full bg-amber-500/15 px-2.5 py-1 text-amber-300" }, "Pinned"), thread?.is_locked && /* @__PURE__ */ React.createElement("span", { className: "rounded-full bg-red-500/15 px-2.5 py-1 text-red-300" }, "Locked"))), canModerate && /* @__PURE__ */ React.createElement("div", { className: "mt-4 flex flex-wrap items-center gap-2 border-t border-white/[0.06] pt-3" }, thread?.is_locked ? /* @__PURE__ */ React.createElement(ModForm, { action: `/forum/topic/${thread.slug}/unlock`, csrf: csrfToken2, label: "Unlock", variant: "danger" }) : /* @__PURE__ */ React.createElement(ModForm, { action: `/forum/topic/${thread.slug}/lock`, csrf: csrfToken2, label: "Lock", variant: "danger" }), thread?.is_pinned ? /* @__PURE__ */ React.createElement(ModForm, { action: `/forum/topic/${thread.slug}/unpin`, csrf: csrfToken2, label: "Unpin", variant: "warning" }) : /* @__PURE__ */ React.createElement(ModForm, { action: `/forum/topic/${thread.slug}/pin`, csrf: csrfToken2, label: "Pin", variant: "warning" }))), /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between" }, /* @__PURE__ */ React.createElement("p", { className: "text-xs text-zinc-500" }, number(replyCount), " ", replyCount === 1 ? "reply" : "replies"), /* @__PURE__ */ React.createElement( "button", { onClick: handleSortToggle, @@ -72925,7 +75847,7 @@ function ModForm({ action, csrf, label, variant }) { function number(n) { return (n ?? 0).toLocaleString(); } -function formatDate$c(dateStr) { +function formatDate$b(dateStr) { try { const d2 = new Date(dateStr); return d2.toLocaleDateString("en-GB", { day: "2-digit", month: "2-digit", year: "numeric" }) + " " + d2.toLocaleTimeString("en-GB", { hour: "2-digit", minute: "2-digit" }); @@ -72933,7 +75855,7 @@ function formatDate$c(dateStr) { return ""; } } -const __vite_glob_0_53 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ +const __vite_glob_0_54 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ __proto__: null, default: ForumThread }, Symbol.toStringTag, { value: "Module" })); @@ -73177,7 +76099,7 @@ function GroupChallengeShow() { const outcomeSections = challenge.outcome_sections || {}; return /* @__PURE__ */ React.createElement("main", { className: "min-h-screen bg-[radial-gradient(circle_at_top_left,_rgba(234,179,8,0.15),_transparent_28%),linear-gradient(180deg,_#020617_0%,_#02040a_100%)] px-4 py-10 sm:px-6 lg:px-8" }, /* @__PURE__ */ React.createElement(SeoHead, { seo: props.seo || {}, title: `${challenge.title || group.name} - Skinbase`, description: challenge.summary || challenge.description || "Group challenge" }), /* @__PURE__ */ React.createElement("div", { className: "mx-auto max-w-6xl space-y-8" }, /* @__PURE__ */ React.createElement("section", { className: "overflow-hidden rounded-[32px] border border-white/10 bg-white/[0.03]" }, challenge.cover_url ? /* @__PURE__ */ React.createElement("img", { src: challenge.cover_url, alt: challenge.title, className: "h-56 w-full object-cover" }) : /* @__PURE__ */ React.createElement("div", { className: "h-40 bg-white/[0.03]" }), /* @__PURE__ */ React.createElement("div", { className: "p-6" }, /* @__PURE__ */ React.createElement("a", { href: group.urls?.public, className: "text-sm font-semibold text-amber-200" }, group.name), /* @__PURE__ */ React.createElement("h1", { className: "mt-4 text-4xl font-semibold text-white" }, challenge.title), /* @__PURE__ */ React.createElement("p", { className: "mt-4 max-w-3xl text-sm leading-7 text-slate-300" }, challenge.summary || challenge.description || "Group challenge"), /* @__PURE__ */ React.createElement("div", { className: "mt-5 flex flex-wrap gap-3 text-xs uppercase tracking-[0.16em] text-slate-400" }, /* @__PURE__ */ React.createElement("span", null, challenge.status), /* @__PURE__ */ React.createElement("span", null, challenge.visibility), /* @__PURE__ */ React.createElement("span", null, String(challenge.participation_scope || "").replace("_", " ")), challenge.start_at ? /* @__PURE__ */ React.createElement("span", null, "Starts ", new Date(challenge.start_at).toLocaleDateString()) : null, challenge.end_at ? /* @__PURE__ */ React.createElement("span", null, "Ends ", new Date(challenge.end_at).toLocaleDateString()) : null), /* @__PURE__ */ React.createElement(ChallengeWorldLinkBadge, { world: linkedWorld, className: "mt-5" }))), /* @__PURE__ */ React.createElement("div", { className: "grid gap-8 xl:grid-cols-[minmax(0,1.15fr)_minmax(0,0.85fr)]" }, /* @__PURE__ */ React.createElement("section", { className: "rounded-[30px] border border-white/10 bg-white/[0.03] p-6" }, /* @__PURE__ */ React.createElement("h2", { className: "text-2xl font-semibold text-white" }, "Challenge brief"), /* @__PURE__ */ React.createElement("p", { className: "mt-4 text-sm leading-7 text-slate-300" }, challenge.description || "No extended challenge brief yet."), challenge.rules_text ? /* @__PURE__ */ React.createElement("div", { className: "mt-6 rounded-2xl border border-white/10 bg-black/20 p-4" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Rules"), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm leading-7 text-slate-300" }, challenge.rules_text)) : null, challenge.submission_instructions ? /* @__PURE__ */ React.createElement("div", { className: "mt-6 rounded-2xl border border-white/10 bg-black/20 p-4" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Submission instructions"), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm leading-7 text-slate-300" }, challenge.submission_instructions)) : null), /* @__PURE__ */ React.createElement("div", { className: "space-y-8" }, /* @__PURE__ */ React.createElement(OutcomeSection, { section: outcomeSections.winner }), /* @__PURE__ */ React.createElement(OutcomeSection, { section: outcomeSections.finalist }), /* @__PURE__ */ React.createElement(OutcomeSection, { section: outcomeSections.runner_up }), /* @__PURE__ */ React.createElement(OutcomeSection, { section: outcomeSections.honorable_mention }), /* @__PURE__ */ React.createElement(OutcomeSection, { section: outcomeSections.featured }), /* @__PURE__ */ React.createElement("section", { className: "rounded-[30px] border border-white/10 bg-white/[0.03] p-6" }, /* @__PURE__ */ React.createElement("h2", { className: "text-2xl font-semibold text-white" }, "Entries"), /* @__PURE__ */ React.createElement("div", { className: "mt-4 grid gap-4 sm:grid-cols-2 xl:grid-cols-1" }, Array.isArray(challenge.artworks) && challenge.artworks.length > 0 ? challenge.artworks.map((artwork) => /* @__PURE__ */ React.createElement("a", { key: artwork.id, href: artwork.url, className: "overflow-hidden rounded-[24px] border border-white/10 bg-black/20" }, artwork.thumb ? /* @__PURE__ */ React.createElement("img", { src: artwork.thumb, alt: artwork.title, className: "aspect-[4/3] w-full object-cover" }) : null, /* @__PURE__ */ React.createElement("div", { className: "p-4 text-white" }, artwork.title))) : /* @__PURE__ */ React.createElement("p", { className: "text-sm text-slate-400" }, "No entries linked yet."))))))); } -const __vite_glob_0_54 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ +const __vite_glob_0_55 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ __proto__: null, default: GroupChallengeShow }, Symbol.toStringTag, { value: "Module" })); @@ -73187,7 +76109,7 @@ function GroupEventShow() { const event = props.event || {}; return /* @__PURE__ */ React.createElement("main", { className: "min-h-screen bg-[radial-gradient(circle_at_top_left,_rgba(16,185,129,0.15),_transparent_28%),linear-gradient(180deg,_#020617_0%,_#02040a_100%)] px-4 py-10 sm:px-6 lg:px-8" }, /* @__PURE__ */ React.createElement(SeoHead, { seo: props.seo || {}, title: `${event.title || group.name} - Skinbase`, description: event.summary || event.description || "Group event" }), /* @__PURE__ */ React.createElement("div", { className: "mx-auto max-w-5xl space-y-8" }, /* @__PURE__ */ React.createElement("section", { className: "overflow-hidden rounded-[32px] border border-white/10 bg-white/[0.03]" }, event.cover_url ? /* @__PURE__ */ React.createElement("img", { src: event.cover_url, alt: event.title, className: "h-56 w-full object-cover" }) : /* @__PURE__ */ React.createElement("div", { className: "h-40 bg-white/[0.03]" }), /* @__PURE__ */ React.createElement("div", { className: "p-6" }, /* @__PURE__ */ React.createElement("a", { href: group.urls?.public, className: "text-sm font-semibold text-emerald-200" }, group.name), /* @__PURE__ */ React.createElement("h1", { className: "mt-4 text-4xl font-semibold text-white" }, event.title), /* @__PURE__ */ React.createElement("p", { className: "mt-4 max-w-3xl text-sm leading-7 text-slate-300" }, event.summary || event.description || "Group event"), /* @__PURE__ */ React.createElement("div", { className: "mt-5 grid gap-3 sm:grid-cols-2" }, /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-black/20 p-4 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Starts"), /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-white" }, event.start_at ? new Date(event.start_at).toLocaleString() : "Not scheduled")), /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-black/20 p-4 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Details"), /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-white" }, event.event_type, " • ", event.visibility), event.location ? /* @__PURE__ */ React.createElement("div", { className: "mt-2" }, event.location) : null)), event.external_url ? /* @__PURE__ */ React.createElement("a", { href: event.external_url, className: "mt-5 inline-flex rounded-full border border-white/10 bg-white/[0.04] px-4 py-2 text-sm font-semibold text-white" }, "Open external link") : null)), /* @__PURE__ */ React.createElement("section", { className: "rounded-[30px] border border-white/10 bg-white/[0.03] p-6" }, /* @__PURE__ */ React.createElement("h2", { className: "text-2xl font-semibold text-white" }, "About this event"), /* @__PURE__ */ React.createElement("p", { className: "mt-4 text-sm leading-7 text-slate-300" }, event.description || "No extended event details yet.")))); } -const __vite_glob_0_55 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ +const __vite_glob_0_56 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ __proto__: null, default: GroupEventShow }, Symbol.toStringTag, { value: "Module" })); @@ -73877,7 +76799,7 @@ function GroupFaqPage() { /* @__PURE__ */ React.createElement("div", { className: "mt-6 grid gap-4 md:grid-cols-2" }, /* @__PURE__ */ React.createElement("a", { href: links.contact_support, className: "rounded-[28px] border border-white/10 bg-black/20 p-5 transition hover:border-white/20 hover:bg-white/[0.05]" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, "Contact"), /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-lg font-semibold text-white" }, "Contact support"), /* @__PURE__ */ React.createElement("p", { className: "mt-3 text-sm leading-6 text-slate-300" }, "Use this if your question is not answered here or if you need help with an account or workflow issue.")), /* @__PURE__ */ React.createElement("a", { href: links.report_issue, className: "rounded-[28px] border border-white/10 bg-black/20 p-5 transition hover:border-white/20 hover:bg-white/[0.05]" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, "Report"), /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-lg font-semibold text-white" }, "Report a problem"), /* @__PURE__ */ React.createElement("p", { className: "mt-3 text-sm leading-6 text-slate-300" }, "Use this if a route, role, contributor record, or Group workflow appears broken rather than just unclear."))) )), /* @__PURE__ */ React.createElement("aside", { className: "hidden xl:block xl:sticky xl:top-24 xl:self-start" }, /* @__PURE__ */ React.createElement("div", { className: "space-y-4 rounded-[28px] border border-white/10 bg-white/[0.03] p-5 shadow-[0_18px_50px_rgba(2,6,23,0.22)]" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-sky-200/80" }, "Support flow"), /* @__PURE__ */ React.createElement("div", { className: "mt-4 space-y-2" }, /* @__PURE__ */ React.createElement("a", { href: links.quickstart, className: "block rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-sm font-semibold text-white transition hover:border-white/20 hover:bg-white/[0.05]" }, "Open Quickstart"), /* @__PURE__ */ React.createElement("a", { href: links.full_documentation, className: "block rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-sm font-semibold text-white transition hover:border-white/20 hover:bg-white/[0.05]" }, "Read full documentation"), /* @__PURE__ */ React.createElement("a", { href: links.group_studio, className: "block rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-sm font-semibold text-white transition hover:border-white/20 hover:bg-white/[0.05]" }, "Open Group Studio"), /* @__PURE__ */ React.createElement("a", { href: links.create_group, className: "block rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-sm font-semibold text-white transition hover:border-white/20 hover:bg-white/[0.05]" }, "Create a Group"))), /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-amber-300/20 bg-amber-400/10 p-4 text-amber-50" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-amber-100/80" }, "Quick troubleshooting rule"), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm leading-6 text-amber-50/85" }, "If something feels wrong, check three things first: are you in the right Group context, do you have the right role, and is the content public or internal?"))))))); } -const __vite_glob_0_56 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ +const __vite_glob_0_57 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ __proto__: null, default: GroupFaqPage }, Symbol.toStringTag, { value: "Module" })); @@ -74425,7 +77347,7 @@ function GroupHelpPage() { /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 md:grid-cols-2 xl:grid-cols-4" }, /* @__PURE__ */ React.createElement("a", { href: links.create_group, className: "rounded-[28px] border border-sky-300/20 bg-sky-300/10 p-5 transition hover:border-sky-300/35 hover:bg-sky-300/15" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-sky-100/80" }, "Create"), /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-lg font-semibold text-white" }, "Create your first Group"), /* @__PURE__ */ React.createElement("p", { className: "mt-3 text-sm leading-6 text-sky-50/80" }, "Start with branding, visibility, and your first member invites.")), /* @__PURE__ */ React.createElement("a", { href: links.group_studio, className: "rounded-[28px] border border-white/10 bg-black/20 p-5 transition hover:border-white/20 hover:bg-white/[0.05]" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, "Manage"), /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-lg font-semibold text-white" }, "Open Group Studio"), /* @__PURE__ */ React.createElement("p", { className: "mt-3 text-sm leading-6 text-slate-300" }, "Check members, workflow, releases, recruitment, and review status.")), /* @__PURE__ */ React.createElement("a", { href: links.contact_support, className: "rounded-[28px] border border-white/10 bg-black/20 p-5 transition hover:border-white/20 hover:bg-white/[0.05]" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, "Contact"), /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-lg font-semibold text-white" }, "Contact support"), /* @__PURE__ */ React.createElement("p", { className: "mt-3 text-sm leading-6 text-slate-300" }, "Use the general support flow if you need help untangling an account or workflow issue.")), /* @__PURE__ */ React.createElement("a", { href: links.report_issue, className: "rounded-[28px] border border-white/10 bg-black/20 p-5 transition hover:border-white/20 hover:bg-white/[0.05]" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, "Report"), /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-lg font-semibold text-white" }, "Report a problem"), /* @__PURE__ */ React.createElement("p", { className: "mt-3 text-sm leading-6 text-slate-300" }, "Use this if a route, permission, credit record, or workflow appears broken."))) )), /* @__PURE__ */ React.createElement("aside", { className: "hidden xl:block xl:sticky xl:top-24 xl:self-start" }, /* @__PURE__ */ React.createElement("div", { className: "space-y-4 rounded-[28px] border border-white/10 bg-white/[0.03] p-5 shadow-[0_18px_50px_rgba(2,6,23,0.22)]" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-sky-200/80" }, "Quick actions"), /* @__PURE__ */ React.createElement("div", { className: "mt-4 space-y-2" }, /* @__PURE__ */ React.createElement("a", { href: links.groups_directory, className: "block rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-sm font-semibold text-white transition hover:border-white/20 hover:bg-white/[0.05]" }, "Browse public Groups"), /* @__PURE__ */ React.createElement("a", { href: links.group_studio, className: "block rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-sm font-semibold text-white transition hover:border-white/20 hover:bg-white/[0.05]" }, "Open Group Studio"), links.faq ? /* @__PURE__ */ React.createElement("a", { href: links.faq, className: "block rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-sm font-semibold text-white transition hover:border-white/20 hover:bg-white/[0.05]" }, "Open Groups FAQ") : null, /* @__PURE__ */ React.createElement("a", { href: "#publishing-as-a-group", className: "block rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-sm font-semibold text-white transition hover:border-white/20 hover:bg-white/[0.05]" }, "Review publishing guidance"), /* @__PURE__ */ React.createElement("a", { href: "#contributor-credit", className: "block rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-sm font-semibold text-white transition hover:border-white/20 hover:bg-white/[0.05]" }, "Check contributor credit rules"))), /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-amber-300/20 bg-amber-400/10 p-4 text-amber-50" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-amber-100/80" }, "Read this before launch day"), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm leading-6 text-amber-50/85" }, "Before the first public release or artwork, confirm the Group context, contributor credit, and review expectations. Those three checks prevent most avoidable confusion."))))))); } -const __vite_glob_0_57 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ +const __vite_glob_0_58 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ __proto__: null, default: GroupHelpPage }, Symbol.toStringTag, { value: "Module" })); @@ -74440,7 +77362,7 @@ function GroupDiscoveryCard({ group, className = "", compact = false }) { "a", { href: group.urls?.public || "/groups", - className: cx$9( + className: cx$7( "group block overflow-hidden rounded-[30px] border border-white/10 bg-[linear-gradient(180deg,rgba(15,23,42,0.96),rgba(2,6,23,0.92))] p-5 shadow-[0_24px_70px_rgba(2,6,23,0.34)] transition duration-200 hover:-translate-y-1 hover:border-white/20", className ) @@ -74500,7 +77422,7 @@ function GroupIndex() { } )), leaderboardItems.length > 0 ? /* @__PURE__ */ React.createElement("section", { className: "mt-10" }, /* @__PURE__ */ React.createElement("div", { className: "mb-5 flex items-end justify-between gap-4" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("h2", { className: "text-2xl font-semibold tracking-[-0.02em] text-white" }, "Monthly group leaderboard"), /* @__PURE__ */ React.createElement("p", { className: "mt-2 max-w-3xl text-sm leading-6 text-slate-400" }, "A fast view of the collaborative teams moving the most attention and publishing energy right now.")), /* @__PURE__ */ React.createElement("a", { href: "/leaderboard?type=groups&period=monthly", className: "text-sm font-semibold text-sky-200 transition hover:text-white" }, "View leaderboard")), /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 xl:grid-cols-3" }, leaderboardItems.slice(0, 3).map((item) => /* @__PURE__ */ React.createElement(GroupLeaderboardCard, { key: item.entity?.id || item.rank, item })))) : null, /* @__PURE__ */ React.createElement("section", { className: "mt-10" }, /* @__PURE__ */ React.createElement("div", { className: "mb-5 flex items-end justify-between gap-4" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("h2", { className: "text-2xl font-semibold tracking-[-0.02em] text-white" }, "Browse groups"), /* @__PURE__ */ React.createElement("p", { className: "mt-2 max-w-3xl text-sm leading-6 text-slate-400" }, "Filter the directory by discovery surface, then jump into each group’s public page for artworks, releases, projects, events, and activity.")), /* @__PURE__ */ React.createElement("div", { className: "text-sm text-slate-500" }, Number(props.groups?.meta?.total || 0).toLocaleString(), " public groups")), /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 md:grid-cols-2 xl:grid-cols-3" }, groups.map((group) => /* @__PURE__ */ React.createElement(GroupDiscoveryCard, { key: group.slug || group.id, group })))))); } -const __vite_glob_0_58 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ +const __vite_glob_0_59 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ __proto__: null, default: GroupIndex }, Symbol.toStringTag, { value: "Module" })); @@ -74530,7 +77452,7 @@ function GroupPostShow() { }; return /* @__PURE__ */ React.createElement("main", { className: "min-h-screen bg-[radial-gradient(circle_at_top_left,_rgba(56,189,248,0.16),_transparent_28%),linear-gradient(180deg,_#020617_0%,_#02040a_100%)] px-4 py-10 sm:px-6 lg:px-8" }, /* @__PURE__ */ React.createElement(SeoHead, { seo: props.seo || {}, title: `${post2.title || group.name} - Skinbase`, description: post2.excerpt || group.headline || group.bio || "Group post" }), /* @__PURE__ */ React.createElement("div", { className: "mx-auto max-w-5xl" }, /* @__PURE__ */ React.createElement("article", { className: "rounded-[32px] border border-white/10 bg-white/[0.03] p-6 sm:p-8" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("a", { href: group.urls?.public, className: "text-sm font-semibold text-sky-200" }, "← Back to ", group.name), props.reportEndpoint ? /* @__PURE__ */ React.createElement("button", { type: "button", onClick: submitReport, className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-2 text-sm font-semibold text-white" }, "Report") : null), /* @__PURE__ */ React.createElement("div", { className: "mt-4 flex flex-wrap gap-2 text-xs uppercase tracking-[0.16em] text-slate-400" }, post2.type ? /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-1" }, post2.type) : null, post2.is_pinned ? /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-amber-300/20 bg-amber-400/10 px-3 py-1 text-amber-100" }, "Pinned") : null), /* @__PURE__ */ React.createElement("h1", { className: "mt-5 text-4xl font-semibold text-white" }, post2.title), /* @__PURE__ */ React.createElement("div", { className: "mt-3 text-sm text-slate-400" }, post2.author?.name || post2.author?.username || group.name, " • ", post2.published_at ? new Date(post2.published_at).toLocaleString() : "Recently"), post2.excerpt ? /* @__PURE__ */ React.createElement("p", { className: "mt-6 text-lg leading-8 text-slate-200" }, post2.excerpt) : null, /* @__PURE__ */ React.createElement("div", { className: "mt-8 whitespace-pre-wrap text-sm leading-7 text-slate-300" }, post2.content || "")), recentPosts.length > 0 ? /* @__PURE__ */ React.createElement("section", { className: "mt-8 rounded-[32px] border border-white/10 bg-white/[0.03] p-6" }, /* @__PURE__ */ React.createElement("h2", { className: "text-2xl font-semibold text-white" }, "More from ", group.name), /* @__PURE__ */ React.createElement("div", { className: "mt-4 grid gap-4 md:grid-cols-2" }, recentPosts.filter((item) => item.id !== post2.id).map((item) => /* @__PURE__ */ React.createElement("a", { key: item.id, href: item.url, className: "rounded-[24px] border border-white/10 bg-black/20 p-4 transition hover:border-white/20" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, item.type), /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-lg font-semibold text-white" }, item.title), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm text-slate-400" }, item.excerpt || "Read the full post."))))) : null)); } -const __vite_glob_0_59 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ +const __vite_glob_0_60 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ __proto__: null, default: GroupPostShow }, Symbol.toStringTag, { value: "Module" })); @@ -74546,7 +77468,7 @@ function GroupProjectShow() { const project = props.project || {}; return /* @__PURE__ */ React.createElement("main", { className: "min-h-screen bg-[radial-gradient(circle_at_top_left,_rgba(56,189,248,0.16),_transparent_28%),linear-gradient(180deg,_#020617_0%,_#02040a_100%)] px-4 py-10 sm:px-6 lg:px-8" }, /* @__PURE__ */ React.createElement(SeoHead, { seo: props.seo || {}, title: `${project.title || group.name} - Skinbase`, description: project.summary || project.description || group.headline || "Group project" }), /* @__PURE__ */ React.createElement("div", { className: "mx-auto max-w-6xl space-y-8" }, /* @__PURE__ */ React.createElement("section", { className: "overflow-hidden rounded-[32px] border border-white/10 bg-white/[0.03]" }, project.cover_url ? /* @__PURE__ */ React.createElement("img", { src: project.cover_url, alt: project.title, className: "h-56 w-full object-cover" }) : /* @__PURE__ */ React.createElement("div", { className: "h-40 bg-white/[0.03]" }), /* @__PURE__ */ React.createElement("div", { className: "p-6" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center gap-3" }, /* @__PURE__ */ React.createElement("a", { href: group.urls?.public, className: "text-sm font-semibold text-sky-200" }, group.name), /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-300" }, project.status), /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-300" }, project.visibility)), /* @__PURE__ */ React.createElement("h1", { className: "mt-4 text-4xl font-semibold text-white" }, project.title), project.summary ? /* @__PURE__ */ React.createElement("p", { className: "mt-4 max-w-3xl text-sm leading-7 text-slate-300" }, project.summary) : null, /* @__PURE__ */ React.createElement("div", { className: "mt-5 flex flex-wrap gap-4 text-xs text-slate-400" }, project.start_date ? /* @__PURE__ */ React.createElement("span", null, "Started ", new Date(project.start_date).toLocaleDateString()) : null, project.target_date ? /* @__PURE__ */ React.createElement("span", null, "Target ", new Date(project.target_date).toLocaleDateString()) : null, project.released_at ? /* @__PURE__ */ React.createElement("span", null, "Released ", new Date(project.released_at).toLocaleDateString()) : null, project.lead?.name || project.lead?.username ? /* @__PURE__ */ React.createElement("span", null, "Lead: ", project.lead?.name || project.lead?.username) : null))), /* @__PURE__ */ React.createElement("div", { className: "grid gap-8 xl:grid-cols-[minmax(0,1.2fr)_minmax(0,0.8fr)]" }, /* @__PURE__ */ React.createElement("section", { className: "rounded-[30px] border border-white/10 bg-white/[0.03] p-6" }, /* @__PURE__ */ React.createElement("h2", { className: "text-2xl font-semibold text-white" }, "Overview"), /* @__PURE__ */ React.createElement("p", { className: "mt-4 text-sm leading-7 text-slate-300" }, project.description || "No long-form description yet."), Array.isArray(project.milestones) && project.milestones.length > 0 ? /* @__PURE__ */ React.createElement("div", { className: "mt-6 space-y-3" }, project.milestones.map((milestone) => /* @__PURE__ */ React.createElement("div", { key: milestone.id, className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-4" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", { className: "font-semibold text-white" }, milestone.title), /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-300" }, milestone.status)), milestone.summary ? /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm text-slate-400" }, milestone.summary) : null, milestone.owner?.name || milestone.owner?.username ? /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-xs text-slate-500" }, "Owner: ", milestone.owner?.name || milestone.owner?.username) : null))) : null, /* @__PURE__ */ React.createElement(ArtworkGrid$2, { artworks: project.artworks })), /* @__PURE__ */ React.createElement("div", { className: "space-y-8" }, /* @__PURE__ */ React.createElement("section", { className: "rounded-[30px] border border-white/10 bg-white/[0.03] p-6" }, /* @__PURE__ */ React.createElement("h2", { className: "text-2xl font-semibold text-white" }, "Pipeline"), /* @__PURE__ */ React.createElement("div", { className: "mt-4 text-sm leading-7 text-slate-300" }, "This project currently has ", project.counts?.milestones || 0, " milestones and is linked to ", project.release_count || project.counts?.releases || 0, " releases.")), Array.isArray(project.assets) && project.assets.length > 0 ? /* @__PURE__ */ React.createElement("section", { className: "rounded-[30px] border border-white/10 bg-white/[0.03] p-6" }, /* @__PURE__ */ React.createElement("h2", { className: "text-2xl font-semibold text-white" }, "Assets"), /* @__PURE__ */ React.createElement("div", { className: "mt-4 space-y-3" }, project.assets.map((asset) => /* @__PURE__ */ React.createElement("a", { key: asset.id, href: asset.download_url, className: "block rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-sm text-white" }, /* @__PURE__ */ React.createElement("div", { className: "font-semibold" }, asset.title), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-xs uppercase tracking-[0.16em] text-slate-400" }, asset.category, " • ", asset.visibility))))) : null, Array.isArray(project.team) && project.team.length > 0 ? /* @__PURE__ */ React.createElement("section", { className: "rounded-[30px] border border-white/10 bg-white/[0.03] p-6" }, /* @__PURE__ */ React.createElement("h2", { className: "text-2xl font-semibold text-white" }, "Team"), /* @__PURE__ */ React.createElement("div", { className: "mt-4 space-y-3" }, project.team.map((member) => /* @__PURE__ */ React.createElement("div", { key: member.id, className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-sm text-white" }, /* @__PURE__ */ React.createElement("div", { className: "font-semibold" }, member.name || member.username), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-xs uppercase tracking-[0.16em] text-slate-400" }, member.role_label || (member.is_lead ? "Lead" : "Contributor")))))) : null, project.pinned_post ? /* @__PURE__ */ React.createElement("section", { className: "rounded-[30px] border border-white/10 bg-white/[0.03] p-6" }, /* @__PURE__ */ React.createElement("h2", { className: "text-2xl font-semibold text-white" }, "Pinned update"), /* @__PURE__ */ React.createElement("a", { href: project.pinned_post.url, className: "mt-4 inline-block text-sm font-semibold text-sky-200" }, project.pinned_post.title)) : null)))); } -const __vite_glob_0_60 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ +const __vite_glob_0_61 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ __proto__: null, default: GroupProjectShow }, Symbol.toStringTag, { value: "Module" })); @@ -74845,7 +77767,7 @@ function GroupQuickstartPage() { /* @__PURE__ */ React.createElement(QuickstartNextSteps, { items: nextSteps }) ))))); } -const __vite_glob_0_61 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ +const __vite_glob_0_62 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ __proto__: null, default: GroupQuickstartPage }, Symbol.toStringTag, { value: "Module" })); @@ -74863,7 +77785,7 @@ function GroupReleaseShow() { const milestones = Array.isArray(release.milestones) ? release.milestones : []; return /* @__PURE__ */ React.createElement("main", { className: "min-h-screen bg-[radial-gradient(circle_at_top_left,_rgba(56,189,248,0.16),_transparent_28%),linear-gradient(180deg,_#020617_0%,_#02040a_100%)] px-4 py-10 sm:px-6 lg:px-8" }, /* @__PURE__ */ React.createElement(SeoHead, { seo: props.seo || {}, title: `${release.title || group.name} - Skinbase`, description: release.summary || release.description || group.headline || "Group release" }), /* @__PURE__ */ React.createElement("div", { className: "mx-auto max-w-6xl space-y-8" }, /* @__PURE__ */ React.createElement("section", { className: "overflow-hidden rounded-[32px] border border-white/10 bg-white/[0.03]" }, release.cover_url ? /* @__PURE__ */ React.createElement("img", { src: release.cover_url, alt: release.title, className: "h-64 w-full object-cover" }) : /* @__PURE__ */ React.createElement("div", { className: "h-44 bg-white/[0.03]" }), /* @__PURE__ */ React.createElement("div", { className: "p-6" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center gap-3" }, /* @__PURE__ */ React.createElement("a", { href: group.urls?.public, className: "text-sm font-semibold text-sky-200" }, group.name), release.status ? /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-300" }, release.status) : null, release.current_stage ? /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-300" }, release.current_stage) : null), /* @__PURE__ */ React.createElement("h1", { className: "mt-4 text-4xl font-semibold text-white" }, release.title), release.summary ? /* @__PURE__ */ React.createElement("p", { className: "mt-4 max-w-3xl text-sm leading-7 text-slate-300" }, release.summary) : null, /* @__PURE__ */ React.createElement("div", { className: "mt-5 flex flex-wrap gap-4 text-xs text-slate-400" }, release.released_at ? /* @__PURE__ */ React.createElement("span", null, "Released ", new Date(release.released_at).toLocaleDateString()) : null, release.planned_release_at ? /* @__PURE__ */ React.createElement("span", null, "Planned ", new Date(release.planned_release_at).toLocaleDateString()) : null, release.lead?.name || release.lead?.username ? /* @__PURE__ */ React.createElement("span", null, "Lead: ", release.lead?.name || release.lead?.username) : null, /* @__PURE__ */ React.createElement("span", null, release.counts?.artworks || 0, " artworks"), /* @__PURE__ */ React.createElement("span", null, release.counts?.contributors || 0, " contributors"), /* @__PURE__ */ React.createElement("span", null, release.counts?.milestones || 0, " milestones")))), /* @__PURE__ */ React.createElement("div", { className: "grid gap-8 xl:grid-cols-[minmax(0,1.15fr)_minmax(0,0.85fr)]" }, /* @__PURE__ */ React.createElement("section", { className: "rounded-[30px] border border-white/10 bg-white/[0.03] p-6" }, /* @__PURE__ */ React.createElement("h2", { className: "text-2xl font-semibold text-white" }, "Overview"), /* @__PURE__ */ React.createElement("p", { className: "mt-4 text-sm leading-7 text-slate-300" }, release.description || "No long-form release description yet."), release.release_notes ? /* @__PURE__ */ React.createElement("div", { className: "mt-6 rounded-[24px] border border-white/10 bg-black/20 p-4" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Release notes"), /* @__PURE__ */ React.createElement("div", { className: "mt-3 whitespace-pre-wrap text-sm leading-7 text-slate-300" }, release.release_notes)) : null, /* @__PURE__ */ React.createElement(ArtworkGrid$1, { artworks: release.artworks })), /* @__PURE__ */ React.createElement("div", { className: "space-y-8" }, /* @__PURE__ */ React.createElement("section", { className: "rounded-[30px] border border-white/10 bg-white/[0.03] p-6" }, /* @__PURE__ */ React.createElement("h2", { className: "text-2xl font-semibold text-white" }, "Links"), /* @__PURE__ */ React.createElement("div", { className: "mt-4 space-y-3" }, release.linked_project?.url ? /* @__PURE__ */ React.createElement("a", { href: release.linked_project.url, className: "block rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-sm text-white" }, /* @__PURE__ */ React.createElement("div", { className: "font-semibold" }, release.linked_project.title), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-xs uppercase tracking-[0.16em] text-slate-400" }, "Linked project")) : null, release.linked_collection?.url ? /* @__PURE__ */ React.createElement("a", { href: release.linked_collection.url, className: "block rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-sm text-white" }, /* @__PURE__ */ React.createElement("div", { className: "font-semibold" }, release.linked_collection.title), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-xs uppercase tracking-[0.16em] text-slate-400" }, "Linked collection")) : null, release.featured_artwork ? /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-sm text-white" }, /* @__PURE__ */ React.createElement("div", { className: "font-semibold" }, release.featured_artwork.title), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-xs uppercase tracking-[0.16em] text-slate-400" }, "Featured artwork")) : null)), /* @__PURE__ */ React.createElement("section", { className: "rounded-[30px] border border-white/10 bg-white/[0.03] p-6" }, /* @__PURE__ */ React.createElement("h2", { className: "text-2xl font-semibold text-white" }, "Contributors"), /* @__PURE__ */ React.createElement("div", { className: "mt-4 space-y-3" }, contributors.length > 0 ? contributors.map((contributor) => /* @__PURE__ */ React.createElement("div", { key: contributor.id, className: "flex items-center gap-3 rounded-2xl border border-white/10 bg-black/20 px-4 py-3" }, contributor.avatar_url ? /* @__PURE__ */ React.createElement("img", { src: contributor.avatar_url, alt: contributor.name || contributor.username, className: "h-11 w-11 rounded-2xl object-cover" }) : /* @__PURE__ */ React.createElement("div", { className: "flex h-11 w-11 items-center justify-center rounded-2xl border border-white/10 bg-white/[0.03] text-slate-400" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-user" })), /* @__PURE__ */ React.createElement("div", { className: "min-w-0" }, /* @__PURE__ */ React.createElement("div", { className: "truncate font-semibold text-white" }, contributor.name || contributor.username), /* @__PURE__ */ React.createElement("div", { className: "text-xs uppercase tracking-[0.16em] text-slate-400" }, contributor.role_label || "Contributor")))) : /* @__PURE__ */ React.createElement("p", { className: "text-sm text-slate-400" }, "No contributor credits yet."))), /* @__PURE__ */ React.createElement("section", { className: "rounded-[30px] border border-white/10 bg-white/[0.03] p-6" }, /* @__PURE__ */ React.createElement("h2", { className: "text-2xl font-semibold text-white" }, "Milestones"), /* @__PURE__ */ React.createElement("div", { className: "mt-4 space-y-3" }, milestones.length > 0 ? milestones.map((milestone) => /* @__PURE__ */ React.createElement("div", { key: milestone.id, className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-4" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", { className: "font-semibold text-white" }, milestone.title), /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-300" }, milestone.status)), milestone.summary ? /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm text-slate-400" }, milestone.summary) : null, /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-xs text-slate-500" }, milestone.owner?.name || milestone.owner?.username || "No owner", milestone.due_date ? ` • due ${milestone.due_date}` : ""))) : /* @__PURE__ */ React.createElement("p", { className: "text-sm text-slate-400" }, "No milestones defined yet."))))))); } -const __vite_glob_0_62 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ +const __vite_glob_0_63 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ __proto__: null, default: GroupReleaseShow }, Symbol.toStringTag, { value: "Module" })); @@ -75291,7 +78213,7 @@ function GroupShow() { return /* @__PURE__ */ React.createElement("section", { key: label, className: "relative overflow-hidden rounded-[30px] border border-white/10 bg-white/[0.03] p-6" }, /* @__PURE__ */ React.createElement("div", { className: `absolute inset-x-0 top-0 h-[3px] rounded-t-[30px] bg-gradient-to-r ${roleKey === "owner" ? "from-amber-400/70 to-transparent" : roleKey === "admin" ? "from-sky-400/70 to-transparent" : roleKey === "editor" ? "from-violet-400/70 to-transparent" : "from-emerald-400/70 to-transparent"}` }), /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-3" }, /* @__PURE__ */ React.createElement("span", { className: `inline-flex h-8 w-8 items-center justify-center rounded-xl border ${roleStyle.badge}` }, /* @__PURE__ */ React.createElement("i", { className: `fa-solid ${roleStyle.icon} fa-fw text-sm ${roleStyle.iconColor}` })), /* @__PURE__ */ React.createElement("h3", { className: "text-lg font-semibold text-white" }, label), /* @__PURE__ */ React.createElement("span", { className: "ml-auto rounded-full border border-white/10 bg-white/[0.04] px-3 py-1 text-xs font-semibold text-slate-300" }, bucket.length)), /* @__PURE__ */ React.createElement("div", { className: "mt-4 grid gap-3 md:grid-cols-2 xl:grid-cols-3" }, bucket.map((member) => /* @__PURE__ */ React.createElement("a", { key: member.id, href: member.user?.profile_url || "#", className: "group flex items-center gap-3 rounded-[24px] border border-white/10 bg-black/20 px-4 py-4 transition hover:border-white/20 hover:bg-white/[0.04]" }, member.user?.avatar_url ? /* @__PURE__ */ React.createElement("img", { src: member.user.avatar_url, alt: member.user.name || member.user.username, className: "h-12 w-12 shrink-0 rounded-2xl object-cover ring-1 ring-white/10 transition group-hover:ring-white/20" }) : /* @__PURE__ */ React.createElement("div", { className: "flex h-12 w-12 shrink-0 items-center justify-center rounded-2xl border border-white/10 bg-white/[0.03] text-slate-400" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-user" })), /* @__PURE__ */ React.createElement("div", { className: "min-w-0" }, /* @__PURE__ */ React.createElement("div", { className: "truncate font-semibold text-white" }, member.user?.name || member.user?.username), /* @__PURE__ */ React.createElement("div", { className: `mt-1 inline-flex items-center gap-1.5 rounded-full border px-2.5 py-0.5 text-[10px] font-semibold uppercase tracking-[0.14em] ${roleStyle.badge}` }, /* @__PURE__ */ React.createElement("i", { className: `fa-solid ${roleStyle.icon} fa-fw text-[9px]` }), member.role_label || member.role)))))); }))) : null, section === "about" ? /* @__PURE__ */ React.createElement("section", { className: "mt-8 relative overflow-hidden rounded-[30px] border border-white/10 bg-white/[0.03] p-6" }, /* @__PURE__ */ React.createElement("div", { className: "absolute inset-x-0 top-0 h-[3px] rounded-t-[30px] bg-gradient-to-r from-slate-400/50 to-transparent" }), /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-3" }, /* @__PURE__ */ React.createElement("span", { className: "inline-flex h-10 w-10 items-center justify-center rounded-[14px] border border-white/10 bg-white/[0.05] text-slate-300" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-id-card fa-fw" })), /* @__PURE__ */ React.createElement("h2", { className: "text-2xl font-semibold text-white" }, "About")), /* @__PURE__ */ React.createElement("div", { className: "mt-5 space-y-4 text-sm leading-7 text-slate-300" }, /* @__PURE__ */ React.createElement("p", null, group.bio || "No long-form description yet."), group.website_url ? /* @__PURE__ */ React.createElement("p", null, /* @__PURE__ */ React.createElement("a", { href: group.website_url, className: "inline-flex items-center gap-1.5 text-sky-200 underline underline-offset-4 transition hover:text-sky-100" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-link" }), group.website_url)) : null, Array.isArray(group.links) && group.links.length > 0 ? /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-3" }, group.links.map((link2) => /* @__PURE__ */ React.createElement("a", { key: `${link2.label}-${link2.url}`, href: link2.url, className: "inline-flex items-center gap-2 rounded-[14px] border border-white/10 bg-white/[0.04] px-4 py-2 text-sm font-semibold text-white transition hover:bg-white/[0.08]" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-arrow-up-right-from-square text-slate-400" }), link2.label))) : null, /* @__PURE__ */ React.createElement("div", { className: "mt-4 flex flex-wrap gap-4 border-t border-white/8 pt-4 text-xs text-slate-400" }, group.founded_at ? /* @__PURE__ */ React.createElement("span", { className: "inline-flex items-center gap-2" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-calendar-days text-slate-500" }), "Founded ", new Date(group.founded_at).toLocaleDateString()) : null, group.type ? /* @__PURE__ */ React.createElement("span", { className: "inline-flex items-center gap-2" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-tag text-slate-500" }), group.type) : null))) : null)); } -const __vite_glob_0_63 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ +const __vite_glob_0_64 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ __proto__: null, default: GroupShow }, Symbol.toStringTag, { value: "Module" })); @@ -75549,7 +78471,7 @@ function AccountHelpPage() { /* @__PURE__ */ React.createElement(QuickstartNextSteps, { items: relatedHelpItems }) )), /* @__PURE__ */ React.createElement("aside", { className: "hidden xl:block xl:sticky xl:top-24 xl:self-start" }, /* @__PURE__ */ React.createElement("div", { className: "space-y-4 rounded-[28px] border border-white/10 bg-white/[0.03] p-5 shadow-[0_18px_50px_rgba(2,6,23,0.22)]" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-emerald-200/80" }, "Quick route map"), /* @__PURE__ */ React.createElement("div", { className: "mt-4 space-y-2" }, /* @__PURE__ */ React.createElement("a", { href: signedIn ? links.profile_settings : links.login, className: "block rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-sm font-semibold text-white transition hover:border-white/20 hover:bg-white/[0.05]" }, signedIn ? "Open account settings" : "Open login"), /* @__PURE__ */ React.createElement("a", { href: links.help_auth, className: "block rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-sm font-semibold text-white transition hover:border-white/20 hover:bg-white/[0.05]" }, "Read auth help"), /* @__PURE__ */ React.createElement("a", { href: links.help_profile, className: "block rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-sm font-semibold text-white transition hover:border-white/20 hover:bg-white/[0.05]" }, "Read Profile help"), /* @__PURE__ */ React.createElement("a", { href: links.help_troubleshooting, className: "block rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-sm font-semibold text-white transition hover:border-white/20 hover:bg-white/[0.05]" }, "Open troubleshooting"))), /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-emerald-300/20 bg-emerald-400/10 p-4 text-emerald-50" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-emerald-100/80" }, "Fast reminder"), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm leading-6 text-emerald-50/85" }, "The healthiest account is the one with a current email, a manageable password, and settings reviewed before they become emergency work."))))))); } -const __vite_glob_0_64 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ +const __vite_glob_0_65 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ __proto__: null, default: AccountHelpPage }, Symbol.toStringTag, { value: "Module" })); @@ -75905,7 +78827,7 @@ function AuthHelpPage() { /* @__PURE__ */ React.createElement(QuickstartNextSteps, { items: relatedHelpItems }) )), /* @__PURE__ */ React.createElement("aside", { className: "hidden xl:block xl:sticky xl:top-24 xl:self-start" }, /* @__PURE__ */ React.createElement("div", { className: "space-y-4 rounded-[28px] border border-white/10 bg-white/[0.03] p-5 shadow-[0_18px_50px_rgba(2,6,23,0.22)]" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-sky-200/80" }, "Quick route map"), /* @__PURE__ */ React.createElement("div", { className: "mt-4 space-y-2" }, /* @__PURE__ */ React.createElement("a", { href: links.login, className: "block rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-sm font-semibold text-white transition hover:border-white/20 hover:bg-white/[0.05]" }, "Open login"), /* @__PURE__ */ React.createElement("a", { href: links.register, className: "block rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-sm font-semibold text-white transition hover:border-white/20 hover:bg-white/[0.05]" }, "Create account"), /* @__PURE__ */ React.createElement("a", { href: links.password_request, className: "block rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-sm font-semibold text-white transition hover:border-white/20 hover:bg-white/[0.05]" }, "Reset password"), /* @__PURE__ */ React.createElement("a", { href: links.help_account, className: "block rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-sm font-semibold text-white transition hover:border-white/20 hover:bg-white/[0.05]" }, "Read account settings help"), /* @__PURE__ */ React.createElement("a", { href: links.help_troubleshooting, className: "block rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-sm font-semibold text-white transition hover:border-white/20 hover:bg-white/[0.05]" }, "Open troubleshooting hub"))), /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-amber-300/20 bg-amber-400/10 p-4 text-amber-50" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-amber-100/80" }, "Fast reminder"), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm leading-6 text-amber-50/85" }, "If access breaks, check four things first: the email, the password, the inbox, and whether the problem is really permissions rather than login."))))))); } -const __vite_glob_0_65 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ +const __vite_glob_0_66 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ __proto__: null, default: AuthHelpPage }, Symbol.toStringTag, { value: "Module" })); @@ -76331,7 +79253,7 @@ function CardsHelpPage() { /* @__PURE__ */ React.createElement(QuickstartNextSteps, { items: relatedHelpItems }) )), /* @__PURE__ */ React.createElement("aside", { className: "hidden xl:block xl:sticky xl:top-24 xl:self-start" }, /* @__PURE__ */ React.createElement("div", { className: "space-y-4 rounded-[28px] border border-white/10 bg-white/[0.03] p-5 shadow-[0_18px_50px_rgba(2,6,23,0.22)]" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-sky-200/80" }, "Quick route map"), /* @__PURE__ */ React.createElement("div", { className: "mt-4 space-y-2" }, /* @__PURE__ */ React.createElement("a", { href: links.create_card, className: "block rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-sm font-semibold text-white transition hover:border-white/20 hover:bg-white/[0.05]" }, "Create a Card"), /* @__PURE__ */ React.createElement("a", { href: links.studio_cards, className: "block rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-sm font-semibold text-white transition hover:border-white/20 hover:bg-white/[0.05]" }, "Open Cards workspace"), /* @__PURE__ */ React.createElement("a", { href: links.cards_index, className: "block rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-sm font-semibold text-white transition hover:border-white/20 hover:bg-white/[0.05]" }, "Browse public Cards"), /* @__PURE__ */ React.createElement("a", { href: links.studio_help, className: "block rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-sm font-semibold text-white transition hover:border-white/20 hover:bg-white/[0.05]" }, "Read Studio help"))), /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-amber-300/20 bg-amber-400/10 p-4 text-amber-50" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-amber-100/80" }, "Fast reminder"), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm leading-6 text-amber-50/85" }, "If the content feels unclear, ask one question first: is this a Card, an artwork, a post, or a collection? The answer usually fixes the workflow too."))))))); } -const __vite_glob_0_66 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ +const __vite_glob_0_67 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ __proto__: null, default: CardsHelpPage }, Symbol.toStringTag, { value: "Module" })); @@ -77240,7 +80162,7 @@ function HelpCenterPage() { /* @__PURE__ */ React.createElement(HelpSupportCta, { items: supportItems }) )), /* @__PURE__ */ React.createElement("aside", { className: "hidden xl:block xl:sticky xl:top-24 xl:self-start" }, /* @__PURE__ */ React.createElement("div", { className: "space-y-4 rounded-[28px] border border-white/10 bg-white/[0.03] p-5 shadow-[0_18px_50px_rgba(2,6,23,0.22)]" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-sky-200/80" }, "Help architecture"), /* @__PURE__ */ React.createElement("ul", { className: "mt-4 space-y-3 text-sm leading-6 text-slate-300" }, /* @__PURE__ */ React.createElement("li", null, "Use ", /* @__PURE__ */ React.createElement("span", { className: "font-semibold text-white" }, "/help"), " as the main hub."), /* @__PURE__ */ React.createElement("li", null, "Use ", /* @__PURE__ */ React.createElement("span", { className: "font-semibold text-white" }, "/help/topic"), " for overview pages."), /* @__PURE__ */ React.createElement("li", null, "Use ", /* @__PURE__ */ React.createElement("span", { className: "font-semibold text-white" }, "/help/topic/subpage"), " for quickstarts, FAQs, and troubleshooting."))), /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-black/20 p-4" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Current coverage"), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm leading-6 text-slate-300" }, "Groups is the first complete multi-page topic family, and Studio, Upload, Cards, Profile, Signup / Login, Account Settings, and Troubleshooting are now live topic guides. The rest of the Help Center still follows the same predictable expansion path."))))))); } -const __vite_glob_0_67 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ +const __vite_glob_0_68 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ __proto__: null, default: HelpCenterPage }, Symbol.toStringTag, { value: "Module" })); @@ -77629,7 +80551,7 @@ function ProfileHelpPage() { /* @__PURE__ */ React.createElement(QuickstartNextSteps, { items: relatedHelpItems }) )), /* @__PURE__ */ React.createElement("aside", { className: "hidden xl:block xl:sticky xl:top-24 xl:self-start" }, /* @__PURE__ */ React.createElement("div", { className: "space-y-4 rounded-[28px] border border-white/10 bg-white/[0.03] p-5 shadow-[0_18px_50px_rgba(2,6,23,0.22)]" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-sky-200/80" }, "Quick route map"), /* @__PURE__ */ React.createElement("div", { className: "mt-4 space-y-2" }, /* @__PURE__ */ React.createElement("a", { href: links.profile_settings, className: "block rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-sm font-semibold text-white transition hover:border-white/20 hover:bg-white/[0.05]" }, "Open profile settings"), /* @__PURE__ */ React.createElement("a", { href: links.groups_help, className: "block rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-sm font-semibold text-white transition hover:border-white/20 hover:bg-white/[0.05]" }, "Read Groups help"), /* @__PURE__ */ React.createElement("a", { href: links.studio_help, className: "block rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-sm font-semibold text-white transition hover:border-white/20 hover:bg-white/[0.05]" }, "Read Studio help"), /* @__PURE__ */ React.createElement("a", { href: links.upload_help, className: "block rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-sm font-semibold text-white transition hover:border-white/20 hover:bg-white/[0.05]" }, "Read Upload help"))), /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-amber-300/20 bg-amber-400/10 p-4 text-amber-50" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-amber-100/80" }, "Fast reminder"), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm leading-6 text-amber-50/85" }, "A better profile usually starts with three things: a recognizable avatar, a clearer bio, and a stronger sense of what you want people to remember about you."))))))); } -const __vite_glob_0_68 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ +const __vite_glob_0_69 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ __proto__: null, default: ProfileHelpPage }, Symbol.toStringTag, { value: "Module" })); @@ -78084,7 +81006,7 @@ function StudioHelpPage() { /* @__PURE__ */ React.createElement(QuickstartNextSteps, { items: relatedHelpItems }) )), /* @__PURE__ */ React.createElement("aside", { className: "hidden xl:block xl:sticky xl:top-24 xl:self-start" }, /* @__PURE__ */ React.createElement("div", { className: "space-y-4 rounded-[28px] border border-white/10 bg-white/[0.03] p-5 shadow-[0_18px_50px_rgba(2,6,23,0.22)]" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-sky-200/80" }, "Quick route map"), /* @__PURE__ */ React.createElement("div", { className: "mt-4 space-y-2" }, /* @__PURE__ */ React.createElement("a", { href: links.open_studio, className: "block rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-sm font-semibold text-white transition hover:border-white/20 hover:bg-white/[0.05]" }, "Open Studio"), /* @__PURE__ */ React.createElement("a", { href: links.studio_drafts, className: "block rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-sm font-semibold text-white transition hover:border-white/20 hover:bg-white/[0.05]" }, "Open drafts"), /* @__PURE__ */ React.createElement("a", { href: links.group_studio, className: "block rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-sm font-semibold text-white transition hover:border-white/20 hover:bg-white/[0.05]" }, "Open Group Studio"), /* @__PURE__ */ React.createElement("a", { href: links.groups_help, className: "block rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-sm font-semibold text-white transition hover:border-white/20 hover:bg-white/[0.05]" }, "Read Groups help"))), /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-amber-300/20 bg-amber-400/10 p-4 text-amber-50" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-amber-100/80" }, "Fast reminder"), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm leading-6 text-amber-50/85" }, "If something feels missing, check context first. Personal Studio and Group Studio are connected, but they are not identical workspaces."))))))); } -const __vite_glob_0_69 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ +const __vite_glob_0_70 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ __proto__: null, default: StudioHelpPage }, Symbol.toStringTag, { value: "Module" })); @@ -78326,7 +81248,7 @@ function TroubleshootingHelpPage() { /* @__PURE__ */ React.createElement(QuickstartNextSteps, { items: relatedHelpItems }) )), /* @__PURE__ */ React.createElement("aside", { className: "hidden xl:block xl:sticky xl:top-24 xl:self-start" }, /* @__PURE__ */ React.createElement("div", { className: "space-y-4 rounded-[28px] border border-white/10 bg-white/[0.03] p-5 shadow-[0_18px_50px_rgba(2,6,23,0.22)]" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-rose-200/80" }, "Quick route map"), /* @__PURE__ */ React.createElement("div", { className: "mt-4 space-y-2" }, /* @__PURE__ */ React.createElement("a", { href: links.help_auth, className: "block rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-sm font-semibold text-white transition hover:border-white/20 hover:bg-white/[0.05]" }, "Read auth help"), /* @__PURE__ */ React.createElement("a", { href: links.help_account, className: "block rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-sm font-semibold text-white transition hover:border-white/20 hover:bg-white/[0.05]" }, "Read account settings help"), /* @__PURE__ */ React.createElement("a", { href: links.upload_help, className: "block rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-sm font-semibold text-white transition hover:border-white/20 hover:bg-white/[0.05]" }, "Read Upload help"), /* @__PURE__ */ React.createElement("a", { href: links.groups_faq, className: "block rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-sm font-semibold text-white transition hover:border-white/20 hover:bg-white/[0.05]" }, "Open Groups FAQ"), /* @__PURE__ */ React.createElement("a", { href: links.report_issue, className: "block rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-sm font-semibold text-white transition hover:border-white/20 hover:bg-white/[0.05]" }, "Report a problem"))), /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-rose-300/20 bg-rose-400/10 p-4 text-rose-50" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-rose-100/80" }, "Fast reminder"), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm leading-6 text-rose-50/85" }, "A clear problem statement beats frantic guessing. Name the route, the context, and what changed before you decide the product is broken."))))))); } -const __vite_glob_0_70 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ +const __vite_glob_0_71 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ __proto__: null, default: TroubleshootingHelpPage }, Symbol.toStringTag, { value: "Module" })); @@ -78744,7 +81666,7 @@ function UploadHelpPage() { /* @__PURE__ */ React.createElement(QuickstartNextSteps, { items: relatedHelpItems }) )), /* @__PURE__ */ React.createElement("aside", { className: "hidden xl:block xl:sticky xl:top-24 xl:self-start" }, /* @__PURE__ */ React.createElement("div", { className: "space-y-4 rounded-[28px] border border-white/10 bg-white/[0.03] p-5 shadow-[0_18px_50px_rgba(2,6,23,0.22)]" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-sky-200/80" }, "Quick route map"), /* @__PURE__ */ React.createElement("div", { className: "mt-4 space-y-2" }, /* @__PURE__ */ React.createElement("a", { href: links.upload, className: "block rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-sm font-semibold text-white transition hover:border-white/20 hover:bg-white/[0.05]" }, "Start upload"), /* @__PURE__ */ React.createElement("a", { href: links.studio_drafts, className: "block rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-sm font-semibold text-white transition hover:border-white/20 hover:bg-white/[0.05]" }, "Open drafts"), /* @__PURE__ */ React.createElement("a", { href: links.studio_help, className: "block rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-sm font-semibold text-white transition hover:border-white/20 hover:bg-white/[0.05]" }, "Read Studio help"), /* @__PURE__ */ React.createElement("a", { href: links.groups_help, className: "block rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-sm font-semibold text-white transition hover:border-white/20 hover:bg-white/[0.05]" }, "Read Groups help"))), /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-amber-300/20 bg-amber-400/10 p-4 text-amber-50" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-amber-100/80" }, "Fast reminder"), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm leading-6 text-amber-50/85" }, "If an upload feels wrong, check three things first: context, draft state, and contributor credit."))))))); } -const __vite_glob_0_71 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ +const __vite_glob_0_72 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ __proto__: null, default: UploadHelpPage }, Symbol.toStringTag, { value: "Module" })); @@ -79207,957 +82129,9 @@ function WorldsHelpPage() { /* @__PURE__ */ React.createElement(QuickstartNextSteps, { items: relatedHelpItems }) )), /* @__PURE__ */ React.createElement("aside", { className: "hidden xl:block xl:sticky xl:top-24 xl:self-start" }, /* @__PURE__ */ React.createElement("div", { className: "space-y-4 rounded-[28px] border border-white/10 bg-white/[0.03] p-5 shadow-[0_18px_50px_rgba(2,6,23,0.22)]" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-sky-200/80" }, "Quick route map"), /* @__PURE__ */ React.createElement("div", { className: "mt-4 space-y-2" }, /* @__PURE__ */ React.createElement("a", { href: links.create_world, className: "block rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-sm font-semibold text-white transition hover:border-white/20 hover:bg-white/[0.05]" }, "Create a World"), /* @__PURE__ */ React.createElement("a", { href: links.studio_worlds, className: "block rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-sm font-semibold text-white transition hover:border-white/20 hover:bg-white/[0.05]" }, "Open Worlds workspace"), /* @__PURE__ */ React.createElement("a", { href: links.worlds_index, className: "block rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-sm font-semibold text-white transition hover:border-white/20 hover:bg-white/[0.05]" }, "Browse public Worlds"), /* @__PURE__ */ React.createElement("a", { href: links.studio_help, className: "block rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-sm font-semibold text-white transition hover:border-white/20 hover:bg-white/[0.05]" }, "Read Studio help"))), /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-sky-300/20 bg-sky-400/10 p-4 text-sky-50" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-sky-100/80" }, "Fast reminder"), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm leading-6 text-sky-50/85" }, "A World should feel like an editorial decision, not a container. If the page feels cluttered, the usual fix is stronger curation, fewer modules, and clearer promotion intent."))))))); } -const __vite_glob_0_72 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ - __proto__: null, - default: WorldsHelpPage -}, Symbol.toStringTag, { value: "Module" })); -const FALLBACK$3 = "https://files.skinbase.org/default/missing_md.webp"; -const AVATAR_FALLBACK$5 = "https://files.skinbase.org/default/avatar_default.webp"; -function ArtCard$2({ item }) { - const username = item.author_username ? `@${item.author_username}` : null; - return /* @__PURE__ */ React.createElement("article", null, /* @__PURE__ */ React.createElement( - "a", - { - href: item.url, - className: "group relative block overflow-hidden rounded-2xl ring-1 ring-white/5 bg-black/20 shadow-lg shadow-black/40 transition-all duration-200 ease-out hover:-translate-y-0.5" - }, - /* @__PURE__ */ React.createElement("div", { className: "relative aspect-video overflow-hidden bg-neutral-900" }, /* @__PURE__ */ React.createElement("div", { className: "absolute inset-0 bg-gradient-to-br from-white/10 via-white/5 to-transparent pointer-events-none z-10" }), /* @__PURE__ */ React.createElement( - "img", - { - src: item.thumb || FALLBACK$3, - alt: item.title, - className: "h-full w-full object-cover transition-transform duration-300 ease-out group-hover:scale-[1.04]", - loading: "lazy", - decoding: "async", - onError: (e) => { - e.currentTarget.src = FALLBACK$3; - } - } - ), /* @__PURE__ */ React.createElement("div", { className: "pointer-events-none absolute inset-x-0 bottom-0 z-20 bg-gradient-to-t from-black/80 via-black/40 to-transparent p-3 opacity-100 transition-opacity duration-200 md:opacity-0 md:group-hover:opacity-100" }, /* @__PURE__ */ React.createElement("div", { className: "truncate text-sm font-semibold text-white" }, item.title), /* @__PURE__ */ React.createElement("div", { className: "mt-1 flex items-center gap-2 text-xs text-white/80" }, /* @__PURE__ */ React.createElement( - "img", - { - src: item.author_avatar || AVATAR_FALLBACK$5, - alt: item.author, - className: "w-5 h-5 rounded-full object-cover shrink-0", - onError: (e) => { - e.currentTarget.src = AVATAR_FALLBACK$5; - } - } - ), /* @__PURE__ */ React.createElement("span", { className: "truncate" }, item.author), username && /* @__PURE__ */ React.createElement("span", { className: "text-white/50 shrink-0" }, username)))), - /* @__PURE__ */ React.createElement("span", { className: "sr-only" }, item.title, " by ", item.author) - )); -} -function HomeBecauseYouLike$1({ items, preferences }) { - const topTag = preferences?.top_tags?.[0]; - if (!Array.isArray(items) || items.length === 0 || !topTag) return null; - return /* @__PURE__ */ React.createElement("section", { className: "mt-14 px-4 sm:px-6 lg:px-8" }, /* @__PURE__ */ React.createElement("div", { className: "mb-5 flex items-center justify-between" }, /* @__PURE__ */ React.createElement("h2", { className: "text-xl font-bold text-white" }, "✨ Because You Like", " ", /* @__PURE__ */ React.createElement("span", { className: "text-accent" }, "#", topTag)), /* @__PURE__ */ React.createElement( - "a", - { - href: `/browse?tags=${encodeURIComponent(topTag)}`, - className: "text-sm text-nova-300 hover:text-white transition" - }, - "See all →" - )), /* @__PURE__ */ React.createElement("div", { className: "grid grid-cols-2 gap-4 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5" }, items.map((item) => /* @__PURE__ */ React.createElement(ArtCard$2, { key: item.id, item })))); -} const __vite_glob_0_73 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ __proto__: null, - default: HomeBecauseYouLike$1 -}, Symbol.toStringTag, { value: "Module" })); -function HomeCTA$1({ isLoggedIn }) { - const uploadHref = isLoggedIn ? "/upload" : "/login?redirect=/upload"; - return /* @__PURE__ */ React.createElement("section", { className: "mt-14 px-4 sm:px-6 lg:px-8" }, /* @__PURE__ */ React.createElement("div", { className: "relative overflow-hidden rounded-2xl bg-gradient-to-br from-accent/20 via-nova-800 to-nova-900 px-8 py-12 text-center ring-1 ring-white/5" }, /* @__PURE__ */ React.createElement("div", { className: "pointer-events-none absolute -top-12 -right-12 h-40 w-40 rounded-full bg-accent/10 blur-3xl" }), /* @__PURE__ */ React.createElement("div", { className: "pointer-events-none absolute -bottom-10 -left-10 h-32 w-32 rounded-full bg-sky-500/10 blur-2xl" }), /* @__PURE__ */ React.createElement("div", { className: "relative z-10" }, /* @__PURE__ */ React.createElement("p", { className: "text-xs font-semibold uppercase tracking-widest text-accent" }, "Join the community"), /* @__PURE__ */ React.createElement("h2", { className: "mt-2 text-2xl font-bold text-white sm:text-3xl" }, "Ready to share your creativity?"), /* @__PURE__ */ React.createElement("p", { className: "mx-auto mt-3 max-w-md text-sm text-nova-300" }, "Upload your artworks, wallpapers, and skins to reach thousands of enthusiasts around the world."), /* @__PURE__ */ React.createElement("div", { className: "mt-6 flex flex-wrap justify-center gap-3" }, /* @__PURE__ */ React.createElement( - "a", - { - href: uploadHref, - className: "btn-accent-solid rounded-xl px-6 py-2.5 text-sm font-semibold" - }, - "Upload your artwork" - ), !isLoggedIn && /* @__PURE__ */ React.createElement( - "a", - { - href: "/register", - className: "rounded-xl border border-white/10 bg-nova-700 px-6 py-2.5 text-sm font-semibold text-white transition hover:bg-nova-600" - }, - "Create account" - ))))); -} -const __vite_glob_0_74 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ - __proto__: null, - default: HomeCTA$1 -}, Symbol.toStringTag, { value: "Module" })); -const CATEGORIES = [ - { - label: "Wallpapers", - description: "Desktop & mobile backgrounds", - href: "/wallpapers", - icon: "🖥️", - mascot: "/gfx/mascot_wallpapers.webp", - color: "from-sky-500/20 to-sky-900/40" - }, - { - label: "Photography", - description: "Real-world captures & edits", - href: "/photography", - icon: "📷", - mascot: "/gfx/mascot_photography.webp", - color: "from-emerald-500/20 to-emerald-900/40" - }, - { - label: "Skins", - description: "App & game skins", - href: "/skins", - icon: "🎨", - mascot: "/gfx/mascot_skins.webp", - color: "from-purple-500/20 to-purple-900/40" - }, - { - label: "Digital Art", - description: "Illustrations & concept art", - href: "/other", - icon: "✏️", - mascot: "/gfx/mascot_other.webp", - color: "from-rose-500/20 to-rose-900/40" - }, - { - label: "Tags Hub", - description: "Browse by theme or style", - href: "/tags", - icon: "🏷️", - mascot: "/gfx/mascot_other.webp", - color: "from-amber-500/20 to-amber-900/40" - } -]; -function CategoryTile({ cat }) { - return /* @__PURE__ */ React.createElement( - "a", - { - href: cat.href, - className: `group relative flex flex-col justify-end overflow-hidden rounded-2xl bg-gradient-to-br ${cat.color} ring-1 ring-white/5 transition hover:-translate-y-1 hover:ring-white/15 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-sky-300/70`, - style: { minHeight: "7rem" } - }, - /* @__PURE__ */ React.createElement("div", { className: "pointer-events-none absolute inset-0 bg-nova-900/20 transition group-hover:bg-nova-900/10" }), - cat.mascot && /* @__PURE__ */ React.createElement( - "img", - { - src: cat.mascot, - alt: "", - "aria-hidden": "true", - className: "pointer-events-none absolute bottom-0 right-0 h-24 w-auto translate-y-2 object-contain drop-shadow-xl transition-transform duration-300 group-hover:-translate-y-1 group-hover:scale-105", - loading: "lazy" - } - ), - /* @__PURE__ */ React.createElement("div", { className: "relative z-10 p-3 pr-24" }, !cat.mascot && /* @__PURE__ */ React.createElement("span", { className: "mb-2 block text-2xl", role: "img", "aria-label": cat.label }, cat.icon), /* @__PURE__ */ React.createElement("p", { className: "font-semibold leading-tight text-white" }, cat.label), /* @__PURE__ */ React.createElement("p", { className: "mt-0.5 text-xs text-nova-300" }, cat.description)) - ); -} -function HomeCategories$1() { - return /* @__PURE__ */ React.createElement("section", { className: "mt-14 px-4 sm:px-6 lg:px-8" }, /* @__PURE__ */ React.createElement("div", { className: "mb-5 flex items-center justify-between" }, /* @__PURE__ */ React.createElement("h2", { className: "text-xl font-bold text-white" }, "🗂️ Explore Categories"), /* @__PURE__ */ React.createElement("a", { href: "/browse", className: "text-sm text-nova-300 hover:text-white transition" }, "Browse all →")), /* @__PURE__ */ React.createElement("div", { className: "grid grid-cols-2 gap-4 sm:grid-cols-3 lg:grid-cols-5" }, CATEGORIES.map((cat) => /* @__PURE__ */ React.createElement(CategoryTile, { key: cat.href, cat })))); -} -const __vite_glob_0_75 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ - __proto__: null, - default: HomeCategories$1 -}, Symbol.toStringTag, { value: "Module" })); -function normalizeItems(items) { - if (!Array.isArray(items)) return []; - return items.filter((item) => item && typeof item === "object"); -} -function HomeCollections$1({ - featured, - recent, - trending, - editorial, - community -}) { - const featuredItems = normalizeItems(featured); - const recentItems = normalizeItems(recent); - const trendingItems = normalizeItems(trending); - const editorialItems = normalizeItems(editorial); - const communityItems = normalizeItems(community); - const displayItems = (trendingItems.length ? trendingItems : featuredItems.length ? featuredItems : recentItems.length ? recentItems : editorialItems.length ? editorialItems : communityItems).slice(0, 3); - if (!displayItems.length) { - return null; - } - return /* @__PURE__ */ React.createElement("section", { className: "mt-14 px-4 sm:px-6 lg:px-8" }, /* @__PURE__ */ React.createElement("div", { className: "mb-5 flex items-center justify-between gap-4" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("h2", { className: "text-xl font-bold text-white" }, "Trending Collections"), /* @__PURE__ */ React.createElement("p", { className: "mt-1 max-w-2xl text-sm text-nova-300" }, "Collections getting the strongest mix of follows, saves, and engagement right now.")), /* @__PURE__ */ React.createElement("a", { href: "/collections/trending", className: "shrink-0 text-sm text-nova-300 transition hover:text-white" }, "All collections →")), /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 lg:grid-cols-2 xl:grid-cols-3" }, displayItems.map((collection) => /* @__PURE__ */ React.createElement(CollectionCard, { key: collection.id, collection, isOwner: false })))); -} -const __vite_glob_0_76 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ - __proto__: null, - default: HomeCollections$1 -}, Symbol.toStringTag, { value: "Module" })); -const AVATAR_FALLBACK$4 = "https://files.skinbase.org/default/avatar_default.webp"; -function CreatorCard$1({ creator }) { - return /* @__PURE__ */ React.createElement("article", { className: "group relative flex flex-col items-center gap-3 overflow-hidden rounded-xl bg-panel p-5 shadow-sm text-center transition hover:ring-1 hover:ring-nova-500" }, creator.bg_thumb && /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement( - "img", - { - src: creator.bg_thumb, - alt: "", - "aria-hidden": "true", - className: "pointer-events-none absolute inset-0 h-full w-full object-cover opacity-50 transition duration-500 group-hover:opacity-20 group-hover:scale-105", - loading: "lazy", - decoding: "async" - } - ), /* @__PURE__ */ React.createElement("div", { className: "pointer-events-none absolute inset-0 bg-gradient-to-t from-panel via-panel/80 to-panel/60" })), /* @__PURE__ */ React.createElement("a", { href: creator.url, className: "relative block" }, /* @__PURE__ */ React.createElement( - "img", - { - src: creator.avatar, - alt: "", - className: "mx-auto h-16 w-16 rounded-full object-cover ring-4 bg-nova-800/80 ring-nova-800", - loading: "lazy", - decoding: "async", - onError: (e) => { - e.currentTarget.src = AVATAR_FALLBACK$4; - } - } - ), /* @__PURE__ */ React.createElement("h3", { className: "mt-2 text-sm font-semibold text-white" }, creator.name)), /* @__PURE__ */ React.createElement("div", { className: "relative flex flex-wrap justify-center gap-3 text-xs text-soft" }, /* @__PURE__ */ React.createElement("span", { title: "Total uploads" }, "📁 ", creator.uploads), creator.weekly_uploads > 0 && /* @__PURE__ */ React.createElement("span", { title: "Uploads this week", className: "text-accent font-semibold" }, "↑", creator.weekly_uploads, " this week"), /* @__PURE__ */ React.createElement("span", { title: "Views" }, "👁 ", creator.views.toLocaleString()), creator.awards > 0 && /* @__PURE__ */ React.createElement("span", { title: "Awards" }, "🏆 ", creator.awards)), /* @__PURE__ */ React.createElement( - "a", - { - href: creator.url, - className: "relative mt-1 rounded-lg bg-nova-700 px-4 py-1.5 text-xs font-semibold text-white transition hover:bg-nova-600" - }, - "View Profile" - )); -} -function HomeCreators$1({ creators }) { - if (!Array.isArray(creators) || creators.length === 0) return null; - return /* @__PURE__ */ React.createElement("section", { className: "mt-14 px-4 sm:px-6 lg:px-8" }, /* @__PURE__ */ React.createElement("div", { className: "mb-5 flex items-center justify-between" }, /* @__PURE__ */ React.createElement("h2", { className: "text-xl font-bold text-white" }, "👤 Creator Spotlight"), /* @__PURE__ */ React.createElement("a", { href: "/members", className: "text-sm text-nova-300 hover:text-white transition" }, "All creators →")), /* @__PURE__ */ React.createElement("div", { className: "grid grid-cols-2 gap-4 sm:grid-cols-3 lg:grid-cols-6" }, creators.map((c) => /* @__PURE__ */ React.createElement(CreatorCard$1, { key: c.id, creator: c })))); -} -const __vite_glob_0_77 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ - __proto__: null, - default: HomeCreators$1 -}, Symbol.toStringTag, { value: "Module" })); -function cx$6(...parts) { - return parts.filter(Boolean).join(" "); -} -function ArtworkGalleryGrid({ - items, - compact = false, - showStats = true, - showAuthor = true, - limit, - className = "", - cardClassName = "" -}) { - if (!Array.isArray(items) || items.length === 0) return null; - const visibleItems = typeof limit === "number" ? items.slice(0, limit) : items; - return /* @__PURE__ */ React.createElement( - ArtworkGallery, - { - items: visibleItems, - layout: "grid", - compact, - showStats, - showAuthor, - className: cx$6(className), - cardClassName - } - ); -} -function HomeFresh$1({ items }) { - if (!Array.isArray(items) || items.length === 0) return null; - return /* @__PURE__ */ React.createElement("section", { className: "mt-14 px-4 sm:px-6 lg:px-8" }, /* @__PURE__ */ React.createElement("div", { className: "mb-5 flex items-center justify-between" }, /* @__PURE__ */ React.createElement("h2", { className: "text-xl font-bold text-white" }, "🆕 Fresh Uploads"), /* @__PURE__ */ React.createElement("a", { href: "/discover/fresh", className: "text-sm text-nova-300 hover:text-white transition" }, "See all →")), /* @__PURE__ */ React.createElement( - ArtworkGalleryGrid, - { - items, - showStats: false - } - )); -} -const __vite_glob_0_78 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ - __proto__: null, - default: HomeFresh$1 -}, Symbol.toStringTag, { value: "Module" })); -const FALLBACK$2 = "https://files.skinbase.org/default/missing_md.webp"; -const AVATAR_FALLBACK$3 = "https://files.skinbase.org/default/avatar_default.webp"; -function ArtCard$1({ item }) { - const username = item.author_username ? `@${item.author_username}` : null; - return /* @__PURE__ */ React.createElement("article", null, /* @__PURE__ */ React.createElement( - "a", - { - href: item.url, - className: "group relative block overflow-hidden rounded-2xl ring-1 ring-white/5 bg-black/20 shadow-lg shadow-black/40 transition-all duration-200 ease-out hover:-translate-y-0.5 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-sky-300/70" - }, - /* @__PURE__ */ React.createElement("div", { className: "relative aspect-video overflow-hidden bg-neutral-900" }, /* @__PURE__ */ React.createElement("div", { className: "absolute inset-0 bg-gradient-to-br from-white/10 via-white/5 to-transparent pointer-events-none z-10" }), /* @__PURE__ */ React.createElement( - "img", - { - src: item.thumb || FALLBACK$2, - alt: item.title, - className: "h-full w-full object-cover transition-[transform,filter] duration-300 ease-out group-hover:scale-[1.04]", - loading: "lazy", - decoding: "async", - onError: (e) => { - e.currentTarget.src = FALLBACK$2; - } - } - ), /* @__PURE__ */ React.createElement("div", { className: "pointer-events-none absolute inset-x-0 bottom-0 z-20 bg-gradient-to-t from-black/80 via-black/40 to-transparent p-3 opacity-100 transition-opacity duration-200 md:opacity-0 md:group-hover:opacity-100" }, /* @__PURE__ */ React.createElement("div", { className: "truncate text-sm font-semibold text-white" }, item.title), /* @__PURE__ */ React.createElement("div", { className: "mt-1 flex items-center gap-2 text-xs text-white/80" }, /* @__PURE__ */ React.createElement( - "img", - { - src: item.author_avatar || AVATAR_FALLBACK$3, - alt: item.author, - className: "w-5 h-5 rounded-full object-cover shrink-0", - onError: (e) => { - e.currentTarget.src = AVATAR_FALLBACK$3; - } - } - ), /* @__PURE__ */ React.createElement("span", { className: "truncate" }, item.author), username && /* @__PURE__ */ React.createElement("span", { className: "text-white/50 shrink-0" }, username)))), - /* @__PURE__ */ React.createElement("span", { className: "sr-only" }, item.title, " by ", item.author) - )); -} -function HomeFromFollowing$1({ items }) { - if (!Array.isArray(items) || items.length === 0) { - return /* @__PURE__ */ React.createElement("section", { className: "mt-14 px-4 sm:px-6 lg:px-8" }, /* @__PURE__ */ React.createElement("div", { className: "mb-5 flex items-center justify-between" }, /* @__PURE__ */ React.createElement("h2", { className: "text-xl font-bold text-white" }, "👥 From Creators You Follow")), /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/5 bg-nova-800/40 px-6 py-10 text-center" }, /* @__PURE__ */ React.createElement("p", { className: "text-sm text-soft" }, "You're not following anyone yet."), /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-xs text-nova-400" }, "Follow creators you love to see their latest uploads here."), /* @__PURE__ */ React.createElement( - "a", - { - href: "/creators/top", - className: "mt-4 inline-flex items-center rounded-xl bg-nova-700 px-4 py-2 text-sm font-medium text-white hover:bg-nova-600 transition" - }, - "Discover creators →" - ))); - } - return /* @__PURE__ */ React.createElement("section", { className: "mt-14 px-4 sm:px-6 lg:px-8" }, /* @__PURE__ */ React.createElement("div", { className: "mb-5 flex items-center justify-between" }, /* @__PURE__ */ React.createElement("h2", { className: "text-xl font-bold text-white" }, "👥 From Creators You Follow"), /* @__PURE__ */ React.createElement("a", { href: "/discover/following", className: "text-sm text-nova-300 hover:text-white transition" }, "See all →")), /* @__PURE__ */ React.createElement("div", { className: "grid grid-cols-2 gap-4 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5" }, items.map((item) => /* @__PURE__ */ React.createElement(ArtCard$1, { key: item.id, item })))); -} -const __vite_glob_0_79 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ - __proto__: null, - default: HomeFromFollowing$1 -}, Symbol.toStringTag, { value: "Module" })); -function GroupSpotlightCard({ group }) { - if (!group) return null; - const stats = [ - { key: "artworks", label: "artworks", value: Number(group.counts?.artworks || 0) }, - { key: "members", label: "members", value: Number(group.counts?.members || 0) }, - { key: "followers", label: "followers", value: Number(group.counts?.followers || 0) } - ].filter((item) => item.value > 0); - return /* @__PURE__ */ React.createElement("article", { className: "group relative flex flex-col overflow-hidden rounded-xl bg-panel p-5 shadow-sm transition hover:ring-1 hover:ring-nova-500" }, group.banner_url ? /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement( - "img", - { - src: group.banner_url, - alt: "", - "aria-hidden": "true", - className: "pointer-events-none absolute inset-0 h-full w-full object-cover opacity-40 transition duration-500 group-hover:scale-105 group-hover:opacity-20", - loading: "lazy", - decoding: "async" - } - ), /* @__PURE__ */ React.createElement("div", { className: "pointer-events-none absolute inset-0 bg-gradient-to-t from-panel via-panel/85 to-panel/70" })) : null, /* @__PURE__ */ React.createElement("a", { href: group.urls?.public || "/groups", className: "relative block" }, /* @__PURE__ */ React.createElement("div", { className: "flex h-16 w-16 items-center justify-center overflow-hidden rounded-2xl bg-nova-800/80 ring-4 ring-nova-800" }, group.avatar_url ? /* @__PURE__ */ React.createElement( - "img", - { - src: group.avatar_url, - alt: "", - className: "h-full w-full object-cover", - loading: "lazy", - decoding: "async" - } - ) : /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-people-group text-2xl text-white", "aria-hidden": "true" })), /* @__PURE__ */ React.createElement("h3", { className: "mt-3 text-base font-semibold text-white" }, group.name)), /* @__PURE__ */ React.createElement("p", { className: "relative mt-2 line-clamp-3 text-sm text-soft" }, group.headline || group.bio_excerpt || "Shared publishing identity for collaborative releases and artwork."), /* @__PURE__ */ React.createElement("div", { className: "relative mt-3 flex flex-wrap gap-2 text-xs text-soft" }, group.is_recruiting ? /* @__PURE__ */ React.createElement("span", { className: "rounded-full bg-emerald-400/15 px-2.5 py-1 font-semibold text-emerald-200" }, "Recruiting") : null, group.is_verified ? /* @__PURE__ */ React.createElement("span", { className: "rounded-full bg-sky-400/15 px-2.5 py-1 font-semibold text-sky-200" }, "Verified") : null, group.owner?.username || group.owner?.name ? /* @__PURE__ */ React.createElement("span", null, "Led by ", group.owner?.username || group.owner?.name) : null), stats.length > 0 ? /* @__PURE__ */ React.createElement("div", { className: "relative mt-4 flex flex-wrap gap-3 text-xs text-soft" }, stats.map((item) => /* @__PURE__ */ React.createElement("span", { key: item.key }, item.value.toLocaleString(), " ", item.label))) : null, /* @__PURE__ */ React.createElement( - "a", - { - href: group.urls?.public || "/groups", - className: "relative mt-4 inline-flex w-fit rounded-lg bg-nova-700 px-4 py-1.5 text-xs font-semibold text-white transition hover:bg-nova-600" - }, - "View Group" - )); -} -function HomeGroups$1({ groups }) { - const spotlightGroups = [ - groups?.spotlight, - ...Array.isArray(groups?.featured) ? groups.featured : [], - ...Array.isArray(groups?.recruiting) ? groups.recruiting : [], - ...Array.isArray(groups?.rising) ? groups.rising : [] - ].filter(Boolean); - const uniqueGroups = spotlightGroups.filter((group, index2, items) => items.findIndex((candidate) => candidate?.id === group?.id) === index2).slice(0, 4); - if (uniqueGroups.length === 0) { - return null; - } - return /* @__PURE__ */ React.createElement("section", { className: "mt-14 px-4 sm:px-6 lg:px-8" }, /* @__PURE__ */ React.createElement("div", { className: "mb-5 flex items-center justify-between" }, /* @__PURE__ */ React.createElement("h2", { className: "text-xl font-bold text-white" }, "Group Spotlight"), /* @__PURE__ */ React.createElement("a", { href: "/groups", className: "text-sm text-nova-300 transition hover:text-white" }, "All groups ->")), /* @__PURE__ */ React.createElement("div", { className: "grid grid-cols-1 gap-4 sm:grid-cols-2 xl:grid-cols-4" }, uniqueGroups.map((group) => /* @__PURE__ */ React.createElement(GroupSpotlightCard, { key: group.id, group })))); -} -const __vite_glob_0_80 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ - __proto__: null, - default: HomeGroups$1 -}, Symbol.toStringTag, { value: "Module" })); -const FALLBACK$1 = "https://files.skinbase.org/default/missing_lg.webp"; -const HERO_SIZES = "100vw"; -function HomeHero({ artwork }) { - if (!artwork) { - return /* @__PURE__ */ React.createElement("section", { className: "relative flex min-h-[62vh] max-h-[420px] w-full items-end overflow-hidden bg-nova-900 md:min-h-[38vh] md:max-h-[460px]" }, /* @__PURE__ */ React.createElement("div", { className: "pointer-events-none absolute inset-0 bg-gradient-to-t from-nova-900 via-nova-900/60 to-transparent" }), /* @__PURE__ */ React.createElement("div", { className: "relative z-10 w-full px-6 pb-7 sm:px-10 lg:px-16" }, /* @__PURE__ */ React.createElement("h1", { className: "text-2xl font-bold tracking-tight text-white sm:text-4xl" }, "Skinbase"), /* @__PURE__ */ React.createElement("p", { className: "mt-2 max-w-xl text-sm text-soft" }, "Discover. Create. Inspire."), /* @__PURE__ */ React.createElement("div", { className: "mt-4 flex flex-wrap gap-3" }, /* @__PURE__ */ React.createElement("a", { href: "/discover/trending", className: "btn-accent-solid rounded-xl px-5 py-2 text-sm font-semibold" }, "Explore Trending")))); - } - const src2 = artwork.thumb_lg || artwork.thumb || FALLBACK$1; - const srcSet = artwork.thumb_srcset || null; - return /* @__PURE__ */ React.createElement("section", { className: "group relative flex min-h-[62vh] max-h-[420px] w-full items-end overflow-hidden bg-nova-900 md:min-h-[38vh] md:max-h-[460px]" }, /* @__PURE__ */ React.createElement( - "img", - { - src: src2, - srcSet: srcSet || void 0, - sizes: srcSet ? HERO_SIZES : void 0, - alt: artwork.title, - className: "absolute inset-0 h-full w-full object-cover transition-transform duration-700 group-hover:scale-[1.02]", - fetchPriority: "high", - loading: "eager", - decoding: "sync", - onError: (e) => { - e.currentTarget.src = FALLBACK$1; - } - } - ), /* @__PURE__ */ React.createElement("div", { className: "pointer-events-none absolute inset-0 bg-gradient-to-t from-nova-900 via-nova-900/55 to-transparent" }), /* @__PURE__ */ React.createElement("div", { className: "relative z-10 w-full px-6 pb-7 sm:px-10 lg:px-16" }, /* @__PURE__ */ React.createElement("p", { className: "mb-1.5 text-xs font-semibold uppercase tracking-widest text-accent" }, "Featured Artwork"), /* @__PURE__ */ React.createElement("h1", { className: "text-2xl font-bold tracking-tight text-white drop-shadow sm:text-4xl lg:text-5xl" }, artwork.title), /* @__PURE__ */ React.createElement("p", { className: "mt-1.5 text-sm text-soft" }, "by ", /* @__PURE__ */ React.createElement("a", { href: artwork.url, className: "text-nova-200 hover:text-white transition" }, artwork.author)), /* @__PURE__ */ React.createElement("div", { className: "mt-4 flex flex-wrap gap-3" }, /* @__PURE__ */ React.createElement( - "a", - { - href: "/discover/trending", - className: "btn-accent-solid rounded-xl px-5 py-2 text-sm font-semibold" - }, - "Explore Trending" - ), /* @__PURE__ */ React.createElement( - "a", - { - href: artwork.url, - className: "rounded-xl border border-nova-600 px-5 py-2 text-sm font-semibold text-nova-200 shadow transition hover:border-nova-400 hover:text-white" - }, - "View Artwork" - )))); -} -const __vite_glob_0_81 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ - __proto__: null, - default: HomeHero -}, Symbol.toStringTag, { value: "Module" })); -function HomeMedalHighlights$1({ title, href = null, items, description = "" }) { - if (!Array.isArray(items) || items.length === 0) return null; - return /* @__PURE__ */ React.createElement("section", { className: "mt-14 px-4 sm:px-6 lg:px-8" }, /* @__PURE__ */ React.createElement("div", { className: "mb-5 flex items-end justify-between gap-4" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("h2", { className: "text-xl font-bold text-white" }, title), description ? /* @__PURE__ */ React.createElement("p", { className: "mt-2 max-w-2xl text-sm text-slate-400" }, description) : null), href ? /* @__PURE__ */ React.createElement("a", { href, className: "text-sm text-nova-300 transition hover:text-white" }, "See all →") : null), /* @__PURE__ */ React.createElement(ArtworkGalleryGrid, { items, className: "xl:grid-cols-4" })); -} -const __vite_glob_0_82 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ - __proto__: null, - default: HomeMedalHighlights$1 -}, Symbol.toStringTag, { value: "Module" })); -function formatDate$b(dateStr) { - if (!dateStr) return ""; - try { - return new Date(dateStr).toLocaleDateString("en-US", { - year: "numeric", - month: "short", - day: "numeric" - }); - } catch { - return ""; - } -} -function HomeNews$1({ items }) { - if (!Array.isArray(items) || items.length === 0) return null; - return /* @__PURE__ */ React.createElement("section", { className: "mt-14 px-4 sm:px-6 lg:px-8" }, /* @__PURE__ */ React.createElement("div", { className: "mb-5 flex items-center justify-between" }, /* @__PURE__ */ React.createElement("h2", { className: "text-xl font-bold text-white" }, "News & Updates"), /* @__PURE__ */ React.createElement("a", { href: "/news", className: "text-sm text-nova-300 hover:text-white transition" }, "All news →")), /* @__PURE__ */ React.createElement("div", { className: "divide-y divide-nova-800 overflow-hidden rounded-[24px] border border-white/10 bg-panel" }, items.map((item) => /* @__PURE__ */ React.createElement( - "a", - { - key: item.id, - href: item.url, - className: "grid gap-3 px-5 py-4 transition hover:bg-nova-800 sm:grid-cols-[minmax(0,1fr)_auto] sm:items-start" - }, - /* @__PURE__ */ React.createElement("div", { className: "min-w-0" }, item.eyebrow ? /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-nova-300" }, item.eyebrow) : null, /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-sm font-medium text-white line-clamp-2" }, item.title), item.excerpt ? /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm leading-6 text-soft line-clamp-2" }, item.excerpt) : null), - item.date ? /* @__PURE__ */ React.createElement("span", { className: "flex-shrink-0 text-xs text-soft" }, formatDate$b(item.date)) : null - )))); -} -const __vite_glob_0_83 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ - __proto__: null, - default: HomeNews$1 -}, Symbol.toStringTag, { value: "Module" })); -const HomeWelcomeRow$1 = reactExports.lazy(() => Promise.resolve().then(() => __vite_glob_0_90)); -const HomeFromFollowing = reactExports.lazy(() => Promise.resolve().then(() => __vite_glob_0_79)); -const HomeTrendingForYou$1 = reactExports.lazy(() => Promise.resolve().then(() => __vite_glob_0_89)); -const HomeBecauseYouLike = reactExports.lazy(() => Promise.resolve().then(() => __vite_glob_0_73)); -const HomeSuggestedCreators$1 = reactExports.lazy(() => Promise.resolve().then(() => __vite_glob_0_86)); -const HomeTrending$1 = reactExports.lazy(() => Promise.resolve().then(() => __vite_glob_0_88)); -const HomeMedalHighlights = reactExports.lazy(() => Promise.resolve().then(() => __vite_glob_0_82)); -const HomeRising$1 = reactExports.lazy(() => Promise.resolve().then(() => __vite_glob_0_85)); -const HomeFresh = reactExports.lazy(() => Promise.resolve().then(() => __vite_glob_0_78)); -const HomeCollections = reactExports.lazy(() => Promise.resolve().then(() => __vite_glob_0_76)); -const HomeWorldSpotlight$1 = reactExports.lazy(() => Promise.resolve().then(() => __vite_glob_0_91)); -const HomeGroups = reactExports.lazy(() => Promise.resolve().then(() => __vite_glob_0_80)); -const HomeCategories = reactExports.lazy(() => Promise.resolve().then(() => __vite_glob_0_75)); -const HomeTags$1 = reactExports.lazy(() => Promise.resolve().then(() => __vite_glob_0_87)); -const HomeCreators = reactExports.lazy(() => Promise.resolve().then(() => __vite_glob_0_77)); -const HomeNews = reactExports.lazy(() => Promise.resolve().then(() => __vite_glob_0_83)); -const HomeCTA = reactExports.lazy(() => Promise.resolve().then(() => __vite_glob_0_74)); -function cx$5(...parts) { - return parts.filter(Boolean).join(" "); -} -function SectionFallback({ variant = "gallery" }) { - if (variant === "welcome") { - return /* @__PURE__ */ React.createElement("div", { className: "mt-10 px-4 sm:px-6 lg:px-8", "aria-hidden": "true" }, /* @__PURE__ */ React.createElement("div", { className: "h-20 animate-pulse rounded-[28px] border border-white/10 bg-nova-800/70" })); - } - if (variant === "tags") { - return /* @__PURE__ */ React.createElement("section", { className: "mt-14 px-4 sm:px-6 lg:px-8", "aria-hidden": "true" }, /* @__PURE__ */ React.createElement("div", { className: "mb-5 h-8 w-48 animate-pulse rounded-xl bg-nova-800/70" }), /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-2" }, Array.from({ length: 12 }).map((_2, index2) => /* @__PURE__ */ React.createElement( - "div", - { - key: index2, - className: "h-9 animate-pulse rounded-full bg-nova-800/70", - style: { width: `${88 + index2 % 4 * 16}px` } - } - )))); - } - if (variant === "cta") { - return /* @__PURE__ */ React.createElement("section", { className: "mt-14 px-4 sm:px-6 lg:px-8", "aria-hidden": "true" }, /* @__PURE__ */ React.createElement("div", { className: "h-40 animate-pulse rounded-[28px] border border-white/10 bg-nova-800/70" })); - } - const cardClassName = variant === "categories" ? "h-28 rounded-2xl" : variant === "news" ? "h-24 rounded-2xl" : variant === "creators" ? "h-64 rounded-2xl" : variant === "collections" ? "h-80 rounded-[28px]" : variant === "groups" ? "h-80 rounded-[28px]" : "aspect-[4/3] rounded-2xl"; - const gridClassName = variant === "creators" ? "grid-cols-2 sm:grid-cols-3 lg:grid-cols-6" : variant === "news" ? "grid-cols-1" : variant === "categories" ? "grid-cols-2 lg:grid-cols-4" : variant === "collections" ? "grid-cols-1 lg:grid-cols-2 xl:grid-cols-3" : variant === "groups" ? "grid-cols-1 sm:grid-cols-2 xl:grid-cols-4" : "grid-cols-2 xl:grid-cols-4"; - const cardCount = variant === "creators" ? 6 : variant === "news" ? 4 : 4; - return /* @__PURE__ */ React.createElement("section", { className: "mt-14 px-4 sm:px-6 lg:px-8", "aria-hidden": "true" }, /* @__PURE__ */ React.createElement("div", { className: "mb-5 flex items-center justify-between gap-4" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "h-8 w-48 animate-pulse rounded-xl bg-nova-800/70" }), (variant === "collections" || variant === "groups" || variant === "news") && /* @__PURE__ */ React.createElement("div", { className: "mt-3 h-4 w-80 max-w-full animate-pulse rounded bg-nova-800/60" })), /* @__PURE__ */ React.createElement("div", { className: "hidden h-5 w-24 animate-pulse rounded bg-nova-800/60 sm:block" })), /* @__PURE__ */ React.createElement("div", { className: cx$5("grid gap-4", gridClassName) }, Array.from({ length: cardCount }).map((_2, index2) => /* @__PURE__ */ React.createElement("div", { key: index2, className: cx$5("animate-pulse bg-nova-800/70", cardClassName) })))); -} -function SectionPlaceholder({ variant = "gallery" }) { - const heightClassName = variant === "welcome" ? "h-20" : variant === "tags" ? "h-28" : variant === "cta" ? "h-40" : variant === "news" ? "h-48" : variant === "categories" ? "h-44" : variant === "creators" ? "h-72" : variant === "collections" ? "h-80" : variant === "groups" ? "h-80" : "h-[28rem]"; - return /* @__PURE__ */ React.createElement("section", { className: "mt-14 px-4 sm:px-6 lg:px-8", "aria-hidden": "true" }, /* @__PURE__ */ React.createElement("div", { className: `rounded-[28px] border border-white/8 bg-nova-900/40 ${heightClassName}` })); -} -function DeferredSection({ children, fallback, variant = "gallery", eager = false, rootMargin = "1200px 0px" }) { - const anchorRef = reactExports.useRef(null); - const [isVisible, setIsVisible] = reactExports.useState(eager); - reactExports.useEffect(() => { - if (eager || isVisible) { - return void 0; - } - const node2 = anchorRef.current; - if (!node2) { - return void 0; - } - if (typeof window === "undefined" || typeof window.IntersectionObserver !== "function") { - setIsVisible(true); - return void 0; - } - const observer = new window.IntersectionObserver((entries) => { - entries.forEach((entry) => { - if (!entry.isIntersecting) { - return; - } - setIsVisible(true); - observer.disconnect(); - }); - }, { rootMargin, threshold: 0.01 }); - observer.observe(node2); - return () => observer.disconnect(); - }, [eager, isVisible, rootMargin]); - return /* @__PURE__ */ React.createElement("div", { ref: anchorRef }, isVisible ? /* @__PURE__ */ React.createElement(reactExports.Suspense, { fallback }, /* @__PURE__ */ React.createElement(React.Fragment, null, children)) : /* @__PURE__ */ React.createElement(SectionPlaceholder, { variant })); -} -function GuestHomePage(props) { - const { rising, trending, community_favorites, hall_of_fame, fresh, tags, creators, news, collections_featured, collections_trending, collections_editorial, collections_community, groups, world_spotlight } = props; - return /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement(DeferredSection, { eager: true, fallback: /* @__PURE__ */ React.createElement(SectionFallback, { variant: "gallery" }) }, /* @__PURE__ */ React.createElement(HomeRising$1, { items: rising })), /* @__PURE__ */ React.createElement(DeferredSection, { eager: true, fallback: /* @__PURE__ */ React.createElement(SectionFallback, { variant: "gallery" }) }, /* @__PURE__ */ React.createElement(HomeTrending$1, { items: trending })), /* @__PURE__ */ React.createElement(DeferredSection, { fallback: /* @__PURE__ */ React.createElement(SectionFallback, { variant: "gallery" }) }, /* @__PURE__ */ React.createElement( - HomeMedalHighlights, - { - title: "Community Favorites", - href: "/explore?sort=top-rated", - description: "Recent medal momentum from the community. This rail highlights the strongest 30-day medal signal.", - items: community_favorites - } - )), /* @__PURE__ */ React.createElement(DeferredSection, { fallback: /* @__PURE__ */ React.createElement(SectionFallback, { variant: "gallery" }) }, /* @__PURE__ */ React.createElement( - HomeMedalHighlights, - { - title: "Hall of Fame", - href: "/explore/best", - description: "All-time medal standouts that keep being remembered long after publication.", - items: hall_of_fame - } - )), /* @__PURE__ */ React.createElement(DeferredSection, { fallback: /* @__PURE__ */ React.createElement(SectionFallback, { variant: "gallery" }) }, /* @__PURE__ */ React.createElement(HomeFresh, { items: fresh })), /* @__PURE__ */ React.createElement(DeferredSection, { variant: "collections", fallback: /* @__PURE__ */ React.createElement(SectionFallback, { variant: "collections" }) }, /* @__PURE__ */ React.createElement( - HomeCollections, - { - featured: collections_featured, - trending: collections_trending, - editorial: collections_editorial, - community: collections_community - } - )), /* @__PURE__ */ React.createElement(DeferredSection, { variant: "collections", fallback: /* @__PURE__ */ React.createElement(SectionFallback, { variant: "collections" }) }, /* @__PURE__ */ React.createElement(HomeWorldSpotlight$1, { world: world_spotlight })), /* @__PURE__ */ React.createElement(DeferredSection, { variant: "groups", fallback: /* @__PURE__ */ React.createElement(SectionFallback, { variant: "groups" }) }, /* @__PURE__ */ React.createElement(HomeGroups, { groups })), /* @__PURE__ */ React.createElement(DeferredSection, { variant: "categories", fallback: /* @__PURE__ */ React.createElement(SectionFallback, { variant: "categories" }) }, /* @__PURE__ */ React.createElement(HomeCategories, null)), /* @__PURE__ */ React.createElement(DeferredSection, { variant: "tags", fallback: /* @__PURE__ */ React.createElement(SectionFallback, { variant: "tags" }) }, /* @__PURE__ */ React.createElement(HomeTags$1, { tags })), /* @__PURE__ */ React.createElement(DeferredSection, { variant: "creators", fallback: /* @__PURE__ */ React.createElement(SectionFallback, { variant: "creators" }) }, /* @__PURE__ */ React.createElement(HomeCreators, { creators })), /* @__PURE__ */ React.createElement(DeferredSection, { variant: "news", fallback: /* @__PURE__ */ React.createElement(SectionFallback, { variant: "news" }) }, /* @__PURE__ */ React.createElement(HomeNews, { items: news })), /* @__PURE__ */ React.createElement(DeferredSection, { variant: "cta", fallback: /* @__PURE__ */ React.createElement(SectionFallback, { variant: "cta" }) }, /* @__PURE__ */ React.createElement(HomeCTA, { isLoggedIn: false }))); -} -function AuthHomePage(props) { - const { - user_data, - for_you, - from_following, - rising, - trending, - community_favorites, - hall_of_fame, - fresh, - collections_featured, - collections_recent, - collections_trending, - collections_editorial, - collections_community, - world_spotlight, - groups, - by_categories, - suggested_creators, - tags, - creators, - news, - preferences - } = props; - return /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement(DeferredSection, { eager: true, variant: "welcome", fallback: /* @__PURE__ */ React.createElement(SectionFallback, { variant: "welcome" }) }, /* @__PURE__ */ React.createElement(HomeWelcomeRow$1, { user_data })), /* @__PURE__ */ React.createElement(DeferredSection, { eager: true, fallback: /* @__PURE__ */ React.createElement(SectionFallback, { variant: "gallery" }) }, /* @__PURE__ */ React.createElement(HomeFromFollowing, { items: from_following })), /* @__PURE__ */ React.createElement(DeferredSection, { eager: true, fallback: /* @__PURE__ */ React.createElement(SectionFallback, { variant: "gallery" }) }, /* @__PURE__ */ React.createElement(HomeTrendingForYou$1, { items: for_you, preferences })), /* @__PURE__ */ React.createElement(DeferredSection, { fallback: /* @__PURE__ */ React.createElement(SectionFallback, { variant: "gallery" }) }, /* @__PURE__ */ React.createElement(HomeRising$1, { items: rising })), /* @__PURE__ */ React.createElement(DeferredSection, { fallback: /* @__PURE__ */ React.createElement(SectionFallback, { variant: "gallery" }) }, /* @__PURE__ */ React.createElement(HomeTrending$1, { items: trending })), /* @__PURE__ */ React.createElement(DeferredSection, { fallback: /* @__PURE__ */ React.createElement(SectionFallback, { variant: "gallery" }) }, /* @__PURE__ */ React.createElement( - HomeMedalHighlights, - { - title: "Community Favorites", - href: "/explore?sort=top-rated", - description: "Recent medal momentum from the community. This rail highlights the strongest 30-day medal signal.", - items: community_favorites - } - )), /* @__PURE__ */ React.createElement(DeferredSection, { fallback: /* @__PURE__ */ React.createElement(SectionFallback, { variant: "gallery" }) }, /* @__PURE__ */ React.createElement( - HomeMedalHighlights, - { - title: "Hall of Fame", - href: "/explore/best", - description: "All-time medal standouts that keep being remembered long after publication.", - items: hall_of_fame - } - )), /* @__PURE__ */ React.createElement(DeferredSection, { fallback: /* @__PURE__ */ React.createElement(SectionFallback, { variant: "gallery" }) }, /* @__PURE__ */ React.createElement(HomeBecauseYouLike, { items: by_categories, preferences })), /* @__PURE__ */ React.createElement(DeferredSection, { fallback: /* @__PURE__ */ React.createElement(SectionFallback, { variant: "gallery" }) }, /* @__PURE__ */ React.createElement(HomeFresh, { items: fresh })), /* @__PURE__ */ React.createElement(DeferredSection, { variant: "collections", fallback: /* @__PURE__ */ React.createElement(SectionFallback, { variant: "collections" }) }, /* @__PURE__ */ React.createElement( - HomeCollections, - { - featured: collections_featured, - recent: collections_recent, - trending: collections_trending, - editorial: collections_editorial, - community: collections_community, - isLoggedIn: true - } - )), /* @__PURE__ */ React.createElement(DeferredSection, { variant: "collections", fallback: /* @__PURE__ */ React.createElement(SectionFallback, { variant: "collections" }) }, /* @__PURE__ */ React.createElement(HomeWorldSpotlight$1, { world: world_spotlight })), /* @__PURE__ */ React.createElement(DeferredSection, { variant: "groups", fallback: /* @__PURE__ */ React.createElement(SectionFallback, { variant: "groups" }) }, /* @__PURE__ */ React.createElement(HomeGroups, { groups })), /* @__PURE__ */ React.createElement(DeferredSection, { variant: "categories", fallback: /* @__PURE__ */ React.createElement(SectionFallback, { variant: "categories" }) }, /* @__PURE__ */ React.createElement(HomeCategories, null)), /* @__PURE__ */ React.createElement(DeferredSection, { variant: "creators", fallback: /* @__PURE__ */ React.createElement(SectionFallback, { variant: "creators" }) }, /* @__PURE__ */ React.createElement(HomeSuggestedCreators$1, { creators: suggested_creators })), /* @__PURE__ */ React.createElement(DeferredSection, { variant: "tags", fallback: /* @__PURE__ */ React.createElement(SectionFallback, { variant: "tags" }) }, /* @__PURE__ */ React.createElement(HomeTags$1, { tags })), /* @__PURE__ */ React.createElement(DeferredSection, { variant: "creators", fallback: /* @__PURE__ */ React.createElement(SectionFallback, { variant: "creators" }) }, /* @__PURE__ */ React.createElement(HomeCreators, { creators })), /* @__PURE__ */ React.createElement(DeferredSection, { variant: "news", fallback: /* @__PURE__ */ React.createElement(SectionFallback, { variant: "news" }) }, /* @__PURE__ */ React.createElement(HomeNews, { items: news })), /* @__PURE__ */ React.createElement(DeferredSection, { variant: "cta", fallback: /* @__PURE__ */ React.createElement(SectionFallback, { variant: "cta" }) }, /* @__PURE__ */ React.createElement(HomeCTA, { isLoggedIn: true }))); -} -function HomePage(props) { - return /* @__PURE__ */ React.createElement("div", { className: "pb-24" }, /* @__PURE__ */ React.createElement(HomepageAnnouncement, { announcement: props.announcement || null }), props.is_logged_in ? /* @__PURE__ */ React.createElement(AuthHomePage, { ...props }) : /* @__PURE__ */ React.createElement(GuestHomePage, { ...props })); -} -if (typeof document !== "undefined") { - const mountEl = document.getElementById("homepage-root"); - if (mountEl) { - let props = {}; - try { - const propsEl = document.getElementById("homepage-props"); - props = propsEl ? JSON.parse(propsEl.textContent || "{}") : {}; - } catch { - props = {}; - } - clientExports.createRoot(mountEl).render(/* @__PURE__ */ React.createElement(HomePage, { ...props })); - } -} -const __vite_glob_0_84 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ - __proto__: null, - default: HomePage -}, Symbol.toStringTag, { value: "Module" })); -const FALLBACK = "https://files.skinbase.org/default/missing_md.webp"; -const AVATAR_FALLBACK$2 = "https://files.skinbase.org/default/avatar_default.webp"; -function ArtCard({ item }) { - const username = item.author_username ? `@${item.author_username}` : null; - return /* @__PURE__ */ React.createElement("article", { className: "min-w-[72%] snap-start sm:min-w-[44%] lg:min-w-0" }, /* @__PURE__ */ React.createElement( - "a", - { - href: item.url, - className: "group relative block overflow-hidden rounded-2xl ring-1 ring-white/5 bg-black/20 shadow-lg shadow-black/40 transition-all duration-200 ease-out hover:-translate-y-0.5 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-sky-300/70" - }, - /* @__PURE__ */ React.createElement("div", { className: "relative aspect-video overflow-hidden bg-neutral-900" }, /* @__PURE__ */ React.createElement("div", { className: "absolute inset-0 bg-gradient-to-br from-white/10 via-white/5 to-transparent pointer-events-none z-10" }), /* @__PURE__ */ React.createElement( - "img", - { - src: item.thumb || FALLBACK, - alt: item.title, - className: "h-full w-full object-cover transition-[transform,filter] duration-300 ease-out group-hover:scale-[1.04]", - loading: "lazy", - decoding: "async", - onError: (e) => { - e.currentTarget.src = FALLBACK; - } - } - ), /* @__PURE__ */ React.createElement("div", { className: "absolute left-3 top-3 z-30" }, /* @__PURE__ */ React.createElement("span", { className: "inline-flex items-center gap-1 rounded-md bg-emerald-500/80 px-2 py-1 text-[11px] font-bold text-white ring-1 ring-white/10 backdrop-blur-sm" }, /* @__PURE__ */ React.createElement("svg", { className: "w-3 h-3", fill: "none", viewBox: "0 0 24 24", stroke: "currentColor", strokeWidth: 2.5 }, /* @__PURE__ */ React.createElement("path", { strokeLinecap: "round", strokeLinejoin: "round", d: "M13 7h8m0 0v8m0-8l-8 8-4-4-6 6" })), "Rising")), /* @__PURE__ */ React.createElement("div", { className: "absolute right-3 top-3 z-30 flex items-center gap-2 opacity-0 transition-opacity duration-200 group-hover:opacity-100" }, /* @__PURE__ */ React.createElement("span", { className: "inline-flex items-center rounded-md bg-black/60 px-2 py-1 text-[11px] font-medium text-white ring-1 ring-white/10" }, "View")), /* @__PURE__ */ React.createElement("div", { className: "pointer-events-none absolute inset-x-0 bottom-0 z-20 bg-gradient-to-t from-black/80 via-black/40 to-transparent p-3 backdrop-blur-[2px] opacity-100 transition-opacity duration-200 md:opacity-0 md:group-hover:opacity-100 md:group-focus-visible:opacity-100" }, /* @__PURE__ */ React.createElement("div", { className: "truncate text-sm font-semibold text-white" }, item.title), /* @__PURE__ */ React.createElement("div", { className: "mt-1 flex items-center gap-2 text-xs text-white/80" }, /* @__PURE__ */ React.createElement( - "img", - { - src: item.author_avatar || AVATAR_FALLBACK$2, - alt: item.author, - className: "w-6 h-6 rounded-full object-cover shrink-0", - onError: (e) => { - e.currentTarget.src = AVATAR_FALLBACK$2; - } - } - ), /* @__PURE__ */ React.createElement("span", { className: "truncate" }, item.author), username && /* @__PURE__ */ React.createElement("span", { className: "text-white/50 shrink-0" }, username)))), - /* @__PURE__ */ React.createElement("span", { className: "sr-only" }, item.title, " by ", item.author) - )); -} -function HomeRising({ items }) { - if (!Array.isArray(items) || items.length === 0) return null; - return /* @__PURE__ */ React.createElement("section", { className: "mt-14 px-4 sm:px-6 lg:px-8" }, /* @__PURE__ */ React.createElement("div", { className: "mb-5 flex items-center justify-between" }, /* @__PURE__ */ React.createElement("h2", { className: "text-xl font-bold text-white flex items-center gap-2" }, /* @__PURE__ */ React.createElement("span", { className: "text-emerald-400" }, "🚀"), " Rising Now"), /* @__PURE__ */ React.createElement("a", { href: "/discover/rising", className: "text-sm text-nova-300 hover:text-white transition" }, "See all →")), /* @__PURE__ */ React.createElement("div", { className: "flex snap-x snap-mandatory gap-4 overflow-x-auto pb-3 lg:grid lg:grid-cols-5 lg:overflow-visible" }, items.map((item) => /* @__PURE__ */ React.createElement(ArtCard, { key: item.id, item })))); -} -const __vite_glob_0_85 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ - __proto__: null, - default: HomeRising -}, Symbol.toStringTag, { value: "Module" })); -const AVATAR_FALLBACK$1 = "https://files.skinbase.org/default/avatar_default.webp"; -function CreatorCard({ creator }) { - return /* @__PURE__ */ React.createElement("article", { className: "group flex flex-col items-center rounded-2xl bg-nova-800/60 p-5 ring-1 ring-white/5 hover:ring-white/10 hover:bg-nova-800 transition" }, /* @__PURE__ */ React.createElement("a", { href: creator.url, className: "block" }, /* @__PURE__ */ React.createElement( - "img", - { - src: creator.avatar || AVATAR_FALLBACK$1, - alt: creator.name, - className: "mx-auto h-14 w-14 rounded-full object-cover ring-2 ring-white/10 group-hover:ring-accent/50 transition", - loading: "lazy", - onError: (e) => { - e.currentTarget.src = AVATAR_FALLBACK$1; - } - } - )), /* @__PURE__ */ React.createElement("div", { className: "mt-3 w-full text-center" }, /* @__PURE__ */ React.createElement("a", { href: creator.url, className: "block truncate text-sm font-semibold text-white hover:text-accent transition" }, creator.name), creator.username && /* @__PURE__ */ React.createElement("p", { className: "truncate text-xs text-nova-400" }, "@", creator.username), /* @__PURE__ */ React.createElement("div", { className: "mt-2 flex items-center justify-center gap-3 text-xs text-nova-500" }, creator.followers_count > 0 && /* @__PURE__ */ React.createElement("span", { title: "Followers" }, creator.followers_count.toLocaleString(), " followers"), creator.artworks_count > 0 && /* @__PURE__ */ React.createElement("span", { title: "Artworks" }, creator.artworks_count.toLocaleString(), " artworks"))), /* @__PURE__ */ React.createElement( - "a", - { - href: creator.url, - className: "mt-4 w-full rounded-lg bg-nova-700 py-1.5 text-center text-xs font-medium text-white hover:bg-nova-600 transition" - }, - "View Profile" - )); -} -function HomeSuggestedCreators({ creators }) { - if (!Array.isArray(creators) || creators.length === 0) return null; - return /* @__PURE__ */ React.createElement("section", { className: "mt-14 px-4 sm:px-6 lg:px-8" }, /* @__PURE__ */ React.createElement("div", { className: "mb-5 flex items-center justify-between" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("h2", { className: "text-xl font-bold text-white" }, "💡 Suggested Creators"), /* @__PURE__ */ React.createElement("p", { className: "mt-0.5 text-xs text-nova-400" }, "Creators you might enjoy following")), /* @__PURE__ */ React.createElement("a", { href: "/creators/top", className: "text-sm text-nova-300 hover:text-white transition" }, "Explore all →")), /* @__PURE__ */ React.createElement("div", { className: "grid grid-cols-2 gap-4 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-4" }, creators.map((creator) => /* @__PURE__ */ React.createElement(CreatorCard, { key: creator.id, creator })))); -} -const __vite_glob_0_86 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ - __proto__: null, - default: HomeSuggestedCreators -}, Symbol.toStringTag, { value: "Module" })); -function HomeTags({ tags }) { - if (!Array.isArray(tags) || tags.length === 0) return null; - return /* @__PURE__ */ React.createElement("section", { className: "mt-14 px-4 sm:px-6 lg:px-8" }, /* @__PURE__ */ React.createElement("h2", { className: "mb-5 text-xl font-bold text-white" }, "🏷️ Popular Tags"), /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-2" }, tags.map((tag) => /* @__PURE__ */ React.createElement( - "a", - { - key: tag.id, - href: `/tag/${tag.slug}`, - className: "rounded-full bg-nova-800 px-4 py-1.5 text-sm font-medium text-nova-200 transition hover:bg-nova-700 hover:text-white" - }, - tag.name, - tag.count > 0 && /* @__PURE__ */ React.createElement("span", { className: "ml-1.5 text-xs text-soft" }, tag.count.toLocaleString()) - )))); -} -const __vite_glob_0_87 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ - __proto__: null, - default: HomeTags -}, Symbol.toStringTag, { value: "Module" })); -function HomeTrending({ items }) { - if (!Array.isArray(items) || items.length === 0) return null; - return /* @__PURE__ */ React.createElement("section", { className: "mt-14 px-4 sm:px-6 lg:px-8" }, /* @__PURE__ */ React.createElement("div", { className: "mb-5 flex items-center justify-between" }, /* @__PURE__ */ React.createElement("h2", { className: "text-xl font-bold text-white" }, "🔥 Trending This Week"), /* @__PURE__ */ React.createElement("a", { href: "/discover/trending", className: "text-sm text-nova-300 hover:text-white transition" }, "See all →")), /* @__PURE__ */ React.createElement( - ArtworkGalleryGrid, - { - items, - className: "xl:grid-cols-4" - } - )); -} -const __vite_glob_0_88 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ - __proto__: null, - default: HomeTrending -}, Symbol.toStringTag, { value: "Module" })); -function HomeTrendingForYou({ items, preferences }) { - if (!Array.isArray(items) || items.length === 0) return null; - const topTag = preferences?.top_tags?.[0]; - const heading2 = "Picked For You"; - const subheading = topTag ? `Fresh recommendations informed by your recent interest in #${topTag}.` : "A live preview of your personalized discovery feed."; - const link2 = "/discover/for-you"; - return /* @__PURE__ */ React.createElement("section", { className: "mt-14 px-4 sm:px-6 lg:px-8" }, /* @__PURE__ */ React.createElement("div", { className: "mb-5 flex flex-col gap-3 md:flex-row md:items-end md:justify-between" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[0.7rem] font-semibold uppercase tracking-[0.28em] text-sky-200/70" }, "Personalized feed"), /* @__PURE__ */ React.createElement("h2", { className: "mt-2 text-xl font-bold text-white" }, heading2), /* @__PURE__ */ React.createElement("p", { className: "mt-1 max-w-2xl text-sm text-slate-300" }, subheading)), /* @__PURE__ */ React.createElement("a", { href: link2, className: "text-sm text-nova-300 transition hover:text-white" }, "Open full feed →")), /* @__PURE__ */ React.createElement(ArtworkGalleryGrid, { items, compact: true })); -} -const __vite_glob_0_89 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ - __proto__: null, - default: HomeTrendingForYou -}, Symbol.toStringTag, { value: "Module" })); -const AVATAR_FALLBACK = "https://files.skinbase.org/default/avatar_default.webp"; -function HomeWelcomeRow({ user_data }) { - if (!user_data) return null; - const { name: name2, avatar, messages_unread, notifications_unread, url } = user_data; - const firstName = name2?.split(" ")[0] || name2 || "there"; - return /* @__PURE__ */ React.createElement("section", { className: "border-b border-white/5 bg-nova-900/60 backdrop-blur-sm" }, /* @__PURE__ */ React.createElement("div", { className: "mx-auto max-w-7xl px-4 sm:px-6 lg:px-8 py-4" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-3" }, /* @__PURE__ */ React.createElement("a", { href: url || "/profile" }, /* @__PURE__ */ React.createElement( - "img", - { - src: avatar || AVATAR_FALLBACK, - alt: name2, - className: "h-9 w-9 rounded-full object-cover ring-2 ring-white/10 hover:ring-accent/60 transition", - onError: (e) => { - e.currentTarget.src = AVATAR_FALLBACK; - } - } - )), /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-sm text-soft" }, "Welcome back,"), /* @__PURE__ */ React.createElement("p", { className: "text-sm font-semibold text-white leading-tight" }, firstName))), /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-2" }, messages_unread > 0 && /* @__PURE__ */ React.createElement( - "a", - { - href: "/messages", - className: "inline-flex items-center gap-1.5 rounded-lg bg-nova-800 px-3 py-1.5 text-xs font-medium text-white ring-1 ring-white/10 hover:bg-nova-700 transition" - }, - /* @__PURE__ */ React.createElement("svg", { className: "h-3.5 w-3.5 text-accent shrink-0", fill: "none", viewBox: "0 0 24 24", stroke: "currentColor", strokeWidth: 2 }, /* @__PURE__ */ React.createElement("path", { strokeLinecap: "round", strokeLinejoin: "round", d: "M3 8l7.89 5.26a2 2 0 002.22 0L21 8M5 19h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z" })), - messages_unread, - " new" - ), notifications_unread > 0 && /* @__PURE__ */ React.createElement( - "a", - { - href: "/dashboard/notifications", - className: "inline-flex items-center gap-1.5 rounded-lg bg-nova-800 px-3 py-1.5 text-xs font-medium text-white ring-1 ring-white/10 hover:bg-nova-700 transition" - }, - /* @__PURE__ */ React.createElement("svg", { className: "h-3.5 w-3.5 text-yellow-400 shrink-0", fill: "none", viewBox: "0 0 24 24", stroke: "currentColor", strokeWidth: 2 }, /* @__PURE__ */ React.createElement("path", { strokeLinecap: "round", strokeLinejoin: "round", d: "M15 17h5l-1.405-1.405A2.032 2.032 0 0118 14.158V11a6.002 6.002 0 00-4-5.659V5a2 2 0 10-4 0v.341C7.67 6.165 6 8.388 6 11v3.159c0 .538-.214 1.055-.595 1.436L4 17h5m6 0v1a3 3 0 11-6 0v-1m6 0H9" })), - notifications_unread - ), /* @__PURE__ */ React.createElement( - "a", - { - href: "/upload", - className: "btn-accent-solid inline-flex items-center gap-1.5 rounded-lg px-3 py-1.5 text-xs font-semibold" - }, - /* @__PURE__ */ React.createElement("svg", { className: "h-3.5 w-3.5 shrink-0", fill: "none", viewBox: "0 0 24 24", stroke: "currentColor", strokeWidth: 2.5 }, /* @__PURE__ */ React.createElement("path", { strokeLinecap: "round", strokeLinejoin: "round", d: "M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-8l-4-4m0 0L8 8m4-4v12" })), - "Upload" - ))))); -} -const __vite_glob_0_90 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ - __proto__: null, - default: HomeWelcomeRow -}, Symbol.toStringTag, { value: "Module" })); -function metaItems(world) { - return [ - world?.promotion_window_label || world?.timeframe_label, - Number(world?.live_submission_count || 0) > 0 ? `${Number(world.live_submission_count)} live submissions` : null, - Number(world?.relation_count || 0) > 0 ? `${Number(world.relation_count)} curated links` : null, - world?.theme?.label || world?.type || null - ].filter(Boolean); -} -function WorldCampaignMeta({ world, className = "" }) { - const items = metaItems(world); - if (items.length === 0) { - return null; - } - return /* @__PURE__ */ React.createElement("div", { className: `flex flex-wrap gap-2 text-xs text-slate-200/75 ${className}`.trim() }, items.map((item) => /* @__PURE__ */ React.createElement("span", { key: item, className: "rounded-full border border-white/12 bg-black/25 px-3 py-1.5" }, item))); -} -function themeStyle$1(theme) { - return { - "--world-accent": theme?.accent_color || "#38bdf8", - "--world-accent-secondary": theme?.accent_color_secondary || "#0f172a" - }; -} -function WorldCard({ world, compact = false, sourceSurface = "", sourceDetail = "" }) { - const cardRef = reactExports.useRef(null); - const href = world && sourceSurface ? withWorldSource(world.public_url, sourceSurface, sourceDetail) : world?.public_url; - reactExports.useEffect(() => { - if (!sourceSurface || !world?.id || typeof window === "undefined") { - return void 0; - } - const node2 = cardRef.current; - if (!node2) { - return void 0; - } - if (typeof window.IntersectionObserver !== "function") { - trackWorldSourceImpression({ - worldId: world.id, - worldTitle: world.title, - sourceSurface, - sourceDetail, - sectionKey: compact ? "compact_card" : "card" - }); - return void 0; - } - const observer = new window.IntersectionObserver((entries) => { - entries.forEach((entry) => { - if (!entry.isIntersecting || entry.intersectionRatio < 0.4) { - return; - } - trackWorldSourceImpression({ - worldId: world.id, - worldTitle: world.title, - sourceSurface, - sourceDetail, - sectionKey: compact ? "compact_card" : "card" - }); - observer.disconnect(); - }); - }, { threshold: [0.4] }); - observer.observe(node2); - return () => observer.disconnect(); - }, [compact, sourceDetail, sourceSurface, world?.id, world?.title]); - if (!world) { - return null; - } - return /* @__PURE__ */ React.createElement( - "a", - { - ref: cardRef, - href, - onClick: () => trackWorldSourceClick({ worldId: world.id, worldTitle: world.title, sourceSurface, sourceDetail }), - className: `group relative block w-full overflow-hidden rounded-[28px] border border-white/10 bg-slate-950/70 transition duration-300 hover:-translate-y-1 hover:border-white/20 ${compact ? "p-5" : "p-6"}`, - style: themeStyle$1(world.theme) - }, - /* @__PURE__ */ React.createElement("div", { className: "absolute inset-0 bg-[radial-gradient(circle_at_top_right,_color-mix(in_srgb,var(--world-accent)_30%,transparent),_transparent_42%),linear-gradient(135deg,_color-mix(in_srgb,var(--world-accent-secondary)_94%,black),_rgba(2,6,23,0.94))] opacity-95" }), - world.cover_url ? /* @__PURE__ */ React.createElement("img", { src: world.cover_url, alt: world.title, className: "absolute inset-0 h-full w-full object-cover opacity-20 transition duration-500 group-hover:scale-[1.03]" }) : null, - /* @__PURE__ */ React.createElement("div", { className: "absolute inset-0 bg-gradient-to-t from-slate-950 via-slate-950/80 to-slate-950/10" }), - /* @__PURE__ */ React.createElement("div", { className: "relative flex h-full min-h-[16rem] flex-col justify-between" }, /* @__PURE__ */ React.createElement("div", null, world.is_recurring ? /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.2em] text-sky-100/70" }, world.family_title || "Recurring family", world.edition_label ? /* @__PURE__ */ React.createElement("span", { className: "ml-2 text-slate-300/70" }, world.edition_label) : null) : null, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center gap-2" }, (Array.isArray(world.status_badges) ? world.status_badges : []).map((badge) => /* @__PURE__ */ React.createElement(WorldStatusBadge, { key: badge.label, badge })), !Array.isArray(world.status_badges) || world.status_badges.length === 0 ? /* @__PURE__ */ React.createElement(WorldStatusBadge, { badge: { label: world.phase || world.status, tone: "slate" } }) : null, world.campaign_label ? /* @__PURE__ */ React.createElement(WorldStatusBadge, { badge: { label: world.campaign_label, tone: "slate" } }) : null, world.badge_label ? /* @__PURE__ */ React.createElement(WorldStatusBadge, { badge: { label: world.badge_label, tone: "rose" } }) : null), world.teaser_title && world.teaser_title !== world.title ? /* @__PURE__ */ React.createElement("p", { className: "mt-4 text-[11px] font-semibold uppercase tracking-[0.2em] text-sky-100/70" }, world.title) : null, /* @__PURE__ */ React.createElement("h3", { className: `mt-4 max-w-xl font-semibold tracking-[-0.03em] text-white ${compact ? "text-2xl" : "text-3xl"}` }, world.teaser_title || world.title), world.tagline ? /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm uppercase tracking-[0.18em] text-white/55" }, world.tagline) : null, world.summary ? /* @__PURE__ */ React.createElement("p", { className: "mt-4 max-w-2xl text-sm leading-6 text-slate-200/85" }, world.summary) : null), /* @__PURE__ */ React.createElement("div", { className: "mt-6 flex flex-wrap items-end justify-between gap-3" }, /* @__PURE__ */ React.createElement(WorldCampaignMeta, { world }), /* @__PURE__ */ React.createElement("span", { className: "inline-flex items-center gap-2 rounded-full border border-white/15 bg-white/10 px-4 py-2 text-sm font-semibold text-white transition group-hover:bg-white/15" }, world.cta_label || world.challenge_cta_label || (world.is_recurring && !world.is_canonical_edition ? "Open edition" : "Open world"), /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-arrow-right" })))) - ); -} -function ActiveWorldSpotlight({ - spotlight, - secondary = [], - indexUrl = "/worlds", - eyebrow = "World spotlight", - secondaryTitle = "Campaign rail", - className = "", - sourceSurface = "", - sourceDetail = "", - secondarySourceSurface = "", - secondarySourceDetail = "" -}) { - const spotlightRef = reactExports.useRef(null); - const primaryHref = spotlight && sourceSurface ? withWorldSource(spotlight.public_url || spotlight.cta_url, sourceSurface, sourceDetail) : spotlight?.public_url || spotlight?.cta_url; - reactExports.useEffect(() => { - if (!spotlight?.id || !sourceSurface || typeof window === "undefined") { - return void 0; - } - const node2 = spotlightRef.current; - if (!node2) { - return void 0; - } - if (typeof window.IntersectionObserver !== "function") { - trackWorldSourceImpression({ - worldId: spotlight.id, - worldTitle: spotlight.title || spotlight.headline, - sourceSurface, - sourceDetail, - sectionKey: "spotlight" - }); - return void 0; - } - const observer = new window.IntersectionObserver((entries) => { - entries.forEach((entry) => { - if (!entry.isIntersecting || entry.intersectionRatio < 0.45) { - return; - } - trackWorldSourceImpression({ - worldId: spotlight.id, - worldTitle: spotlight.title || spotlight.headline, - sourceSurface, - sourceDetail, - sectionKey: "spotlight" - }); - observer.disconnect(); - }); - }, { threshold: [0.45] }); - observer.observe(node2); - return () => observer.disconnect(); - }, [spotlight?.headline, spotlight?.id, spotlight?.title, sourceDetail, sourceSurface]); - if (!spotlight) { - return null; - } - return /* @__PURE__ */ React.createElement("section", { className }, /* @__PURE__ */ React.createElement( - "div", - { - ref: spotlightRef, - className: "group relative overflow-hidden rounded-[32px] border border-white/10 bg-slate-950/70", - style: { - "--world-accent": spotlight.theme?.accent_color || "#f97316", - "--world-accent-secondary": spotlight.theme?.accent_color_secondary || "#0f172a" - } - }, - /* @__PURE__ */ React.createElement("div", { className: "absolute inset-0 bg-[radial-gradient(circle_at_top_left,_color-mix(in_srgb,var(--world-accent)_30%,transparent),_transparent_36%),linear-gradient(135deg,_color-mix(in_srgb,var(--world-accent-secondary)_92%,black),_rgba(2,6,23,0.98))]" }), - spotlight.cover_url ? /* @__PURE__ */ React.createElement("img", { src: spotlight.cover_url, alt: spotlight.title || spotlight.headline, className: "absolute inset-0 h-full w-full object-cover opacity-20 transition duration-500 group-hover:scale-[1.03]" }) : null, - /* @__PURE__ */ React.createElement("div", { className: "absolute inset-0 bg-gradient-to-r from-slate-950 via-slate-950/84 to-slate-950/28" }), - /* @__PURE__ */ React.createElement("div", { className: "relative grid gap-8 px-6 py-7 sm:px-8 lg:grid-cols-[minmax(0,1.2fr)_20rem] lg:px-10" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.22em] text-white/70" }, eyebrow), /* @__PURE__ */ React.createElement("div", { className: "mt-4 flex flex-wrap gap-2" }, (Array.isArray(spotlight.status_badges) ? spotlight.status_badges : []).map((badge) => /* @__PURE__ */ React.createElement(WorldStatusBadge, { key: badge.label, badge })), spotlight.campaign_label ? /* @__PURE__ */ React.createElement(WorldStatusBadge, { badge: { label: spotlight.campaign_label, tone: "slate" } }) : null), spotlight.title && spotlight.headline && spotlight.title !== spotlight.headline ? /* @__PURE__ */ React.createElement("p", { className: "mt-5 text-[11px] font-semibold uppercase tracking-[0.22em] text-sky-100/70" }, spotlight.title) : null, /* @__PURE__ */ React.createElement("h2", { className: "mt-3 text-3xl font-semibold tracking-[-0.04em] text-white sm:text-4xl" }, spotlight.headline || spotlight.title), spotlight.tagline ? /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm uppercase tracking-[0.18em] text-white/55" }, spotlight.tagline) : null, spotlight.summary ? /* @__PURE__ */ React.createElement("p", { className: "mt-4 max-w-3xl text-sm leading-7 text-slate-200/88" }, spotlight.summary) : null, /* @__PURE__ */ React.createElement(WorldCampaignMeta, { world: spotlight, className: "mt-6" }), spotlight.supporting_item ? /* @__PURE__ */ React.createElement("a", { href: spotlight.supporting_item.url, className: "mt-6 inline-flex max-w-xl items-center gap-3 rounded-[22px] border border-white/12 bg-black/25 px-4 py-3 text-left text-sm text-slate-100 transition hover:border-white/20 hover:bg-white/[0.06]" }, /* @__PURE__ */ React.createElement("div", { className: "min-w-0" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-400" }, spotlight.supporting_item.entity_label || "Related item"), /* @__PURE__ */ React.createElement("div", { className: "mt-1 truncate font-semibold text-white" }, spotlight.supporting_item.title), spotlight.supporting_item.context_label ? /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-xs text-slate-300/80" }, spotlight.supporting_item.context_label) : null), /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-arrow-right shrink-0 text-xs text-sky-100" })) : null, /* @__PURE__ */ React.createElement("div", { className: "mt-6 flex flex-wrap gap-3" }, /* @__PURE__ */ React.createElement("a", { href: primaryHref, onClick: () => trackWorldSourceClick({ worldId: spotlight.id, worldTitle: spotlight.title || spotlight.headline, sourceSurface, sourceDetail }), className: "inline-flex items-center gap-2 rounded-full bg-white px-4 py-2.5 text-sm font-semibold text-slate-950 transition group-hover:bg-sky-100" }, spotlight.cta_label || "Explore world", /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-arrow-right" })), /* @__PURE__ */ React.createElement("a", { href: indexUrl, className: "inline-flex items-center gap-2 rounded-full border border-white/12 bg-white/[0.05] px-4 py-2.5 text-sm font-semibold text-white transition hover:bg-white/[0.08]" }, "Browse all worlds"))), /* @__PURE__ */ React.createElement("div", { className: "rounded-[28px] border border-white/12 bg-black/25 p-5 text-white backdrop-blur-sm" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-400" }, "Campaign state"), /* @__PURE__ */ React.createElement("div", { className: "mt-3 flex items-center gap-3 text-lg font-semibold" }, /* @__PURE__ */ React.createElement("i", { className: spotlight.icon_name || "fa-solid fa-globe" }), /* @__PURE__ */ React.createElement("span", null, spotlight.theme?.label || "Editorial world")), spotlight.timeframe_label ? /* @__PURE__ */ React.createElement("div", { className: "mt-4 text-sm text-slate-300" }, spotlight.timeframe_label) : null, spotlight.promotion_window_label ? /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-sm text-slate-400" }, spotlight.promotion_window_label) : null, Number(spotlight.live_submission_count || 0) > 0 ? /* @__PURE__ */ React.createElement("div", { className: "mt-5 rounded-2xl border border-emerald-300/20 bg-emerald-400/10 px-4 py-3 text-sm text-emerald-100" }, spotlight.live_submission_count, " live submissions are already part of this campaign.") : null)) - ), Array.isArray(secondary) && secondary.length > 0 ? /* @__PURE__ */ React.createElement("div", { className: "mt-6" }, /* @__PURE__ */ React.createElement("div", { className: "mb-4 flex items-end justify-between gap-4" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("h3", { className: "text-xl font-semibold tracking-[-0.03em] text-white" }, secondaryTitle), /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-sm leading-6 text-slate-400" }, "More live or upcoming worlds that are being actively surfaced right now.")), /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-400" }, secondary.length, " worlds")), /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 xl:grid-cols-3" }, secondary.map((world) => /* @__PURE__ */ React.createElement(WorldCard, { key: world.id, world, compact: true, sourceSurface: secondarySourceSurface || sourceSurface, sourceDetail: secondarySourceDetail || sourceDetail })))) : null); -} -function HomeWorldSpotlight({ world }) { - if (!world) { - return null; - } - const spotlight = world.primary || world; - const secondary = Array.isArray(world.secondary) ? world.secondary : []; - return /* @__PURE__ */ React.createElement("section", { className: "mt-14 px-4 sm:px-6 lg:px-8" }, /* @__PURE__ */ React.createElement( - ActiveWorldSpotlight, - { - spotlight, - secondary, - indexUrl: world.index_url || "/worlds", - eyebrow: "Homepage spotlight", - secondaryTitle: "More live worlds", - sourceSurface: "homepage_spotlight", - sourceDetail: "primary", - secondarySourceSurface: "homepage_worlds_rail", - secondarySourceDetail: "secondary" - } - )); -} -const __vite_glob_0_91 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ - __proto__: null, - default: HomeWorldSpotlight + default: WorldsHelpPage }, Symbol.toStringTag, { value: "Module" })); function cx$4(...parts) { return parts.filter(Boolean).join(" "); @@ -80266,7 +82240,7 @@ function LeaderboardPage() { const items = Array.isArray(data?.items) ? data.items : []; return /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement(SeoHead, { seo, title: seo?.title || "Leaderboard — Skinbase", description: seo?.description || "Top creators, groups, artworks, stories, and Worlds on Skinbase." }), /* @__PURE__ */ React.createElement("div", { className: "min-h-screen bg-[radial-gradient(circle_at_top,rgba(14,165,233,0.14),transparent_34%),linear-gradient(180deg,#020617_0%,#0f172a_48%,#020617_100%)] pb-16 text-slate-100" }, /* @__PURE__ */ React.createElement("div", { className: "mx-auto w-full max-w-7xl px-4 py-8 sm:px-6 lg:px-8" }, /* @__PURE__ */ React.createElement("header", { className: "rounded-[2rem] border border-white/10 bg-slate-950/70 px-6 py-8 shadow-[0_35px_120px_rgba(2,6,23,0.75)] backdrop-blur" }, /* @__PURE__ */ React.createElement("p", { className: "text-xs font-semibold uppercase tracking-[0.28em] text-sky-300" }, "Skinbase Competition Board"), /* @__PURE__ */ React.createElement("h1", { className: "mt-4 max-w-3xl text-4xl font-black tracking-tight text-white sm:text-5xl" }, "Top creators, groups, standout artworks, stories, and Worlds with momentum."), /* @__PURE__ */ React.createElement("p", { className: "mt-4 max-w-2xl text-sm leading-6 text-slate-300 sm:text-base" }, "Switch between creators, groups, artworks, stories, and Worlds, then filter by daily, weekly, monthly, or all-time performance.")), /* @__PURE__ */ React.createElement("div", { className: "mt-6 space-y-4" }, /* @__PURE__ */ React.createElement(LeaderboardTabs, { items: TYPE_TABS, active: type2, onChange: setType, sticky: true, label: "Leaderboard type" }), /* @__PURE__ */ React.createElement(LeaderboardTabs, { items: PERIOD_TABS, active: period, onChange: setPeriod, label: "Leaderboard period" })), loading ? /* @__PURE__ */ React.createElement("div", { className: "mt-6 rounded-3xl border border-white/10 bg-white/[0.03] px-6 py-5 text-sm text-slate-400" }, "Refreshing leaderboard...") : null, /* @__PURE__ */ React.createElement("div", { className: "mt-8" }, /* @__PURE__ */ React.createElement(LeaderboardList, { items, type: type2 }))))); } -const __vite_glob_0_92 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ +const __vite_glob_0_74 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ __proto__: null, default: LeaderboardPage }, Symbol.toStringTag, { value: "Module" })); @@ -82204,7 +84178,7 @@ if (typeof document !== "undefined") { ); } } -const __vite_glob_0_93 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ +const __vite_glob_0_75 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ __proto__: null, default: MessagesPage }, Symbol.toStringTag, { value: "Module" })); @@ -82371,7 +84345,7 @@ function ArtworkMaturityQueue() { } )); } -const __vite_glob_0_95 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ +const __vite_glob_0_77 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ __proto__: null, default: ArtworkMaturityQueue }, Symbol.toStringTag, { value: "Module" })); @@ -82792,7 +84766,7 @@ if (typeof document !== "undefined") { clientExports.createRoot(mountEl).render(/* @__PURE__ */ React.createElement(NewsComments, { ...props })); } } -const __vite_glob_0_96 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ +const __vite_glob_0_78 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ __proto__: null, default: NewsComments }, Symbol.toStringTag, { value: "Module" })); @@ -83756,7 +85730,7 @@ function ProfileGallery() { } )))); } -const __vite_glob_0_97 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ +const __vite_glob_0_79 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ __proto__: null, default: ProfileGallery }, Symbol.toStringTag, { value: "Module" })); @@ -85503,7 +87477,6 @@ function TagPeopleModal({ isOpen, onClose, selected = [], onConfirm }) { staged.length === 0 ? "Continue without tagging" : `Tag ${staged.length} ${staged.length === 1 ? "person" : "people"}` )))); } -const EmojiPicker = reactExports.lazy(() => Promise.resolve().then(() => EmojiMartPicker$1)); const VISIBILITY_OPTIONS = [ { value: "public", icon: "fa-globe", label: "Public" }, { value: "followers", icon: "fa-user-friends", label: "Followers" }, @@ -85745,7 +87718,7 @@ function PostComposer({ user, onPosted }) { }, /* @__PURE__ */ React.createElement("i", { className: "fa-regular fa-face-smile fa-fw" }) ), emojiOpen && /* @__PURE__ */ React.createElement("div", { className: "absolute bottom-full mb-2 left-0 z-50 shadow-2xl" }, /* @__PURE__ */ React.createElement(reactExports.Suspense, { fallback: /* @__PURE__ */ React.createElement("div", { className: "w-[352px] h-[400px] rounded-2xl bg-[#10192e] border border-white/10 flex items-center justify-center text-slate-600" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-spinner fa-spin text-xl" })) }, emojiData && /* @__PURE__ */ React.createElement( - EmojiPicker, + EmojiMartPicker, { data: emojiData, onEmojiSelect: insertEmoji, @@ -86607,7 +88580,7 @@ function ProfileShow() { } )))); } -const __vite_glob_0_98 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ +const __vite_glob_0_80 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ __proto__: null, default: ProfileShow }, Symbol.toStringTag, { value: "Module" })); @@ -88035,7 +90008,7 @@ function ProfileEdit() { ) ); } -const __vite_glob_0_99 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ +const __vite_glob_0_81 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ __proto__: null, default: ProfileEdit }, Symbol.toStringTag, { value: "Module" })); @@ -88548,7 +90521,7 @@ function StudioActivity() { /* @__PURE__ */ React.createElement("div", { className: "space-y-6" }, /* @__PURE__ */ React.createElement("section", { className: "grid gap-4 md:grid-cols-3" }, /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-white/[0.03] p-5" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, "New since last read"), /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-3xl font-semibold text-white" }, Number(summary.new_items || 0).toLocaleString())), /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-white/[0.03] p-5" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, "Unread notifications"), /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-3xl font-semibold text-white" }, Number(summary.unread_notifications || 0).toLocaleString())), /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-white/[0.03] p-5" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, "Last inbox reset"), /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-base font-semibold text-white" }, summary.last_read_at ? formatDate$7(summary.last_read_at) : "Not yet"))), /* @__PURE__ */ React.createElement("section", { className: "rounded-[30px] border border-white/10 bg-[radial-gradient(circle_at_top_left,_rgba(56,189,248,0.14),_transparent_35%),linear-gradient(135deg,_rgba(15,23,42,0.86),_rgba(2,6,23,0.96))] p-5 lg:p-6" }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-3 md:grid-cols-2 xl:grid-cols-4" }, /* @__PURE__ */ React.createElement("label", { className: "space-y-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "block text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, "Search activity"), /* @__PURE__ */ React.createElement("input", { value: filters.q || "", onChange: (event) => updateFilters({ q: event.target.value }), className: "w-full rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white", placeholder: "Message, actor, or module" })), /* @__PURE__ */ React.createElement("div", { className: "space-y-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "block text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, "Type"), /* @__PURE__ */ React.createElement(NovaSelect, { value: filters.type || "all", onChange: (val) => updateFilters({ type: val }), options: typeOptions, searchable: false })), /* @__PURE__ */ React.createElement("div", { className: "space-y-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "block text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, "Content type"), /* @__PURE__ */ React.createElement(NovaSelect, { value: filters.module || "all", onChange: (val) => updateFilters({ module: val }), options: moduleOptions, searchable: false })), /* @__PURE__ */ React.createElement("div", { className: "flex items-end" }, /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => updateFilters({ q: "", type: "all", module: "all" }), className: "w-full rounded-2xl border border-white/10 px-4 py-3 text-sm text-slate-200" }, "Reset")))), /* @__PURE__ */ React.createElement("section", { className: "space-y-4" }, items.length > 0 ? items.map((item) => /* @__PURE__ */ React.createElement("article", { key: item.id, className: `rounded-[28px] border p-5 ${item.is_new ? "border-sky-300/25 bg-sky-300/10" : "border-white/10 bg-white/[0.03]"}` }, /* @__PURE__ */ React.createElement("div", { className: "flex gap-4" }, item.actor?.avatar_url ? /* @__PURE__ */ React.createElement("img", { src: item.actor.avatar_url, alt: item.actor.name || "Activity actor", className: "h-12 w-12 rounded-2xl object-cover" }) : /* @__PURE__ */ React.createElement("div", { className: "flex h-12 w-12 items-center justify-center rounded-2xl bg-black/20 text-slate-400" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-bell" })), /* @__PURE__ */ React.createElement("div", { className: "min-w-0 flex-1" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center gap-3 text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, /* @__PURE__ */ React.createElement("span", null, item.module_label), /* @__PURE__ */ React.createElement("span", null, formatDate$7(item.created_at)), item.is_new && /* @__PURE__ */ React.createElement("span", { className: "rounded-full bg-sky-300/20 px-2 py-1 text-sky-100" }, "New")), /* @__PURE__ */ React.createElement("h2", { className: "mt-2 text-lg font-semibold text-white" }, item.title), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm leading-6 text-slate-400" }, item.body), /* @__PURE__ */ React.createElement("div", { className: "mt-4 flex flex-wrap items-center gap-3 text-sm text-slate-400" }, item.actor?.name && /* @__PURE__ */ React.createElement("span", null, item.actor.name), /* @__PURE__ */ React.createElement("a", { href: item.url, className: "inline-flex items-center gap-2 rounded-full border border-white/10 px-3 py-1.5 text-slate-200" }, "Open")))))) : /* @__PURE__ */ React.createElement("div", { className: "rounded-[28px] border border-dashed border-white/15 px-6 py-16 text-center text-slate-400" }, "No activity matches this filter.")), /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between rounded-[24px] border border-white/10 bg-white/[0.03] px-4 py-3 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("button", { type: "button", disabled: (meta.current_page || 1) <= 1, onClick: () => updateFilters({ page: Math.max(1, (meta.current_page || 1) - 1) }), className: "rounded-full border border-white/10 px-4 py-2 disabled:opacity-40" }, "Previous"), /* @__PURE__ */ React.createElement("span", { className: "text-xs uppercase tracking-[0.18em] text-slate-500" }, "Page ", meta.current_page || 1, " of ", meta.last_page || 1), /* @__PURE__ */ React.createElement("button", { type: "button", disabled: (meta.current_page || 1) >= (meta.last_page || 1), onClick: () => updateFilters({ page: (meta.current_page || 1) + 1 }), className: "rounded-full border border-white/10 px-4 py-2 disabled:opacity-40" }, "Next"))) ); } -const __vite_glob_0_100 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ +const __vite_glob_0_82 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ __proto__: null, default: StudioActivity }, Symbol.toStringTag, { value: "Module" })); @@ -88639,7 +90612,7 @@ function StudioAnalytics() { return /* @__PURE__ */ React.createElement("div", { key: item.key, className: "rounded-[22px] border border-white/10 bg-black/20 p-4" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between gap-4" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-3 text-slate-200" }, /* @__PURE__ */ React.createElement("i", { className: item.icon }), /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "font-semibold text-white" }, item.label), /* @__PURE__ */ React.createElement("div", { className: "text-xs text-slate-400" }, Number(item.published_count || 0).toLocaleString(), " published"))), /* @__PURE__ */ React.createElement("a", { href: moduleBreakdown?.find((entry) => entry.key === item.key)?.index_url, className: "text-xs font-semibold uppercase tracking-[0.18em] text-sky-100" }, "Open")), /* @__PURE__ */ React.createElement("div", { className: "mt-4 grid gap-4 md:grid-cols-2" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between text-xs text-slate-400" }, /* @__PURE__ */ React.createElement("span", null, "Views"), /* @__PURE__ */ React.createElement("span", null, Number(item.views || 0).toLocaleString())), /* @__PURE__ */ React.createElement("div", { className: "mt-2 h-2 overflow-hidden rounded-full bg-white/5" }, /* @__PURE__ */ React.createElement("div", { className: "h-full rounded-full bg-emerald-400/60", style: { width: `${Math.max(4, Math.round(Number(item.views || 0) / viewMax * 100))}%` } }))), /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between text-xs text-slate-400" }, /* @__PURE__ */ React.createElement("span", null, "Engagement"), /* @__PURE__ */ React.createElement("span", null, Number(item.engagement || 0).toLocaleString())), /* @__PURE__ */ React.createElement("div", { className: "mt-2 h-2 overflow-hidden rounded-full bg-white/5" }, /* @__PURE__ */ React.createElement("div", { className: "h-full rounded-full bg-pink-400/60", style: { width: `${Math.max(4, Math.round(Number(item.engagement || 0) / engagementMax * 100))}%` } }))))); }))), /* @__PURE__ */ React.createElement("section", { className: "rounded-[28px] border border-white/10 bg-white/[0.03] p-6" }, /* @__PURE__ */ React.createElement("h2", { className: "text-lg font-semibold text-white" }, "Readable insights"), /* @__PURE__ */ React.createElement("div", { className: "mt-4 space-y-3 text-sm text-slate-400" }, (insightBlocks || []).map((item) => /* @__PURE__ */ React.createElement("a", { key: item.key, href: item.href, className: "block rounded-[22px] border border-white/10 bg-black/20 p-4 transition hover:border-white/20" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-start gap-3" }, /* @__PURE__ */ React.createElement("div", { className: "flex h-10 w-10 items-center justify-center rounded-2xl bg-white/[0.04] text-sky-100" }, /* @__PURE__ */ React.createElement("i", { className: item.icon })), /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("h3", { className: "text-sm font-semibold text-white" }, item.title), /* @__PURE__ */ React.createElement("p", { className: "mt-2 leading-6 text-slate-400" }, item.body), /* @__PURE__ */ React.createElement("span", { className: "mt-3 inline-flex items-center gap-2 text-sm font-medium text-sky-100" }, item.cta, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-arrow-right" }))))))))), /* @__PURE__ */ React.createElement("div", { className: "mt-6 grid gap-6 xl:grid-cols-[minmax(0,1fr)_360px]" }, /* @__PURE__ */ React.createElement("section", { className: "rounded-[28px] border border-white/10 bg-white/[0.03] p-6" }, /* @__PURE__ */ React.createElement("h2", { className: "text-lg font-semibold text-white" }, "Top content"), /* @__PURE__ */ React.createElement("div", { className: "mt-5 overflow-x-auto" }, /* @__PURE__ */ React.createElement("table", { className: "w-full text-sm" }, /* @__PURE__ */ React.createElement("thead", null, /* @__PURE__ */ React.createElement("tr", { className: "border-b border-white/5 text-left text-[11px] uppercase tracking-[0.18em] text-slate-500" }, /* @__PURE__ */ React.createElement("th", { className: "pb-3 pr-4" }, "Module"), /* @__PURE__ */ React.createElement("th", { className: "pb-3 pr-4" }, "Title"), /* @__PURE__ */ React.createElement("th", { className: "pb-3 pr-4 text-right" }, "Views"), /* @__PURE__ */ React.createElement("th", { className: "pb-3 pr-4 text-right" }, "Reactions"), /* @__PURE__ */ React.createElement("th", { className: "pb-3 pr-4 text-right" }, "Comments"), /* @__PURE__ */ React.createElement("th", { className: "pb-3 text-right" }, "Open"))), /* @__PURE__ */ React.createElement("tbody", { className: "divide-y divide-white/5" }, (topContent || []).map((item) => /* @__PURE__ */ React.createElement("tr", { key: item.id }, /* @__PURE__ */ React.createElement("td", { className: "py-3 pr-4 text-slate-300" }, item.module_label), /* @__PURE__ */ React.createElement("td", { className: "py-3 pr-4 text-white" }, item.title), /* @__PURE__ */ React.createElement("td", { className: "py-3 pr-4 text-right text-slate-300" }, Number(item.metrics?.views || 0).toLocaleString()), /* @__PURE__ */ React.createElement("td", { className: "py-3 pr-4 text-right text-slate-300" }, Number(item.metrics?.appreciation || 0).toLocaleString()), /* @__PURE__ */ React.createElement("td", { className: "py-3 pr-4 text-right text-slate-300" }, Number(item.metrics?.comments || 0).toLocaleString()), /* @__PURE__ */ React.createElement("td", { className: "py-3 text-right" }, /* @__PURE__ */ React.createElement("a", { href: item.analytics_url || item.view_url, className: "text-sky-100" }, "Open")))))))), /* @__PURE__ */ React.createElement("section", { className: "rounded-[28px] border border-white/10 bg-white/[0.03] p-6" }, /* @__PURE__ */ React.createElement("h2", { className: "text-lg font-semibold text-white" }, "Recent comments"), /* @__PURE__ */ React.createElement("div", { className: "mt-4 space-y-3" }, (recentComments || []).map((comment) => /* @__PURE__ */ React.createElement("article", { key: comment.id, className: "rounded-[22px] border border-white/10 bg-black/20 p-4" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-sky-200/70" }, comment.module_label), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm text-white" }, comment.author_name, " on ", comment.item_title), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm leading-6 text-slate-400" }, comment.body))))))); } -const __vite_glob_0_101 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ +const __vite_glob_0_83 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ __proto__: null, default: StudioAnalytics }, Symbol.toStringTag, { value: "Module" })); @@ -89455,7 +91428,7 @@ function StudioArchived() { } )); } -const __vite_glob_0_102 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ +const __vite_glob_0_84 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ __proto__: null, default: StudioArchived }, Symbol.toStringTag, { value: "Module" })); @@ -89491,7 +91464,7 @@ function StudioArtworkAnalytics() { } ), /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("h2", { className: "text-lg font-bold text-white" }, artwork?.title), /* @__PURE__ */ React.createElement("p", { className: "text-xs text-slate-500 mt-1" }, "/", artwork?.slug))), /* @__PURE__ */ React.createElement("div", { className: "grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-5 gap-4 mb-8" }, kpiItems$1.map((item) => /* @__PURE__ */ React.createElement("div", { key: item.key, className: "bg-nova-900/60 border border-white/10 rounded-2xl p-5" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-2 mb-2" }, /* @__PURE__ */ React.createElement("i", { className: `fa-solid ${item.icon} ${item.color}` }), /* @__PURE__ */ React.createElement("span", { className: "text-xs font-medium text-slate-400 uppercase tracking-wider" }, item.label)), /* @__PURE__ */ React.createElement("p", { className: "text-2xl font-bold text-white tabular-nums" }, (analytics?.[item.key] ?? 0).toLocaleString())))), /* @__PURE__ */ React.createElement("h3", { className: "text-base font-bold text-white mb-4" }, "Performance Metrics"), /* @__PURE__ */ React.createElement("div", { className: "grid grid-cols-1 sm:grid-cols-3 gap-4 mb-8" }, metricCards.map((item) => /* @__PURE__ */ React.createElement("div", { key: item.key, className: "bg-nova-900/60 border border-white/10 rounded-2xl p-5" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-2 mb-3" }, /* @__PURE__ */ React.createElement("div", { className: `w-10 h-10 rounded-xl bg-white/5 flex items-center justify-center ${item.color}` }, /* @__PURE__ */ React.createElement("i", { className: `fa-solid ${item.icon} text-lg` })), /* @__PURE__ */ React.createElement("span", { className: "text-sm font-medium text-slate-300" }, item.label)), /* @__PURE__ */ React.createElement("p", { className: "text-3xl font-bold text-white tabular-nums" }, (analytics?.[item.key] ?? 0).toFixed(1))))), /* @__PURE__ */ React.createElement("div", { className: "grid grid-cols-1 lg:grid-cols-2 gap-4" }, /* @__PURE__ */ React.createElement("div", { className: "bg-nova-900/40 border border-white/10 rounded-2xl p-6" }, /* @__PURE__ */ React.createElement("h4", { className: "text-sm font-semibold text-white mb-3" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-chart-line mr-2 text-slate-500" }), "Traffic Sources"), /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-center py-8" }, /* @__PURE__ */ React.createElement("div", { className: "text-center" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-chart-pie text-3xl text-slate-700 mb-3" }), /* @__PURE__ */ React.createElement("p", { className: "text-xs text-slate-500" }, "Coming soon"), /* @__PURE__ */ React.createElement("p", { className: "text-[10px] text-slate-600 mt-1" }, "Traffic source tracking is on the roadmap")))), /* @__PURE__ */ React.createElement("div", { className: "bg-nova-900/40 border border-white/10 rounded-2xl p-6" }, /* @__PURE__ */ React.createElement("h4", { className: "text-sm font-semibold text-white mb-3" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-share-from-square mr-2 text-slate-500" }), "Shares by Platform"), /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-center py-8" }, /* @__PURE__ */ React.createElement("div", { className: "text-center" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-share-nodes text-3xl text-slate-700 mb-3" }), /* @__PURE__ */ React.createElement("p", { className: "text-xs text-slate-500" }, "Coming soon"), /* @__PURE__ */ React.createElement("p", { className: "text-[10px] text-slate-600 mt-1" }, "Per-platform breakdown coming in a future update")))), /* @__PURE__ */ React.createElement("div", { className: "bg-nova-900/40 border border-white/10 rounded-2xl p-6 lg:col-span-2" }, /* @__PURE__ */ React.createElement("h4", { className: "text-sm font-semibold text-white mb-3" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-trophy mr-2 text-slate-500" }), "Ranking History"), /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-center py-8" }, /* @__PURE__ */ React.createElement("div", { className: "text-center" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-chart-area text-3xl text-slate-700 mb-3" }), /* @__PURE__ */ React.createElement("p", { className: "text-xs text-slate-500" }, "Coming soon"), /* @__PURE__ */ React.createElement("p", { className: "text-[10px] text-slate-600 mt-1" }, "Historical ranking data will be tracked in a future update")))))); } -const __vite_glob_0_103 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ +const __vite_glob_0_85 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ __proto__: null, default: StudioArtworkAnalytics }, Symbol.toStringTag, { value: "Module" })); @@ -90252,6 +92225,21 @@ function ArtworkEvolutionSearchPicker({ artworkId, selected, onSelect, disabled /* @__PURE__ */ React.createElement("span", { className: "inline-flex items-center gap-2 self-start rounded-2xl border border-sky-300/25 bg-sky-400/10 px-4 py-3 text-sm font-semibold text-sky-100 md:self-center" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-link" }), "Link older version") )) : /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-dashed border-white/12 bg-white/[0.02] px-5 py-10 text-center text-sm text-slate-300" }, loading ? "Searching artworks…" : "No manageable published artworks matched this search yet.")))); } +function metaItems(world) { + return [ + world?.promotion_window_label || world?.timeframe_label, + Number(world?.live_submission_count || 0) > 0 ? `${Number(world.live_submission_count)} live submissions` : null, + Number(world?.relation_count || 0) > 0 ? `${Number(world.relation_count)} curated links` : null, + world?.theme?.label || world?.type || null + ].filter(Boolean); +} +function WorldCampaignMeta({ world, className = "" }) { + const items = metaItems(world); + if (items.length === 0) { + return null; + } + return /* @__PURE__ */ React.createElement("div", { className: `flex flex-wrap gap-2 text-xs text-slate-200/75 ${className}`.trim() }, items.map((item) => /* @__PURE__ */ React.createElement("span", { key: item, className: "rounded-full border border-white/12 bg-black/25 px-3 py-1.5" }, item))); +} function UploadWorldHighlightCard({ world, sourceSurface = "", sourceDetail = "" }) { const cardRef = reactExports.useRef(null); reactExports.useEffect(() => { @@ -90457,7 +92445,7 @@ const TABS = [ function getCsrfToken() { return document.querySelector('meta[name="csrf-token"]')?.getAttribute("content") || ""; } -function formatBytes$2(bytes) { +function formatBytes$1(bytes) { if (!bytes) return "—"; if (bytes < 1024) return bytes + " B"; if (bytes < 1048576) return (bytes / 1024).toFixed(1) + " KB"; @@ -91271,7 +93259,7 @@ function StudioArtworkEdit() { alt: title || "Artwork preview", className: "h-full w-full object-cover" } - ) : /* @__PURE__ */ React.createElement("div", { className: "flex h-full w-full items-center justify-center text-slate-600" }, /* @__PURE__ */ React.createElement("svg", { width: "48", height: "48", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "1.5", "aria-hidden": "true" }, /* @__PURE__ */ React.createElement("rect", { x: "3", y: "3", width: "18", height: "18", rx: "2" }), /* @__PURE__ */ React.createElement("circle", { cx: "8.5", cy: "8.5", r: "1.5", fill: "currentColor" }), /* @__PURE__ */ React.createElement("path", { d: "M21 15l-5-5L5 21" }))), /* @__PURE__ */ React.createElement("div", { className: "pointer-events-none absolute inset-x-0 bottom-0 z-10 bg-gradient-to-t from-black/85 via-black/45 to-transparent p-4" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-white/50" }, activeMediaLabel), /* @__PURE__ */ React.createElement("p", { className: "mt-1 truncate text-sm font-semibold text-white", title: fileMeta.name }, fileMeta.name), /* @__PURE__ */ React.createElement("div", { className: "mt-2 flex flex-wrap items-center gap-2 text-[11px] text-white/65" }, currentFileExt && /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/10 px-2 py-0.5 uppercase tracking-[0.14em] text-white/70" }, currentFileExt), screenshotItems.length > 0 && /* @__PURE__ */ React.createElement("span", null, screenshotItems.length, " screenshot", screenshotItems.length !== 1 ? "s" : ""), fileMeta.width > 0 && /* @__PURE__ */ React.createElement("span", null, fileMeta.width, " × ", fileMeta.height))), replacing && /* @__PURE__ */ React.createElement("div", { className: "absolute inset-0 z-20 flex items-center justify-center bg-black/60" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-3 rounded-full border border-white/10 bg-black/55 px-4 py-2 text-xs text-white/80 backdrop-blur" }, /* @__PURE__ */ React.createElement("div", { className: "h-5 w-5 rounded-full border-2 border-accent/30 border-t-accent animate-spin" }), "Uploading new revision…"))))), /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", { className: "inline-flex items-center gap-2 rounded-full border border-white/10 bg-white/[0.04] px-3 py-2 text-[11px] text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Size"), /* @__PURE__ */ React.createElement("span", { className: "font-semibold text-white" }, formatBytes$2(fileMeta.size))), downloadUrl ? /* @__PURE__ */ React.createElement( + ) : /* @__PURE__ */ React.createElement("div", { className: "flex h-full w-full items-center justify-center text-slate-600" }, /* @__PURE__ */ React.createElement("svg", { width: "48", height: "48", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "1.5", "aria-hidden": "true" }, /* @__PURE__ */ React.createElement("rect", { x: "3", y: "3", width: "18", height: "18", rx: "2" }), /* @__PURE__ */ React.createElement("circle", { cx: "8.5", cy: "8.5", r: "1.5", fill: "currentColor" }), /* @__PURE__ */ React.createElement("path", { d: "M21 15l-5-5L5 21" }))), /* @__PURE__ */ React.createElement("div", { className: "pointer-events-none absolute inset-x-0 bottom-0 z-10 bg-gradient-to-t from-black/85 via-black/45 to-transparent p-4" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-white/50" }, activeMediaLabel), /* @__PURE__ */ React.createElement("p", { className: "mt-1 truncate text-sm font-semibold text-white", title: fileMeta.name }, fileMeta.name), /* @__PURE__ */ React.createElement("div", { className: "mt-2 flex flex-wrap items-center gap-2 text-[11px] text-white/65" }, currentFileExt && /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/10 px-2 py-0.5 uppercase tracking-[0.14em] text-white/70" }, currentFileExt), screenshotItems.length > 0 && /* @__PURE__ */ React.createElement("span", null, screenshotItems.length, " screenshot", screenshotItems.length !== 1 ? "s" : ""), fileMeta.width > 0 && /* @__PURE__ */ React.createElement("span", null, fileMeta.width, " × ", fileMeta.height))), replacing && /* @__PURE__ */ React.createElement("div", { className: "absolute inset-0 z-20 flex items-center justify-center bg-black/60" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-3 rounded-full border border-white/10 bg-black/55 px-4 py-2 text-xs text-white/80 backdrop-blur" }, /* @__PURE__ */ React.createElement("div", { className: "h-5 w-5 rounded-full border-2 border-accent/30 border-t-accent animate-spin" }), "Uploading new revision…"))))), /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", { className: "inline-flex items-center gap-2 rounded-full border border-white/10 bg-white/[0.04] px-3 py-2 text-[11px] text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Size"), /* @__PURE__ */ React.createElement("span", { className: "font-semibold text-white" }, formatBytes$1(fileMeta.size))), downloadUrl ? /* @__PURE__ */ React.createElement( "a", { href: downloadUrl, @@ -91544,7 +93532,7 @@ function StudioArtworkEdit() { }, /* @__PURE__ */ React.createElement("svg", { width: "12", height: "12", viewBox: "0 0 16 16", fill: "currentColor", "aria-hidden": "true" }, /* @__PURE__ */ React.createElement("path", { fillRule: "evenodd", d: "M8 3.5a4.5 4.5 0 00-4.04 2.51.75.75 0 01-1.34-.67A6 6 0 1114 8a.75.75 0 01-1.5 0A4.5 4.5 0 008 3.5z", clipRule: "evenodd" }), /* @__PURE__ */ React.createElement("path", { fillRule: "evenodd", d: "M4.75.75a.75.75 0 00-.75.75v3.5c0 .414.336.75.75.75h3.5a.75.75 0 000-1.5H5.5V1.5a.75.75 0 00-.75-.75z", clipRule: "evenodd" })), "History" - )), /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-4 rounded-2xl border border-white/10 bg-white/[0.03] px-4 py-3" }, /* @__PURE__ */ React.createElement("div", { className: "h-12 w-12 shrink-0 overflow-hidden rounded-xl border border-white/10 bg-black/25" }, thumbUrl && /* @__PURE__ */ React.createElement("img", { src: thumbUrl, alt: "", className: "h-full w-full object-cover" })), /* @__PURE__ */ React.createElement("div", { className: "min-w-0 flex-1" }, /* @__PURE__ */ React.createElement("p", { className: "truncate text-sm font-semibold text-white", title: fileMeta.name }, fileMeta.name || "Artwork file"), /* @__PURE__ */ React.createElement("div", { className: "mt-1 flex flex-wrap gap-1.5" }, currentFileExt && /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.05] px-2 py-0.5 text-[10px] uppercase tracking-[0.12em] text-white/55" }, currentFileExt), fileMeta.width > 0 && /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.05] px-2 py-0.5 text-[10px] text-white/55" }, fileMeta.width, " × ", fileMeta.height), fileMeta.size > 0 && /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.05] px-2 py-0.5 text-[10px] text-white/55" }, formatBytes$2(fileMeta.size)), screenshotItems.length > 0 && /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.05] px-2 py-0.5 text-[10px] text-white/55" }, screenshotItems.length, " screenshot", screenshotItems.length !== 1 ? "s" : ""))), /* @__PURE__ */ React.createElement("span", { className: "shrink-0 rounded-full border border-white/10 bg-white/[0.04] px-2.5 py-1 text-[11px] font-semibold text-slate-400" }, "v", versionCount)), requiresReapproval && /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-amber-300/20 bg-amber-400/10 px-4 py-3 text-sm text-amber-100" }, "Visual changes on this artwork require a new moderation pass."), quickReplaceSupported && (() => { + )), /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-4 rounded-2xl border border-white/10 bg-white/[0.03] px-4 py-3" }, /* @__PURE__ */ React.createElement("div", { className: "h-12 w-12 shrink-0 overflow-hidden rounded-xl border border-white/10 bg-black/25" }, thumbUrl && /* @__PURE__ */ React.createElement("img", { src: thumbUrl, alt: "", className: "h-full w-full object-cover" })), /* @__PURE__ */ React.createElement("div", { className: "min-w-0 flex-1" }, /* @__PURE__ */ React.createElement("p", { className: "truncate text-sm font-semibold text-white", title: fileMeta.name }, fileMeta.name || "Artwork file"), /* @__PURE__ */ React.createElement("div", { className: "mt-1 flex flex-wrap gap-1.5" }, currentFileExt && /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.05] px-2 py-0.5 text-[10px] uppercase tracking-[0.12em] text-white/55" }, currentFileExt), fileMeta.width > 0 && /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.05] px-2 py-0.5 text-[10px] text-white/55" }, fileMeta.width, " × ", fileMeta.height), fileMeta.size > 0 && /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.05] px-2 py-0.5 text-[10px] text-white/55" }, formatBytes$1(fileMeta.size)), screenshotItems.length > 0 && /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.05] px-2 py-0.5 text-[10px] text-white/55" }, screenshotItems.length, " screenshot", screenshotItems.length !== 1 ? "s" : ""))), /* @__PURE__ */ React.createElement("span", { className: "shrink-0 rounded-full border border-white/10 bg-white/[0.04] px-2.5 py-1 text-[11px] font-semibold text-slate-400" }, "v", versionCount)), requiresReapproval && /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-amber-300/20 bg-amber-400/10 px-4 py-3 text-sm text-amber-100" }, "Visual changes on this artwork require a new moderation pass."), quickReplaceSupported && (() => { const zone = "single-replace"; const isDragging = dragOverZone === zone; const stageFile = (file) => { @@ -91575,7 +93563,7 @@ function StudioArtworkEdit() { stageFile(e.dataTransfer.files?.[0]); } }, - pendingReplacePreview ? /* @__PURE__ */ React.createElement("div", { className: "flex items-start gap-4 p-4" }, /* @__PURE__ */ React.createElement("div", { className: "h-24 w-24 shrink-0 overflow-hidden rounded-xl border border-white/10 bg-black/25" }, /* @__PURE__ */ React.createElement("img", { src: pendingReplacePreview, alt: "Preview", className: "h-full w-full object-cover" })), /* @__PURE__ */ React.createElement("div", { className: "flex-1 min-w-0 py-1" }, /* @__PURE__ */ React.createElement("p", { className: "text-xs font-semibold uppercase tracking-[0.14em] text-emerald-400" }, "Ready to upload"), /* @__PURE__ */ React.createElement("p", { className: "mt-1 truncate text-sm font-medium text-white" }, pendingReplaceFile?.name), /* @__PURE__ */ React.createElement("p", { className: "mt-0.5 text-xs text-slate-400" }, formatBytes$2(pendingReplaceFile?.size)), /* @__PURE__ */ React.createElement( + pendingReplacePreview ? /* @__PURE__ */ React.createElement("div", { className: "flex items-start gap-4 p-4" }, /* @__PURE__ */ React.createElement("div", { className: "h-24 w-24 shrink-0 overflow-hidden rounded-xl border border-white/10 bg-black/25" }, /* @__PURE__ */ React.createElement("img", { src: pendingReplacePreview, alt: "Preview", className: "h-full w-full object-cover" })), /* @__PURE__ */ React.createElement("div", { className: "flex-1 min-w-0 py-1" }, /* @__PURE__ */ React.createElement("p", { className: "text-xs font-semibold uppercase tracking-[0.14em] text-emerald-400" }, "Ready to upload"), /* @__PURE__ */ React.createElement("p", { className: "mt-1 truncate text-sm font-medium text-white" }, pendingReplaceFile?.name), /* @__PURE__ */ React.createElement("p", { className: "mt-0.5 text-xs text-slate-400" }, formatBytes$1(pendingReplaceFile?.size)), /* @__PURE__ */ React.createElement( "button", { type: "button", @@ -91647,7 +93635,7 @@ function StudioArtworkEdit() { stageFile(e.dataTransfer.files?.[0]); } }, - /* @__PURE__ */ React.createElement("div", { className: "flex items-start gap-4 p-4" }, /* @__PURE__ */ React.createElement("div", { className: "h-20 w-20 shrink-0 overflow-hidden rounded-xl border border-white/10 bg-black/25" }, archiveCoverPreview ? /* @__PURE__ */ React.createElement("img", { src: archiveCoverPreview, alt: "New cover", className: "h-full w-full object-cover" }) : thumbUrl ? /* @__PURE__ */ React.createElement("img", { src: thumbUrl, alt: "Current cover", className: "h-full w-full object-cover opacity-60" }) : null), /* @__PURE__ */ React.createElement("div", { className: "flex-1 min-w-0 py-1" }, archiveCoverFile ? /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement("p", { className: "text-xs font-semibold uppercase tracking-[0.14em] text-emerald-400" }, "New cover staged"), /* @__PURE__ */ React.createElement("p", { className: "mt-1 truncate text-sm font-medium text-white" }, archiveCoverFile.name), /* @__PURE__ */ React.createElement("p", { className: "mt-0.5 text-xs text-slate-400" }, formatBytes$2(archiveCoverFile.size)), /* @__PURE__ */ React.createElement( + /* @__PURE__ */ React.createElement("div", { className: "flex items-start gap-4 p-4" }, /* @__PURE__ */ React.createElement("div", { className: "h-20 w-20 shrink-0 overflow-hidden rounded-xl border border-white/10 bg-black/25" }, archiveCoverPreview ? /* @__PURE__ */ React.createElement("img", { src: archiveCoverPreview, alt: "New cover", className: "h-full w-full object-cover" }) : thumbUrl ? /* @__PURE__ */ React.createElement("img", { src: thumbUrl, alt: "Current cover", className: "h-full w-full object-cover opacity-60" }) : null), /* @__PURE__ */ React.createElement("div", { className: "flex-1 min-w-0 py-1" }, archiveCoverFile ? /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement("p", { className: "text-xs font-semibold uppercase tracking-[0.14em] text-emerald-400" }, "New cover staged"), /* @__PURE__ */ React.createElement("p", { className: "mt-1 truncate text-sm font-medium text-white" }, archiveCoverFile.name), /* @__PURE__ */ React.createElement("p", { className: "mt-0.5 text-xs text-slate-400" }, formatBytes$1(archiveCoverFile.size)), /* @__PURE__ */ React.createElement( "button", { type: "button", @@ -91690,7 +93678,7 @@ function StudioArtworkEdit() { stageFile(e.dataTransfer.files?.[0]); } }, - /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-4 px-4 py-4" }, /* @__PURE__ */ React.createElement("span", { className: "inline-flex h-11 w-11 shrink-0 items-center justify-center rounded-xl border border-white/10 bg-white/[0.04] text-slate-400" }, /* @__PURE__ */ React.createElement("svg", { width: "18", height: "18", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "1.5", "aria-hidden": "true" }, /* @__PURE__ */ React.createElement("path", { strokeLinecap: "round", strokeLinejoin: "round", d: "M20.25 7.5l-.625 10.632a2.25 2.25 0 01-2.247 2.118H6.622a2.25 2.25 0 01-2.247-2.118L3.75 7.5M10 11.25h4M3.375 7.5h17.25c.621 0 1.125-.504 1.125-1.125v-1.5c0-.621-.504-1.125-1.125-1.125H3.375c-.621 0-1.125.504-1.125 1.125v1.5c0 .621.504 1.125 1.125 1.125z" }))), /* @__PURE__ */ React.createElement("div", { className: "flex-1 min-w-0" }, archivePackageFile ? /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement("p", { className: "text-xs font-semibold uppercase tracking-[0.14em] text-emerald-400" }, "New package staged"), /* @__PURE__ */ React.createElement("p", { className: "mt-0.5 truncate text-sm font-medium text-white" }, archivePackageFile.name), /* @__PURE__ */ React.createElement("p", { className: "mt-0.5 text-xs text-slate-400" }, formatBytes$2(archivePackageFile.size))) : /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement("p", { className: "text-xs font-semibold text-slate-500" }, "Current package"), /* @__PURE__ */ React.createElement("p", { className: "mt-0.5 truncate text-sm text-slate-300" }, fileMeta.name || "—"))), /* @__PURE__ */ React.createElement("div", { className: "flex shrink-0 flex-col gap-2" }, archivePackageFile ? /* @__PURE__ */ React.createElement( + /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-4 px-4 py-4" }, /* @__PURE__ */ React.createElement("span", { className: "inline-flex h-11 w-11 shrink-0 items-center justify-center rounded-xl border border-white/10 bg-white/[0.04] text-slate-400" }, /* @__PURE__ */ React.createElement("svg", { width: "18", height: "18", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: "1.5", "aria-hidden": "true" }, /* @__PURE__ */ React.createElement("path", { strokeLinecap: "round", strokeLinejoin: "round", d: "M20.25 7.5l-.625 10.632a2.25 2.25 0 01-2.247 2.118H6.622a2.25 2.25 0 01-2.247-2.118L3.75 7.5M10 11.25h4M3.375 7.5h17.25c.621 0 1.125-.504 1.125-1.125v-1.5c0-.621-.504-1.125-1.125-1.125H3.375c-.621 0-1.125.504-1.125 1.125v1.5c0 .621.504 1.125 1.125 1.125z" }))), /* @__PURE__ */ React.createElement("div", { className: "flex-1 min-w-0" }, archivePackageFile ? /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement("p", { className: "text-xs font-semibold uppercase tracking-[0.14em] text-emerald-400" }, "New package staged"), /* @__PURE__ */ React.createElement("p", { className: "mt-0.5 truncate text-sm font-medium text-white" }, archivePackageFile.name), /* @__PURE__ */ React.createElement("p", { className: "mt-0.5 text-xs text-slate-400" }, formatBytes$1(archivePackageFile.size))) : /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement("p", { className: "text-xs font-semibold text-slate-500" }, "Current package"), /* @__PURE__ */ React.createElement("p", { className: "mt-0.5 truncate text-sm text-slate-300" }, fileMeta.name || "—"))), /* @__PURE__ */ React.createElement("div", { className: "flex shrink-0 flex-col gap-2" }, archivePackageFile ? /* @__PURE__ */ React.createElement( "button", { type: "button", @@ -92020,7 +94008,7 @@ function StudioArtworkEdit() { v.is_current ? "border-accent/40 bg-accent/10" : "border-white/10 bg-white/[0.03] hover:bg-white/[0.06]" ].join(" ") }, - /* @__PURE__ */ React.createElement("div", { className: "flex items-start justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", { className: "flex-1 min-w-0" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-2 mb-1" }, /* @__PURE__ */ React.createElement("span", { className: "text-xs font-bold text-white" }, "v", v.version_number), v.is_current && /* @__PURE__ */ React.createElement("span", { className: "text-[10px] font-semibold px-1.5 py-0.5 rounded-full bg-accent/20 text-accent border border-accent/30" }, "Current")), /* @__PURE__ */ React.createElement("p", { className: "text-[11px] text-slate-400" }, v.created_at ? new Date(v.created_at).toLocaleString() : ""), v.width && /* @__PURE__ */ React.createElement("p", { className: "text-[11px] text-slate-400" }, v.width, " × ", v.height, " px · ", formatBytes$2(v.file_size)), v.change_note && /* @__PURE__ */ React.createElement("p", { className: "text-xs text-slate-300 mt-1 italic" }, "“", v.change_note, "”")), !v.is_current && /* @__PURE__ */ React.createElement( + /* @__PURE__ */ React.createElement("div", { className: "flex items-start justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", { className: "flex-1 min-w-0" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-2 mb-1" }, /* @__PURE__ */ React.createElement("span", { className: "text-xs font-bold text-white" }, "v", v.version_number), v.is_current && /* @__PURE__ */ React.createElement("span", { className: "text-[10px] font-semibold px-1.5 py-0.5 rounded-full bg-accent/20 text-accent border border-accent/30" }, "Current")), /* @__PURE__ */ React.createElement("p", { className: "text-[11px] text-slate-400" }, v.created_at ? new Date(v.created_at).toLocaleString() : ""), v.width && /* @__PURE__ */ React.createElement("p", { className: "text-[11px] text-slate-400" }, v.width, " × ", v.height, " px · ", formatBytes$1(v.file_size)), v.change_note && /* @__PURE__ */ React.createElement("p", { className: "text-xs text-slate-300 mt-1 italic" }, "“", v.change_note, "”")), !v.is_current && /* @__PURE__ */ React.createElement( Button$1, { variant: "ghost", @@ -92033,7 +94021,7 @@ function StudioArtworkEdit() { )), historyData.versions.length === 0 && /* @__PURE__ */ React.createElement("p", { className: "text-sm text-slate-500 text-center py-8" }, "No version history yet.")) )); } -const __vite_glob_0_104 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ +const __vite_glob_0_86 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ __proto__: null, default: StudioArtworkEdit }, Symbol.toStringTag, { value: "Module" })); @@ -92045,7 +94033,7 @@ function StudioArtworks() { const summary = props.summary || {}; return /* @__PURE__ */ React.createElement(StudioLayout, { title: props.title, subtitle: props.description }, /* @__PURE__ */ React.createElement("div", { className: "mb-6 grid gap-4 md:grid-cols-4" }, /* @__PURE__ */ React.createElement(SummaryCard$3, { label: "Artworks", value: summary.count, icon: "fa-solid fa-images" }), /* @__PURE__ */ React.createElement(SummaryCard$3, { label: "Drafts", value: summary.draft_count, icon: "fa-solid fa-file-pen" }), /* @__PURE__ */ React.createElement(SummaryCard$3, { label: "Published", value: summary.published_count, icon: "fa-solid fa-rocket" }), /* @__PURE__ */ React.createElement("a", { href: "/upload", className: "rounded-[24px] border border-sky-300/20 bg-sky-300/10 p-5 text-sky-100 transition hover:border-sky-300/35 hover:bg-sky-300/15" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.2em]" }, "Upload artwork"), /* @__PURE__ */ React.createElement("p", { className: "mt-3 text-sm leading-6" }, "Start a new visual upload flow without leaving Creator Studio."))), /* @__PURE__ */ React.createElement(StudioContentBrowser, { listing: props.listing, quickCreate: props.quickCreate, hideModuleFilter: true })); } -const __vite_glob_0_105 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ +const __vite_glob_0_87 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ __proto__: null, default: StudioArtworks }, Symbol.toStringTag, { value: "Module" })); @@ -92171,7 +94159,7 @@ function StudioAssets() { /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-arrow-right" }) )))); } -const __vite_glob_0_106 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ +const __vite_glob_0_88 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ __proto__: null, default: StudioAssets }, Symbol.toStringTag, { value: "Module" })); @@ -92343,7 +94331,7 @@ function StudioCalendar() { }, [selectedDay]); return /* @__PURE__ */ React.createElement(StudioLayout, { title: props.title, subtitle: props.description }, /* @__PURE__ */ React.createElement("div", { className: "space-y-6" }, /* @__PURE__ */ React.createElement("section", { className: "grid gap-4 md:grid-cols-2 xl:grid-cols-4" }, /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-white/[0.03] p-5" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, "Scheduled"), /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-3xl font-semibold text-white" }, Number(summary.scheduled_total || 0).toLocaleString())), /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-white/[0.03] p-5" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, "Unscheduled"), /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-3xl font-semibold text-white" }, Number(summary.unscheduled_total || 0).toLocaleString())), /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-white/[0.03] p-5" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, "Overloaded days"), /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-3xl font-semibold text-white" }, Number(summary.overloaded_days || 0).toLocaleString())), /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-white/[0.03] p-5" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, "Next publish"), /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-base font-semibold text-white" }, formatReleaseCountdown(summary.next_publish_at, nowMs)), summary.next_publish_at && /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-sm text-slate-400" }, formatScheduledDate(summary.next_publish_at)))), /* @__PURE__ */ React.createElement("section", { className: "rounded-[30px] border border-white/10 bg-[radial-gradient(circle_at_top_left,_rgba(56,189,248,0.14),_transparent_35%),linear-gradient(135deg,_rgba(15,23,42,0.86),_rgba(2,6,23,0.96))] p-5 lg:p-6" }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-3 md:grid-cols-2 xl:grid-cols-5" }, /* @__PURE__ */ React.createElement("label", { className: "space-y-2 text-sm text-slate-300 xl:col-span-2" }, /* @__PURE__ */ React.createElement("span", { className: "block text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, "Search planning queue"), /* @__PURE__ */ React.createElement("input", { value: filters.q || "", onChange: (event) => updateFilters({ q: event.target.value }), className: "w-full rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white", placeholder: "Title or module" })), /* @__PURE__ */ React.createElement("div", { className: "space-y-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "block text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, "View"), /* @__PURE__ */ React.createElement(NovaSelect, { value: filters.view || "month", onChange: (val) => updateFilters({ view: val }), options: calendar.view_options || [], searchable: false })), /* @__PURE__ */ React.createElement("div", { className: "space-y-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "block text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, "Module"), /* @__PURE__ */ React.createElement(NovaSelect, { value: filters.module || "all", onChange: (val) => updateFilters({ module: val }), options: calendar.module_options || [], searchable: false })), /* @__PURE__ */ React.createElement("div", { className: "space-y-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "block text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, "Queue"), /* @__PURE__ */ React.createElement(NovaSelect, { value: filters.status || "scheduled", onChange: (val) => updateFilters({ status: val }), options: calendar.status_options || [], searchable: false })))), /* @__PURE__ */ React.createElement("div", { className: "grid gap-6 xl:grid-cols-[minmax(0,1fr)_340px]" }, /* @__PURE__ */ React.createElement("section", { className: "rounded-[30px] border border-white/10 bg-white/[0.03] p-5" }, filters.view === "week" ? /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("h2", { className: "text-lg font-semibold text-white" }, calendar.week?.label), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-xs uppercase tracking-[0.18em] text-slate-500" }, "Week planning")), /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-2" }, /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => shiftCalendar(-1), className: "rounded-full border border-white/10 px-3 py-1.5 text-sm text-slate-200 transition hover:border-sky-300/20 hover:bg-sky-300/10 hover:text-sky-100" }, "Prev week"), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: resetCalendarFocus, className: "rounded-full border border-white/10 px-3 py-1.5 text-sm text-slate-200 transition hover:border-sky-300/20 hover:bg-sky-300/10 hover:text-sky-100" }, "Today"), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => shiftCalendar(1), className: "rounded-full border border-white/10 px-3 py-1.5 text-sm text-slate-200 transition hover:border-sky-300/20 hover:bg-sky-300/10 hover:text-sky-100" }, "Next week"))), /* @__PURE__ */ React.createElement("div", { className: "mt-4 grid gap-3 md:grid-cols-2 xl:grid-cols-7" }, (calendar.week?.days || []).map((day) => /* @__PURE__ */ React.createElement("div", { key: day.date, className: "rounded-[22px] border border-white/10 bg-black/20 p-3" }, /* @__PURE__ */ React.createElement("div", { className: "text-sm font-semibold text-white" }, day.label), /* @__PURE__ */ React.createElement("div", { className: "mt-3 space-y-2" }, day.items.length > 0 ? day.items.map((item) => /* @__PURE__ */ React.createElement(CalendarInlineItem, { key: item.id, item })) : /* @__PURE__ */ React.createElement("div", { className: "text-xs text-slate-500" }, "No scheduled items")))))) : filters.view === "agenda" ? /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement("h2", { className: "text-lg font-semibold text-white" }, "Agenda"), /* @__PURE__ */ React.createElement("div", { className: "mt-4 space-y-4" }, (calendar.agenda || []).map((group) => /* @__PURE__ */ React.createElement("div", { key: group.date, className: "rounded-[22px] border border-white/10 bg-black/20 p-4" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", { className: "text-base font-semibold text-white" }, group.label), /* @__PURE__ */ React.createElement("div", { className: "text-xs uppercase tracking-[0.18em] text-slate-500" }, group.count, " items")), /* @__PURE__ */ React.createElement("div", { className: "mt-3 space-y-2" }, group.items.map((item) => /* @__PURE__ */ React.createElement(CalendarInlineItem, { key: item.id, item }))))))) : /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("h2", { className: "text-lg font-semibold text-white" }, calendar.month?.label), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-xs uppercase tracking-[0.18em] text-slate-500" }, "Month planning")), /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-2" }, /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => shiftCalendar(-1), className: "rounded-full border border-white/10 px-3 py-1.5 text-sm text-slate-200 transition hover:border-sky-300/20 hover:bg-sky-300/10 hover:text-sky-100" }, "Prev month"), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: resetCalendarFocus, className: "rounded-full border border-white/10 px-3 py-1.5 text-sm text-slate-200 transition hover:border-sky-300/20 hover:bg-sky-300/10 hover:text-sky-100" }, "Today"), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => shiftCalendar(1), className: "rounded-full border border-white/10 px-3 py-1.5 text-sm text-slate-200 transition hover:border-sky-300/20 hover:bg-sky-300/10 hover:text-sky-100" }, "Next month"))), /* @__PURE__ */ React.createElement("div", { className: "mt-4 grid grid-cols-7 gap-2 text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"].map((label) => /* @__PURE__ */ React.createElement("div", { key: label, className: "px-2 py-1" }, label))), /* @__PURE__ */ React.createElement("div", { className: "mt-2 grid grid-cols-7 gap-2" }, (calendar.month?.days || []).map((day) => /* @__PURE__ */ React.createElement(CalendarMonthDay, { key: day.date, day, onOpenDetail: setSelectedDay }))))), /* @__PURE__ */ React.createElement("aside", { className: "space-y-6" }, /* @__PURE__ */ React.createElement("section", { className: "rounded-[30px] border border-white/10 bg-white/[0.03] p-5" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between" }, /* @__PURE__ */ React.createElement("h2", { className: "text-lg font-semibold text-white" }, "Coverage gaps"), /* @__PURE__ */ React.createElement("a", { href: "/studio/drafts", className: "text-sm font-medium text-sky-100" }, "Open drafts")), /* @__PURE__ */ React.createElement("div", { className: "mt-4 space-y-3" }, (calendar.gaps || []).length > 0 ? (calendar.gaps || []).map((gap) => /* @__PURE__ */ React.createElement("div", { key: gap.date, className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-sm text-slate-200" }, gap.label)) : /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-dashed border-white/15 px-4 py-8 text-sm text-slate-500" }, "No empty days in the next two weeks."))), /* @__PURE__ */ React.createElement("section", { className: "rounded-[30px] border border-white/10 bg-white/[0.03] p-5" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between" }, /* @__PURE__ */ React.createElement("h2", { className: "text-lg font-semibold text-white" }, "Unscheduled queue"), /* @__PURE__ */ React.createElement("span", { className: "text-xs uppercase tracking-[0.18em] text-slate-500" }, (calendar.unscheduled_items || []).length)), /* @__PURE__ */ React.createElement("div", { className: "mt-4 space-y-3" }, (calendar.unscheduled_items || []).map((item) => /* @__PURE__ */ React.createElement("a", { key: item.id, href: item.edit_url || item.manage_url, className: "block rounded-2xl border border-white/10 bg-black/20 p-4" }, /* @__PURE__ */ React.createElement("div", { className: "text-sm font-semibold text-white" }, item.title), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-xs text-slate-500" }, item.module_label, " · ", item.workflow?.readiness?.label || "Needs review"))))), /* @__PURE__ */ React.createElement("section", { className: "rounded-[30px] border border-white/10 bg-white/[0.03] p-5" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between" }, /* @__PURE__ */ React.createElement("h2", { className: "text-lg font-semibold text-white" }, "Upcoming actions"), /* @__PURE__ */ React.createElement("a", { href: "/studio/scheduled", className: "text-sm font-medium text-sky-100" }, "Open list")), /* @__PURE__ */ React.createElement("div", { className: "mt-4 space-y-3" }, (calendar.scheduled_items || []).slice(0, 5).map((item) => /* @__PURE__ */ React.createElement("div", { key: item.id, className: "rounded-2xl border border-white/10 bg-black/20 p-4" }, /* @__PURE__ */ React.createElement("div", { className: "text-sm font-semibold text-white" }, item.title), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-xs font-medium text-sky-200" }, formatReleaseCountdown(item.scheduled_at, nowMs)), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-xs text-slate-500" }, formatScheduledDate(item.scheduled_at)), /* @__PURE__ */ React.createElement("div", { className: "mt-3 flex flex-wrap gap-2" }, /* @__PURE__ */ React.createElement("button", { type: "button", disabled: busyKey === `publish:${item.id}`, onClick: () => runAction(props.endpoints.publishNowPattern, item, "publish"), className: "rounded-full border border-sky-300/20 bg-sky-300/10 px-3 py-1.5 text-xs text-sky-100 disabled:opacity-50" }, "Publish now"), /* @__PURE__ */ React.createElement("button", { type: "button", disabled: busyKey === `unschedule:${item.id}`, onClick: () => runAction(props.endpoints.unschedulePattern, item, "unschedule"), className: "rounded-full border border-white/10 px-3 py-1.5 text-xs text-slate-200 disabled:opacity-50" }, "Unschedule")))))))), /* @__PURE__ */ React.createElement(CalendarDayModal, { day: selectedDay, busyKey, endpoints: props.endpoints, onAction: runAction, onClose: () => setSelectedDay(null), nowMs }))); } -const __vite_glob_0_107 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ +const __vite_glob_0_89 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ __proto__: null, default: StudioCalendar }, Symbol.toStringTag, { value: "Module" })); @@ -92365,7 +94353,7 @@ function StudioCardAnalytics() { const { card, analytics } = props; return /* @__PURE__ */ React.createElement(StudioLayout, { title: `Analytics: ${card?.title || "Nova Card"}` }, /* @__PURE__ */ React.createElement(xe, { href: "/studio/cards", className: "mb-6 inline-flex items-center gap-2 text-sm text-slate-400 transition-colors hover:text-white" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-arrow-left" }), "Back to Cards"), /* @__PURE__ */ React.createElement("div", { className: "mb-8 flex items-center gap-4 rounded-2xl border border-white/10 bg-nova-900/60 p-4" }, card?.preview_url ? /* @__PURE__ */ React.createElement("img", { src: card.preview_url, alt: card.title, className: "h-20 w-20 rounded-xl object-cover bg-nova-800" }) : null, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("h2", { className: "text-lg font-bold text-white" }, card?.title), /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-xs text-slate-500" }, "/", card?.slug), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-xs uppercase tracking-[0.18em] text-slate-400" }, card?.status, " • ", card?.visibility))), /* @__PURE__ */ React.createElement("div", { className: "mb-8 grid grid-cols-2 gap-4 sm:grid-cols-3 xl:grid-cols-6" }, kpiItems.map((item) => /* @__PURE__ */ React.createElement("div", { key: item.key, className: "rounded-2xl border border-white/10 bg-nova-900/60 p-5" }, /* @__PURE__ */ React.createElement("div", { className: "mb-2 flex items-center gap-2" }, /* @__PURE__ */ React.createElement("i", { className: `fa-solid ${item.icon} ${item.color}` }), /* @__PURE__ */ React.createElement("span", { className: "text-xs font-medium uppercase tracking-wider text-slate-400" }, item.label)), /* @__PURE__ */ React.createElement("p", { className: "text-2xl font-bold tabular-nums text-white" }, (analytics?.[item.key] ?? 0).toLocaleString())))), /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 lg:grid-cols-[minmax(0,1.1fr)_minmax(0,0.9fr)]" }, /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-nova-900/40 p-6" }, /* @__PURE__ */ React.createElement("h3", { className: "mb-4 text-sm font-semibold uppercase tracking-[0.18em] text-slate-300" }, "Ranking signals"), /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 sm:grid-cols-2" }, /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-white/[0.03] p-4" }, /* @__PURE__ */ React.createElement("div", { className: "text-xs uppercase tracking-[0.18em] text-slate-400" }, "Trending score"), /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-3xl font-bold tabular-nums text-white" }, Number(analytics?.trending_score ?? 0).toFixed(2))), /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-white/[0.03] p-4" }, /* @__PURE__ */ React.createElement("div", { className: "text-xs uppercase tracking-[0.18em] text-slate-400" }, "Last engaged"), /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-sm text-white" }, analytics?.last_engaged_at || "No activity yet")))), /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-nova-900/40 p-6" }, /* @__PURE__ */ React.createElement("h3", { className: "mb-4 text-sm font-semibold uppercase tracking-[0.18em] text-slate-300" }, "Secondary metrics"), /* @__PURE__ */ React.createElement("div", { className: "space-y-3" }, secondaryItems.map((item) => /* @__PURE__ */ React.createElement("div", { key: item.key, className: "flex items-center justify-between rounded-2xl border border-white/10 bg-white/[0.03] px-4 py-3" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("i", { className: `fa-solid ${item.icon} text-slate-500` }), item.label), /* @__PURE__ */ React.createElement("div", { className: "text-base font-semibold tabular-nums text-white" }, (analytics?.[item.key] ?? 0).toLocaleString()))))))); } -const __vite_glob_0_108 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ +const __vite_glob_0_90 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ __proto__: null, default: StudioCardAnalytics }, Symbol.toStringTag, { value: "Module" })); @@ -93509,7 +95497,7 @@ function StudioCardEditor() { fmt2.label ))), exportStatus && /* @__PURE__ */ React.createElement("div", { className: "mt-3 flex items-center gap-3 rounded-[18px] border border-white/10 bg-white/[0.03] p-3" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "text-xs font-semibold uppercase tracking-[0.18em] text-slate-400" }, "Export status"), /* @__PURE__ */ React.createElement("div", { className: "text-sm font-semibold capitalize text-white" }, exportStatus.status)), exportStatus.status === "ready" && exportStatus.output_url && /* @__PURE__ */ React.createElement("a", { href: exportStatus.output_url, download: true, className: "ml-auto rounded-full border border-emerald-300/20 bg-emerald-400/10 px-3 py-1.5 text-xs font-semibold text-emerald-200 transition hover:bg-emerald-400/15" }, "Download"))))), /* @__PURE__ */ React.createElement("nav", { className: "sticky bottom-0 z-20 mt-6 border-t border-white/10 bg-[rgba(2,6,23,0.92)] px-4 py-3 backdrop-blur xl:hidden" }, /* @__PURE__ */ React.createElement("div", { className: "mx-auto flex max-w-7xl items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => goToNextTab(-1), disabled: tabIndex === 0, className: "rounded-2xl border border-white/10 bg-white/[0.05] px-4 py-2.5 text-sm font-semibold text-white transition hover:bg-white/[0.08] disabled:opacity-50" }, "Back"), /* @__PURE__ */ React.createElement("div", { className: "text-center" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, "Step ", tabIndex + 1, " / ", editorTabs.length), /* @__PURE__ */ React.createElement("div", { className: "mt-0.5 text-sm font-semibold text-white" }, editorTabs[tabIndex]?.label)), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => goToNextTab(1), disabled: tabIndex >= editorTabs.length - 1, className: "rounded-2xl border border-sky-300/20 bg-sky-400/10 px-4 py-2.5 text-sm font-semibold text-sky-100 transition hover:bg-sky-400/15 disabled:opacity-50" }, "Next")))); } -const __vite_glob_0_109 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ +const __vite_glob_0_91 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ __proto__: null, default: StudioCardEditor }, Symbol.toStringTag, { value: "Module" })); @@ -93521,7 +95509,7 @@ function StudioCardsIndex() { const summary = props.summary || {}; return /* @__PURE__ */ React.createElement(StudioLayout, { title: props.title, subtitle: props.description }, /* @__PURE__ */ React.createElement("section", { className: "rounded-[32px] border border-white/10 bg-[radial-gradient(circle_at_top_left,rgba(56,189,248,0.15),transparent_38%),linear-gradient(180deg,rgba(15,23,42,0.96),rgba(2,6,23,0.88))] p-6 shadow-[0_24px_70px_rgba(2,6,23,0.32)]" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-col gap-5 lg:flex-row lg:items-end lg:justify-between" }, /* @__PURE__ */ React.createElement("div", { className: "max-w-3xl" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.28em] text-sky-200/75" }, "Creation surface"), /* @__PURE__ */ React.createElement("h2", { className: "mt-3 text-3xl font-semibold tracking-[-0.04em] text-white" }, "Build quote cards, mood cards, and visual text art."), /* @__PURE__ */ React.createElement("p", { className: "mt-3 text-sm leading-7 text-slate-300" }, "Cards now live inside the same shared Creator Studio queue as artworks, collections, and stories, while keeping the dedicated editor and analytics flow.")), /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-3" }, /* @__PURE__ */ React.createElement("a", { href: "/studio/cards/create", className: "inline-flex items-center gap-2 rounded-2xl border border-sky-300/20 bg-sky-400/10 px-5 py-3 text-sm font-semibold text-sky-100 transition hover:bg-sky-400/15" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-plus" }), "New card"), /* @__PURE__ */ React.createElement("a", { href: props.publicBrowseUrl, className: "inline-flex items-center gap-2 rounded-2xl border border-white/10 bg-white/[0.05] px-5 py-3 text-sm font-semibold text-white transition hover:bg-white/[0.08]" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-compass" }), "Browse public cards")))), /* @__PURE__ */ React.createElement("section", { className: "mt-6 grid gap-4 md:grid-cols-2 xl:grid-cols-4" }, /* @__PURE__ */ React.createElement(StatCard$1, { label: "All cards", value: summary.count || 0, icon: "fa-layer-group" }), /* @__PURE__ */ React.createElement(StatCard$1, { label: "Drafts", value: summary.draft_count || 0, icon: "fa-file-lines" }), /* @__PURE__ */ React.createElement(StatCard$1, { label: "Archived", value: summary.archived_count || 0, icon: "fa-box-archive" }), /* @__PURE__ */ React.createElement(StatCard$1, { label: "Published", value: summary.published_count || 0, icon: "fa-earth-americas" })), /* @__PURE__ */ React.createElement("section", { className: "mt-8" }, /* @__PURE__ */ React.createElement(StudioContentBrowser, { listing: props.listing, quickCreate: props.quickCreate, hideModuleFilter: true, emptyTitle: "No cards yet", emptyBody: "Create your first Nova card and it will appear here alongside your other Creator Studio content." }))); } -const __vite_glob_0_110 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ +const __vite_glob_0_92 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ __proto__: null, default: StudioCardsIndex }, Symbol.toStringTag, { value: "Module" })); @@ -93594,7 +95582,7 @@ function StudioChallenges() { "Challenge" ), /* @__PURE__ */ React.createElement("a", { href: entry.card.edit_url, className: "text-slate-300" }, "Edit card"), /* @__PURE__ */ React.createElement("a", { href: entry.card.analytics_url, className: "text-slate-300" }, "Analytics")))))), /* @__PURE__ */ React.createElement("section", { className: "rounded-[28px] border border-white/10 bg-white/[0.03] p-6" }, /* @__PURE__ */ React.createElement("h2", { className: "text-lg font-semibold text-white" }, "Cards with challenge traction"), /* @__PURE__ */ React.createElement("div", { className: "mt-4 space-y-3" }, (cardLeaders || []).map((card) => /* @__PURE__ */ React.createElement("div", { key: card.id, className: "rounded-[22px] border border-white/10 bg-black/20 p-4" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-start justify-between gap-4" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "text-sm font-semibold text-white" }, card.title), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-xs uppercase tracking-[0.16em] text-slate-500" }, card.status, " • ", card.challenge_entries_count, " challenge entries")), /* @__PURE__ */ React.createElement("a", { href: card.edit_url, className: "text-xs font-semibold uppercase tracking-[0.16em] text-sky-100" }, "Open")), /* @__PURE__ */ React.createElement("div", { className: "mt-4 grid grid-cols-2 gap-3 text-sm text-slate-400" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", null, "Views"), /* @__PURE__ */ React.createElement("div", { className: "mt-1 font-semibold text-white" }, Number(card.views_count || 0).toLocaleString())), /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", null, "Comments"), /* @__PURE__ */ React.createElement("div", { className: "mt-1 font-semibold text-white" }, Number(card.comments_count || 0).toLocaleString()))))))))); } -const __vite_glob_0_111 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ +const __vite_glob_0_93 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ __proto__: null, default: StudioChallenges }, Symbol.toStringTag, { value: "Module" })); @@ -93606,7 +95594,7 @@ function StudioCollections() { const summary = props.summary || {}; return /* @__PURE__ */ React.createElement(StudioLayout, { title: props.title, subtitle: props.description }, /* @__PURE__ */ React.createElement("div", { className: "mb-6 grid gap-4 md:grid-cols-4" }, /* @__PURE__ */ React.createElement(SummaryCard$2, { label: "Collections", value: summary.count, icon: "fa-solid fa-layer-group" }), /* @__PURE__ */ React.createElement(SummaryCard$2, { label: "Drafts", value: summary.draft_count, icon: "fa-solid fa-file-pen" }), /* @__PURE__ */ React.createElement(SummaryCard$2, { label: "Published", value: summary.published_count, icon: "fa-solid fa-rocket" }), /* @__PURE__ */ React.createElement("a", { href: props.dashboardUrl, className: "rounded-[24px] border border-sky-300/20 bg-sky-300/10 p-5 text-sky-100 transition hover:border-sky-300/35 hover:bg-sky-300/15" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.2em]" }, "Collection dashboard"), /* @__PURE__ */ React.createElement("p", { className: "mt-3 text-sm leading-6" }, "Open the full collection workflow surface for rules, history, and collaboration."))), /* @__PURE__ */ React.createElement(StudioContentBrowser, { listing: props.listing, quickCreate: props.quickCreate, hideModuleFilter: true })); } -const __vite_glob_0_112 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ +const __vite_glob_0_94 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ __proto__: null, default: StudioCollections }, Symbol.toStringTag, { value: "Module" })); @@ -93893,7 +95881,7 @@ function StudioComments() { /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-arrow-right" }) ))))); } -const __vite_glob_0_113 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ +const __vite_glob_0_95 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ __proto__: null, default: StudioComments }, Symbol.toStringTag, { value: "Module" })); @@ -93909,7 +95897,7 @@ function StudioContentIndex() { } )); } -const __vite_glob_0_114 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ +const __vite_glob_0_96 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ __proto__: null, default: StudioContentIndex }, Symbol.toStringTag, { value: "Module" })); @@ -94035,7 +96023,7 @@ function StudioDashboard() { ["Comments", analytics.totals?.comments] ].map(([label, value]) => /* @__PURE__ */ React.createElement("div", { key: label, className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", null, label), /* @__PURE__ */ React.createElement("span", { className: "font-semibold text-white" }, Number(value || 0).toLocaleString()))))))), showWidget("stale_drafts") && /* @__PURE__ */ React.createElement("div", { className: "mt-6 rounded-[30px] border border-white/10 bg-white/[0.03] p-6" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between" }, /* @__PURE__ */ React.createElement("h2", { className: "text-lg font-semibold text-white" }, "Stale drafts"), /* @__PURE__ */ React.createElement("a", { href: "/studio/content?bucket=drafts&stale=only&module=stories", className: "text-sm font-medium text-sky-100" }, "Filter stale work")), /* @__PURE__ */ React.createElement("div", { className: "mt-4 grid gap-3 md:grid-cols-4" }, (overview.stale_drafts || []).map((item) => /* @__PURE__ */ React.createElement(ContinueWorkingCard, { key: item.id, item }))))); } -const __vite_glob_0_115 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ +const __vite_glob_0_97 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ __proto__: null, default: StudioDashboard }, Symbol.toStringTag, { value: "Module" })); @@ -94052,7 +96040,7 @@ function StudioDrafts() { } )); } -const __vite_glob_0_116 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ +const __vite_glob_0_98 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ __proto__: null, default: StudioDrafts }, Symbol.toStringTag, { value: "Module" })); @@ -94135,7 +96123,7 @@ function StudioFeatured() { })) : /* @__PURE__ */ React.createElement("div", { className: "mt-5 rounded-[24px] border border-dashed border-white/15 px-6 py-10 text-center text-sm text-slate-400" }, "No published ", module.label.toLowerCase(), " candidates yet.")); }))); } -const __vite_glob_0_117 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ +const __vite_glob_0_99 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ __proto__: null, default: StudioFeatured }, Symbol.toStringTag, { value: "Module" })); @@ -94161,7 +96149,7 @@ function StudioFollowers() { }; return /* @__PURE__ */ React.createElement(StudioLayout, { title: props.title, subtitle: props.description }, /* @__PURE__ */ React.createElement("div", { className: "mb-6 grid gap-4 md:grid-cols-3" }, /* @__PURE__ */ React.createElement(SummaryCard$1, { label: "Total followers", value: summary.total_followers, icon: "fa-solid fa-user-group" }), /* @__PURE__ */ React.createElement(SummaryCard$1, { label: "Following back", value: summary.following_back, icon: "fa-solid fa-arrows-rotate" }), /* @__PURE__ */ React.createElement(SummaryCard$1, { label: "Not followed yet", value: summary.not_followed, icon: "fa-solid fa-user-plus" })), /* @__PURE__ */ React.createElement("section", { className: "rounded-[28px] border border-white/10 bg-white/[0.03] p-5" }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-3 lg:grid-cols-[minmax(0,1fr)_220px_220px]" }, /* @__PURE__ */ React.createElement("label", { className: "space-y-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "block text-[11px] font-semibold uppercase tracking-[0.2em] text-slate-500" }, "Search"), /* @__PURE__ */ React.createElement("input", { value: filters.q || "", onChange: (event) => updateQuery({ q: event.target.value, page: 1 }), placeholder: "Search followers", className: "w-full rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-sm text-white" })), /* @__PURE__ */ React.createElement("div", { className: "space-y-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "block text-[11px] font-semibold uppercase tracking-[0.2em] text-slate-500" }, "Sort"), /* @__PURE__ */ React.createElement(NovaSelect, { value: filters.sort || "recent", onChange: (val) => updateQuery({ sort: val, page: 1 }), options: listing.sort_options || [], searchable: false })), /* @__PURE__ */ React.createElement("div", { className: "space-y-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "block text-[11px] font-semibold uppercase tracking-[0.2em] text-slate-500" }, "Relationship"), /* @__PURE__ */ React.createElement(NovaSelect, { value: filters.relationship || "all", onChange: (val) => updateQuery({ relationship: val, page: 1 }), options: listing.relationship_options || [], searchable: false }))), /* @__PURE__ */ React.createElement("div", { className: "mt-6 space-y-3" }, items.map((item) => /* @__PURE__ */ React.createElement("article", { key: item.id, className: "flex flex-col gap-4 rounded-[24px] border border-white/10 bg-black/20 p-4 md:flex-row md:items-center md:justify-between" }, /* @__PURE__ */ React.createElement("a", { href: item.profile_url, className: "flex min-w-0 items-center gap-4" }, item.avatar_url ? /* @__PURE__ */ React.createElement("img", { src: item.avatar_url, alt: item.username, className: "h-14 w-14 rounded-[18px] object-cover" }) : /* @__PURE__ */ React.createElement("div", { className: "flex h-14 w-14 items-center justify-center rounded-[18px] bg-white/5 text-slate-400" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-user" })), /* @__PURE__ */ React.createElement("div", { className: "min-w-0" }, /* @__PURE__ */ React.createElement("div", { className: "truncate text-base font-semibold text-white" }, item.name), /* @__PURE__ */ React.createElement("div", { className: "text-sm text-slate-400" }, "@", item.username))), /* @__PURE__ */ React.createElement("div", { className: "grid grid-cols-2 gap-4 text-sm text-slate-400 md:grid-cols-4 md:text-right" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", null, "Uploads"), /* @__PURE__ */ React.createElement("div", { className: "mt-1 font-semibold text-white" }, Number(item.uploads_count || 0).toLocaleString())), /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", null, "Followers"), /* @__PURE__ */ React.createElement("div", { className: "mt-1 font-semibold text-white" }, Number(item.followers_count || 0).toLocaleString())), /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", null, "Followed"), /* @__PURE__ */ React.createElement("div", { className: "mt-1 font-semibold text-white" }, item.followed_at ? new Date(item.followed_at).toLocaleDateString() : "—")), /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", null, "Status"), /* @__PURE__ */ React.createElement("div", { className: "mt-1 font-semibold text-white" }, item.is_following_back ? "Following back" : "Not followed")))))), /* @__PURE__ */ React.createElement("div", { className: "mt-6 flex items-center justify-between rounded-[24px] border border-white/10 bg-white/[0.03] px-4 py-3 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("button", { type: "button", disabled: (meta.current_page || 1) <= 1, onClick: () => updateQuery({ page: Math.max(1, (meta.current_page || 1) - 1) }), className: "inline-flex items-center gap-2 rounded-full border border-white/10 px-4 py-2 disabled:opacity-40" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-arrow-left" }), "Previous"), /* @__PURE__ */ React.createElement("span", null, "Page ", meta.current_page || 1, " of ", meta.last_page || 1), /* @__PURE__ */ React.createElement("button", { type: "button", disabled: (meta.current_page || 1) >= (meta.last_page || 1), onClick: () => updateQuery({ page: (meta.current_page || 1) + 1 }), className: "inline-flex items-center gap-2 rounded-full border border-white/10 px-4 py-2 disabled:opacity-40" }, "Next", /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-arrow-right" }))))); } -const __vite_glob_0_118 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ +const __vite_glob_0_100 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ __proto__: null, default: StudioFollowers }, Symbol.toStringTag, { value: "Module" })); @@ -94170,7 +96158,7 @@ function StudioGroupActivity() { const items = Array.isArray(props.activity) ? props.activity : []; return /* @__PURE__ */ React.createElement(StudioLayout, { title: props.title, subtitle: props.description }, /* @__PURE__ */ React.createElement("div", { className: "space-y-4" }, items.length > 0 ? items.map((item) => /* @__PURE__ */ React.createElement("div", { key: item.id, className: "rounded-[24px] border border-white/10 bg-white/[0.03] p-5" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-start justify-between gap-4" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center gap-2" }, /* @__PURE__ */ React.createElement("h2", { className: "text-base font-semibold text-white" }, item.headline), item.is_pinned ? /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-amber-300/20 bg-amber-300/10 px-2 py-1 text-[10px] font-semibold uppercase tracking-[0.16em] text-amber-100" }, "Pinned") : null, /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.04] px-2 py-1 text-[10px] font-semibold uppercase tracking-[0.16em] text-slate-300" }, item.visibility)), item.summary ? /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm leading-6 text-slate-400" }, item.summary) : null, /* @__PURE__ */ React.createElement("div", { className: "mt-3 text-xs text-slate-500" }, item.actor?.name || item.actor?.username || "System", " • ", item.occurred_at ? new Date(item.occurred_at).toLocaleString() : "Recently"), item.subject?.url ? /* @__PURE__ */ React.createElement("a", { href: item.subject.url, className: "mt-3 inline-flex text-sm font-semibold text-sky-200" }, "Open subject") : null), props.pinPattern ? /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => At.post(props.pinPattern.replace("__ITEM__", String(item.id)), { is_pinned: !item.is_pinned }), className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-1.5 text-sm font-semibold text-white" }, item.is_pinned ? "Unpin" : "Pin") : null))) : /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-dashed border-white/10 bg-white/[0.02] p-6 text-sm text-slate-400" }, "No activity yet."))); } -const __vite_glob_0_119 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ +const __vite_glob_0_101 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ __proto__: null, default: StudioGroupActivity }, Symbol.toStringTag, { value: "Module" })); @@ -94178,7 +96166,7 @@ function StudioGroupArtworks() { const { props } = X(); return /* @__PURE__ */ React.createElement(StudioLayout, { title: props.title, subtitle: props.description }, /* @__PURE__ */ React.createElement("div", { className: "mb-6 rounded-[28px] border border-sky-300/20 bg-sky-300/10 p-5 text-sky-100" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.18em]" }, "Group publish flow"), /* @__PURE__ */ React.createElement("h2", { className: "mt-2 text-xl font-semibold" }, "Upload into ", props.studioGroup?.name), /* @__PURE__ */ React.createElement("a", { href: props.uploadUrl, className: "mt-4 inline-flex rounded-full border border-sky-200/20 bg-sky-200/10 px-4 py-2 text-sm font-semibold text-sky-50" }, "New group artwork")), /* @__PURE__ */ React.createElement(StudioContentBrowser, { listing: props.listing, quickCreate: [{ key: "artworks", label: "Artwork", icon: "fa-solid fa-cloud-arrow-up", url: props.uploadUrl }], hideModuleFilter: true })); } -const __vite_glob_0_120 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ +const __vite_glob_0_102 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ __proto__: null, default: StudioGroupArtworks }, Symbol.toStringTag, { value: "Module" })); @@ -94219,7 +96207,7 @@ function StudioGroupAssets() { }; return /* @__PURE__ */ React.createElement(StudioLayout, { title: props.title, subtitle: props.description }, props.storeUrl ? /* @__PURE__ */ React.createElement("form", { onSubmit: submit, className: "rounded-[28px] border border-white/10 bg-white/[0.03] p-6" }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 lg:grid-cols-6" }, /* @__PURE__ */ React.createElement("input", { value: form.data.title, onChange: (event) => form.setData("title", event.target.value), placeholder: "Asset title", className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white outline-none lg:col-span-2" }), /* @__PURE__ */ React.createElement(NovaSelect, { value: form.data.category, onChange: (val) => form.setData("category", val), options: props.categoryOptions || [], searchable: false }), /* @__PURE__ */ React.createElement(NovaSelect, { value: form.data.visibility, onChange: (val) => form.setData("visibility", val), options: props.visibilityOptions || [], searchable: false }), /* @__PURE__ */ React.createElement(NovaSelect, { value: form.data.status, onChange: (val) => form.setData("status", val), options: props.statusOptions || [], searchable: false }), /* @__PURE__ */ React.createElement("input", { type: "file", onChange: (event) => form.setData("file", event.target.files?.[0] || null), className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white outline-none" })), /* @__PURE__ */ React.createElement("textarea", { value: form.data.description, onChange: (event) => form.setData("description", event.target.value), placeholder: "What is this asset for?", rows: 3, className: "mt-4 w-full rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white outline-none" }), /* @__PURE__ */ React.createElement("div", { className: "mt-4 grid gap-4 md:grid-cols-2" }, /* @__PURE__ */ React.createElement(NovaSelect, { value: String(form.data.linked_project_id || ""), onChange: (val) => form.setData("linked_project_id", val), placeholder: "No linked project", options: (props.projectOptions || []).map((o) => ({ value: String(o.id), label: o.title })) }), /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-3 rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-sm text-white" }, /* @__PURE__ */ React.createElement(Checkbox, { checked: form.data.is_featured, onChange: (event) => form.setData("is_featured", event.target.checked), label: "Featured asset" }))), /* @__PURE__ */ React.createElement("button", { type: "submit", className: "mt-4 rounded-full border border-white/10 bg-white/[0.05] px-5 py-2.5 text-sm font-semibold text-white" }, "Upload asset")) : null, /* @__PURE__ */ React.createElement("form", { onSubmit: applyFilters, className: "mt-6 rounded-[28px] border border-white/10 bg-white/[0.03] p-6" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-end justify-between gap-4" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("h2", { className: "text-lg font-semibold text-white" }, "Browse library"), /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-sm text-slate-400" }, "Search and filter shared assets by visibility and category.")), /* @__PURE__ */ React.createElement("button", { type: "submit", className: "rounded-full border border-white/10 bg-white/[0.05] px-4 py-2 text-sm font-semibold text-white" }, "Apply filters")), /* @__PURE__ */ React.createElement("div", { className: "mt-4 grid gap-4 lg:grid-cols-3" }, /* @__PURE__ */ React.createElement("input", { value: filters.data.q, onChange: (event) => filters.setData("q", event.target.value), placeholder: "Search title, description, or filename", className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white outline-none" }), /* @__PURE__ */ React.createElement(NovaSelect, { value: filters.data.category, onChange: (val) => filters.setData("category", val), options: [{ value: "all", label: "All categories" }, ...props.categoryOptions || []], searchable: false }), /* @__PURE__ */ React.createElement(NovaSelect, { value: filters.data.bucket, onChange: (val) => filters.setData("bucket", val), options: [{ value: "all", label: "All visibility levels" }, ...(props.listing?.bucket_options || []).filter((option) => option.value !== "all")], searchable: false }))), /* @__PURE__ */ React.createElement("div", { className: "mt-6 grid gap-4 lg:grid-cols-2" }, items.length > 0 ? items.map((asset) => /* @__PURE__ */ React.createElement("div", { key: asset.id, className: "rounded-[24px] border border-white/10 bg-white/[0.03] p-5" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("h2", { className: "text-xl font-semibold text-white" }, asset.title), /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-xs uppercase tracking-[0.16em] text-slate-500" }, asset.category, " • ", asset.visibility, " • ", asset.status)), /* @__PURE__ */ React.createElement("a", { href: asset.download_url, className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-1.5 text-sm font-semibold text-white" }, "Download")), asset.description ? /* @__PURE__ */ React.createElement("p", { className: "mt-3 text-sm leading-6 text-slate-400" }, asset.description) : null, props.updatePattern ? /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => At.patch(props.updatePattern.replace("__ASSET__", String(asset.id)), { title: asset.title, description: asset.description || "", category: asset.category, visibility: asset.visibility, status: asset.status === "active" ? "archived" : "active", linked_project_id: asset.linked_project?.id || "", is_featured: asset.is_featured }), className: "mt-4 rounded-full border border-white/10 bg-white/[0.04] px-4 py-2 text-sm font-semibold text-white" }, asset.status === "active" ? "Archive" : "Reactivate") : null)) : /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-dashed border-white/10 bg-white/[0.02] p-6 text-sm text-slate-400" }, "No assets yet."))); } -const __vite_glob_0_121 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ +const __vite_glob_0_103 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ __proto__: null, default: StudioGroupAssets }, Symbol.toStringTag, { value: "Module" })); @@ -94291,7 +96279,7 @@ function StudioGroupChallengeEditor() { attachForm.post(props.attachArtworkUrl, { preserveScroll: true }); }, className: "rounded-[28px] border border-white/10 bg-white/[0.03] p-6" }, /* @__PURE__ */ React.createElement("h2", { className: "text-lg font-semibold text-white" }, "Attach artwork"), /* @__PURE__ */ React.createElement(NovaSelect, { value: String(attachForm.data.artwork_id || ""), onChange: (val) => attachForm.setData("artwork_id", val), placeholder: "Choose artwork", options: (props.artworkOptions || []).map((o) => ({ value: String(o.id), label: o.title })) }), /* @__PURE__ */ React.createElement("button", { type: "submit", className: "mt-4 rounded-full border border-white/10 bg-white/[0.05] px-4 py-2 text-sm font-semibold text-white" }, "Attach")) : null))); } -const __vite_glob_0_122 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ +const __vite_glob_0_104 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ __proto__: null, default: StudioGroupChallengeEditor }, Symbol.toStringTag, { value: "Module" })); @@ -94300,7 +96288,7 @@ function StudioGroupChallenges() { const items = Array.isArray(props.listing?.items) ? props.listing.items : []; return /* @__PURE__ */ React.createElement(StudioLayout, { title: props.title, subtitle: props.description }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", { className: "text-sm text-slate-400" }, "Challenges keep the group active between releases and give members a focused creative prompt."), props.createUrl ? /* @__PURE__ */ React.createElement("a", { href: props.createUrl, className: "rounded-full border border-white/10 bg-white/[0.04] px-4 py-2 text-sm font-semibold text-white" }, "Create challenge") : null), /* @__PURE__ */ React.createElement("div", { className: "mt-6 grid gap-4 lg:grid-cols-2" }, items.length > 0 ? items.map((challenge) => /* @__PURE__ */ React.createElement("a", { key: challenge.id, href: challenge.urls?.edit || challenge.url, className: "rounded-[24px] border border-white/10 bg-white/[0.03] p-5 transition hover:border-white/20" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("h2", { className: "text-xl font-semibold text-white" }, challenge.title), /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-300" }, challenge.status)), /* @__PURE__ */ React.createElement("p", { className: "mt-3 text-sm leading-6 text-slate-400" }, challenge.summary || "Challenge page"), /* @__PURE__ */ React.createElement("div", { className: "mt-4 text-xs text-slate-500" }, challenge.entry_count || 0, " linked entries"))) : /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-dashed border-white/10 bg-white/[0.02] p-6 text-sm text-slate-400" }, "No challenges yet."))); } -const __vite_glob_0_123 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ +const __vite_glob_0_105 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ __proto__: null, default: StudioGroupChallenges }, Symbol.toStringTag, { value: "Module" })); @@ -94308,7 +96296,7 @@ function StudioGroupCollections() { const { props } = X(); return /* @__PURE__ */ React.createElement(StudioLayout, { title: props.title, subtitle: props.description }, /* @__PURE__ */ React.createElement("div", { className: "mb-6 rounded-[28px] border border-sky-300/20 bg-sky-300/10 p-5 text-sky-100" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.18em]" }, "Shared curation"), /* @__PURE__ */ React.createElement("h2", { className: "mt-2 text-xl font-semibold" }, "Create collections for ", props.studioGroup?.name), /* @__PURE__ */ React.createElement("a", { href: props.createUrl, className: "mt-4 inline-flex rounded-full border border-sky-200/20 bg-sky-200/10 px-4 py-2 text-sm font-semibold text-sky-50" }, "New group collection")), /* @__PURE__ */ React.createElement(StudioContentBrowser, { listing: props.listing, quickCreate: [{ key: "collections", label: "Collection", icon: "fa-solid fa-layer-group", url: props.createUrl }], hideModuleFilter: true })); } -const __vite_glob_0_124 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ +const __vite_glob_0_106 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ __proto__: null, default: StudioGroupCollections }, Symbol.toStringTag, { value: "Module" })); @@ -94422,7 +96410,7 @@ function StudioGroupCreate() { } )), /* @__PURE__ */ React.createElement("section", { className: "mx-auto max-w-3xl rounded-[30px] border border-white/10 bg-white/[0.03] p-6" }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-5" }, /* @__PURE__ */ React.createElement("label", { className: "grid gap-2 text-sm text-slate-200" }, /* @__PURE__ */ React.createElement("span", null, "Name"), /* @__PURE__ */ React.createElement("input", { value: form.name, onChange: handleNameChange, className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white outline-none" })), /* @__PURE__ */ React.createElement("label", { className: "grid gap-2 text-sm text-slate-200" }, /* @__PURE__ */ React.createElement("span", null, "Slug"), /* @__PURE__ */ React.createElement("input", { value: form.slug, onChange: handleSlugChange, className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white outline-none" })), /* @__PURE__ */ React.createElement("label", { className: "grid gap-2 text-sm text-slate-200" }, /* @__PURE__ */ React.createElement("span", null, "Short description"), /* @__PURE__ */ React.createElement("input", { value: form.headline, onChange: (event) => setForm((current) => ({ ...current, headline: event.target.value })), className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white outline-none" })), /* @__PURE__ */ React.createElement("label", { className: "grid gap-2 text-sm text-slate-200" }, /* @__PURE__ */ React.createElement("span", null, "About"), /* @__PURE__ */ React.createElement("textarea", { value: form.bio, onChange: (event) => setForm((current) => ({ ...current, bio: event.target.value })), rows: 6, className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white outline-none" })), /* @__PURE__ */ React.createElement("div", { className: "grid gap-5 md:grid-cols-2" }, /* @__PURE__ */ React.createElement("label", { className: "grid gap-2 text-sm text-slate-200" }, /* @__PURE__ */ React.createElement("span", null, "Type / category"), /* @__PURE__ */ React.createElement("input", { value: form.type, onChange: (event) => setForm((current) => ({ ...current, type: event.target.value })), className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white outline-none" })), /* @__PURE__ */ React.createElement("div", { className: "grid gap-2 text-sm text-slate-200" }, /* @__PURE__ */ React.createElement("span", null, "Founded date"), /* @__PURE__ */ React.createElement(DateTimePicker, { value: form.founded_at, onChange: (nextValue) => setForm((current) => ({ ...current, founded_at: nextValue })), mode: "date", placeholder: "Pick the founding date", clearable: true, className: "bg-black/20" }))), /* @__PURE__ */ React.createElement("label", { className: "grid gap-2 text-sm text-slate-200" }, /* @__PURE__ */ React.createElement("span", null, "Website"), /* @__PURE__ */ React.createElement("input", { value: form.website_url, onChange: (event) => setForm((current) => ({ ...current, website_url: event.target.value })), className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white outline-none" })), /* @__PURE__ */ React.createElement("div", { className: "grid gap-5 md:grid-cols-2" }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-3 rounded-[24px] border border-white/10 bg-black/20 p-4 text-sm text-slate-200" }, /* @__PURE__ */ React.createElement("span", { className: "text-sm font-semibold text-white" }, "Avatar / logo"), /* @__PURE__ */ React.createElement("div", { className: "flex h-28 w-28 items-center justify-center overflow-hidden rounded-[24px] border border-white/10 bg-white/[0.04]" }, resolvedAvatarPreview ? /* @__PURE__ */ React.createElement("img", { src: resolvedAvatarPreview, alt: "Avatar preview", className: "h-full w-full object-cover" }) : /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-image text-slate-500" })), /* @__PURE__ */ React.createElement("input", { ref: avatarInputRef, type: "file", accept: "image/png,image/jpeg,image/webp", onChange: handleFileSelected("avatar_file", setAvatarPreview), className: "hidden" }), /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-2" }, /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => avatarInputRef.current?.click(), className: "rounded-full border border-white/10 bg-white/[0.04] px-4 py-2 text-sm font-semibold text-white" }, "Upload avatar"), form.avatar_file ? /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => clearSelectedFile("avatar_file", setAvatarPreview, avatarInputRef), className: "rounded-full border border-white/10 bg-transparent px-4 py-2 text-sm font-semibold text-slate-300" }, "Use URL instead") : null), /* @__PURE__ */ React.createElement("label", { className: "grid gap-2 text-sm text-slate-200" }, /* @__PURE__ */ React.createElement("span", null, "Or paste an image URL"), /* @__PURE__ */ React.createElement("input", { value: form.avatar_path, onChange: (event) => setForm((current) => ({ ...current, avatar_path: event.target.value })), placeholder: "https://", className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white outline-none" }))), /* @__PURE__ */ React.createElement("div", { className: "grid gap-3 rounded-[24px] border border-white/10 bg-black/20 p-4 text-sm text-slate-200" }, /* @__PURE__ */ React.createElement("span", { className: "text-sm font-semibold text-white" }, "Cover image"), /* @__PURE__ */ React.createElement("div", { className: "flex h-28 w-full items-center justify-center overflow-hidden rounded-[24px] border border-white/10 bg-white/[0.04]" }, resolvedBannerPreview ? /* @__PURE__ */ React.createElement("img", { src: resolvedBannerPreview, alt: "Cover preview", className: "h-full w-full object-cover" }) : /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-panorama text-slate-500" })), /* @__PURE__ */ React.createElement("input", { ref: bannerInputRef, type: "file", accept: "image/png,image/jpeg,image/webp", onChange: handleFileSelected("banner_file", setBannerPreview), className: "hidden" }), /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-2" }, /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => bannerInputRef.current?.click(), className: "rounded-full border border-white/10 bg-white/[0.04] px-4 py-2 text-sm font-semibold text-white" }, "Upload cover"), form.banner_file ? /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => clearSelectedFile("banner_file", setBannerPreview, bannerInputRef), className: "rounded-full border border-white/10 bg-transparent px-4 py-2 text-sm font-semibold text-slate-300" }, "Use URL instead") : null), /* @__PURE__ */ React.createElement("label", { className: "grid gap-2 text-sm text-slate-200" }, /* @__PURE__ */ React.createElement("span", null, "Or paste an image URL"), /* @__PURE__ */ React.createElement("input", { value: form.banner_path, onChange: (event) => setForm((current) => ({ ...current, banner_path: event.target.value })), placeholder: "https://", className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white outline-none" })))), /* @__PURE__ */ React.createElement("div", { className: "grid gap-2 text-sm text-slate-200" }, /* @__PURE__ */ React.createElement("span", null, "Visibility"), /* @__PURE__ */ React.createElement(NovaSelect, { value: form.visibility, onChange: (val) => setForm((current) => ({ ...current, visibility: val })), options: props.visibilityOptions || [], searchable: false })), /* @__PURE__ */ React.createElement("div", { className: "grid gap-2 text-sm text-slate-200" }, /* @__PURE__ */ React.createElement("span", null, "Membership policy"), /* @__PURE__ */ React.createElement(NovaSelect, { value: form.membership_policy, onChange: (val) => setForm((current) => ({ ...current, membership_policy: val })), options: props.membershipPolicyOptions || [], searchable: false })), /* @__PURE__ */ React.createElement("div", { className: "grid gap-3" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("span", { className: "text-sm text-slate-200" }, "Links"), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: addLink, className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-1.5 text-xs font-semibold text-white" }, "Add link")), form.links_json.map((item, index2) => /* @__PURE__ */ React.createElement("div", { key: `link-${index2}`, className: "grid gap-3 md:grid-cols-[0.8fr_1.2fr_auto]" }, /* @__PURE__ */ React.createElement("input", { value: item.label, onChange: (event) => updateLink(index2, "label", event.target.value), placeholder: "Label", className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white outline-none" }), /* @__PURE__ */ React.createElement("input", { value: item.url, onChange: (event) => updateLink(index2, "url", event.target.value), placeholder: "https://", className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white outline-none" }), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => removeLink(index2), className: "rounded-full border border-rose-300/20 bg-rose-400/10 px-4 py-2 text-sm font-semibold text-rose-100" }, "Remove")))), /* @__PURE__ */ React.createElement("div", { className: "flex justify-end gap-3" }, /* @__PURE__ */ React.createElement("a", { href: "/studio/groups", className: "rounded-full border border-white/10 bg-white/[0.03] px-4 py-2 text-sm font-semibold text-white" }, "Cancel"), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: submit, className: "rounded-full border border-sky-300/20 bg-sky-300/10 px-4 py-2 text-sm font-semibold text-sky-100" }, "Create group"))))); } -const __vite_glob_0_125 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ +const __vite_glob_0_107 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ __proto__: null, default: StudioGroupCreate }, Symbol.toStringTag, { value: "Module" })); @@ -94487,7 +96475,7 @@ function StudioGroupDashboard() { }; return /* @__PURE__ */ React.createElement(StudioLayout, { title: props.title, subtitle: props.description }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 md:grid-cols-3 xl:grid-cols-6" }, /* @__PURE__ */ React.createElement(StatCard, { label: "Artworks", value: group?.counts?.artworks, icon: "fa-solid fa-images" }), /* @__PURE__ */ React.createElement(StatCard, { label: "Collections", value: group?.counts?.collections, icon: "fa-solid fa-layer-group" }), /* @__PURE__ */ React.createElement(StatCard, { label: "Followers", value: group?.counts?.followers, icon: "fa-solid fa-user-group" }), /* @__PURE__ */ React.createElement(StatCard, { label: "Active members", value: dashboard?.active_members_count || group?.counts?.members, icon: "fa-solid fa-people-group" }), /* @__PURE__ */ React.createElement(StatCard, { label: "Projects", value: dashboard?.projects_count, icon: "fa-solid fa-diagram-project" }), /* @__PURE__ */ React.createElement(StatCard, { label: "Releases", value: dashboard?.published_releases_count || dashboard?.releases_count, icon: "fa-solid fa-rocket" }), /* @__PURE__ */ React.createElement(StatCard, { label: "Assets", value: dashboard?.assets_count, icon: "fa-solid fa-box-archive" })), /* @__PURE__ */ React.createElement("div", { className: "mt-6 grid gap-6 xl:grid-cols-[minmax(0,1.2fr)_minmax(0,0.8fr)]" }, /* @__PURE__ */ React.createElement("section", { className: "rounded-[28px] border border-white/10 bg-white/[0.03] p-5" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("h2", { className: "text-xl font-semibold text-white" }, "Quick actions"), /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-sm text-slate-400" }, "Run the most common group tasks without leaving the dashboard."))), /* @__PURE__ */ React.createElement("div", { className: "mt-4 grid gap-3 md:grid-cols-2" }, quickActions.map((action) => /* @__PURE__ */ React.createElement("a", { key: action.label, href: action.href, className: `rounded-[24px] border px-4 py-4 transition hover:translate-y-[-1px] hover:border-white/20 ${toneClasses2[action.tone] || toneClasses2.sky}` }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-3" }, /* @__PURE__ */ React.createElement("span", { className: "inline-flex h-11 w-11 items-center justify-center rounded-2xl border border-current/20 bg-black/10" }, /* @__PURE__ */ React.createElement("i", { className: action.icon })), /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "text-sm font-semibold" }, action.label), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-xs opacity-80" }, action.detail)))))), /* @__PURE__ */ React.createElement("div", { className: "mt-6 rounded-[24px] border border-white/10 bg-black/20 p-4" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("h3", { className: "text-lg font-semibold text-white" }, "Pending action"), /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-sm text-slate-400" }, "Drafts and scheduled items that still need a publishing decision.")), /* @__PURE__ */ React.createElement("div", { className: "text-right text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("div", null, Number(dashboard?.draft_artworks_count || 0), " drafts"), /* @__PURE__ */ React.createElement("div", null, Number(dashboard?.scheduled_artworks_count || 0), " scheduled"))), /* @__PURE__ */ React.createElement("div", { className: "mt-4 grid gap-3 md:grid-cols-2" }, draftsPendingAction.length > 0 ? draftsPendingAction.map((artwork) => /* @__PURE__ */ React.createElement(ContentCard, { key: artwork.id, item: artwork, fallbackLabel: "Draft" })) : /* @__PURE__ */ React.createElement(EmptyCard, { title: "No drafts waiting", description: "This group has no draft artworks waiting for review or completion right now." }))), pendingJoinRequests.length > 0 ? /* @__PURE__ */ React.createElement("div", { className: "mt-6 rounded-[24px] border border-white/10 bg-black/20 p-4" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("h3", { className: "text-lg font-semibold text-white" }, "Pending join requests"), /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-sm text-slate-400" }, "Applicants waiting for a review decision.")), group?.urls?.studio_join_requests ? /* @__PURE__ */ React.createElement("a", { href: group.urls.studio_join_requests, className: "text-sm font-semibold text-sky-200" }, "Open queue") : null), /* @__PURE__ */ React.createElement("div", { className: "mt-4 space-y-3" }, pendingJoinRequests.map((item) => /* @__PURE__ */ React.createElement("div", { key: item.id, className: "rounded-2xl border border-white/10 bg-white/[0.03] px-4 py-3" }, /* @__PURE__ */ React.createElement("div", { className: "font-semibold text-white" }, item.user?.name || item.user?.username), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-sm text-slate-400" }, item.desired_role_label || item.desired_role || "Contributor", " • ", item.created_at ? new Date(item.created_at).toLocaleDateString() : "New"))))) : null), /* @__PURE__ */ React.createElement("section", { className: "rounded-[28px] border border-white/10 bg-white/[0.03] p-5" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("h2", { className: "text-xl font-semibold text-white" }, "Members"), /* @__PURE__ */ React.createElement("a", { href: group?.urls?.studio_members, className: "text-sm font-semibold text-sky-200" }, "Manage")), /* @__PURE__ */ React.createElement("div", { className: "mt-4 grid gap-2 sm:grid-cols-2" }, Object.entries(roleSummary).map(([role, count]) => /* @__PURE__ */ React.createElement("div", { key: role, className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, role), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-xl font-semibold text-white" }, Number(count))))), /* @__PURE__ */ React.createElement("div", { className: "mt-4 space-y-3" }, members.slice(0, 6).map((member) => /* @__PURE__ */ React.createElement("div", { key: member.id, className: "flex items-center gap-3 rounded-2xl border border-white/10 bg-black/20 px-4 py-3" }, member.user?.avatar_url ? /* @__PURE__ */ React.createElement("img", { src: member.user.avatar_url, alt: member.user.name || member.user.username, className: "h-11 w-11 rounded-2xl object-cover" }) : /* @__PURE__ */ React.createElement("div", { className: "flex h-11 w-11 items-center justify-center rounded-2xl border border-white/10 bg-white/[0.03] text-slate-400" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-user" })), /* @__PURE__ */ React.createElement("div", { className: "min-w-0 flex-1" }, /* @__PURE__ */ React.createElement("div", { className: "truncate font-semibold text-white" }, member.user?.name || member.user?.username), /* @__PURE__ */ React.createElement("div", { className: "text-xs uppercase tracking-[0.16em] text-slate-400" }, member.role))))), /* @__PURE__ */ React.createElement("div", { className: "mt-6 rounded-[24px] border border-white/10 bg-black/20 p-4" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Recruitment"), /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-lg font-semibold text-white" }, recruitment?.is_recruiting ? recruitment.headline || "Recruiting is active" : "Recruitment is off"), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm text-slate-400" }, recruitment?.description || "Set open roles, skills, and contact instructions from the recruitment page.")))), /* @__PURE__ */ React.createElement("div", { className: "mt-6 grid gap-6 xl:grid-cols-2" }, /* @__PURE__ */ React.createElement("section", { className: "rounded-[28px] border border-white/10 bg-white/[0.03] p-5" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("h2", { className: "text-xl font-semibold text-white" }, "Releases"), /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-sm text-slate-400" }, "Track featured drops and current release pipelines.")), group?.urls?.studio_releases ? /* @__PURE__ */ React.createElement("a", { href: group.urls.studio_releases, className: "text-sm font-semibold text-sky-200" }, "Manage") : null), /* @__PURE__ */ React.createElement("div", { className: "mt-4 grid gap-3 md:grid-cols-2" }, recentReleases.length > 0 ? recentReleases.map((release) => /* @__PURE__ */ React.createElement(ContentCard, { key: release.id, item: release, fallbackLabel: "Release" })) : /* @__PURE__ */ React.createElement(EmptyCard, { title: "No releases yet", description: "Create a release to track milestones, contributors, and publication status." }))), /* @__PURE__ */ React.createElement("section", { className: "rounded-[28px] border border-white/10 bg-white/[0.03] p-5" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("h2", { className: "text-xl font-semibold text-white" }, "Projects"), /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-sm text-slate-400" }, "Recent structured releases and collaboration hubs.")), group?.urls?.studio_projects ? /* @__PURE__ */ React.createElement("a", { href: group.urls.studio_projects, className: "text-sm font-semibold text-sky-200" }, "Manage") : null), /* @__PURE__ */ React.createElement("div", { className: "mt-4 grid gap-3 md:grid-cols-2" }, recentProjects.length > 0 ? recentProjects.map((project) => /* @__PURE__ */ React.createElement(ContentCard, { key: project.id, item: project, fallbackLabel: "Project" })) : /* @__PURE__ */ React.createElement(EmptyCard, { title: "No projects yet", description: "Create a project to bundle shared assets, linked artworks, and a release state." }))), /* @__PURE__ */ React.createElement("section", { className: "rounded-[28px] border border-white/10 bg-white/[0.03] p-5" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("h2", { className: "text-xl font-semibold text-white" }, "Challenges"), /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-sm text-slate-400" }, "Current creative prompts and challenge arcs.")), group?.urls?.studio_challenges ? /* @__PURE__ */ React.createElement("a", { href: group.urls.studio_challenges, className: "text-sm font-semibold text-sky-200" }, "Manage") : null), /* @__PURE__ */ React.createElement("div", { className: "mt-4 grid gap-3 md:grid-cols-2" }, recentChallenges.length > 0 ? recentChallenges.map((challenge) => /* @__PURE__ */ React.createElement(ContentCard, { key: challenge.id, item: challenge, fallbackLabel: "Challenge" })) : /* @__PURE__ */ React.createElement(EmptyCard, { title: "No challenges yet", description: "Launch a challenge to keep the group active between major releases." })))), /* @__PURE__ */ React.createElement("div", { className: "mt-6 grid gap-6 xl:grid-cols-2" }, /* @__PURE__ */ React.createElement("section", { className: "rounded-[28px] border border-white/10 bg-white/[0.03] p-5" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("h2", { className: "text-xl font-semibold text-white" }, "Trust summary"), /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-sm text-slate-400" }, "Public-facing trust labels and internal contributor health snapshot.")), group?.urls?.studio_reputation ? /* @__PURE__ */ React.createElement("a", { href: group.urls.studio_reputation, className: "text-sm font-semibold text-sky-200" }, "Open dashboard") : null), /* @__PURE__ */ React.createElement("div", { className: "mt-4 flex flex-wrap gap-2" }, trustSignals.map((signal) => /* @__PURE__ */ React.createElement("span", { key: signal.key, className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-2 text-sm font-semibold text-white" }, signal.label))), /* @__PURE__ */ React.createElement("div", { className: "mt-5 grid gap-3 md:grid-cols-2" }, /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-4 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Contributors"), /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-2xl font-semibold text-white" }, Number(reputationSummary?.counts?.contributors || 0))), /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-4 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Group badges"), /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-2xl font-semibold text-white" }, Number(reputationSummary?.counts?.group_badges || 0))))), /* @__PURE__ */ React.createElement("section", { className: "rounded-[28px] border border-white/10 bg-white/[0.03] p-5" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("h2", { className: "text-xl font-semibold text-white" }, "Contributor highlights"), /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-sm text-slate-400" }, "Recent high-trust contributors and badge unlocks."))), /* @__PURE__ */ React.createElement("div", { className: "mt-4 space-y-3" }, Array.isArray(reputationSummary?.top_contributors) && reputationSummary.top_contributors.length > 0 ? reputationSummary.top_contributors.slice(0, 4).map((entry) => /* @__PURE__ */ React.createElement("div", { key: entry.user?.id, className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-4" }, /* @__PURE__ */ React.createElement("div", { className: "font-semibold text-white" }, entry.user?.name || entry.user?.username), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-sm text-slate-400" }, entry.summary || "Contributor"), /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-xs text-slate-500" }, entry.counts?.releases || 0, " releases • ", entry.counts?.credited_artworks || 0, " artworks"))) : /* @__PURE__ */ React.createElement(EmptyCard, { title: "No contributor signals yet", description: "Release and milestone activity will populate contributor reputation here." })))), /* @__PURE__ */ React.createElement("div", { className: "mt-6 grid gap-6 xl:grid-cols-2" }, /* @__PURE__ */ React.createElement("section", { className: "rounded-[28px] border border-white/10 bg-white/[0.03] p-5" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("h2", { className: "text-xl font-semibold text-white" }, "Recent artworks"), /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-sm text-slate-400" }, "Latest published work released under this group identity.")), /* @__PURE__ */ React.createElement("a", { href: group?.urls?.studio_artworks, className: "text-sm font-semibold text-sky-200" }, "View all")), /* @__PURE__ */ React.createElement("div", { className: "mt-4 grid gap-3 md:grid-cols-2" }, recentArtworks.length > 0 ? recentArtworks.map((artwork) => /* @__PURE__ */ React.createElement(ContentCard, { key: artwork.id, item: artwork, fallbackLabel: "Published" })) : /* @__PURE__ */ React.createElement(EmptyCard, { title: "No published artworks yet", description: "Publish the first group artwork to start building this feed." }))), /* @__PURE__ */ React.createElement("section", { className: "rounded-[28px] border border-white/10 bg-white/[0.03] p-5" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("h2", { className: "text-xl font-semibold text-white" }, "Events"), /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-sm text-slate-400" }, "Upcoming or recently updated moments on the group timeline.")), group?.urls?.studio_events ? /* @__PURE__ */ React.createElement("a", { href: group.urls.studio_events, className: "text-sm font-semibold text-sky-200" }, "Manage") : null), /* @__PURE__ */ React.createElement("div", { className: "mt-4 grid gap-3 md:grid-cols-2" }, recentEvents.length > 0 ? recentEvents.map((event) => /* @__PURE__ */ React.createElement(ContentCard, { key: event.id, item: event, fallbackLabel: "Event" })) : /* @__PURE__ */ React.createElement(EmptyCard, { title: "No events yet", description: "Schedule a launch, stream, or milestone to start the group timeline." })))), /* @__PURE__ */ React.createElement("div", { className: "mt-6 grid gap-6 xl:grid-cols-2" }, /* @__PURE__ */ React.createElement("section", { className: "rounded-[28px] border border-white/10 bg-white/[0.03] p-5" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("h2", { className: "text-xl font-semibold text-white" }, "Recent collections"), /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-sm text-slate-400" }, "Collections most recently updated in this group workspace.")), /* @__PURE__ */ React.createElement("a", { href: group?.urls?.studio_collections, className: "text-sm font-semibold text-sky-200" }, "View all")), /* @__PURE__ */ React.createElement("div", { className: "mt-4 grid gap-3 md:grid-cols-2" }, recentCollections.length > 0 ? recentCollections.map((collection) => /* @__PURE__ */ React.createElement(ContentCard, { key: collection.id, item: collection, fallbackLabel: "Collection" })) : /* @__PURE__ */ React.createElement(EmptyCard, { title: "No collections yet", description: "Create a collection to organize group work into campaigns, series, or themed sets." }))), /* @__PURE__ */ React.createElement("section", { className: "rounded-[28px] border border-white/10 bg-white/[0.03] p-5" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("h2", { className: "text-xl font-semibold text-white" }, "Activity feed"), /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-sm text-slate-400" }, "Pinned and recent internal or public timeline items.")), group?.urls?.studio_activity ? /* @__PURE__ */ React.createElement("a", { href: group.urls.studio_activity, className: "text-sm font-semibold text-sky-200" }, "Open feed") : null), /* @__PURE__ */ React.createElement("div", { className: "mt-4 space-y-3" }, recentActivity.length > 0 ? recentActivity.map((item) => /* @__PURE__ */ React.createElement(ActivityCard, { key: item.id, item })) : /* @__PURE__ */ React.createElement(EmptyCard, { title: "No activity items yet", description: "Publishing projects, events, posts, and member milestones will populate this feed." })))), /* @__PURE__ */ React.createElement("div", { className: "mt-6 grid gap-6 xl:grid-cols-2" }, /* @__PURE__ */ React.createElement("section", { className: "rounded-[28px] border border-white/10 bg-white/[0.03] p-5" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("h2", { className: "text-xl font-semibold text-white" }, "Review queue"), /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-sm text-slate-400" }, "Latest artwork submissions waiting for moderation.")), group?.urls?.studio_review ? /* @__PURE__ */ React.createElement("a", { href: group.urls.studio_review, className: "text-sm font-semibold text-sky-200" }, "Open queue") : null), /* @__PURE__ */ React.createElement("div", { className: "mt-4 grid gap-3 md:grid-cols-2" }, reviewQueuePreview.length > 0 ? reviewQueuePreview.map((item) => /* @__PURE__ */ React.createElement("a", { key: item.id, href: item.urls?.edit, className: "rounded-[24px] border border-white/10 bg-black/20 p-4 transition hover:border-white/20" }, /* @__PURE__ */ React.createElement("div", { className: "text-sm font-semibold text-white" }, item.title), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-xs uppercase tracking-[0.16em] text-slate-500" }, item.group_review_status))) : /* @__PURE__ */ React.createElement(EmptyCard, { title: "No pending reviews", description: "Contributor submissions will appear here when they are sent for review." }))), /* @__PURE__ */ React.createElement("section", { className: "rounded-[28px] border border-white/10 bg-white/[0.03] p-5" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("h2", { className: "text-xl font-semibold text-white" }, "Recent posts"), /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-sm text-slate-400" }, "Announcements and updates published from the group.")), group?.urls?.studio_posts ? /* @__PURE__ */ React.createElement("a", { href: group.urls.studio_posts, className: "text-sm font-semibold text-sky-200" }, "Manage posts") : null), /* @__PURE__ */ React.createElement("div", { className: "mt-4 grid gap-3 md:grid-cols-2" }, recentPosts.length > 0 ? recentPosts.map((post2) => /* @__PURE__ */ React.createElement("a", { key: post2.id, href: post2.url, className: "rounded-[24px] border border-white/10 bg-black/20 p-4 transition hover:border-white/20" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, post2.type), /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-base font-semibold text-white" }, post2.title), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm text-slate-400" }, post2.excerpt || "Open post"))) : /* @__PURE__ */ React.createElement(EmptyCard, { title: "No posts yet", description: "Create the first group announcement to add a public news feed." })))), /* @__PURE__ */ React.createElement("section", { className: "mt-6 rounded-[28px] border border-white/10 bg-white/[0.03] p-5" }, /* @__PURE__ */ React.createElement("h2", { className: "text-xl font-semibold text-white" }, "Recent history"), /* @__PURE__ */ React.createElement("div", { className: "mt-4 grid gap-3 md:grid-cols-2 xl:grid-cols-3" }, recentHistory.length > 0 ? recentHistory.map((item) => /* @__PURE__ */ React.createElement("div", { key: item.id, className: "rounded-[24px] border border-white/10 bg-black/20 p-4" }, /* @__PURE__ */ React.createElement("div", { className: "text-sm font-semibold text-white" }, item.summary || item.action_type), /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-xs text-slate-400" }, item.actor?.name || item.actor?.username || "System", " • ", item.created_at ? new Date(item.created_at).toLocaleString() : "Recently"))) : /* @__PURE__ */ React.createElement(EmptyCard, { title: "No history yet", description: "Audit events will appear here as members review requests, posts, and submissions." })))); } -const __vite_glob_0_126 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ +const __vite_glob_0_108 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ __proto__: null, default: StudioGroupDashboard }, Symbol.toStringTag, { value: "Module" })); @@ -94526,7 +96514,7 @@ function StudioGroupEventEditor() { form.post(props.publishUrl, { preserveScroll: true }); }, className: "rounded-[28px] border border-white/10 bg-white/[0.03] p-6" }, /* @__PURE__ */ React.createElement("button", { type: "submit", className: "rounded-full border border-white/10 bg-white/[0.05] px-5 py-2.5 text-sm font-semibold text-white" }, "Publish event")) : null)); } -const __vite_glob_0_127 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ +const __vite_glob_0_109 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ __proto__: null, default: StudioGroupEventEditor }, Symbol.toStringTag, { value: "Module" })); @@ -94535,7 +96523,7 @@ function StudioGroupEvents() { const items = Array.isArray(props.listing?.items) ? props.listing.items : []; return /* @__PURE__ */ React.createElement(StudioLayout, { title: props.title, subtitle: props.description }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", { className: "text-sm text-slate-400" }, "Events let the group announce launches, sessions, milestones, and time-based updates."), props.createUrl ? /* @__PURE__ */ React.createElement("a", { href: props.createUrl, className: "rounded-full border border-white/10 bg-white/[0.04] px-4 py-2 text-sm font-semibold text-white" }, "Create event") : null), /* @__PURE__ */ React.createElement("div", { className: "mt-6 grid gap-4 lg:grid-cols-2" }, items.length > 0 ? items.map((event) => /* @__PURE__ */ React.createElement("a", { key: event.id, href: event.urls?.edit || event.url, className: "rounded-[24px] border border-white/10 bg-white/[0.03] p-5 transition hover:border-white/20" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("h2", { className: "text-xl font-semibold text-white" }, event.title), /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-300" }, event.status)), /* @__PURE__ */ React.createElement("p", { className: "mt-3 text-sm leading-6 text-slate-400" }, event.summary || "Event page"), /* @__PURE__ */ React.createElement("div", { className: "mt-4 text-xs text-slate-500" }, event.start_at ? new Date(event.start_at).toLocaleString() : "Unscheduled", " • ", event.event_type))) : /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-dashed border-white/10 bg-white/[0.02] p-6 text-sm text-slate-400" }, "No events yet."))); } -const __vite_glob_0_128 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ +const __vite_glob_0_110 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ __proto__: null, default: StudioGroupEvents }, Symbol.toStringTag, { value: "Module" })); @@ -94562,7 +96550,7 @@ function StudioGroupInvitations() { ); return /* @__PURE__ */ React.createElement(StudioLayout, { title: props.title, subtitle: props.description }, /* @__PURE__ */ React.createElement("section", { className: "mb-6 rounded-[28px] border border-white/10 bg-white/[0.03] p-5" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-start justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-sky-200/75" }, "Group invitations"), /* @__PURE__ */ React.createElement("h2", { className: "mt-2 text-xl font-semibold text-white" }, "Invite collaborators into ", props.studioGroup?.name), /* @__PURE__ */ React.createElement("p", { className: "mt-2 max-w-2xl text-sm leading-6 text-slate-300" }, "Pending invites stay separate from active members here, so owners and admins can review who was invited, when the invite expires, and revoke access before acceptance.")), /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-2" }, /* @__PURE__ */ React.createElement(xe, { href: props.studioGroup?.urls?.studio_members, className: "rounded-full border border-white/10 bg-white/[0.04] px-4 py-2 text-sm font-semibold text-white" }, "Members"), /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-sky-300/20 bg-sky-300/10 px-4 py-2 text-sm font-semibold text-sky-100" }, pendingInvites.length, " pending"))), /* @__PURE__ */ React.createElement("div", { className: "mt-5 grid gap-3 md:grid-cols-[1.1fr_0.8fr_1fr_0.7fr_auto]" }, /* @__PURE__ */ React.createElement("input", { value: invite.username, onChange: (event) => setInvite((current) => ({ ...current, username: event.target.value })), placeholder: "Username", className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white outline-none" }), /* @__PURE__ */ React.createElement(NovaSelect, { value: invite.role, onChange: (val) => setInvite((current) => ({ ...current, role: val })), searchable: false, options: [{ value: "contributor", label: "Contributor" }, { value: "editor", label: "Editor" }, { value: "admin", label: "Admin" }] }), /* @__PURE__ */ React.createElement("input", { value: invite.note, onChange: (event) => setInvite((current) => ({ ...current, note: event.target.value })), placeholder: "Optional note", className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white outline-none" }), /* @__PURE__ */ React.createElement("input", { value: invite.expires_in_days, onChange: (event) => setInvite((current) => ({ ...current, expires_in_days: event.target.value })), type: "number", min: "1", max: "30", className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white outline-none" }), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => At.post(props.endpoints?.invite, { ...invite, expires_in_days: Number(invite.expires_in_days || 7) || 7 }), className: "rounded-full border border-sky-300/20 bg-sky-300/10 px-4 py-2 text-sm font-semibold text-sky-100" }, "Send invite"))), /* @__PURE__ */ React.createElement("div", { className: "grid gap-6 xl:grid-cols-[minmax(0,1.15fr)_minmax(0,0.85fr)]" }, /* @__PURE__ */ React.createElement("section", { className: "rounded-[28px] border border-white/10 bg-white/[0.03] p-5" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("h2", { className: "text-lg font-semibold text-white" }, "Pending invitations"), /* @__PURE__ */ React.createElement("span", { className: "text-sm text-slate-400" }, pendingInvites.length, " outstanding")), /* @__PURE__ */ React.createElement("div", { className: "mt-4 space-y-3" }, pendingInvites.length > 0 ? pendingInvites.map((inviteRow) => /* @__PURE__ */ React.createElement("article", { key: inviteRow.id, className: "rounded-[24px] border border-white/10 bg-black/20 p-4" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-col gap-4 md:flex-row md:items-center" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-3" }, inviteRow.user?.avatar_url ? /* @__PURE__ */ React.createElement("img", { src: inviteRow.user.avatar_url, alt: inviteRow.user.name || inviteRow.user.username, className: "h-12 w-12 rounded-2xl object-cover" }) : /* @__PURE__ */ React.createElement("div", { className: "flex h-12 w-12 items-center justify-center rounded-2xl border border-white/10 bg-white/[0.03] text-slate-400" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-user" })), /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "font-semibold text-white" }, inviteRow.user?.name || inviteRow.user?.username), /* @__PURE__ */ React.createElement("div", { className: "text-xs uppercase tracking-[0.16em] text-slate-400" }, inviteRow.role_label || inviteRow.role))), /* @__PURE__ */ React.createElement("div", { className: "md:ml-auto flex flex-wrap items-center gap-3 text-xs text-slate-400" }, inviteRow.invited_by ? /* @__PURE__ */ React.createElement("span", null, "Invited by ", inviteRow.invited_by.name || inviteRow.invited_by.username) : null, inviteRow.invited_at ? /* @__PURE__ */ React.createElement("span", null, "Sent ", formatInviteTimestamp(inviteRow.invited_at)) : null, inviteRow.expires_at ? /* @__PURE__ */ React.createElement("span", null, "Expires ", formatInviteTimestamp(inviteRow.expires_at)) : null)), inviteRow.note ? /* @__PURE__ */ React.createElement("p", { className: "mt-3 text-sm text-slate-300" }, inviteRow.note) : null, /* @__PURE__ */ React.createElement("div", { className: "mt-4 flex flex-wrap gap-2" }, inviteRow.can_revoke && inviteRow.revoke_url ? /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => At.delete(inviteRow.revoke_url), className: "rounded-full border border-rose-300/20 bg-rose-400/10 px-3 py-2 text-sm font-semibold text-rose-100" }, "Revoke invite") : null))) : /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-dashed border-white/10 px-6 py-12 text-center text-slate-400" }, "No pending invites for this group."))), /* @__PURE__ */ React.createElement("div", { className: "space-y-6" }, /* @__PURE__ */ React.createElement("section", { className: "rounded-[28px] border border-white/10 bg-white/[0.03] p-5" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("h2", { className: "text-lg font-semibold text-white" }, "Recent invite history"), /* @__PURE__ */ React.createElement("span", { className: "text-sm text-slate-400" }, revokedInvites.length, " revoked or expired")), /* @__PURE__ */ React.createElement("div", { className: "mt-4 space-y-3" }, revokedInvites.length > 0 ? revokedInvites.map((inviteRow) => /* @__PURE__ */ React.createElement("article", { key: inviteRow.id, className: "rounded-2xl border border-white/10 bg-black/20 p-4" }, /* @__PURE__ */ React.createElement("div", { className: "font-semibold text-white" }, inviteRow.user?.name || inviteRow.user?.username), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-xs uppercase tracking-[0.16em] text-slate-400" }, inviteRow.is_expired ? "Expired" : "Revoked", " • ", inviteRow.role_label || inviteRow.role), inviteRow.invited_at ? /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm text-slate-400" }, "Originally sent ", formatInviteTimestamp(inviteRow.invited_at)) : null)) : /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-dashed border-white/10 px-4 py-8 text-center text-slate-400" }, "No recent invite history yet."))), /* @__PURE__ */ React.createElement("section", { className: "rounded-[28px] border border-white/10 bg-white/[0.03] p-5" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("h2", { className: "text-lg font-semibold text-white" }, "Active members"), /* @__PURE__ */ React.createElement("span", { className: "text-sm text-slate-400" }, activeMembers.length, " active")), /* @__PURE__ */ React.createElement("div", { className: "mt-4 space-y-3" }, activeMembers.slice(0, 6).map((member) => /* @__PURE__ */ React.createElement("div", { key: member.id, className: "flex items-center gap-3 rounded-2xl border border-white/10 bg-black/20 px-4 py-3" }, member.user?.avatar_url ? /* @__PURE__ */ React.createElement("img", { src: member.user.avatar_url, alt: member.user.name || member.user.username, className: "h-11 w-11 rounded-2xl object-cover" }) : /* @__PURE__ */ React.createElement("div", { className: "flex h-11 w-11 items-center justify-center rounded-2xl border border-white/10 bg-white/[0.03] text-slate-400" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-user" })), /* @__PURE__ */ React.createElement("div", { className: "min-w-0 flex-1" }, /* @__PURE__ */ React.createElement("div", { className: "truncate font-semibold text-white" }, member.user?.name || member.user?.username), /* @__PURE__ */ React.createElement("div", { className: "text-xs uppercase tracking-[0.16em] text-slate-400" }, member.role_label || member.role))))))))); } -const __vite_glob_0_129 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ +const __vite_glob_0_111 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ __proto__: null, default: StudioGroupInvitations }, Symbol.toStringTag, { value: "Module" })); @@ -94591,7 +96579,7 @@ function routeUrl(baseUrl, id, action) { if (!baseUrl) return ""; return `${String(baseUrl).replace(/\/$/, "")}/${id}/${action}`; } -const __vite_glob_0_130 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ +const __vite_glob_0_112 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ __proto__: null, default: StudioGroupJoinRequests }, Symbol.toStringTag, { value: "Module" })); @@ -94658,7 +96646,7 @@ function StudioGroupMembers() { return /* @__PURE__ */ React.createElement("div", { key: option.value, className: "rounded-2xl border border-white/10 bg-white/[0.03] p-3" }, /* @__PURE__ */ React.createElement("div", { className: "text-sm font-semibold text-white" }, option.label), /* @__PURE__ */ React.createElement("div", { className: "mt-3 flex flex-wrap gap-2" }, /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => setPermissionState(member.id, option.value, "inherit"), className: `rounded-full border px-3 py-1.5 text-xs font-semibold ${current === "inherit" ? "border-white/20 bg-white/[0.08] text-white" : "border-white/10 bg-transparent text-slate-300"}` }, "Inherit"), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => setPermissionState(member.id, option.value, "allow"), className: `rounded-full border px-3 py-1.5 text-xs font-semibold ${current === "allow" ? "border-emerald-300/20 bg-emerald-400/10 text-emerald-100" : "border-white/10 bg-transparent text-slate-300"}` }, "Allow"), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => setPermissionState(member.id, option.value, "deny"), className: `rounded-full border px-3 py-1.5 text-xs font-semibold ${current === "deny" ? "border-rose-300/20 bg-rose-400/10 text-rose-100" : "border-white/10 bg-transparent text-slate-300"}` }, "Deny"))); }))) : null)), filteredMembers.length === 0 ? /* @__PURE__ */ React.createElement("div", { className: "px-4 py-8 text-sm text-slate-400" }, "No members match the current search.") : null)))); } -const __vite_glob_0_131 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ +const __vite_glob_0_113 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ __proto__: null, default: StudioGroupMembers }, Symbol.toStringTag, { value: "Module" })); @@ -94682,7 +96670,7 @@ function StudioGroupPostEditor() { }; return /* @__PURE__ */ React.createElement(StudioLayout, { title: props.title, subtitle: props.description }, /* @__PURE__ */ React.createElement("form", { onSubmit: submit, className: "grid gap-6 xl:grid-cols-[minmax(0,1.1fr)_minmax(0,0.9fr)]" }, /* @__PURE__ */ React.createElement("section", { className: "rounded-[28px] border border-white/10 bg-white/[0.03] p-5" }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-4" }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Type"), /* @__PURE__ */ React.createElement(NovaSelect, { value: form.data.type, onChange: (val) => form.setData("type", val), options: Array.isArray(props.typeOptions) ? props.typeOptions : [], searchable: false })), /* @__PURE__ */ React.createElement("label", { className: "grid gap-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Title"), /* @__PURE__ */ React.createElement("input", { value: form.data.title, onChange: (event) => form.setData("title", event.target.value), className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white outline-none" })), /* @__PURE__ */ React.createElement("label", { className: "grid gap-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Excerpt"), /* @__PURE__ */ React.createElement("textarea", { value: form.data.excerpt, onChange: (event) => form.setData("excerpt", event.target.value), rows: 3, className: "rounded-[24px] border border-white/10 bg-black/20 px-4 py-3 text-white outline-none" })), /* @__PURE__ */ React.createElement("label", { className: "grid gap-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Content"), /* @__PURE__ */ React.createElement("textarea", { value: form.data.content, onChange: (event) => form.setData("content", event.target.value), rows: 12, className: "rounded-[24px] border border-white/10 bg-black/20 px-4 py-3 text-white outline-none" })))), /* @__PURE__ */ React.createElement("section", { className: "rounded-[28px] border border-white/10 bg-white/[0.03] p-5" }, /* @__PURE__ */ React.createElement("h2", { className: "text-xl font-semibold text-white" }, "Post controls"), /* @__PURE__ */ React.createElement("div", { className: "mt-5 space-y-3" }, /* @__PURE__ */ React.createElement("button", { type: "submit", disabled: form.processing, className: "w-full rounded-full border border-sky-300/20 bg-sky-300/10 px-4 py-3 text-sm font-semibold text-sky-100 disabled:opacity-60" }, "Save"), props.publishUrl ? /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => At.post(props.publishUrl), className: "w-full rounded-full border border-emerald-300/20 bg-emerald-400/10 px-4 py-3 text-sm font-semibold text-emerald-100" }, "Publish") : null, props.pinUrl ? /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => At.post(props.pinUrl), className: "w-full rounded-full border border-amber-300/20 bg-amber-400/10 px-4 py-3 text-sm font-semibold text-amber-100" }, "Toggle pinned") : null, props.archiveUrl ? /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => At.post(props.archiveUrl), className: "w-full rounded-full border border-rose-300/20 bg-rose-400/10 px-4 py-3 text-sm font-semibold text-rose-100" }, "Archive") : null)))); } -const __vite_glob_0_132 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ +const __vite_glob_0_114 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ __proto__: null, default: StudioGroupPostEditor }, Symbol.toStringTag, { value: "Module" })); @@ -94691,7 +96679,7 @@ function StudioGroupPosts() { const items = Array.isArray(props.listing?.items) ? props.listing.items : []; return /* @__PURE__ */ React.createElement(StudioLayout, { title: props.title, subtitle: props.description }, /* @__PURE__ */ React.createElement("section", { className: "rounded-[28px] border border-white/10 bg-white/[0.03] p-5" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("h2", { className: "text-xl font-semibold text-white" }, "Post library"), /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-sm text-slate-400" }, "Draft, publish, pin, and archive public group posts.")), props.createUrl ? /* @__PURE__ */ React.createElement("a", { href: props.createUrl, className: "rounded-full border border-sky-300/20 bg-sky-300/10 px-4 py-2 text-sm font-semibold text-sky-100" }, "New post") : null), /* @__PURE__ */ React.createElement("div", { className: "mt-5 grid gap-4 md:grid-cols-2" }, items.length > 0 ? items.map((item) => /* @__PURE__ */ React.createElement("article", { key: item.id, className: "rounded-[24px] border border-white/10 bg-black/20 p-4" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-start justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, item.type), /* @__PURE__ */ React.createElement("h3", { className: "mt-2 text-lg font-semibold text-white" }, item.title)), /* @__PURE__ */ React.createElement("div", { className: "flex flex-col items-end gap-2" }, /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-1 text-xs font-semibold uppercase tracking-[0.16em] text-slate-300" }, item.status), item.is_pinned ? /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-amber-300/20 bg-amber-400/10 px-3 py-1 text-xs font-semibold uppercase tracking-[0.16em] text-amber-100" }, "Pinned") : null)), /* @__PURE__ */ React.createElement("p", { className: "mt-3 text-sm leading-6 text-slate-300" }, item.excerpt || item.content || "No excerpt yet."), /* @__PURE__ */ React.createElement("div", { className: "mt-4 flex flex-wrap gap-2" }, /* @__PURE__ */ React.createElement("a", { href: item.urls?.edit, className: "rounded-full border border-white/10 bg-white/[0.04] px-4 py-2 text-sm font-semibold text-white" }, "Edit"), item.urls?.public ? /* @__PURE__ */ React.createElement("a", { href: item.urls.public, className: "rounded-full border border-white/10 bg-white/[0.04] px-4 py-2 text-sm font-semibold text-white" }, "View") : null))) : /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-dashed border-white/10 bg-white/[0.02] p-5 text-sm text-slate-400" }, "No posts yet.")))); } -const __vite_glob_0_133 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ +const __vite_glob_0_115 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ __proto__: null, default: StudioGroupPosts }, Symbol.toStringTag, { value: "Module" })); @@ -94740,7 +96728,7 @@ function StudioGroupProjectEditor() { milestoneForm.post(props.storeMilestoneUrl, { preserveScroll: true, onSuccess: () => milestoneForm.reset("title", "summary", "due_date", "owner_user_id", "notes") }); }, className: "rounded-[28px] border border-white/10 bg-white/[0.03] p-6" }, /* @__PURE__ */ React.createElement("h2", { className: "text-lg font-semibold text-white" }, "Milestones"), /* @__PURE__ */ React.createElement("div", { className: "mt-4 space-y-3" }, /* @__PURE__ */ React.createElement("input", { value: milestoneForm.data.title, onChange: (event) => milestoneForm.setData("title", event.target.value), placeholder: "Milestone title", className: "w-full rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white outline-none" }), /* @__PURE__ */ React.createElement("textarea", { value: milestoneForm.data.summary, onChange: (event) => milestoneForm.setData("summary", event.target.value), placeholder: "Summary", rows: 3, className: "w-full rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white outline-none" }), /* @__PURE__ */ React.createElement("div", { className: "grid gap-3 md:grid-cols-2" }, /* @__PURE__ */ React.createElement(NovaSelect, { value: milestoneForm.data.status, onChange: (val) => milestoneForm.setData("status", val), searchable: false, options: ["pending", "active", "blocked", "completed", "cancelled"].map((s2) => ({ value: s2, label: s2 })) }), /* @__PURE__ */ React.createElement(DateTimePicker, { value: milestoneForm.data.due_date, onChange: (nextValue) => milestoneForm.setData("due_date", nextValue), mode: "date", placeholder: "Due date", clearable: true, className: "bg-black/20" })), /* @__PURE__ */ React.createElement(NovaSelect, { value: String(milestoneForm.data.owner_user_id || ""), onChange: (val) => milestoneForm.setData("owner_user_id", val), placeholder: "No owner", options: (props.memberOptions || []).map((o) => ({ value: String(o.id), label: o.name || o.username })) }), /* @__PURE__ */ React.createElement("textarea", { value: milestoneForm.data.notes, onChange: (event) => milestoneForm.setData("notes", event.target.value), placeholder: "Notes", rows: 3, className: "w-full rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white outline-none" }), /* @__PURE__ */ React.createElement("button", { type: "submit", className: "rounded-full border border-white/10 bg-white/[0.05] px-4 py-2 text-sm font-semibold text-white" }, "Add milestone")), Array.isArray(project?.milestones) && project.milestones.length > 0 ? /* @__PURE__ */ React.createElement("div", { className: "mt-6 space-y-3" }, project.milestones.map((milestone) => /* @__PURE__ */ React.createElement("div", { key: milestone.id, className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-4" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "font-semibold text-white" }, milestone.title), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-xs text-slate-500" }, milestone.owner?.name || milestone.owner?.username || "No owner", milestone.due_date ? ` • due ${milestone.due_date}` : "")), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => At.patch(props.updateMilestonePattern.replace("__MILESTONE__", String(milestone.id)), { title: milestone.title, summary: milestone.summary || "", status: milestone.status === "completed" ? "active" : "completed", due_date: milestone.due_date || "", owner_user_id: milestone.owner?.id || "", notes: milestone.notes || "" }, { preserveScroll: true }), className: "rounded-full border border-white/10 bg-white/[0.05] px-3 py-1 text-xs font-semibold text-white" }, "Mark ", milestone.status === "completed" ? "active" : "complete")), milestone.summary ? /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm text-slate-400" }, milestone.summary) : null))) : null) : null))); } -const __vite_glob_0_134 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ +const __vite_glob_0_116 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ __proto__: null, default: StudioGroupProjectEditor }, Symbol.toStringTag, { value: "Module" })); @@ -94750,7 +96738,7 @@ function StudioGroupProjects() { const items = Array.isArray(listing.items) ? listing.items : []; return /* @__PURE__ */ React.createElement(StudioLayout, { title: props.title, subtitle: props.description }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", { className: "text-sm text-slate-400" }, "Projects give the group a structured place for releases, teams, and linked outputs."), props.createUrl ? /* @__PURE__ */ React.createElement("a", { href: props.createUrl, className: "rounded-full border border-white/10 bg-white/[0.04] px-4 py-2 text-sm font-semibold text-white" }, "Create project") : null), /* @__PURE__ */ React.createElement("div", { className: "mt-6 grid gap-4 lg:grid-cols-2" }, items.length > 0 ? items.map((project) => /* @__PURE__ */ React.createElement("a", { key: project.id, href: project.urls?.edit || project.url, className: "rounded-[24px] border border-white/10 bg-white/[0.03] p-5 transition hover:border-white/20" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("h2", { className: "text-xl font-semibold text-white" }, project.title), /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-300" }, project.status)), /* @__PURE__ */ React.createElement("p", { className: "mt-3 text-sm leading-6 text-slate-400" }, project.summary || "Project page"), /* @__PURE__ */ React.createElement("div", { className: "mt-4 text-xs text-slate-500" }, project.counts?.artworks || 0, " artworks • ", project.counts?.assets || 0, " assets • ", project.counts?.team || 0, " team • ", project.counts?.milestones || 0, " milestones • ", project.counts?.releases || 0, " releases"))) : /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-dashed border-white/10 bg-white/[0.02] p-6 text-sm text-slate-400" }, "No projects yet."))); } -const __vite_glob_0_135 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ +const __vite_glob_0_117 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ __proto__: null, default: StudioGroupProjects }, Symbol.toStringTag, { value: "Module" })); @@ -94781,7 +96769,7 @@ function StudioGroupRecruitment() { return /* @__PURE__ */ React.createElement("button", { key: option.value, type: "button", onClick: () => form.setData("skills_json", toggleItem(form.data.skills_json, option.value)), className: `rounded-full border px-3 py-1.5 text-xs font-semibold ${selected ? "border-sky-300/20 bg-sky-300/10 text-sky-100" : "border-white/10 bg-white/[0.03] text-slate-300"}` }, option.label); }))))), /* @__PURE__ */ React.createElement("section", { className: "rounded-[28px] border border-white/10 bg-white/[0.03] p-5" }, /* @__PURE__ */ React.createElement("h2", { className: "text-xl font-semibold text-white" }, "Application settings"), /* @__PURE__ */ React.createElement("div", { className: "mt-5 grid gap-4" }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Contact mode"), /* @__PURE__ */ React.createElement(NovaSelect, { value: form.data.contact_mode, onChange: (val) => form.setData("contact_mode", val), options: Array.isArray(props.contactModes) ? props.contactModes : [], searchable: false })), /* @__PURE__ */ React.createElement("div", { className: "grid gap-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Visibility"), /* @__PURE__ */ React.createElement(NovaSelect, { value: form.data.visibility, onChange: (val) => form.setData("visibility", val), options: Array.isArray(props.visibilityOptions) ? props.visibilityOptions : [], searchable: false })), /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-black/20 p-4 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("p", { className: "font-semibold text-white" }, "Public preview"), /* @__PURE__ */ React.createElement("p", { className: "mt-2" }, form.data.headline || "No headline yet."), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-slate-400" }, form.data.description || "Recruitment copy will show here once you add it."), form.data.roles_json.length > 0 ? /* @__PURE__ */ React.createElement("div", { className: "mt-3 flex flex-wrap gap-2" }, form.data.roles_json.map((role) => /* @__PURE__ */ React.createElement("span", { key: role, className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-1 text-xs font-semibold text-white" }, role))) : null), /* @__PURE__ */ React.createElement("button", { type: "submit", disabled: form.processing, className: "rounded-full border border-sky-300/20 bg-sky-300/10 px-4 py-3 text-sm font-semibold text-sky-100 disabled:opacity-60" }, "Save recruitment profile"))))); } -const __vite_glob_0_136 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ +const __vite_glob_0_118 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ __proto__: null, default: StudioGroupRecruitment }, Symbol.toStringTag, { value: "Module" })); @@ -94834,7 +96822,7 @@ function StudioGroupReleaseEditor() { milestoneForm.post(props.storeMilestoneUrl, { preserveScroll: true, onSuccess: () => milestoneForm.reset("title", "summary", "due_date", "owner_user_id", "notes") }); }, className: "rounded-[28px] border border-white/10 bg-white/[0.03] p-6" }, /* @__PURE__ */ React.createElement("h2", { className: "text-lg font-semibold text-white" }, "Milestones"), /* @__PURE__ */ React.createElement("div", { className: "mt-4 space-y-3" }, /* @__PURE__ */ React.createElement("input", { value: milestoneForm.data.title, onChange: (event) => milestoneForm.setData("title", event.target.value), placeholder: "Milestone title", className: "w-full rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white outline-none" }), /* @__PURE__ */ React.createElement("textarea", { value: milestoneForm.data.summary, onChange: (event) => milestoneForm.setData("summary", event.target.value), placeholder: "Summary", rows: 3, className: "w-full rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white outline-none" }), /* @__PURE__ */ React.createElement("div", { className: "grid gap-3 md:grid-cols-2" }, /* @__PURE__ */ React.createElement(NovaSelect, { value: milestoneForm.data.status, onChange: (val) => milestoneForm.setData("status", val), searchable: false, options: ["pending", "active", "blocked", "completed", "cancelled"].map((s2) => ({ value: s2, label: s2 })) }), /* @__PURE__ */ React.createElement(DateTimePicker, { value: milestoneForm.data.due_date, onChange: (nextValue) => milestoneForm.setData("due_date", nextValue), mode: "date", placeholder: "Due date", clearable: true, className: "bg-black/20" })), /* @__PURE__ */ React.createElement(NovaSelect, { value: String(milestoneForm.data.owner_user_id || ""), onChange: (val) => milestoneForm.setData("owner_user_id", val), placeholder: "No owner", options: (props.memberOptions || []).map((o) => ({ value: String(o.id), label: o.name || o.username })) }), /* @__PURE__ */ React.createElement("textarea", { value: milestoneForm.data.notes, onChange: (event) => milestoneForm.setData("notes", event.target.value), placeholder: "Notes", rows: 3, className: "w-full rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white outline-none" }), /* @__PURE__ */ React.createElement("button", { type: "submit", className: "rounded-full border border-white/10 bg-white/[0.05] px-4 py-2 text-sm font-semibold text-white" }, "Add milestone")), Array.isArray(release?.milestones) && release.milestones.length > 0 ? /* @__PURE__ */ React.createElement("div", { className: "mt-6 space-y-3" }, release.milestones.map((milestone) => /* @__PURE__ */ React.createElement("div", { key: milestone.id, className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-4" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "font-semibold text-white" }, milestone.title), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-xs text-slate-500" }, milestone.owner?.name || milestone.owner?.username || "No owner", milestone.due_date ? ` • due ${milestone.due_date}` : "")), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => At.patch(props.updateMilestonePattern.replace("__MILESTONE__", String(milestone.id)), { title: milestone.title, summary: milestone.summary || "", status: milestone.status === "completed" ? "active" : "completed", due_date: milestone.due_date || "", owner_user_id: milestone.owner?.id || "", notes: milestone.notes || "" }, { preserveScroll: true }), className: "rounded-full border border-white/10 bg-white/[0.05] px-3 py-1 text-xs font-semibold text-white" }, "Mark ", milestone.status === "completed" ? "active" : "complete")), milestone.summary ? /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm text-slate-400" }, milestone.summary) : null))) : null) : null))); } -const __vite_glob_0_137 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ +const __vite_glob_0_119 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ __proto__: null, default: StudioGroupReleaseEditor }, Symbol.toStringTag, { value: "Module" })); @@ -94846,7 +96834,7 @@ function StudioGroupReleases() { const currentBucket = listing.filters?.bucket || "all"; return /* @__PURE__ */ React.createElement(StudioLayout, { title: props.title, subtitle: props.description }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-col gap-3 lg:flex-row lg:items-center lg:justify-between" }, /* @__PURE__ */ React.createElement("div", { className: "text-sm text-slate-400" }, "Track the release pipeline from draft through public launch, with milestones and contributor credits."), /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-3" }, /* @__PURE__ */ React.createElement(NovaSelect, { value: currentBucket, onChange: (val) => At.get(window.location.pathname, { bucket: val }, { preserveScroll: true, preserveState: true }), options: bucketOptions, searchable: false }), props.createUrl ? /* @__PURE__ */ React.createElement("a", { href: props.createUrl, className: "rounded-full border border-white/10 bg-white/[0.04] px-4 py-2 text-sm font-semibold text-white" }, "Create release") : null)), /* @__PURE__ */ React.createElement("div", { className: "mt-6 grid gap-4 lg:grid-cols-2" }, items.length > 0 ? items.map((release) => /* @__PURE__ */ React.createElement("div", { key: release.id, className: "overflow-hidden rounded-[24px] border border-white/10 bg-white/[0.03]" }, release.cover_url ? /* @__PURE__ */ React.createElement("img", { src: release.cover_url, alt: release.title, className: "aspect-[4/3] w-full object-cover" }) : /* @__PURE__ */ React.createElement("div", { className: "flex aspect-[4/3] items-center justify-center bg-white/[0.03] text-slate-500" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-rocket text-2xl" })), /* @__PURE__ */ React.createElement("div", { className: "p-5" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center gap-2" }, /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-300" }, release.status), /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-300" }, release.current_stage), /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-300" }, release.visibility)), /* @__PURE__ */ React.createElement("h2", { className: "mt-3 text-xl font-semibold text-white" }, release.title), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm leading-6 text-slate-400" }, release.summary || "Release page"), /* @__PURE__ */ React.createElement("div", { className: "mt-4 text-xs text-slate-500" }, release.counts?.artworks || 0, " artworks • ", release.counts?.contributors || 0, " contributors • ", release.counts?.milestones || 0, " milestones"), /* @__PURE__ */ React.createElement("div", { className: "mt-4 flex flex-wrap gap-2" }, /* @__PURE__ */ React.createElement("a", { href: release.urls?.edit || release.url, className: "rounded-full border border-white/10 bg-white/[0.04] px-4 py-2 text-sm font-semibold text-white" }, "Manage"), release.urls?.public ? /* @__PURE__ */ React.createElement("a", { href: release.urls.public, className: "rounded-full border border-white/10 bg-black/20 px-4 py-2 text-sm font-semibold text-white" }, "View public") : null)))) : /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-dashed border-white/10 bg-white/[0.02] p-6 text-sm text-slate-400" }, "No releases yet."))); } -const __vite_glob_0_138 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ +const __vite_glob_0_120 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ __proto__: null, default: StudioGroupReleases }, Symbol.toStringTag, { value: "Module" })); @@ -94863,7 +96851,7 @@ function StudioGroupReputation() { const memberBadgeUnlocks = Array.isArray(reputation.member_badge_unlocks) ? reputation.member_badge_unlocks : []; return /* @__PURE__ */ React.createElement(StudioLayout, { title: props.title, subtitle: props.description }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 md:grid-cols-2 xl:grid-cols-5" }, /* @__PURE__ */ React.createElement(MetricCard, { label: "Freshness", value: metrics.freshness_score }), /* @__PURE__ */ React.createElement(MetricCard, { label: "Activity", value: metrics.activity_score }), /* @__PURE__ */ React.createElement(MetricCard, { label: "Release", value: metrics.release_score }), /* @__PURE__ */ React.createElement(MetricCard, { label: "Trust", value: metrics.trust_score }), /* @__PURE__ */ React.createElement(MetricCard, { label: "Collaboration", value: metrics.collaboration_score })), /* @__PURE__ */ React.createElement("div", { className: "mt-6 grid gap-6 xl:grid-cols-[minmax(0,0.9fr)_minmax(0,1.1fr)]" }, /* @__PURE__ */ React.createElement("section", { className: "rounded-[28px] border border-white/10 bg-white/[0.03] p-5" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("h2", { className: "text-xl font-semibold text-white" }, "Trust signals"), /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-sm text-slate-400" }, "Public-safe labels that shape discovery and confidence."))), /* @__PURE__ */ React.createElement("div", { className: "mt-4 flex flex-wrap gap-2" }, trustSignals.map((signal) => /* @__PURE__ */ React.createElement("span", { key: signal.key, className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-2 text-sm font-semibold text-white" }, signal.label))), /* @__PURE__ */ React.createElement("div", { className: "mt-5 grid gap-3 md:grid-cols-2" }, /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-4" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Contributors"), /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-2xl font-semibold text-white" }, Number(reputation.counts?.contributors || 0))), /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-4" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Member badges"), /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-2xl font-semibold text-white" }, Number(reputation.counts?.member_badges || 0)))), metrics.last_calculated_at ? /* @__PURE__ */ React.createElement("div", { className: "mt-4 text-xs text-slate-500" }, "Last calculated ", new Date(metrics.last_calculated_at).toLocaleString()) : null), /* @__PURE__ */ React.createElement("section", { className: "rounded-[28px] border border-white/10 bg-white/[0.03] p-5" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("h2", { className: "text-xl font-semibold text-white" }, "Top contributors"), /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-sm text-slate-400" }, "Reputation summaries derived from visible collaboration history."))), /* @__PURE__ */ React.createElement("div", { className: "mt-4 space-y-3" }, topContributors.length > 0 ? topContributors.map((entry) => /* @__PURE__ */ React.createElement("div", { key: entry.user?.id, className: "rounded-[24px] border border-white/10 bg-black/20 px-4 py-4" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-3" }, entry.user?.avatar_url ? /* @__PURE__ */ React.createElement("img", { src: entry.user.avatar_url, alt: entry.user?.name || entry.user?.username, className: "h-11 w-11 rounded-2xl object-cover" }) : /* @__PURE__ */ React.createElement("div", { className: "flex h-11 w-11 items-center justify-center rounded-2xl border border-white/10 bg-white/[0.03] text-slate-400" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-user" })), /* @__PURE__ */ React.createElement("div", { className: "min-w-0 flex-1" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center gap-2" }, /* @__PURE__ */ React.createElement("div", { className: "truncate font-semibold text-white" }, entry.user?.name || entry.user?.username), entry.trusted_indicator ? /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-emerald-300/20 bg-emerald-300/10 px-2 py-1 text-[10px] font-semibold uppercase tracking-[0.16em] text-emerald-100" }, "Trusted") : null), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-sm text-slate-400" }, entry.summary || "Contributor"))), /* @__PURE__ */ React.createElement("div", { className: "mt-3 text-xs text-slate-500" }, entry.counts?.releases || 0, " releases • ", entry.counts?.projects || 0, " projects • ", entry.counts?.credited_artworks || 0, " artworks • ", entry.counts?.review_actions || 0, " reviews"), Array.isArray(entry.badges) && entry.badges.length > 0 ? /* @__PURE__ */ React.createElement("div", { className: "mt-3 flex flex-wrap gap-2" }, entry.badges.map((badge) => /* @__PURE__ */ React.createElement("span", { key: `${entry.user?.id}-${badge.key}`, className: "rounded-full border border-white/10 bg-white/[0.04] px-2.5 py-1 text-[10px] font-semibold uppercase tracking-[0.16em] text-slate-300" }, badge.label))) : null)) : /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-dashed border-white/10 bg-white/[0.02] p-6 text-sm text-slate-400" }, "No contributor reputation signals yet.")))), /* @__PURE__ */ React.createElement("div", { className: "mt-6 grid gap-6 xl:grid-cols-2" }, /* @__PURE__ */ React.createElement("section", { className: "rounded-[28px] border border-white/10 bg-white/[0.03] p-5" }, /* @__PURE__ */ React.createElement("h2", { className: "text-xl font-semibold text-white" }, "Group badges"), /* @__PURE__ */ React.createElement("div", { className: "mt-4 space-y-3" }, recentBadges.length > 0 ? recentBadges.map((badge) => /* @__PURE__ */ React.createElement("div", { key: badge.key, className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-4" }, /* @__PURE__ */ React.createElement("div", { className: "font-semibold text-white" }, badge.label), /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-sm text-slate-400" }, badge.reason))) : /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-dashed border-white/10 bg-white/[0.02] p-6 text-sm text-slate-400" }, "No group badges awarded yet."))), /* @__PURE__ */ React.createElement("section", { className: "rounded-[28px] border border-white/10 bg-white/[0.03] p-5" }, /* @__PURE__ */ React.createElement("h2", { className: "text-xl font-semibold text-white" }, "Recent member badge unlocks"), /* @__PURE__ */ React.createElement("div", { className: "mt-4 space-y-3" }, memberBadgeUnlocks.length > 0 ? memberBadgeUnlocks.map((entry) => /* @__PURE__ */ React.createElement("div", { key: `${entry.user?.id}-${entry.badge?.key}`, className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-4" }, /* @__PURE__ */ React.createElement("div", { className: "font-semibold text-white" }, entry.user?.name || entry.user?.username), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-sm text-sky-200" }, entry.badge?.label), /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-sm text-slate-400" }, entry.badge?.reason))) : /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-dashed border-white/10 bg-white/[0.02] p-6 text-sm text-slate-400" }, "No member badge unlocks yet."))))); } -const __vite_glob_0_139 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ +const __vite_glob_0_121 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ __proto__: null, default: StudioGroupReputation }, Symbol.toStringTag, { value: "Module" })); @@ -94880,7 +96868,7 @@ function StudioGroupReviewQueue() { }; return /* @__PURE__ */ React.createElement(StudioLayout, { title: props.title, subtitle: props.description }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-6 xl:grid-cols-[minmax(0,1.2fr)_minmax(0,0.8fr)]" }, /* @__PURE__ */ React.createElement("section", { className: "rounded-[28px] border border-white/10 bg-white/[0.03] p-5" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("h2", { className: "text-xl font-semibold text-white" }, "Submission queue"), /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-sm text-slate-400" }, "Review artwork drafts before they publish under the group identity.")), /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-1 text-xs font-semibold uppercase tracking-[0.16em] text-slate-300" }, listing.filters?.bucket || "submitted")), /* @__PURE__ */ React.createElement("div", { className: "mt-4 space-y-4" }, items.length > 0 ? items.map((item) => /* @__PURE__ */ React.createElement("article", { key: item.id, className: "rounded-[24px] border border-white/10 bg-black/20 p-4" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-start gap-4" }, item.thumb ? /* @__PURE__ */ React.createElement("img", { src: item.thumb, alt: item.title, className: "h-24 w-24 rounded-2xl object-cover" }) : /* @__PURE__ */ React.createElement("div", { className: "flex h-24 w-24 items-center justify-center rounded-2xl border border-white/10 bg-white/[0.03] text-slate-400" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-image" })), /* @__PURE__ */ React.createElement("div", { className: "min-w-0 flex-1" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("h3", { className: "text-lg font-semibold text-white" }, item.title), /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-1 text-xs font-semibold uppercase tracking-[0.16em] text-slate-300" }, item.group_review_status)), /* @__PURE__ */ React.createElement("div", { className: "mt-2 flex flex-wrap gap-3 text-xs text-slate-400" }, item.primary_author ? /* @__PURE__ */ React.createElement("span", null, "Author: ", item.primary_author.name || item.primary_author.username) : null, item.uploader ? /* @__PURE__ */ React.createElement("span", null, "Uploader: ", item.uploader.name || item.uploader.username) : null, item.submitted_at ? /* @__PURE__ */ React.createElement("span", null, "Submitted ", new Date(item.submitted_at).toLocaleString()) : null), item.group_review_notes ? /* @__PURE__ */ React.createElement("p", { className: "mt-3 rounded-2xl border border-white/10 bg-white/[0.03] px-3 py-2 text-sm text-slate-300" }, item.group_review_notes) : null, /* @__PURE__ */ React.createElement("div", { className: "mt-4 flex flex-wrap gap-2" }, /* @__PURE__ */ React.createElement("a", { href: item.urls?.edit, className: "rounded-full border border-white/10 bg-white/[0.04] px-4 py-2 text-sm font-semibold text-white" }, "Open draft"), item.can_review ? /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => sendAction(item, "approve"), className: "rounded-full border border-emerald-300/20 bg-emerald-400/10 px-4 py-2 text-sm font-semibold text-emerald-100" }, "Approve") : null, item.can_review ? /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => sendAction(item, "needs_changes"), className: "rounded-full border border-amber-300/20 bg-amber-400/10 px-4 py-2 text-sm font-semibold text-amber-100" }, "Needs changes") : null, item.can_review ? /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => sendAction(item, "reject"), className: "rounded-full border border-rose-300/20 bg-rose-400/10 px-4 py-2 text-sm font-semibold text-rose-100" }, "Reject") : null))))) : /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-dashed border-white/10 bg-white/[0.02] p-5 text-sm text-slate-400" }, "No submissions in this bucket."))), /* @__PURE__ */ React.createElement("section", { className: "rounded-[28px] border border-white/10 bg-white/[0.03] p-5" }, /* @__PURE__ */ React.createElement("h2", { className: "text-xl font-semibold text-white" }, "Recent history"), /* @__PURE__ */ React.createElement("div", { className: "mt-4 space-y-3" }, (Array.isArray(props.recentHistory) ? props.recentHistory : []).map((item) => /* @__PURE__ */ React.createElement("div", { key: item.id, className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3" }, /* @__PURE__ */ React.createElement("div", { className: "text-sm font-semibold text-white" }, item.summary || item.action_type), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-xs text-slate-400" }, item.actor?.name || item.actor?.username || "System", " • ", item.created_at ? new Date(item.created_at).toLocaleString() : "Recently"))))))); } -const __vite_glob_0_140 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ +const __vite_glob_0_122 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ __proto__: null, default: StudioGroupReviewQueue }, Symbol.toStringTag, { value: "Module" })); @@ -94973,7 +96961,7 @@ function StudioGroupSettings() { }; return /* @__PURE__ */ React.createElement(StudioLayout, { title: props.title, subtitle: props.description }, /* @__PURE__ */ React.createElement("section", { className: "mx-auto max-w-3xl rounded-[30px] border border-white/10 bg-white/[0.03] p-6" }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-5" }, /* @__PURE__ */ React.createElement("label", { className: "grid gap-2 text-sm text-slate-200" }, /* @__PURE__ */ React.createElement("span", null, "Name"), /* @__PURE__ */ React.createElement("input", { value: form.name, onChange: (event) => setForm((current) => ({ ...current, name: event.target.value })), className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white outline-none" })), /* @__PURE__ */ React.createElement("label", { className: "grid gap-2 text-sm text-slate-200" }, /* @__PURE__ */ React.createElement("span", null, "Slug"), /* @__PURE__ */ React.createElement("input", { value: form.slug, onChange: (event) => setForm((current) => ({ ...current, slug: event.target.value })), className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white outline-none" })), /* @__PURE__ */ React.createElement("label", { className: "grid gap-2 text-sm text-slate-200" }, /* @__PURE__ */ React.createElement("span", null, "Short description"), /* @__PURE__ */ React.createElement("input", { value: form.headline, onChange: (event) => setForm((current) => ({ ...current, headline: event.target.value })), className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white outline-none" })), /* @__PURE__ */ React.createElement("label", { className: "grid gap-2 text-sm text-slate-200" }, /* @__PURE__ */ React.createElement("span", null, "About"), /* @__PURE__ */ React.createElement("textarea", { value: form.bio, onChange: (event) => setForm((current) => ({ ...current, bio: event.target.value })), rows: 6, className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white outline-none" })), /* @__PURE__ */ React.createElement("div", { className: "grid gap-5 md:grid-cols-2" }, /* @__PURE__ */ React.createElement("label", { className: "grid gap-2 text-sm text-slate-200" }, /* @__PURE__ */ React.createElement("span", null, "Type / category"), /* @__PURE__ */ React.createElement("input", { value: form.type, onChange: (event) => setForm((current) => ({ ...current, type: event.target.value })), className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white outline-none" })), /* @__PURE__ */ React.createElement("div", { className: "grid gap-2 text-sm text-slate-200" }, /* @__PURE__ */ React.createElement("span", null, "Founded date"), /* @__PURE__ */ React.createElement(DateTimePicker, { value: form.founded_at, onChange: (nextValue) => setForm((current) => ({ ...current, founded_at: nextValue })), mode: "date", placeholder: "Pick the founding date", clearable: true, className: "bg-black/20" }))), /* @__PURE__ */ React.createElement("label", { className: "grid gap-2 text-sm text-slate-200" }, /* @__PURE__ */ React.createElement("span", null, "Website"), /* @__PURE__ */ React.createElement("input", { value: form.website_url, onChange: (event) => setForm((current) => ({ ...current, website_url: event.target.value })), className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white outline-none" })), /* @__PURE__ */ React.createElement("div", { className: "grid gap-5 md:grid-cols-2" }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-3 rounded-[24px] border border-white/10 bg-black/20 p-4 text-sm text-slate-200" }, /* @__PURE__ */ React.createElement("span", { className: "text-sm font-semibold text-white" }, "Avatar / logo"), /* @__PURE__ */ React.createElement("div", { className: "flex h-28 w-28 items-center justify-center overflow-hidden rounded-[24px] border border-white/10 bg-white/[0.04]" }, resolvedAvatarPreview ? /* @__PURE__ */ React.createElement("img", { src: resolvedAvatarPreview, alt: "Avatar preview", className: "h-full w-full object-cover" }) : /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-image text-slate-500" })), /* @__PURE__ */ React.createElement("input", { ref: avatarInputRef, type: "file", accept: "image/png,image/jpeg,image/webp", onChange: handleFileSelected("avatar_file", setAvatarPreview), className: "hidden" }), /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-2" }, /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => avatarInputRef.current?.click(), className: "rounded-full border border-white/10 bg-white/[0.04] px-4 py-2 text-sm font-semibold text-white" }, "Upload avatar"), form.avatar_file ? /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => clearSelectedFile("avatar_file", setAvatarPreview, avatarInputRef), className: "rounded-full border border-white/10 bg-transparent px-4 py-2 text-sm font-semibold text-slate-300" }, "Use current path") : null), /* @__PURE__ */ React.createElement("label", { className: "grid gap-2 text-sm text-slate-200" }, /* @__PURE__ */ React.createElement("span", null, "Or paste an image URL"), /* @__PURE__ */ React.createElement("input", { value: form.avatar_path, onChange: (event) => setForm((current) => ({ ...current, avatar_path: event.target.value })), placeholder: "https://", className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white outline-none" }))), /* @__PURE__ */ React.createElement("div", { className: "grid gap-3 rounded-[24px] border border-white/10 bg-black/20 p-4 text-sm text-slate-200" }, /* @__PURE__ */ React.createElement("span", { className: "text-sm font-semibold text-white" }, "Cover image"), /* @__PURE__ */ React.createElement("div", { className: "flex h-28 w-full items-center justify-center overflow-hidden rounded-[24px] border border-white/10 bg-white/[0.04]" }, resolvedBannerPreview ? /* @__PURE__ */ React.createElement("img", { src: resolvedBannerPreview, alt: "Cover preview", className: "h-full w-full object-cover" }) : /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-panorama text-slate-500" })), /* @__PURE__ */ React.createElement("input", { ref: bannerInputRef, type: "file", accept: "image/png,image/jpeg,image/webp", onChange: handleFileSelected("banner_file", setBannerPreview), className: "hidden" }), /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-2" }, /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => bannerInputRef.current?.click(), className: "rounded-full border border-white/10 bg-white/[0.04] px-4 py-2 text-sm font-semibold text-white" }, "Upload cover"), form.banner_file ? /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => clearSelectedFile("banner_file", setBannerPreview, bannerInputRef), className: "rounded-full border border-white/10 bg-transparent px-4 py-2 text-sm font-semibold text-slate-300" }, "Use current path") : null), /* @__PURE__ */ React.createElement("label", { className: "grid gap-2 text-sm text-slate-200" }, /* @__PURE__ */ React.createElement("span", null, "Or paste an image URL"), /* @__PURE__ */ React.createElement("input", { value: form.banner_path, onChange: (event) => setForm((current) => ({ ...current, banner_path: event.target.value })), placeholder: "https://", className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white outline-none" })))), /* @__PURE__ */ React.createElement("div", { className: "grid gap-3 rounded-[24px] border border-white/10 bg-black/20 p-4" }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-2 text-sm text-slate-200" }, /* @__PURE__ */ React.createElement("span", null, "Featured artwork"), /* @__PURE__ */ React.createElement(NovaSelect, { value: String(form.featured_artwork_id || ""), onChange: (val) => setForm((current) => ({ ...current, featured_artwork_id: val })), placeholder: "Use latest published artwork", options: featuredArtworkOptions.map((item) => ({ value: String(item.id), label: item.title })) })), selectedFeaturedArtwork ? /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-3 rounded-[20px] border border-white/10 bg-white/[0.04] p-3" }, selectedFeaturedArtwork.thumb ? /* @__PURE__ */ React.createElement("img", { src: selectedFeaturedArtwork.thumb, alt: selectedFeaturedArtwork.title, className: "h-16 w-16 rounded-2xl object-cover" }) : null, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "font-semibold text-white" }, selectedFeaturedArtwork.title), /* @__PURE__ */ React.createElement("div", { className: "text-sm text-slate-400" }, selectedFeaturedArtwork.author || "Group member"))) : /* @__PURE__ */ React.createElement("p", { className: "text-sm text-slate-400" }, "When this is empty, the public overview falls back to the latest published works automatically.")), /* @__PURE__ */ React.createElement("div", { className: "grid gap-2 text-sm text-slate-200" }, /* @__PURE__ */ React.createElement("span", null, "Visibility"), /* @__PURE__ */ React.createElement(NovaSelect, { value: form.visibility, onChange: (val) => setForm((current) => ({ ...current, visibility: val })), options: props.visibilityOptions || [], searchable: false })), /* @__PURE__ */ React.createElement("div", { className: "grid gap-2 text-sm text-slate-200" }, /* @__PURE__ */ React.createElement("span", null, "Membership policy"), /* @__PURE__ */ React.createElement(NovaSelect, { value: form.membership_policy, onChange: (val) => setForm((current) => ({ ...current, membership_policy: val })), options: props.membershipPolicyOptions || [], searchable: false })), /* @__PURE__ */ React.createElement("div", { className: "grid gap-3" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("span", { className: "text-sm text-slate-200" }, "Links"), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: addLink, className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-1.5 text-xs font-semibold text-white" }, "Add link")), form.links_json.map((item, index2) => /* @__PURE__ */ React.createElement("div", { key: `link-${index2}`, className: "grid gap-3 md:grid-cols-[0.8fr_1.2fr_auto]" }, /* @__PURE__ */ React.createElement("input", { value: item.label, onChange: (event) => updateLink(index2, "label", event.target.value), placeholder: "Label", className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white outline-none" }), /* @__PURE__ */ React.createElement("input", { value: item.url, onChange: (event) => updateLink(index2, "url", event.target.value), placeholder: "https://", className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white outline-none" }), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => removeLink(index2), className: "rounded-full border border-rose-300/20 bg-rose-400/10 px-4 py-2 text-sm font-semibold text-rose-100" }, "Remove")))), /* @__PURE__ */ React.createElement("div", { className: "flex justify-between gap-3" }, /* @__PURE__ */ React.createElement("button", { type: "button", onClick: archiveGroup, className: "rounded-full border border-rose-300/20 bg-rose-400/10 px-4 py-2 text-sm font-semibold text-rose-100" }, "Archive group"), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: submit, className: "rounded-full border border-sky-300/20 bg-sky-300/10 px-4 py-2 text-sm font-semibold text-sky-100" }, "Save settings"))))); } -const __vite_glob_0_141 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ +const __vite_glob_0_123 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ __proto__: null, default: StudioGroupSettings }, Symbol.toStringTag, { value: "Module" })); @@ -95001,7 +96989,7 @@ function StudioGroupsIndex() { } ), /* @__PURE__ */ React.createElement("div", { className: "mb-6 flex items-center justify-between gap-3 rounded-[28px] border border-white/10 bg-white/[0.03] p-5" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-sky-200/80" }, "Collective publishing"), /* @__PURE__ */ React.createElement("h2", { className: "mt-2 text-2xl font-semibold text-white" }, "Launch and manage shared identities")), /* @__PURE__ */ React.createElement(xe, { href: props.endpoints?.create, className: "rounded-full border border-sky-300/20 bg-sky-300/10 px-4 py-2 text-sm font-semibold text-sky-100 transition hover:border-sky-300/35 hover:bg-sky-300/15" }, "Create group")), pendingInvites.length > 0 ? /* @__PURE__ */ React.createElement("section", { className: "mb-6 rounded-[28px] border border-amber-300/20 bg-amber-400/10 p-5" }, /* @__PURE__ */ React.createElement("h2", { className: "text-lg font-semibold text-amber-50" }, "Pending invites"), /* @__PURE__ */ React.createElement("div", { className: "mt-4 grid gap-3 md:grid-cols-2" }, pendingInvites.map((invite) => /* @__PURE__ */ React.createElement("article", { key: invite.id, className: "rounded-2xl border border-white/10 bg-black/20 p-4 text-white" }, /* @__PURE__ */ React.createElement("h3", { className: "text-base font-semibold" }, invite.group?.name), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm text-amber-50/80" }, "Role: ", invite.role), invite.invited_by ? /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-sm text-amber-50/70" }, "Invited by ", invite.invited_by.name || invite.invited_by.username) : null, /* @__PURE__ */ React.createElement("div", { className: "mt-4 flex gap-2" }, /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => At.post(invite.accept_url), className: "rounded-full border border-emerald-300/20 bg-emerald-400/10 px-3 py-2 text-sm font-semibold text-emerald-100" }, "Accept"), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => At.post(invite.decline_url), className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-2 text-sm font-semibold text-white" }, "Decline")))))) : null, /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 xl:grid-cols-2" }, groups.length > 0 ? groups.map((group) => /* @__PURE__ */ React.createElement(GroupCard, { key: group.slug, group })) : /* @__PURE__ */ React.createElement("div", { className: "rounded-[28px] border border-dashed border-white/10 px-6 py-16 text-center text-slate-400" }, "No groups yet. Create one to start publishing collaboratively."))); } -const __vite_glob_0_142 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ +const __vite_glob_0_124 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ __proto__: null, default: StudioGroupsIndex }, Symbol.toStringTag, { value: "Module" })); @@ -95102,7 +97090,7 @@ function StudioGrowth() { /* @__PURE__ */ React.createElement("div", { className: "mt-3 grid grid-cols-3 gap-3 text-xs text-slate-400" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", null, "Views"), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-sm font-semibold text-white" }, Number(item.metrics?.views || 0).toLocaleString())), /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", null, "Reactions"), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-sm font-semibold text-white" }, Number(item.metrics?.appreciation || 0).toLocaleString())), /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", null, "Comments"), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-sm font-semibold text-white" }, Number(item.metrics?.comments || 0).toLocaleString()))) )))))); } -const __vite_glob_0_143 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ +const __vite_glob_0_125 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ __proto__: null, default: StudioGrowth }, Symbol.toStringTag, { value: "Module" })); @@ -95162,191 +97150,10 @@ function StudioInbox() { }; return /* @__PURE__ */ React.createElement(StudioLayout, { title: props.title, subtitle: props.description, actions: /* @__PURE__ */ React.createElement("button", { type: "button", onClick: markAllRead, disabled: marking, className: "inline-flex items-center gap-2 rounded-full border border-white/10 px-4 py-2 text-sm text-slate-100 disabled:opacity-50" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-check-double" }), marking ? "Updating..." : "Mark all read") }, /* @__PURE__ */ React.createElement("div", { className: "space-y-6" }, /* @__PURE__ */ React.createElement("section", { className: "grid gap-4 md:grid-cols-2 xl:grid-cols-4" }, /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-white/[0.03] p-5" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, "Unread"), /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-3xl font-semibold text-white" }, Number(summary.unread_count || 0).toLocaleString())), /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-white/[0.03] p-5" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, "High priority"), /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-3xl font-semibold text-white" }, Number(summary.high_priority_count || 0).toLocaleString())), /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-white/[0.03] p-5" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, "Comments"), /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-3xl font-semibold text-white" }, Number(summary.comment_count || 0).toLocaleString())), /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-white/[0.03] p-5" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, "Followers"), /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-3xl font-semibold text-white" }, Number(summary.follower_count || 0).toLocaleString()))), /* @__PURE__ */ React.createElement("div", { className: "grid gap-6 xl:grid-cols-[320px_minmax(0,1fr)]" }, /* @__PURE__ */ React.createElement("aside", { className: "space-y-6" }, /* @__PURE__ */ React.createElement("section", { className: "rounded-[28px] border border-white/10 bg-white/[0.03] p-5" }, /* @__PURE__ */ React.createElement("h2", { className: "text-lg font-semibold text-white" }, "Filters"), /* @__PURE__ */ React.createElement("div", { className: "mt-4 space-y-3" }, /* @__PURE__ */ React.createElement("label", { className: "space-y-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "block text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, "Search"), /* @__PURE__ */ React.createElement("input", { value: filters.q || "", onChange: (event) => updateFilters({ q: event.target.value }), className: "w-full rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white", placeholder: "Actor, title, or module" })), /* @__PURE__ */ React.createElement("div", { className: "space-y-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "block text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, "Type"), /* @__PURE__ */ React.createElement(NovaSelect, { value: filters.type || "all", onChange: (val) => updateFilters({ type: val }), options: inbox.type_options || [], searchable: false })), /* @__PURE__ */ React.createElement("div", { className: "space-y-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "block text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, "Module"), /* @__PURE__ */ React.createElement(NovaSelect, { value: filters.module || "all", onChange: (val) => updateFilters({ module: val }), options: inbox.module_options || [], searchable: false })), /* @__PURE__ */ React.createElement("div", { className: "space-y-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "block text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, "Read state"), /* @__PURE__ */ React.createElement(NovaSelect, { value: filters.read_state || "all", onChange: (val) => updateFilters({ read_state: val }), options: inbox.read_state_options || [], searchable: false })), /* @__PURE__ */ React.createElement("div", { className: "space-y-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "block text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, "Priority"), /* @__PURE__ */ React.createElement(NovaSelect, { value: filters.priority || "all", onChange: (val) => updateFilters({ priority: val }), options: inbox.priority_options || [], searchable: false })))), /* @__PURE__ */ React.createElement("section", { className: "rounded-[28px] border border-white/10 bg-white/[0.03] p-5" }, /* @__PURE__ */ React.createElement("h2", { className: "text-lg font-semibold text-white" }, "Attention now"), /* @__PURE__ */ React.createElement("div", { className: "mt-4 space-y-3" }, (inbox.panels?.attention_now || []).map((item) => /* @__PURE__ */ React.createElement("a", { key: item.id, href: item.url, className: "block rounded-2xl border border-white/10 bg-black/20 p-4" }, /* @__PURE__ */ React.createElement("div", { className: "text-sm font-semibold text-white" }, item.title), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-xs text-slate-500" }, item.module_label)))))), /* @__PURE__ */ React.createElement("section", { className: "space-y-4" }, items.length > 0 ? items.map((item) => /* @__PURE__ */ React.createElement("article", { key: item.id, className: `rounded-[28px] border p-5 ${item.is_new ? "border-sky-300/20 bg-sky-300/10" : "border-white/10 bg-white/[0.03]"}` }, /* @__PURE__ */ React.createElement("div", { className: "flex gap-4" }, item.actor?.avatar_url ? /* @__PURE__ */ React.createElement("img", { src: item.actor.avatar_url, alt: item.actor.name || "Actor", className: "h-12 w-12 rounded-2xl object-cover" }) : /* @__PURE__ */ React.createElement("div", { className: "flex h-12 w-12 items-center justify-center rounded-2xl bg-black/20 text-slate-400" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-bell" })), /* @__PURE__ */ React.createElement("div", { className: "min-w-0 flex-1" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center gap-2 text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, /* @__PURE__ */ React.createElement("span", null, item.module_label), /* @__PURE__ */ React.createElement("span", { className: `inline-flex items-center rounded-full border px-2 py-1 ${priorityClasses[item.priority] || priorityClasses.low}` }, item.priority), item.is_new && /* @__PURE__ */ React.createElement("span", { className: "rounded-full bg-sky-300/20 px-2 py-1 text-sky-100" }, "Unread")), /* @__PURE__ */ React.createElement("h2", { className: "mt-2 text-lg font-semibold text-white" }, item.title), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm leading-6 text-slate-400" }, item.body), /* @__PURE__ */ React.createElement("div", { className: "mt-4 flex flex-wrap items-center gap-3 text-sm text-slate-400" }, /* @__PURE__ */ React.createElement("span", null, formatDate$2(item.created_at)), item.actor?.name && /* @__PURE__ */ React.createElement("span", null, item.actor.name), /* @__PURE__ */ React.createElement("a", { href: item.url, className: "inline-flex items-center gap-2 rounded-full border border-white/10 px-3 py-1.5 text-slate-200" }, "Open")))))) : /* @__PURE__ */ React.createElement("div", { className: "rounded-[28px] border border-dashed border-white/15 px-6 py-16 text-center text-slate-400" }, "No inbox items match this filter."), /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between rounded-[24px] border border-white/10 bg-white/[0.03] px-4 py-3 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("button", { type: "button", disabled: (meta.current_page || 1) <= 1, onClick: () => updateFilters({ page: Math.max(1, (meta.current_page || 1) - 1) }), className: "rounded-full border border-white/10 px-4 py-2 disabled:opacity-40" }, "Previous"), /* @__PURE__ */ React.createElement("span", { className: "text-xs uppercase tracking-[0.18em] text-slate-500" }, "Page ", meta.current_page || 1, " of ", meta.last_page || 1), /* @__PURE__ */ React.createElement("button", { type: "button", disabled: (meta.current_page || 1) >= (meta.last_page || 1), onClick: () => updateFilters({ page: (meta.current_page || 1) + 1 }), className: "rounded-full border border-white/10 px-4 py-2 disabled:opacity-40" }, "Next")))))); } -const __vite_glob_0_144 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ +const __vite_glob_0_126 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ __proto__: null, default: StudioInbox }, Symbol.toStringTag, { value: "Module" })); -function formatBytes$1(bytes) { - const value = Number(bytes || 0); - if (!Number.isFinite(value) || value <= 0) return null; - if (value < 1024 * 1024) return `${Math.round(value / 1024)} KB`; - return `${(value / (1024 * 1024)).toFixed(1)} MB`; -} -function WorldMediaUploadField({ - label, - slot, - value, - previewUrl, - emptyLabel, - helperText, - uploadUrl, - deleteUrl, - worldId = null, - onChange, - isTemporaryValue = false, - accept = "image/jpeg,image/png,image/webp", - maxFileSizeMb = 6 -}) { - const inputRef = reactExports.useRef(null); - const [dragging, setDragging] = reactExports.useState(false); - const [uploading, setUploading] = reactExports.useState(false); - const [error, setError] = reactExports.useState(""); - const [meta, setMeta] = reactExports.useState(null); - const csrfToken2 = reactExports.useMemo(() => { - if (typeof document === "undefined") { - return ""; - } - return document.querySelector('meta[name="csrf-token"]')?.getAttribute("content") || ""; - }, []); - const deleteTemporaryUpload = async (path) => { - if (!deleteUrl || !path) return; - const response = await fetch(deleteUrl, { - method: "DELETE", - headers: { - "Content-Type": "application/json", - "X-CSRF-TOKEN": csrfToken2, - Accept: "application/json" - }, - credentials: "same-origin", - body: JSON.stringify({ - path, - world_id: worldId || void 0 - }) - }); - const payload = await response.json().catch(() => ({})); - if (!response.ok) { - throw new Error(payload?.message || payload?.error || "Could not remove uploaded image."); - } - }; - const handleFile = async (file) => { - if (!file || uploading) return; - const allowed = ["image/jpeg", "image/png", "image/webp"]; - if (!allowed.includes(String(file.type || "").toLowerCase())) { - setError("Use a JPG, PNG, or WEBP image."); - return; - } - if (file.size > maxFileSizeMb * 1024 * 1024) { - setError(`Image is too large. Maximum allowed size is ${maxFileSizeMb} MB.`); - return; - } - setUploading(true); - setError(""); - try { - if (value && isTemporaryValue) { - await deleteTemporaryUpload(value); - } - const body2 = new FormData(); - body2.append("slot", slot); - body2.append("image", file); - if (worldId) { - body2.append("world_id", String(worldId)); - } - const response = await fetch(uploadUrl, { - method: "POST", - headers: { - "X-CSRF-TOKEN": csrfToken2, - Accept: "application/json" - }, - credentials: "same-origin", - body: body2 - }); - const payload = await response.json().catch(() => ({})); - if (!response.ok) { - throw new Error(payload?.message || payload?.error || "Upload failed."); - } - setMeta({ - width: payload?.width || null, - height: payload?.height || null, - size: formatBytes$1(payload?.size_bytes) - }); - onChange?.({ path: payload?.path || "", url: payload?.url || "" }); - } catch (uploadError) { - setError(uploadError?.message || "Upload failed."); - } finally { - setUploading(false); - if (inputRef.current) { - inputRef.current.value = ""; - } - } - }; - return /* @__PURE__ */ React.createElement("div", { className: "grid gap-3 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("span", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, label), value ? /* @__PURE__ */ React.createElement( - "button", - { - type: "button", - onClick: async (event) => { - event.stopPropagation(); - setError(""); - setMeta(null); - try { - if (value && isTemporaryValue) { - setUploading(true); - await deleteTemporaryUpload(value); - } - onChange?.({ path: "", url: "" }); - } catch (deleteError) { - setError(deleteError?.message || "Could not remove uploaded image."); - } finally { - setUploading(false); - } - }, - disabled: uploading, - className: "rounded-full border border-white/10 bg-white/[0.04] px-3 py-1 text-[11px] font-semibold uppercase tracking-[0.14em] text-white" - }, - "Clear" - ) : null), /* @__PURE__ */ React.createElement( - "div", - { - role: "button", - tabIndex: 0, - onClick: () => !uploading && inputRef.current?.click(), - onKeyDown: (event) => { - if (uploading) return; - if (event.key === "Enter" || event.key === " ") { - event.preventDefault(); - inputRef.current?.click(); - } - }, - onDragOver: (event) => { - event.preventDefault(); - if (!uploading) setDragging(true); - }, - onDragEnter: (event) => { - event.preventDefault(); - if (!uploading) setDragging(true); - }, - onDragLeave: (event) => { - event.preventDefault(); - setDragging(false); - }, - onDrop: (event) => { - event.preventDefault(); - setDragging(false); - void handleFile(event.dataTransfer?.files?.[0]); - }, - className: [ - "rounded-[24px] border border-dashed px-5 py-5 transition outline-none", - uploading ? "cursor-progress border-sky-300/35 bg-sky-400/10" : dragging ? "cursor-pointer border-sky-300/50 bg-sky-400/12" : "cursor-pointer border-white/10 bg-black/20 hover:border-white/20 hover:bg-white/[0.04]" - ].join(" ") - }, - /* @__PURE__ */ React.createElement("div", { className: "flex flex-col gap-4 lg:flex-row lg:items-center lg:justify-between" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-start gap-4" }, /* @__PURE__ */ React.createElement("div", { className: "flex h-12 w-12 shrink-0 items-center justify-center rounded-2xl border border-sky-300/20 bg-sky-400/10 text-sky-100" }, /* @__PURE__ */ React.createElement("i", { className: `fa-solid ${uploading ? "fa-circle-notch fa-spin" : "fa-cloud-arrow-up"}` })), /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "text-sm font-semibold text-white" }, uploading ? "Uploading image…" : "Drop image here or browse"), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-xs leading-5 text-slate-400" }, helperText), /* @__PURE__ */ React.createElement("div", { className: "mt-2 flex flex-wrap gap-2 text-[11px] text-slate-400" }, /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.04] px-2.5 py-1" }, "JPG"), /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.04] px-2.5 py-1" }, "PNG"), /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.04] px-2.5 py-1" }, "WEBP"), /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.04] px-2.5 py-1" }, "Max ", maxFileSizeMb, " MB")))), /* @__PURE__ */ React.createElement("div", { className: "h-28 w-full overflow-hidden rounded-[20px] border border-white/10 bg-slate-950 lg:w-44" }, previewUrl ? /* @__PURE__ */ React.createElement("img", { src: previewUrl, alt: "", className: "h-full w-full object-cover" }) : /* @__PURE__ */ React.createElement("div", { className: "flex h-full items-center justify-center px-4 text-center text-sm text-slate-500" }, emptyLabel))), - value ? /* @__PURE__ */ React.createElement("div", { className: "mt-4 truncate rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-xs text-slate-400" }, "Stored path: ", /* @__PURE__ */ React.createElement("span", { className: "text-slate-200" }, value)) : null, - meta ? /* @__PURE__ */ React.createElement("div", { className: "mt-3 text-xs text-slate-400" }, "Optimized to ", meta.width, "×", meta.height, meta.size ? ` • ${meta.size}` : "") : null, - error ? /* @__PURE__ */ React.createElement("div", { className: "mt-3 rounded-2xl border border-rose-300/20 bg-rose-400/10 px-4 py-3 text-sm text-rose-100" }, error) : null, - /* @__PURE__ */ React.createElement( - "input", - { - ref: inputRef, - type: "file", - accept, - className: "hidden", - disabled: uploading, - onChange: (event) => { - void handleFile(event.target.files?.[0]); - } - } - ) - )); -} let _toastId = 0; function useToast() { const [toasts, setToasts] = reactExports.useState([]); @@ -96564,7 +98371,7 @@ function StudioNewsEditor() { } )); } -const __vite_glob_0_145 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ +const __vite_glob_0_127 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ __proto__: null, default: StudioNewsEditor }, Symbol.toStringTag, { value: "Module" })); @@ -96660,7 +98467,7 @@ function StudioNewsIndex() { } )), /* @__PURE__ */ React.createElement("div", { className: "text-sm text-slate-400 lg:text-right" }, Number(meta.total || 0).toLocaleString(), " articles"))), /* @__PURE__ */ React.createElement("section", { className: "mt-6 grid gap-4 md:grid-cols-2 xl:grid-cols-3" }, items.length > 0 ? items.map((item) => /* @__PURE__ */ React.createElement("article", { key: item.id, className: "overflow-hidden rounded-[24px] border border-white/10 bg-black/20 shadow-[0_18px_40px_rgba(2,6,23,0.18)]" }, /* @__PURE__ */ React.createElement("div", { className: "aspect-[16/9] bg-slate-950/60" }, item.cover_url ? /* @__PURE__ */ React.createElement("img", { src: item.cover_url, alt: item.title, className: "h-full w-full object-cover" }) : /* @__PURE__ */ React.createElement("div", { className: "flex h-full items-center justify-center text-slate-500" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-newspaper text-3xl" }))), /* @__PURE__ */ React.createElement("div", { className: "p-5" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center gap-2 text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-400" }, /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-white/10 bg-white/[0.04] px-2.5 py-1 text-white/70" }, item.type_label), /* @__PURE__ */ React.createElement("span", { className: `rounded-full border px-2.5 py-1 ${statusTone$1(item.editorial_status)}` }, item.editorial_status.replaceAll("_", " ")), item.is_pinned ? /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-amber-300/20 bg-amber-400/10 px-2.5 py-1 text-amber-100" }, "Pinned") : null, item.is_featured ? /* @__PURE__ */ React.createElement("span", { className: "rounded-full border border-emerald-300/20 bg-emerald-400/10 px-2.5 py-1 text-emerald-100" }, "Featured") : null), /* @__PURE__ */ React.createElement("h3", { className: "mt-3 text-xl font-semibold text-white" }, item.title), /* @__PURE__ */ React.createElement("div", { className: "mt-3 flex flex-wrap gap-3 text-sm text-slate-400" }, item.category_name ? /* @__PURE__ */ React.createElement("span", null, item.category_name) : null, /* @__PURE__ */ React.createElement("span", null, item.author_name), /* @__PURE__ */ React.createElement("span", null, formatDate$1(item.published_at))), /* @__PURE__ */ React.createElement("div", { className: "mt-5 flex flex-wrap gap-2" }, /* @__PURE__ */ React.createElement("a", { href: item.edit_url, className: "rounded-full border border-sky-300/20 bg-sky-400/10 px-4 py-2 text-sm font-semibold text-sky-100" }, "Edit"), /* @__PURE__ */ React.createElement("a", { href: item.editorial_status === "published" ? item.public_url : item.preview_url, className: "rounded-full border border-white/10 bg-white/[0.04] px-4 py-2 text-sm font-semibold text-white" }, item.editorial_status === "published" ? "View" : "Preview"), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => deleteItem(item), className: "rounded-full border border-rose-300/20 bg-rose-400/10 px-4 py-2 text-sm font-semibold text-rose-100" }, "Trash"))))) : /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-dashed border-white/10 bg-white/[0.02] p-6 text-sm text-slate-400" }, "No News articles match the current filters."))); } -const __vite_glob_0_146 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ +const __vite_glob_0_128 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ __proto__: null, default: StudioNewsIndex }, Symbol.toStringTag, { value: "Module" })); @@ -96693,7 +98500,7 @@ function StudioNewsTaxonomies() { tagForm.post(props.storeTagUrl); }, className: "mt-5 grid gap-3 md:grid-cols-[minmax(0,1fr)_minmax(0,1fr)_auto] md:items-center" }, /* @__PURE__ */ React.createElement("input", { value: tagForm.data.name, onChange: (event) => tagForm.setData("name", event.target.value), placeholder: "Tag name", className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white outline-none" }), /* @__PURE__ */ React.createElement("input", { value: tagForm.data.slug, onChange: (event) => tagForm.setData("slug", event.target.value), placeholder: "optional slug", className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white outline-none" }), /* @__PURE__ */ React.createElement("button", { type: "submit", className: "rounded-full border border-sky-300/20 bg-sky-400/10 px-4 py-3 text-sm font-semibold text-sky-100" }, "Create tag")), /* @__PURE__ */ React.createElement("div", { className: "mt-6 grid gap-3" }, tags.map((tag, index2) => /* @__PURE__ */ React.createElement("div", { key: tag.id, className: "rounded-[24px] border border-white/10 bg-black/20 p-4" }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-3 md:grid-cols-[minmax(0,1fr)_minmax(0,1fr)_auto_auto] md:items-center" }, /* @__PURE__ */ React.createElement("input", { value: tag.name, onChange: (event) => updateTag(index2, "name", event.target.value), className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white outline-none" }), /* @__PURE__ */ React.createElement("input", { value: tag.slug, onChange: (event) => updateTag(index2, "slug", event.target.value), className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white outline-none" }), /* @__PURE__ */ React.createElement("span", { className: "text-xs uppercase tracking-[0.14em] text-slate-500" }, Number(tag.published_count || 0).toLocaleString(), " published"), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => saveTag(tag), className: "rounded-full border border-white/10 bg-white/[0.05] px-4 py-2 text-sm font-semibold text-white" }, "Save")))))))); } -const __vite_glob_0_147 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ +const __vite_glob_0_129 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ __proto__: null, default: StudioNewsTaxonomies }, Symbol.toStringTag, { value: "Module" })); @@ -96843,7 +98650,7 @@ function StudioPreferences() { return /* @__PURE__ */ React.createElement("div", { key: widgetKey, className: "flex flex-col gap-3 rounded-[22px] border border-white/10 bg-black/20 p-4 md:flex-row md:items-center md:justify-between" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "text-sm font-semibold text-white" }, option.label), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-xs uppercase tracking-[0.16em] text-slate-500" }, "Position ", index2 + 1)), /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center gap-2" }, /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => toggleWidget(widgetKey), className: `rounded-full border px-3 py-1.5 text-xs ${enabled ? "border-sky-300/25 bg-sky-300/10 text-sky-100" : "border-white/10 text-slate-300"}` }, enabled ? "Visible" : "Hidden"), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => moveWidget(widgetKey, "up"), className: "rounded-full border border-white/10 px-3 py-1.5 text-xs text-slate-300" }, "Up"), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => moveWidget(widgetKey, "down"), className: "rounded-full border border-white/10 px-3 py-1.5 text-xs text-slate-300" }, "Down"))); })))), /* @__PURE__ */ React.createElement("div", { className: "space-y-6" }, /* @__PURE__ */ React.createElement("section", { className: "rounded-[30px] border border-white/10 bg-white/[0.03] p-6" }, /* @__PURE__ */ React.createElement("h2", { className: "text-lg font-semibold text-white" }, "Related surfaces"), /* @__PURE__ */ React.createElement("div", { className: "mt-4 space-y-3" }, (props.links || []).map((link2) => /* @__PURE__ */ React.createElement("a", { key: link2.url, href: link2.url, className: "block rounded-[22px] border border-white/10 bg-black/20 p-4 transition hover:border-white/20" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-3 text-sky-100" }, /* @__PURE__ */ React.createElement("i", { className: link2.icon }), /* @__PURE__ */ React.createElement("span", { className: "text-base font-semibold text-white" }, link2.label)))))), /* @__PURE__ */ React.createElement("section", { className: "rounded-[30px] border border-white/10 bg-white/[0.03] p-6" }, /* @__PURE__ */ React.createElement("h2", { className: "text-lg font-semibold text-white" }, "Preference notes"), /* @__PURE__ */ React.createElement("div", { className: "mt-4 space-y-3 text-sm text-slate-400" }, /* @__PURE__ */ React.createElement("div", { className: "rounded-[22px] border border-white/10 bg-black/20 p-4" }, "Landing page and widget order are stored in the shared Studio preference record, so new Creator Studio surfaces can plug into the same contract without another migration."), /* @__PURE__ */ React.createElement("div", { className: "rounded-[22px] border border-white/10 bg-black/20 p-4" }, "Analytics range and card density stay here so Analytics, Growth, and the main dashboard can stay visually consistent.")))))); } -const __vite_glob_0_148 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ +const __vite_glob_0_130 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ __proto__: null, default: StudioPreferences }, Symbol.toStringTag, { value: "Module" })); @@ -97023,7 +98830,7 @@ function StudioProfile() { /* @__PURE__ */ React.createElement("div", { className: "p-6 pt-0" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-col gap-5 lg:flex-row lg:items-end lg:justify-between" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-end gap-4" }, /* @__PURE__ */ React.createElement("div", { className: "relative" }, profile.avatar_url ? /* @__PURE__ */ React.createElement("img", { src: profile.avatar_url, alt: profile.username, className: "h-24 w-24 rounded-[28px] border border-white/10 object-cover shadow-lg" }) : /* @__PURE__ */ React.createElement("div", { className: "flex h-24 w-24 items-center justify-center rounded-[28px] border border-white/10 bg-black/30 text-slate-400 shadow-lg" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-user text-2xl" })), /* @__PURE__ */ React.createElement("input", { ref: avatarInputRef, type: "file", accept: "image/png,image/jpeg,image/webp", onChange: handleAvatarSelected, className: "hidden" }), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => avatarInputRef.current?.click(), disabled: uploadingAvatar, className: "absolute -bottom-2 -right-2 inline-flex h-10 w-10 items-center justify-center rounded-full border border-sky-300/25 bg-sky-300/15 text-sky-100 disabled:opacity-50" }, /* @__PURE__ */ React.createElement("i", { className: `fa-solid ${uploadingAvatar ? "fa-spinner fa-spin" : "fa-camera"}` }))), /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("h2", { className: "text-3xl font-semibold text-white" }, profile.name), /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-sm text-slate-300" }, "@", profile.username), /* @__PURE__ */ React.createElement("div", { className: "mt-2 flex flex-wrap gap-4 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", null, Number(profile.followers || 0).toLocaleString(), " followers"), profile.location && /* @__PURE__ */ React.createElement("span", null, profile.location)))), profile.cover_url && /* @__PURE__ */ React.createElement("div", { className: "w-full max-w-sm rounded-[24px] border border-white/10 bg-black/30 p-4" }, /* @__PURE__ */ React.createElement("label", { className: "block text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-400" }, "Banner position"), /* @__PURE__ */ React.createElement("input", { type: "range", min: "0", max: "100", value: coverPosition, onChange: (event) => setCoverPosition(Number(event.target.value)), className: "mt-3 w-full" }), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: saveCoverPosition, disabled: savingCoverPosition, className: "mt-3 inline-flex items-center gap-2 rounded-full border border-white/10 px-4 py-2 text-sm text-white disabled:opacity-50" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-arrows-up-down" }), savingCoverPosition ? "Saving..." : "Save banner position")))) )), /* @__PURE__ */ React.createElement("div", { className: "grid gap-6 xl:grid-cols-[minmax(0,1fr)_360px]" }, /* @__PURE__ */ React.createElement("section", { className: "rounded-[30px] border border-white/10 bg-white/[0.03] p-6" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between gap-4" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("h2", { className: "text-lg font-semibold text-white" }, "Public profile details"), /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-sm text-slate-400" }, "Update the creator information that supports your public presence across Nova.")), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: saveProfile, disabled: savingProfile, className: "inline-flex items-center gap-2 rounded-full border border-sky-300/20 bg-sky-300/10 px-4 py-2 text-sm font-semibold text-sky-100 disabled:opacity-50" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-floppy-disk" }), savingProfile ? "Saving..." : "Save profile")), /* @__PURE__ */ React.createElement("div", { className: "mt-5 grid gap-4 md:grid-cols-2" }, /* @__PURE__ */ React.createElement("label", { className: "space-y-2 text-sm text-slate-300 md:col-span-2" }, /* @__PURE__ */ React.createElement("span", { className: "block text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, "Display name"), /* @__PURE__ */ React.createElement("input", { value: form.display_name, onChange: (event) => setForm((current) => ({ ...current, display_name: event.target.value })), className: "w-full rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-sm text-white outline-none" })), /* @__PURE__ */ React.createElement("label", { className: "space-y-2 text-sm text-slate-300 md:col-span-2" }, /* @__PURE__ */ React.createElement("span", { className: "block text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, "Tagline"), /* @__PURE__ */ React.createElement("input", { value: form.tagline, onChange: (event) => setForm((current) => ({ ...current, tagline: event.target.value })), placeholder: "One-line creator summary", className: "w-full rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-sm text-white outline-none placeholder:text-slate-500" })), /* @__PURE__ */ React.createElement("label", { className: "space-y-2 text-sm text-slate-300 md:col-span-2" }, /* @__PURE__ */ React.createElement("span", { className: "block text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, "Bio"), /* @__PURE__ */ React.createElement("textarea", { value: form.bio, onChange: (event) => setForm((current) => ({ ...current, bio: event.target.value })), rows: 5, placeholder: "Tell visitors what you create and what makes your work distinct.", className: "w-full rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-sm text-white outline-none placeholder:text-slate-500" })), /* @__PURE__ */ React.createElement("label", { className: "space-y-2 text-sm text-slate-300 md:col-span-2" }, /* @__PURE__ */ React.createElement("span", { className: "block text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, "Website"), /* @__PURE__ */ React.createElement("input", { value: form.website, onChange: (event) => setForm((current) => ({ ...current, website: event.target.value })), placeholder: "https://example.com", className: "w-full rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-sm text-white outline-none placeholder:text-slate-500" }))), /* @__PURE__ */ React.createElement("div", { className: "mt-6" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between gap-4" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("h3", { className: "text-base font-semibold text-white" }, "Social links"), /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-sm text-slate-400" }, "Add the channels that matter for your creator identity.")), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: addSocialLink, className: "inline-flex items-center gap-2 rounded-full border border-white/10 px-4 py-2 text-sm text-white" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-plus" }), "Add link")), /* @__PURE__ */ React.createElement("div", { className: "mt-4 space-y-3" }, form.social_links.map((link2, index2) => /* @__PURE__ */ React.createElement("div", { key: `${index2}-${link2.platform}`, className: "grid gap-3 rounded-[24px] border border-white/10 bg-black/20 p-4 md:grid-cols-[180px_minmax(0,1fr)_auto]" }, /* @__PURE__ */ React.createElement("input", { value: link2.platform, onChange: (event) => updateSocialLink(index2, "platform", event.target.value), placeholder: "instagram", className: "rounded-2xl border border-white/10 bg-black/30 px-4 py-3 text-sm text-white outline-none placeholder:text-slate-500" }), /* @__PURE__ */ React.createElement("input", { value: link2.url, onChange: (event) => updateSocialLink(index2, "url", event.target.value), placeholder: "https://...", className: "rounded-2xl border border-white/10 bg-black/30 px-4 py-3 text-sm text-white outline-none placeholder:text-slate-500" }), /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => removeSocialLink(index2), className: "inline-flex items-center justify-center rounded-2xl border border-rose-300/20 bg-rose-300/10 px-4 py-3 text-sm text-rose-100" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-trash" }))))))), /* @__PURE__ */ React.createElement("div", { className: "space-y-6" }, /* @__PURE__ */ React.createElement("section", { className: "rounded-[30px] border border-white/10 bg-white/[0.03] p-6" }, /* @__PURE__ */ React.createElement("h2", { className: "text-lg font-semibold text-white" }, "Publishing footprint"), /* @__PURE__ */ React.createElement("div", { className: "mt-5 grid gap-4" }, (props.moduleSummaries || []).map((item) => /* @__PURE__ */ React.createElement("div", { key: item.key, className: "rounded-[22px] border border-white/10 bg-black/20 p-4" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-3 text-slate-200" }, /* @__PURE__ */ React.createElement("i", { className: item.icon }), /* @__PURE__ */ React.createElement("span", null, item.label)), /* @__PURE__ */ React.createElement("div", { className: "mt-3 text-3xl font-semibold text-white" }, Number(item.count || 0).toLocaleString()), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm text-slate-400" }, Number(item.published_count || 0).toLocaleString(), " published, ", Number(item.draft_count || 0).toLocaleString(), " drafts"))))), /* @__PURE__ */ React.createElement("section", { className: "rounded-[30px] border border-white/10 bg-white/[0.03] p-6" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between gap-4" }, /* @__PURE__ */ React.createElement("h2", { className: "text-lg font-semibold text-white" }, "Featured identity"), /* @__PURE__ */ React.createElement("a", { href: "/studio/featured", className: "text-sm font-medium text-sky-100" }, "Manage featured")), /* @__PURE__ */ React.createElement("div", { className: "mt-4 flex flex-wrap gap-2" }, featuredModules.length > 0 ? featuredModules.map((module) => /* @__PURE__ */ React.createElement("span", { key: module, className: "inline-flex items-center rounded-full border border-sky-300/20 bg-sky-300/10 px-3 py-1 text-xs font-semibold uppercase tracking-[0.16em] text-sky-100" }, socialPlatformLabel(module))) : /* @__PURE__ */ React.createElement("p", { className: "text-sm text-slate-400" }, "No featured modules selected yet.")), /* @__PURE__ */ React.createElement("div", { className: "mt-4 space-y-3" }, Object.entries(featuredContent).map(([module, item]) => item ? /* @__PURE__ */ React.createElement("a", { key: module, href: item.view_url || item.preview_url || "/studio/featured", className: "flex items-center gap-3 rounded-2xl border border-white/10 bg-black/20 p-3" }, item.image_url ? /* @__PURE__ */ React.createElement("img", { src: item.image_url, alt: item.title, className: "h-14 w-14 rounded-2xl object-cover" }) : /* @__PURE__ */ React.createElement("div", { className: "flex h-14 w-14 items-center justify-center rounded-2xl bg-white/5 text-slate-400" }, /* @__PURE__ */ React.createElement("i", { className: item.module_icon || "fa-solid fa-star" })), /* @__PURE__ */ React.createElement("div", { className: "min-w-0" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, socialPlatformLabel(module)), /* @__PURE__ */ React.createElement("div", { className: "truncate text-sm font-semibold text-white" }, item.title))) : null))))))); } -const __vite_glob_0_149 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ +const __vite_glob_0_131 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ __proto__: null, default: StudioProfile }, Symbol.toStringTag, { value: "Module" })); @@ -97100,7 +98907,7 @@ function StudioScheduled() { }, [items, summary.next_publish_at]); return /* @__PURE__ */ React.createElement(StudioLayout, { title: props.title, subtitle: props.description }, /* @__PURE__ */ React.createElement("div", { className: "space-y-6" }, /* @__PURE__ */ React.createElement("section", { className: "grid gap-4 xl:grid-cols-[minmax(0,1fr)_340px]" }, /* @__PURE__ */ React.createElement("div", { className: "rounded-[30px] border border-white/10 bg-white/[0.03] p-6" }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 md:grid-cols-3" }, /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-black/20 p-4" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, "Scheduled total"), /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-3xl font-semibold text-white" }, Number(summary.total || 0).toLocaleString())), /* @__PURE__ */ React.createElement("div", { className: "rounded-[24px] border border-white/10 bg-black/20 p-4 md:col-span-2" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, "Next publish slot"), /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-xl font-semibold text-white" }, formatReleaseCountdown(summary.next_publish_at, nowMs)), summary.next_publish_at && /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-sm text-slate-400" }, formatScheduledDate(summary.next_publish_at)))), /* @__PURE__ */ React.createElement("div", { className: "mt-5 grid gap-3 md:grid-cols-2 xl:grid-cols-4" }, (summary.by_module || []).map((entry) => /* @__PURE__ */ React.createElement("div", { key: entry.key, className: "rounded-[22px] border border-white/10 bg-black/20 p-4" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-3 text-slate-300" }, /* @__PURE__ */ React.createElement("i", { className: entry.icon }), /* @__PURE__ */ React.createElement("span", { className: "text-sm font-medium text-white" }, entry.label)), /* @__PURE__ */ React.createElement("div", { className: "mt-3 text-2xl font-semibold text-white" }, Number(entry.count || 0).toLocaleString()))))), /* @__PURE__ */ React.createElement("div", { className: "rounded-[30px] border border-white/10 bg-white/[0.03] p-6" }, /* @__PURE__ */ React.createElement("h2", { className: "text-lg font-semibold text-white" }, "Agenda"), /* @__PURE__ */ React.createElement("div", { className: "mt-4 space-y-3" }, agenda.length > 0 ? agenda.slice(0, 6).map((day) => /* @__PURE__ */ React.createElement("div", { key: day.date, className: "rounded-[22px] border border-white/10 bg-black/20 p-4" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("span", { className: "text-sm font-semibold text-white" }, day.label), /* @__PURE__ */ React.createElement("span", { className: "text-xs uppercase tracking-[0.18em] text-slate-500" }, day.count, " items")), /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-sm text-slate-400" }, day.items.slice(0, 2).map((item) => item.title).join(" • ")))) : /* @__PURE__ */ React.createElement("div", { className: "rounded-[22px] border border-dashed border-white/15 px-4 py-8 text-sm text-slate-400" }, "No scheduled items yet.")))), /* @__PURE__ */ React.createElement("section", { className: "rounded-[30px] border border-white/10 bg-[radial-gradient(circle_at_top_left,_rgba(56,189,248,0.14),_transparent_35%),linear-gradient(135deg,_rgba(15,23,42,0.86),_rgba(2,6,23,0.96))] p-5 lg:p-6" }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-3 md:grid-cols-2 xl:grid-cols-5" }, /* @__PURE__ */ React.createElement("label", { className: "space-y-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "block text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, "Search scheduled work"), /* @__PURE__ */ React.createElement("input", { value: filters.q || "", onChange: (event) => updateFilters({ q: event.target.value }), className: "w-full rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white", placeholder: "Title or module" })), /* @__PURE__ */ React.createElement("div", { className: "space-y-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "block text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, "Module"), /* @__PURE__ */ React.createElement(NovaSelect, { value: filters.module || "all", onChange: (val) => updateFilters({ module: val }), options: listing.module_options || [], searchable: false })), /* @__PURE__ */ React.createElement("div", { className: "space-y-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "block text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, "Date range"), /* @__PURE__ */ React.createElement(NovaSelect, { value: filters.range || "upcoming", onChange: (val) => updateFilters({ range: val }), options: rangeOptions2, searchable: false })), /* @__PURE__ */ React.createElement("div", { className: "space-y-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "block text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, "Start date"), /* @__PURE__ */ React.createElement(DateTimePicker, { value: filters.start_date || "", onChange: (nextValue) => updateFilters({ range: "custom", start_date: nextValue }), mode: "date", placeholder: "Start date", clearable: true, className: "bg-black/20" })), /* @__PURE__ */ React.createElement("div", { className: "space-y-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "block text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, "End date"), /* @__PURE__ */ React.createElement(DateTimePicker, { value: filters.end_date || "", onChange: (nextValue) => updateFilters({ range: "custom", end_date: nextValue }), mode: "date", placeholder: "End date", clearable: true, className: "bg-black/20" })), /* @__PURE__ */ React.createElement("div", { className: "flex items-end" }, /* @__PURE__ */ React.createElement("button", { type: "button", onClick: () => updateFilters({ q: "", module: "all", range: "upcoming", start_date: "", end_date: "" }), className: "w-full rounded-2xl border border-white/10 px-4 py-3 text-sm text-slate-200" }, "Reset")))), /* @__PURE__ */ React.createElement("section", { className: "space-y-4" }, items.length > 0 ? items.map((item) => /* @__PURE__ */ React.createElement("article", { key: item.id, className: "rounded-[28px] border border-white/10 bg-white/[0.03] p-5" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-col gap-4 lg:flex-row lg:items-center lg:justify-between" }, /* @__PURE__ */ React.createElement("div", { className: "min-w-0" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center gap-3 text-[11px] font-semibold uppercase tracking-[0.18em] text-sky-200/70" }, /* @__PURE__ */ React.createElement("span", null, item.module_label), /* @__PURE__ */ React.createElement("span", null, item.status)), /* @__PURE__ */ React.createElement("h2", { className: "mt-2 text-xl font-semibold text-white" }, item.title), /* @__PURE__ */ React.createElement("div", { className: "mt-2 flex flex-wrap items-center gap-4 text-sm text-slate-400" }, /* @__PURE__ */ React.createElement("span", null, formatReleaseCountdown(item.scheduled_at || item.published_at, nowMs)), /* @__PURE__ */ React.createElement("span", null, formatScheduledDate(item.scheduled_at || item.published_at)), item.visibility && /* @__PURE__ */ React.createElement("span", null, "Visibility: ", item.visibility), item.updated_at && /* @__PURE__ */ React.createElement("span", null, "Last edited ", formatScheduledDate(item.updated_at)), item.schedule_timezone && /* @__PURE__ */ React.createElement("span", null, item.schedule_timezone))), /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap gap-2" }, /* @__PURE__ */ React.createElement("a", { href: item.edit_url || item.manage_url, className: "inline-flex items-center gap-2 rounded-full border border-white/10 px-4 py-2 text-sm text-slate-200" }, "Edit"), /* @__PURE__ */ React.createElement("a", { href: item.edit_url || item.manage_url, className: "inline-flex items-center gap-2 rounded-full border border-white/10 px-4 py-2 text-sm text-slate-200" }, "Reschedule"), item.preview_url && /* @__PURE__ */ React.createElement("a", { href: item.preview_url, className: "inline-flex items-center gap-2 rounded-full border border-white/10 px-4 py-2 text-sm text-slate-200" }, "Preview"), /* @__PURE__ */ React.createElement("button", { type: "button", disabled: busyId === `publish:${item.id}`, onClick: () => runAction(item, "publish"), className: "inline-flex items-center gap-2 rounded-full border border-sky-300/20 bg-sky-300/10 px-4 py-2 text-sm text-sky-100 disabled:opacity-50" }, "Publish now"), /* @__PURE__ */ React.createElement("button", { type: "button", disabled: busyId === `unschedule:${item.id}`, onClick: () => runAction(item, "unschedule"), className: "inline-flex items-center gap-2 rounded-full border border-white/10 px-4 py-2 text-sm text-slate-200 disabled:opacity-50" }, "Unschedule"))))) : /* @__PURE__ */ React.createElement("div", { className: "rounded-[28px] border border-dashed border-white/15 px-6 py-16 text-center text-slate-400" }, "No scheduled content matches this view.")), /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between rounded-[24px] border border-white/10 bg-white/[0.03] px-4 py-3 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("button", { type: "button", disabled: (meta.current_page || 1) <= 1, onClick: () => updateFilters({ page: Math.max(1, (meta.current_page || 1) - 1) }), className: "rounded-full border border-white/10 px-4 py-2 disabled:opacity-40" }, "Previous"), /* @__PURE__ */ React.createElement("span", { className: "text-xs uppercase tracking-[0.18em] text-slate-500" }, "Page ", meta.current_page || 1, " of ", meta.last_page || 1), /* @__PURE__ */ React.createElement("button", { type: "button", disabled: (meta.current_page || 1) >= (meta.last_page || 1), onClick: () => updateFilters({ page: (meta.current_page || 1) + 1 }), className: "rounded-full border border-white/10 px-4 py-2 disabled:opacity-40" }, "Next")))); } -const __vite_glob_0_150 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ +const __vite_glob_0_132 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ __proto__: null, default: StudioScheduled }, Symbol.toStringTag, { value: "Module" })); @@ -97118,7 +98925,7 @@ function StudioSearch() { }; return /* @__PURE__ */ React.createElement(StudioLayout, { title: props.title, subtitle: props.description }, /* @__PURE__ */ React.createElement("div", { className: "space-y-6" }, /* @__PURE__ */ React.createElement("section", { className: "rounded-[30px] border border-white/10 bg-[radial-gradient(circle_at_top_left,_rgba(56,189,248,0.14),_transparent_35%),linear-gradient(135deg,_rgba(15,23,42,0.86),_rgba(2,6,23,0.96))] p-5 lg:p-6" }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-3 md:grid-cols-2 xl:grid-cols-5" }, /* @__PURE__ */ React.createElement("label", { className: "space-y-2 text-sm text-slate-300 xl:col-span-3" }, /* @__PURE__ */ React.createElement("span", { className: "block text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, "Search Studio"), /* @__PURE__ */ React.createElement("input", { value: filters.q || "", onChange: (event) => updateFilters({ q: event.target.value }), className: "w-full rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white", placeholder: "Search content, comments, inbox, or assets" })), /* @__PURE__ */ React.createElement("div", { className: "space-y-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "block text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, "Surface"), /* @__PURE__ */ React.createElement(NovaSelect, { value: filters.type || "all", onChange: (val) => updateFilters({ type: val }), options: search2.type_options || [], searchable: false })), /* @__PURE__ */ React.createElement("div", { className: "space-y-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "block text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, "Module"), /* @__PURE__ */ React.createElement(NovaSelect, { value: filters.module || "all", onChange: (val) => updateFilters({ module: val }), options: search2.module_options || [], searchable: false })))), filters.q ? /* @__PURE__ */ React.createElement("div", { className: "space-y-6" }, /* @__PURE__ */ React.createElement("div", { className: "text-sm text-slate-400" }, "Found ", /* @__PURE__ */ React.createElement("span", { className: "font-semibold text-white" }, Number(search2.summary?.total || 0).toLocaleString()), " matches for ", /* @__PURE__ */ React.createElement("span", { className: "font-semibold text-white" }, search2.summary?.query)), sections.length > 0 ? sections.map((section) => /* @__PURE__ */ React.createElement("section", { key: section.key, className: "rounded-[30px] border border-white/10 bg-white/[0.03] p-6" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("h2", { className: "text-lg font-semibold text-white" }, section.label), /* @__PURE__ */ React.createElement("span", { className: "text-xs uppercase tracking-[0.18em] text-slate-500" }, section.count, " matches")), /* @__PURE__ */ React.createElement("div", { className: "mt-4 grid gap-3 md:grid-cols-2 xl:grid-cols-3" }, section.items.map((item) => /* @__PURE__ */ React.createElement("a", { key: item.id, href: item.href, className: "block rounded-[24px] border border-white/10 bg-black/20 p-4 transition hover:border-white/20" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-start gap-3" }, /* @__PURE__ */ React.createElement("div", { className: "flex h-10 w-10 items-center justify-center rounded-2xl bg-white/[0.04] text-sky-100" }, /* @__PURE__ */ React.createElement("i", { className: item.icon })), /* @__PURE__ */ React.createElement("div", { className: "min-w-0" }, /* @__PURE__ */ React.createElement("div", { className: "truncate text-base font-semibold text-white" }, item.title), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-xs uppercase tracking-[0.18em] text-slate-500" }, item.subtitle), /* @__PURE__ */ React.createElement("p", { className: "mt-3 line-clamp-3 text-sm leading-6 text-slate-400" }, item.description)))))))) : /* @__PURE__ */ React.createElement("div", { className: "rounded-[28px] border border-dashed border-white/15 px-6 py-16 text-center text-slate-400" }, "No results matched this search yet.")) : /* @__PURE__ */ React.createElement("div", { className: "grid gap-6 xl:grid-cols-[minmax(0,1fr)_320px]" }, /* @__PURE__ */ React.createElement("section", { className: "rounded-[30px] border border-white/10 bg-white/[0.03] p-6" }, /* @__PURE__ */ React.createElement("h2", { className: "text-lg font-semibold text-white" }, "Continue working"), /* @__PURE__ */ React.createElement("div", { className: "mt-4 grid gap-3 md:grid-cols-2" }, (search2.empty_state?.continue_working || []).map((item) => /* @__PURE__ */ React.createElement("a", { key: item.id, href: item.edit_url || item.manage_url, className: "block rounded-[24px] border border-white/10 bg-black/20 p-4" }, /* @__PURE__ */ React.createElement("div", { className: "text-sm font-semibold text-white" }, item.title), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-xs text-slate-500" }, item.module_label, " · ", item.workflow?.readiness?.label))))), /* @__PURE__ */ React.createElement("aside", { className: "space-y-6" }, /* @__PURE__ */ React.createElement("section", { className: "rounded-[30px] border border-white/10 bg-white/[0.03] p-5" }, /* @__PURE__ */ React.createElement("h2", { className: "text-lg font-semibold text-white" }, "Stale drafts"), /* @__PURE__ */ React.createElement("div", { className: "mt-4 space-y-3" }, (search2.empty_state?.stale_drafts || []).map((item) => /* @__PURE__ */ React.createElement("a", { key: item.id, href: item.edit_url || item.manage_url, className: "block rounded-2xl border border-white/10 bg-black/20 p-4" }, /* @__PURE__ */ React.createElement("div", { className: "text-sm font-semibold text-white" }, item.title), /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-xs text-slate-500" }, item.module_label))))), /* @__PURE__ */ React.createElement("section", { className: "rounded-[30px] border border-white/10 bg-white/[0.03] p-5" }, /* @__PURE__ */ React.createElement("h2", { className: "text-lg font-semibold text-white" }, "Quick create"), /* @__PURE__ */ React.createElement("div", { className: "mt-4 grid gap-3" }, (props.quickCreate || []).map((item) => /* @__PURE__ */ React.createElement("a", { key: item.key, href: item.url, className: "inline-flex items-center gap-3 rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-sm text-slate-100" }, /* @__PURE__ */ React.createElement("i", { className: item.icon }), /* @__PURE__ */ React.createElement("span", null, "New ", item.label))))))))); } -const __vite_glob_0_151 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ +const __vite_glob_0_133 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ __proto__: null, default: StudioSearch }, Symbol.toStringTag, { value: "Module" })); @@ -97126,7 +98933,7 @@ function StudioSettings() { const { props } = X(); return /* @__PURE__ */ React.createElement(StudioLayout, { title: props.title, subtitle: props.description }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-6 xl:grid-cols-[minmax(0,1fr)_360px]" }, /* @__PURE__ */ React.createElement("section", { className: "rounded-[30px] border border-white/10 bg-white/[0.03] p-6" }, /* @__PURE__ */ React.createElement("h2", { className: "text-lg font-semibold text-white" }, "System handoff"), /* @__PURE__ */ React.createElement("p", { className: "mt-2 max-w-2xl text-sm leading-6 text-slate-400" }, "Studio now keeps creator workflow preferences in their own surface. This page stays focused on links out to adjacent dashboards and the control points that do not belong in the day-to-day workflow UI."), /* @__PURE__ */ React.createElement("div", { className: "mt-5 grid gap-3 md:grid-cols-2" }, (props.links || []).map((link2) => /* @__PURE__ */ React.createElement("a", { key: link2.url, href: link2.url, className: "rounded-[22px] border border-white/10 bg-black/20 p-4 transition hover:border-white/20 hover:bg-black/30" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-3 text-sky-100" }, /* @__PURE__ */ React.createElement("i", { className: link2.icon }), /* @__PURE__ */ React.createElement("span", { className: "text-base font-semibold text-white" }, link2.label)), /* @__PURE__ */ React.createElement("p", { className: "mt-3 text-sm leading-6 text-slate-400" }, "Open the linked dashboard or settings surface without losing the Studio navigation shell as the default control plane."))))), /* @__PURE__ */ React.createElement("section", { className: "space-y-6" }, (props.sections || []).map((section) => /* @__PURE__ */ React.createElement("div", { key: section.title, className: "rounded-[30px] border border-white/10 bg-white/[0.03] p-6" }, /* @__PURE__ */ React.createElement("h2", { className: "text-lg font-semibold text-white" }, section.title), /* @__PURE__ */ React.createElement("p", { className: "mt-3 text-sm leading-6 text-slate-400" }, section.body), /* @__PURE__ */ React.createElement("a", { href: section.href, className: "mt-4 inline-flex items-center gap-2 rounded-full border border-sky-300/20 bg-sky-300/10 px-4 py-2 text-sm font-semibold text-sky-100 transition hover:border-sky-300/35 hover:bg-sky-300/15" }, section.cta, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-arrow-right" }))))))); } -const __vite_glob_0_152 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ +const __vite_glob_0_134 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ __proto__: null, default: StudioSettings }, Symbol.toStringTag, { value: "Module" })); @@ -97139,7 +98946,7 @@ function StudioStories() { ["Published", summary.published_count, "fa-solid fa-sparkles"] ].map(([label, value, icon]) => /* @__PURE__ */ React.createElement("div", { key: label, className: "rounded-[24px] border border-white/10 bg-white/[0.03] p-5" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center gap-3 text-slate-300" }, /* @__PURE__ */ React.createElement("i", { className: icon }), /* @__PURE__ */ React.createElement("span", { className: "text-sm" }, label)), /* @__PURE__ */ React.createElement("div", { className: "mt-3 text-3xl font-semibold text-white" }, Number(value || 0).toLocaleString()))), /* @__PURE__ */ React.createElement("a", { href: props.dashboardUrl, className: "rounded-[24px] border border-sky-300/20 bg-sky-300/10 p-5 text-sky-100 transition hover:border-sky-300/35 hover:bg-sky-300/15" }, /* @__PURE__ */ React.createElement("p", { className: "text-[11px] font-semibold uppercase tracking-[0.2em]" }, "Story dashboard"), /* @__PURE__ */ React.createElement("p", { className: "mt-3 text-sm leading-6" }, "Jump into the existing story workspace when you need the full editor and publishing controls."))), /* @__PURE__ */ React.createElement(StudioContentBrowser, { listing: props.listing, quickCreate: props.quickCreate, hideModuleFilter: true })); } -const __vite_glob_0_153 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ +const __vite_glob_0_135 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ __proto__: null, default: StudioStories }, Symbol.toStringTag, { value: "Module" })); @@ -97802,7 +99609,7 @@ function StudioUploadQueue() { ))))); }))))); } -const __vite_glob_0_154 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ +const __vite_glob_0_136 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ __proto__: null, default: StudioUploadQueue }, Symbol.toStringTag, { value: "Module" })); @@ -99534,7 +101341,7 @@ function StudioWorldEditor() { )) : null )); } -const __vite_glob_0_155 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ +const __vite_glob_0_137 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ __proto__: null, default: StudioWorldEditor }, Symbol.toStringTag, { value: "Module" })); @@ -99620,7 +101427,7 @@ function StudioWorldsIndex() { }; return /* @__PURE__ */ React.createElement(StudioLayout, { title: props.title, subtitle: props.description }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-6" }, /* @__PURE__ */ React.createElement(WorldAnalyticsPortfolioPanel, { analytics: props.analytics }), /* @__PURE__ */ React.createElement("section", { className: "rounded-[28px] border border-white/10 bg-white/[0.03] p-5" }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 lg:grid-cols-[minmax(0,1fr)_12rem_12rem_auto] lg:items-end" }, /* @__PURE__ */ React.createElement("label", { className: "grid gap-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Search"), /* @__PURE__ */ React.createElement("input", { value: filters.q || "", onChange: (event) => updateFilter("q", event.target.value), placeholder: "Search title, slug, or summary", className: "rounded-2xl border border-white/10 bg-black/20 px-4 py-3 text-white outline-none" })), /* @__PURE__ */ React.createElement("div", { className: "grid gap-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Status"), /* @__PURE__ */ React.createElement(NovaSelect, { value: filters.status || "", onChange: (val) => updateFilter("status", val), options: [{ value: "", label: "All statuses" }, ...props.statusOptions || []], searchable: false })), /* @__PURE__ */ React.createElement("div", { className: "grid gap-2 text-sm text-slate-300" }, /* @__PURE__ */ React.createElement("span", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-500" }, "Type"), /* @__PURE__ */ React.createElement(NovaSelect, { value: filters.type || "", onChange: (val) => updateFilter("type", val), options: [{ value: "", label: "All types" }, ...props.typeOptions || []], searchable: false })), /* @__PURE__ */ React.createElement("a", { href: props.createUrl, className: "inline-flex items-center justify-center gap-2 rounded-2xl border border-sky-300/20 bg-sky-400/10 px-5 py-3 text-sm font-semibold text-sky-100 transition hover:bg-sky-400/15" }, /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-plus" }), "New world"))), /* @__PURE__ */ React.createElement("section", { className: "grid gap-4 xl:grid-cols-2" }, items.length > 0 ? items.map((world) => /* @__PURE__ */ React.createElement("a", { key: world.id, href: world.edit_url, className: "rounded-[28px] border border-white/10 bg-white/[0.03] p-5 transition hover:-translate-y-1 hover:border-white/20 hover:bg-white/[0.05]" }, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center gap-2 text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-500" }, /* @__PURE__ */ React.createElement(WorldStatusBadge, { badge: { label: world.status, tone: "slate" } }), /* @__PURE__ */ React.createElement(WorldStatusBadge, { badge: { label: world.type, tone: "slate" } }), (Array.isArray(world.status_badges) ? world.status_badges : []).map((badge) => /* @__PURE__ */ React.createElement(WorldStatusBadge, { key: `${world.id}-${badge.label}`, badge }))), /* @__PURE__ */ React.createElement("h2", { className: "mt-4 text-2xl font-semibold tracking-[-0.03em] text-white" }, world.title), /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-sm text-slate-500" }, "/", world.slug), world.summary ? /* @__PURE__ */ React.createElement("p", { className: "mt-4 text-sm leading-6 text-slate-300" }, world.summary) : null, /* @__PURE__ */ React.createElement("div", { className: "mt-5 flex flex-wrap gap-4 text-sm text-slate-400" }, world.timeframe_label ? /* @__PURE__ */ React.createElement("span", null, world.timeframe_label) : null, world.promotion_window_label ? /* @__PURE__ */ React.createElement("span", null, world.promotion_window_label) : null, /* @__PURE__ */ React.createElement("span", null, world.relation_count, " relations"), world.live_submission_count > 0 ? /* @__PURE__ */ React.createElement("span", null, world.live_submission_count, " live submissions") : null, world.theme_key ? /* @__PURE__ */ React.createElement("span", null, world.theme_key) : null), /* @__PURE__ */ React.createElement("div", { className: "mt-5 flex flex-wrap gap-3 text-sm font-semibold" }, /* @__PURE__ */ React.createElement("span", { className: "text-sky-100" }, "Edit"), /* @__PURE__ */ React.createElement("span", { className: "text-slate-500" }, "Preview"), world.public_url ? /* @__PURE__ */ React.createElement("span", { className: "text-slate-500" }, "Public") : null))) : /* @__PURE__ */ React.createElement("div", { className: "rounded-[28px] border border-dashed border-white/10 bg-white/[0.02] p-6 text-sm text-slate-400" }, "No worlds match this filter yet.")))); } -const __vite_glob_0_156 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ +const __vite_glob_0_138 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ __proto__: null, default: StudioWorldsIndex }, Symbol.toStringTag, { value: "Module" })); @@ -104227,10 +106034,142 @@ function UploadPage({ draftId, filesCdnUrl, chunkSize, chunkRequestTimeoutMs }) "Reset" )))), /* @__PURE__ */ React.createElement("div", { className: "space-y-6" }, /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-white/5 p-6" }, /* @__PURE__ */ React.createElement("h3", { className: "text-lg font-semibold" }, "Pipeline status"), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm text-white/60" }, "Stage: ", /* @__PURE__ */ React.createElement("span", { className: "text-white" }, statusLabel2)), /* @__PURE__ */ React.createElement("div", { className: "mt-4 h-2 w-full overflow-hidden rounded-full bg-white/10" }, /* @__PURE__ */ React.createElement("div", { className: "h-full bg-sky-400 transition-all", style: { width: `${state.progress}%` } })), state.failureReason && /* @__PURE__ */ React.createElement("div", { className: "mt-3 text-sm text-red-200" }, "Failure: ", state.failureReason), state.previewUrl && state.phase === phases.success && /* @__PURE__ */ React.createElement("div", { className: "mt-6" }, /* @__PURE__ */ React.createElement("h4", { className: "text-sm font-semibold text-white/80" }, "CDN preview"), /* @__PURE__ */ React.createElement("div", { className: "mt-2 overflow-hidden rounded-xl border border-white/10" }, /* @__PURE__ */ React.createElement("img", { src: state.previewUrl, alt: "CDN preview", className: "h-56 w-full object-cover" }))), /* @__PURE__ */ React.createElement("div", { className: "mt-6 rounded-xl border border-white/10 bg-white/5 px-4 py-3 text-xs text-white/60" }, "Session: ", state.sessionId ?? "—")), /* @__PURE__ */ React.createElement("div", { className: "rounded-2xl border border-white/10 bg-white/5 p-6" }, /* @__PURE__ */ React.createElement("h3", { className: "text-lg font-semibold" }, "Draft resume"), /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm text-white/60" }, "Use the draft link to resume an interrupted upload."), draftId ? /* @__PURE__ */ React.createElement("div", { className: "mt-4 text-sm text-white/80" }, "Draft ID: ", draftId) : /* @__PURE__ */ React.createElement("div", { className: "mt-4 text-sm text-white/50" }, "No draft loaded.")))))); } -const __vite_glob_0_157 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ +const __vite_glob_0_139 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ __proto__: null, default: UploadPage }, Symbol.toStringTag, { value: "Module" })); +function themeStyle$1(theme) { + return { + "--world-accent": theme?.accent_color || "#38bdf8", + "--world-accent-secondary": theme?.accent_color_secondary || "#0f172a" + }; +} +function WorldCard({ world, compact = false, sourceSurface = "", sourceDetail = "" }) { + const cardRef = reactExports.useRef(null); + const href = world && sourceSurface ? withWorldSource(world.public_url, sourceSurface, sourceDetail) : world?.public_url; + reactExports.useEffect(() => { + if (!sourceSurface || !world?.id || typeof window === "undefined") { + return void 0; + } + const node2 = cardRef.current; + if (!node2) { + return void 0; + } + if (typeof window.IntersectionObserver !== "function") { + trackWorldSourceImpression({ + worldId: world.id, + worldTitle: world.title, + sourceSurface, + sourceDetail, + sectionKey: compact ? "compact_card" : "card" + }); + return void 0; + } + const observer = new window.IntersectionObserver((entries) => { + entries.forEach((entry) => { + if (!entry.isIntersecting || entry.intersectionRatio < 0.4) { + return; + } + trackWorldSourceImpression({ + worldId: world.id, + worldTitle: world.title, + sourceSurface, + sourceDetail, + sectionKey: compact ? "compact_card" : "card" + }); + observer.disconnect(); + }); + }, { threshold: [0.4] }); + observer.observe(node2); + return () => observer.disconnect(); + }, [compact, sourceDetail, sourceSurface, world?.id, world?.title]); + if (!world) { + return null; + } + return /* @__PURE__ */ React.createElement( + "a", + { + ref: cardRef, + href, + onClick: () => trackWorldSourceClick({ worldId: world.id, worldTitle: world.title, sourceSurface, sourceDetail }), + className: `group relative block w-full overflow-hidden rounded-[28px] border border-white/10 bg-slate-950/70 transition duration-300 hover:-translate-y-1 hover:border-white/20 ${compact ? "p-5" : "p-6"}`, + style: themeStyle$1(world.theme) + }, + /* @__PURE__ */ React.createElement("div", { className: "absolute inset-0 bg-[radial-gradient(circle_at_top_right,_color-mix(in_srgb,var(--world-accent)_30%,transparent),_transparent_42%),linear-gradient(135deg,_color-mix(in_srgb,var(--world-accent-secondary)_94%,black),_rgba(2,6,23,0.94))] opacity-95" }), + world.cover_url ? /* @__PURE__ */ React.createElement("img", { src: world.cover_url, alt: world.title, className: "absolute inset-0 h-full w-full object-cover opacity-20 transition duration-500 group-hover:scale-[1.03]" }) : null, + /* @__PURE__ */ React.createElement("div", { className: "absolute inset-0 bg-gradient-to-t from-slate-950 via-slate-950/80 to-slate-950/10" }), + /* @__PURE__ */ React.createElement("div", { className: "relative flex h-full min-h-[16rem] flex-col justify-between" }, /* @__PURE__ */ React.createElement("div", null, world.is_recurring ? /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.2em] text-sky-100/70" }, world.family_title || "Recurring family", world.edition_label ? /* @__PURE__ */ React.createElement("span", { className: "ml-2 text-slate-300/70" }, world.edition_label) : null) : null, /* @__PURE__ */ React.createElement("div", { className: "flex flex-wrap items-center gap-2" }, (Array.isArray(world.status_badges) ? world.status_badges : []).map((badge) => /* @__PURE__ */ React.createElement(WorldStatusBadge, { key: badge.label, badge })), !Array.isArray(world.status_badges) || world.status_badges.length === 0 ? /* @__PURE__ */ React.createElement(WorldStatusBadge, { badge: { label: world.phase || world.status, tone: "slate" } }) : null, world.campaign_label ? /* @__PURE__ */ React.createElement(WorldStatusBadge, { badge: { label: world.campaign_label, tone: "slate" } }) : null, world.badge_label ? /* @__PURE__ */ React.createElement(WorldStatusBadge, { badge: { label: world.badge_label, tone: "rose" } }) : null), world.teaser_title && world.teaser_title !== world.title ? /* @__PURE__ */ React.createElement("p", { className: "mt-4 text-[11px] font-semibold uppercase tracking-[0.2em] text-sky-100/70" }, world.title) : null, /* @__PURE__ */ React.createElement("h3", { className: `mt-4 max-w-xl font-semibold tracking-[-0.03em] text-white ${compact ? "text-2xl" : "text-3xl"}` }, world.teaser_title || world.title), world.tagline ? /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm uppercase tracking-[0.18em] text-white/55" }, world.tagline) : null, world.summary ? /* @__PURE__ */ React.createElement("p", { className: "mt-4 max-w-2xl text-sm leading-6 text-slate-200/85" }, world.summary) : null), /* @__PURE__ */ React.createElement("div", { className: "mt-6 flex flex-wrap items-end justify-between gap-3" }, /* @__PURE__ */ React.createElement(WorldCampaignMeta, { world }), /* @__PURE__ */ React.createElement("span", { className: "inline-flex items-center gap-2 rounded-full border border-white/15 bg-white/10 px-4 py-2 text-sm font-semibold text-white transition group-hover:bg-white/15" }, world.cta_label || world.challenge_cta_label || (world.is_recurring && !world.is_canonical_edition ? "Open edition" : "Open world"), /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-arrow-right" })))) + ); +} +function ActiveWorldSpotlight({ + spotlight, + secondary = [], + indexUrl = "/worlds", + eyebrow = "World spotlight", + secondaryTitle = "Campaign rail", + className = "", + sourceSurface = "", + sourceDetail = "", + secondarySourceSurface = "", + secondarySourceDetail = "" +}) { + const spotlightRef = reactExports.useRef(null); + const primaryHref = spotlight && sourceSurface ? withWorldSource(spotlight.public_url || spotlight.cta_url, sourceSurface, sourceDetail) : spotlight?.public_url || spotlight?.cta_url; + reactExports.useEffect(() => { + if (!spotlight?.id || !sourceSurface || typeof window === "undefined") { + return void 0; + } + const node2 = spotlightRef.current; + if (!node2) { + return void 0; + } + if (typeof window.IntersectionObserver !== "function") { + trackWorldSourceImpression({ + worldId: spotlight.id, + worldTitle: spotlight.title || spotlight.headline, + sourceSurface, + sourceDetail, + sectionKey: "spotlight" + }); + return void 0; + } + const observer = new window.IntersectionObserver((entries) => { + entries.forEach((entry) => { + if (!entry.isIntersecting || entry.intersectionRatio < 0.45) { + return; + } + trackWorldSourceImpression({ + worldId: spotlight.id, + worldTitle: spotlight.title || spotlight.headline, + sourceSurface, + sourceDetail, + sectionKey: "spotlight" + }); + observer.disconnect(); + }); + }, { threshold: [0.45] }); + observer.observe(node2); + return () => observer.disconnect(); + }, [spotlight?.headline, spotlight?.id, spotlight?.title, sourceDetail, sourceSurface]); + if (!spotlight) { + return null; + } + return /* @__PURE__ */ React.createElement("section", { className }, /* @__PURE__ */ React.createElement( + "div", + { + ref: spotlightRef, + className: "group relative overflow-hidden rounded-[32px] border border-white/10 bg-slate-950/70", + style: { + "--world-accent": spotlight.theme?.accent_color || "#f97316", + "--world-accent-secondary": spotlight.theme?.accent_color_secondary || "#0f172a" + } + }, + /* @__PURE__ */ React.createElement("div", { className: "absolute inset-0 bg-[radial-gradient(circle_at_top_left,_color-mix(in_srgb,var(--world-accent)_30%,transparent),_transparent_36%),linear-gradient(135deg,_color-mix(in_srgb,var(--world-accent-secondary)_92%,black),_rgba(2,6,23,0.98))]" }), + spotlight.cover_url ? /* @__PURE__ */ React.createElement("img", { src: spotlight.cover_url, alt: spotlight.title || spotlight.headline, className: "absolute inset-0 h-full w-full object-cover opacity-20 transition duration-500 group-hover:scale-[1.03]" }) : null, + /* @__PURE__ */ React.createElement("div", { className: "absolute inset-0 bg-gradient-to-r from-slate-950 via-slate-950/84 to-slate-950/28" }), + /* @__PURE__ */ React.createElement("div", { className: "relative grid gap-8 px-6 py-7 sm:px-8 lg:grid-cols-[minmax(0,1.2fr)_20rem] lg:px-10" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.22em] text-white/70" }, eyebrow), /* @__PURE__ */ React.createElement("div", { className: "mt-4 flex flex-wrap gap-2" }, (Array.isArray(spotlight.status_badges) ? spotlight.status_badges : []).map((badge) => /* @__PURE__ */ React.createElement(WorldStatusBadge, { key: badge.label, badge })), spotlight.campaign_label ? /* @__PURE__ */ React.createElement(WorldStatusBadge, { badge: { label: spotlight.campaign_label, tone: "slate" } }) : null), spotlight.title && spotlight.headline && spotlight.title !== spotlight.headline ? /* @__PURE__ */ React.createElement("p", { className: "mt-5 text-[11px] font-semibold uppercase tracking-[0.22em] text-sky-100/70" }, spotlight.title) : null, /* @__PURE__ */ React.createElement("h2", { className: "mt-3 text-3xl font-semibold tracking-[-0.04em] text-white sm:text-4xl" }, spotlight.headline || spotlight.title), spotlight.tagline ? /* @__PURE__ */ React.createElement("p", { className: "mt-2 text-sm uppercase tracking-[0.18em] text-white/55" }, spotlight.tagline) : null, spotlight.summary ? /* @__PURE__ */ React.createElement("p", { className: "mt-4 max-w-3xl text-sm leading-7 text-slate-200/88" }, spotlight.summary) : null, /* @__PURE__ */ React.createElement(WorldCampaignMeta, { world: spotlight, className: "mt-6" }), spotlight.supporting_item ? /* @__PURE__ */ React.createElement("a", { href: spotlight.supporting_item.url, className: "mt-6 inline-flex max-w-xl items-center gap-3 rounded-[22px] border border-white/12 bg-black/25 px-4 py-3 text-left text-sm text-slate-100 transition hover:border-white/20 hover:bg-white/[0.06]" }, /* @__PURE__ */ React.createElement("div", { className: "min-w-0" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-400" }, spotlight.supporting_item.entity_label || "Related item"), /* @__PURE__ */ React.createElement("div", { className: "mt-1 truncate font-semibold text-white" }, spotlight.supporting_item.title), spotlight.supporting_item.context_label ? /* @__PURE__ */ React.createElement("div", { className: "mt-1 text-xs text-slate-300/80" }, spotlight.supporting_item.context_label) : null), /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-arrow-right shrink-0 text-xs text-sky-100" })) : null, /* @__PURE__ */ React.createElement("div", { className: "mt-6 flex flex-wrap gap-3" }, /* @__PURE__ */ React.createElement("a", { href: primaryHref, onClick: () => trackWorldSourceClick({ worldId: spotlight.id, worldTitle: spotlight.title || spotlight.headline, sourceSurface, sourceDetail }), className: "inline-flex items-center gap-2 rounded-full bg-white px-4 py-2.5 text-sm font-semibold text-slate-950 transition group-hover:bg-sky-100" }, spotlight.cta_label || "Explore world", /* @__PURE__ */ React.createElement("i", { className: "fa-solid fa-arrow-right" })), /* @__PURE__ */ React.createElement("a", { href: indexUrl, className: "inline-flex items-center gap-2 rounded-full border border-white/12 bg-white/[0.05] px-4 py-2.5 text-sm font-semibold text-white transition hover:bg-white/[0.08]" }, "Browse all worlds"))), /* @__PURE__ */ React.createElement("div", { className: "rounded-[28px] border border-white/12 bg-black/25 p-5 text-white backdrop-blur-sm" }, /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-400" }, "Campaign state"), /* @__PURE__ */ React.createElement("div", { className: "mt-3 flex items-center gap-3 text-lg font-semibold" }, /* @__PURE__ */ React.createElement("i", { className: spotlight.icon_name || "fa-solid fa-globe" }), /* @__PURE__ */ React.createElement("span", null, spotlight.theme?.label || "Editorial world")), spotlight.timeframe_label ? /* @__PURE__ */ React.createElement("div", { className: "mt-4 text-sm text-slate-300" }, spotlight.timeframe_label) : null, spotlight.promotion_window_label ? /* @__PURE__ */ React.createElement("div", { className: "mt-2 text-sm text-slate-400" }, spotlight.promotion_window_label) : null, Number(spotlight.live_submission_count || 0) > 0 ? /* @__PURE__ */ React.createElement("div", { className: "mt-5 rounded-2xl border border-emerald-300/20 bg-emerald-400/10 px-4 py-3 text-sm text-emerald-100" }, spotlight.live_submission_count, " live submissions are already part of this campaign.") : null)) + ), Array.isArray(secondary) && secondary.length > 0 ? /* @__PURE__ */ React.createElement("div", { className: "mt-6" }, /* @__PURE__ */ React.createElement("div", { className: "mb-4 flex items-end justify-between gap-4" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("h3", { className: "text-xl font-semibold tracking-[-0.03em] text-white" }, secondaryTitle), /* @__PURE__ */ React.createElement("p", { className: "mt-1 text-sm leading-6 text-slate-400" }, "More live or upcoming worlds that are being actively surfaced right now.")), /* @__PURE__ */ React.createElement("div", { className: "text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-400" }, secondary.length, " worlds")), /* @__PURE__ */ React.createElement("div", { className: "grid gap-4 xl:grid-cols-3" }, secondary.map((world) => /* @__PURE__ */ React.createElement(WorldCard, { key: world.id, world, compact: true, sourceSurface: secondarySourceSurface || sourceSurface, sourceDetail: secondarySourceDetail || sourceDetail })))) : null); +} function themeStyle(theme) { return { "--world-accent": theme?.accent_color || "#38bdf8", @@ -104339,7 +106278,7 @@ function WorldIndex() { } ))); } -const __vite_glob_0_158 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ +const __vite_glob_0_140 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ __proto__: null, default: WorldIndex }, Symbol.toStringTag, { value: "Module" })); @@ -104633,7 +106572,7 @@ function WorldShow() { } ))); } -const __vite_glob_0_159 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ +const __vite_glob_0_141 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ __proto__: null, default: WorldShow }, Symbol.toStringTag, { value: "Module" })); @@ -130223,7 +132162,150 @@ function requireServer_node() { } var server_nodeExports = requireServer_node(); const ReactDOMServer = /* @__PURE__ */ getDefaultExportFromCjs(server_nodeExports); -const pages = /* @__PURE__ */ Object.assign({ "./Pages/Academy/ChallengeSubmit.jsx": __vite_glob_0_0, "./Pages/Academy/Index.jsx": __vite_glob_0_1, "./Pages/Academy/List.jsx": __vite_glob_0_2, "./Pages/Academy/Pricing.jsx": __vite_glob_0_3, "./Pages/Academy/Show.jsx": __vite_glob_0_4, "./Pages/Admin/Academy/CrudForm.jsx": __vite_glob_0_5, "./Pages/Admin/Academy/CrudIndex.jsx": __vite_glob_0_6, "./Pages/Admin/Academy/Dashboard.jsx": __vite_glob_0_7, "./Pages/Admin/Academy/Submissions.jsx": __vite_glob_0_8, "./Pages/Admin/AiBiography.jsx": __vite_glob_0_9, "./Pages/Admin/Artworks.jsx": __vite_glob_0_10, "./Pages/Admin/AuthAudit.jsx": __vite_glob_0_11, "./Pages/Admin/DailyActivity.jsx": __vite_glob_0_12, "./Pages/Admin/Dashboard.jsx": __vite_glob_0_13, "./Pages/Admin/FeaturedArtworks.jsx": __vite_glob_0_14, "./Pages/Admin/HomepageAnnouncements/Form.jsx": __vite_glob_0_15, "./Pages/Admin/HomepageAnnouncements/Index.jsx": __vite_glob_0_16, "./Pages/Admin/Settings.jsx": __vite_glob_0_17, "./Pages/Admin/Stories.jsx": __vite_glob_0_18, "./Pages/Admin/UploadQueue.jsx": __vite_glob_0_19, "./Pages/Admin/UsernameQueue.jsx": __vite_glob_0_20, "./Pages/Admin/Users/Index.jsx": __vite_glob_0_21, "./Pages/Artwork/SimilarArtworksHeader.jsx": __vite_glob_0_22, "./Pages/ArtworkPage.jsx": __vite_glob_0_23, "./Pages/CategoriesPage.jsx": __vite_glob_0_24, "./Pages/Collection/CollectionAnalytics.jsx": __vite_glob_0_25, "./Pages/Collection/CollectionDashboard.jsx": __vite_glob_0_26, "./Pages/Collection/CollectionFeaturedIndex.jsx": __vite_glob_0_27, "./Pages/Collection/CollectionHistory.jsx": __vite_glob_0_28, "./Pages/Collection/CollectionManage.jsx": __vite_glob_0_29, "./Pages/Collection/CollectionSeriesShow.jsx": __vite_glob_0_30, "./Pages/Collection/CollectionShow.jsx": __vite_glob_0_31, "./Pages/Collection/CollectionStaffProgramming.jsx": __vite_glob_0_32, "./Pages/Collection/CollectionStaffSurfaces.jsx": __vite_glob_0_33, "./Pages/Collection/FeaturedArtworksAdmin.jsx": __vite_glob_0_34, "./Pages/Collection/NovaCardsAdminIndex.jsx": __vite_glob_0_35, "./Pages/Collection/NovaCardsAssetPackAdmin.jsx": __vite_glob_0_36, "./Pages/Collection/NovaCardsChallengeAdmin.jsx": __vite_glob_0_37, "./Pages/Collection/NovaCardsCollectionAdmin.jsx": __vite_glob_0_38, "./Pages/Collection/NovaCardsTemplateAdmin.jsx": __vite_glob_0_39, "./Pages/Collection/SavedCollections.jsx": __vite_glob_0_40, "./Pages/Community/CommunityActivityPage.jsx": __vite_glob_0_41, "./Pages/Community/LatestCommentsPage.jsx": __vite_glob_0_42, "./Pages/Feed/FollowingFeed.jsx": __vite_glob_0_43, "./Pages/Feed/HashtagFeed.jsx": __vite_glob_0_44, "./Pages/Feed/SavedFeed.jsx": __vite_glob_0_45, "./Pages/Feed/SearchFeed.jsx": __vite_glob_0_46, "./Pages/Feed/TrendingFeed.jsx": __vite_glob_0_47, "./Pages/Forum/ForumCategory.jsx": __vite_glob_0_48, "./Pages/Forum/ForumEditPost.jsx": __vite_glob_0_49, "./Pages/Forum/ForumIndex.jsx": __vite_glob_0_50, "./Pages/Forum/ForumNewThread.jsx": __vite_glob_0_51, "./Pages/Forum/ForumSection.jsx": __vite_glob_0_52, "./Pages/Forum/ForumThread.jsx": __vite_glob_0_53, "./Pages/Group/GroupChallengeShow.jsx": __vite_glob_0_54, "./Pages/Group/GroupEventShow.jsx": __vite_glob_0_55, "./Pages/Group/GroupFaqPage.jsx": __vite_glob_0_56, "./Pages/Group/GroupHelpPage.jsx": __vite_glob_0_57, "./Pages/Group/GroupIndex.jsx": __vite_glob_0_58, "./Pages/Group/GroupPostShow.jsx": __vite_glob_0_59, "./Pages/Group/GroupProjectShow.jsx": __vite_glob_0_60, "./Pages/Group/GroupQuickstartPage.jsx": __vite_glob_0_61, "./Pages/Group/GroupReleaseShow.jsx": __vite_glob_0_62, "./Pages/Group/GroupShow.jsx": __vite_glob_0_63, "./Pages/Help/AccountHelpPage.jsx": __vite_glob_0_64, "./Pages/Help/AuthHelpPage.jsx": __vite_glob_0_65, "./Pages/Help/CardsHelpPage.jsx": __vite_glob_0_66, "./Pages/Help/HelpCenterPage.jsx": __vite_glob_0_67, "./Pages/Help/ProfileHelpPage.jsx": __vite_glob_0_68, "./Pages/Help/StudioHelpPage.jsx": __vite_glob_0_69, "./Pages/Help/TroubleshootingHelpPage.jsx": __vite_glob_0_70, "./Pages/Help/UploadHelpPage.jsx": __vite_glob_0_71, "./Pages/Help/WorldsHelpPage.jsx": __vite_glob_0_72, "./Pages/Home/HomeBecauseYouLike.jsx": __vite_glob_0_73, "./Pages/Home/HomeCTA.jsx": __vite_glob_0_74, "./Pages/Home/HomeCategories.jsx": __vite_glob_0_75, "./Pages/Home/HomeCollections.jsx": __vite_glob_0_76, "./Pages/Home/HomeCreators.jsx": __vite_glob_0_77, "./Pages/Home/HomeFresh.jsx": __vite_glob_0_78, "./Pages/Home/HomeFromFollowing.jsx": __vite_glob_0_79, "./Pages/Home/HomeGroups.jsx": __vite_glob_0_80, "./Pages/Home/HomeHero.jsx": __vite_glob_0_81, "./Pages/Home/HomeMedalHighlights.jsx": __vite_glob_0_82, "./Pages/Home/HomeNews.jsx": __vite_glob_0_83, "./Pages/Home/HomePage.jsx": __vite_glob_0_84, "./Pages/Home/HomeRising.jsx": __vite_glob_0_85, "./Pages/Home/HomeSuggestedCreators.jsx": __vite_glob_0_86, "./Pages/Home/HomeTags.jsx": __vite_glob_0_87, "./Pages/Home/HomeTrending.jsx": __vite_glob_0_88, "./Pages/Home/HomeTrendingForYou.jsx": __vite_glob_0_89, "./Pages/Home/HomeWelcomeRow.jsx": __vite_glob_0_90, "./Pages/Home/HomeWorldSpotlight.jsx": __vite_glob_0_91, "./Pages/Leaderboard/LeaderboardPage.jsx": __vite_glob_0_92, "./Pages/Messages/Index.jsx": __vite_glob_0_93, "./Pages/Moderation/AiBiographyAdmin.jsx": __vite_glob_0_94, "./Pages/Moderation/ArtworkMaturityQueue.jsx": __vite_glob_0_95, "./Pages/News/NewsComments.jsx": __vite_glob_0_96, "./Pages/Profile/ProfileGallery.jsx": __vite_glob_0_97, "./Pages/Profile/ProfileShow.jsx": __vite_glob_0_98, "./Pages/Settings/ProfileEdit.jsx": __vite_glob_0_99, "./Pages/Studio/StudioActivity.jsx": __vite_glob_0_100, "./Pages/Studio/StudioAnalytics.jsx": __vite_glob_0_101, "./Pages/Studio/StudioArchived.jsx": __vite_glob_0_102, "./Pages/Studio/StudioArtworkAnalytics.jsx": __vite_glob_0_103, "./Pages/Studio/StudioArtworkEdit.jsx": __vite_glob_0_104, "./Pages/Studio/StudioArtworks.jsx": __vite_glob_0_105, "./Pages/Studio/StudioAssets.jsx": __vite_glob_0_106, "./Pages/Studio/StudioCalendar.jsx": __vite_glob_0_107, "./Pages/Studio/StudioCardAnalytics.jsx": __vite_glob_0_108, "./Pages/Studio/StudioCardEditor.jsx": __vite_glob_0_109, "./Pages/Studio/StudioCardsIndex.jsx": __vite_glob_0_110, "./Pages/Studio/StudioChallenges.jsx": __vite_glob_0_111, "./Pages/Studio/StudioCollections.jsx": __vite_glob_0_112, "./Pages/Studio/StudioComments.jsx": __vite_glob_0_113, "./Pages/Studio/StudioContentIndex.jsx": __vite_glob_0_114, "./Pages/Studio/StudioDashboard.jsx": __vite_glob_0_115, "./Pages/Studio/StudioDrafts.jsx": __vite_glob_0_116, "./Pages/Studio/StudioFeatured.jsx": __vite_glob_0_117, "./Pages/Studio/StudioFollowers.jsx": __vite_glob_0_118, "./Pages/Studio/StudioGroupActivity.jsx": __vite_glob_0_119, "./Pages/Studio/StudioGroupArtworks.jsx": __vite_glob_0_120, "./Pages/Studio/StudioGroupAssets.jsx": __vite_glob_0_121, "./Pages/Studio/StudioGroupChallengeEditor.jsx": __vite_glob_0_122, "./Pages/Studio/StudioGroupChallenges.jsx": __vite_glob_0_123, "./Pages/Studio/StudioGroupCollections.jsx": __vite_glob_0_124, "./Pages/Studio/StudioGroupCreate.jsx": __vite_glob_0_125, "./Pages/Studio/StudioGroupDashboard.jsx": __vite_glob_0_126, "./Pages/Studio/StudioGroupEventEditor.jsx": __vite_glob_0_127, "./Pages/Studio/StudioGroupEvents.jsx": __vite_glob_0_128, "./Pages/Studio/StudioGroupInvitations.jsx": __vite_glob_0_129, "./Pages/Studio/StudioGroupJoinRequests.jsx": __vite_glob_0_130, "./Pages/Studio/StudioGroupMembers.jsx": __vite_glob_0_131, "./Pages/Studio/StudioGroupPostEditor.jsx": __vite_glob_0_132, "./Pages/Studio/StudioGroupPosts.jsx": __vite_glob_0_133, "./Pages/Studio/StudioGroupProjectEditor.jsx": __vite_glob_0_134, "./Pages/Studio/StudioGroupProjects.jsx": __vite_glob_0_135, "./Pages/Studio/StudioGroupRecruitment.jsx": __vite_glob_0_136, "./Pages/Studio/StudioGroupReleaseEditor.jsx": __vite_glob_0_137, "./Pages/Studio/StudioGroupReleases.jsx": __vite_glob_0_138, "./Pages/Studio/StudioGroupReputation.jsx": __vite_glob_0_139, "./Pages/Studio/StudioGroupReviewQueue.jsx": __vite_glob_0_140, "./Pages/Studio/StudioGroupSettings.jsx": __vite_glob_0_141, "./Pages/Studio/StudioGroupsIndex.jsx": __vite_glob_0_142, "./Pages/Studio/StudioGrowth.jsx": __vite_glob_0_143, "./Pages/Studio/StudioInbox.jsx": __vite_glob_0_144, "./Pages/Studio/StudioNewsEditor.jsx": __vite_glob_0_145, "./Pages/Studio/StudioNewsIndex.jsx": __vite_glob_0_146, "./Pages/Studio/StudioNewsTaxonomies.jsx": __vite_glob_0_147, "./Pages/Studio/StudioPreferences.jsx": __vite_glob_0_148, "./Pages/Studio/StudioProfile.jsx": __vite_glob_0_149, "./Pages/Studio/StudioScheduled.jsx": __vite_glob_0_150, "./Pages/Studio/StudioSearch.jsx": __vite_glob_0_151, "./Pages/Studio/StudioSettings.jsx": __vite_glob_0_152, "./Pages/Studio/StudioStories.jsx": __vite_glob_0_153, "./Pages/Studio/StudioUploadQueue.jsx": __vite_glob_0_154, "./Pages/Studio/StudioWorldEditor.jsx": __vite_glob_0_155, "./Pages/Studio/StudioWorldsIndex.jsx": __vite_glob_0_156, "./Pages/Upload/Index.jsx": __vite_glob_0_157, "./Pages/World/WorldIndex.jsx": __vite_glob_0_158, "./Pages/World/WorldShow.jsx": __vite_glob_0_159 }); +const pages = /* @__PURE__ */ Object.assign({ + "./Pages/Academy/ChallengeSubmit.jsx": __vite_glob_0_0, + "./Pages/Academy/Index.jsx": __vite_glob_0_1, + "./Pages/Academy/List.jsx": __vite_glob_0_2, + "./Pages/Academy/Pricing.jsx": __vite_glob_0_3, + "./Pages/Academy/Show.jsx": __vite_glob_0_4, + "./Pages/Admin/Academy/CrudForm.jsx": __vite_glob_0_5, + "./Pages/Admin/Academy/CrudIndex.jsx": __vite_glob_0_6, + "./Pages/Admin/Academy/Dashboard.jsx": __vite_glob_0_7, + "./Pages/Admin/Academy/LessonEditor.jsx": __vite_glob_0_8, + "./Pages/Admin/Academy/Submissions.jsx": __vite_glob_0_9, + "./Pages/Admin/AiBiography.jsx": __vite_glob_0_10, + "./Pages/Admin/Artworks.jsx": __vite_glob_0_11, + "./Pages/Admin/AuthAudit.jsx": __vite_glob_0_12, + "./Pages/Admin/DailyActivity.jsx": __vite_glob_0_13, + "./Pages/Admin/Dashboard.jsx": __vite_glob_0_14, + "./Pages/Admin/FeaturedArtworks.jsx": __vite_glob_0_15, + "./Pages/Admin/HomepageAnnouncements/Form.jsx": __vite_glob_0_16, + "./Pages/Admin/HomepageAnnouncements/Index.jsx": __vite_glob_0_17, + "./Pages/Admin/Settings.jsx": __vite_glob_0_18, + "./Pages/Admin/Stories.jsx": __vite_glob_0_19, + "./Pages/Admin/UploadQueue.jsx": __vite_glob_0_20, + "./Pages/Admin/UsernameQueue.jsx": __vite_glob_0_21, + "./Pages/Admin/Users/Index.jsx": __vite_glob_0_22, + "./Pages/Artwork/SimilarArtworksHeader.jsx": __vite_glob_0_23, + "./Pages/ArtworkPage.jsx": __vite_glob_0_24, + "./Pages/CategoriesPage.jsx": __vite_glob_0_25, + "./Pages/Collection/CollectionAnalytics.jsx": __vite_glob_0_26, + "./Pages/Collection/CollectionDashboard.jsx": __vite_glob_0_27, + "./Pages/Collection/CollectionFeaturedIndex.jsx": __vite_glob_0_28, + "./Pages/Collection/CollectionHistory.jsx": __vite_glob_0_29, + "./Pages/Collection/CollectionManage.jsx": __vite_glob_0_30, + "./Pages/Collection/CollectionSeriesShow.jsx": __vite_glob_0_31, + "./Pages/Collection/CollectionShow.jsx": __vite_glob_0_32, + "./Pages/Collection/CollectionStaffProgramming.jsx": __vite_glob_0_33, + "./Pages/Collection/CollectionStaffSurfaces.jsx": __vite_glob_0_34, + "./Pages/Collection/FeaturedArtworksAdmin.jsx": __vite_glob_0_35, + "./Pages/Collection/NovaCardsAdminIndex.jsx": __vite_glob_0_36, + "./Pages/Collection/NovaCardsAssetPackAdmin.jsx": __vite_glob_0_37, + "./Pages/Collection/NovaCardsChallengeAdmin.jsx": __vite_glob_0_38, + "./Pages/Collection/NovaCardsCollectionAdmin.jsx": __vite_glob_0_39, + "./Pages/Collection/NovaCardsTemplateAdmin.jsx": __vite_glob_0_40, + "./Pages/Collection/SavedCollections.jsx": __vite_glob_0_41, + "./Pages/Community/CommunityActivityPage.jsx": __vite_glob_0_42, + "./Pages/Community/LatestCommentsPage.jsx": __vite_glob_0_43, + "./Pages/Feed/FollowingFeed.jsx": __vite_glob_0_44, + "./Pages/Feed/HashtagFeed.jsx": __vite_glob_0_45, + "./Pages/Feed/SavedFeed.jsx": __vite_glob_0_46, + "./Pages/Feed/SearchFeed.jsx": __vite_glob_0_47, + "./Pages/Feed/TrendingFeed.jsx": __vite_glob_0_48, + "./Pages/Forum/ForumCategory.jsx": __vite_glob_0_49, + "./Pages/Forum/ForumEditPost.jsx": __vite_glob_0_50, + "./Pages/Forum/ForumIndex.jsx": __vite_glob_0_51, + "./Pages/Forum/ForumNewThread.jsx": __vite_glob_0_52, + "./Pages/Forum/ForumSection.jsx": __vite_glob_0_53, + "./Pages/Forum/ForumThread.jsx": __vite_glob_0_54, + "./Pages/Group/GroupChallengeShow.jsx": __vite_glob_0_55, + "./Pages/Group/GroupEventShow.jsx": __vite_glob_0_56, + "./Pages/Group/GroupFaqPage.jsx": __vite_glob_0_57, + "./Pages/Group/GroupHelpPage.jsx": __vite_glob_0_58, + "./Pages/Group/GroupIndex.jsx": __vite_glob_0_59, + "./Pages/Group/GroupPostShow.jsx": __vite_glob_0_60, + "./Pages/Group/GroupProjectShow.jsx": __vite_glob_0_61, + "./Pages/Group/GroupQuickstartPage.jsx": __vite_glob_0_62, + "./Pages/Group/GroupReleaseShow.jsx": __vite_glob_0_63, + "./Pages/Group/GroupShow.jsx": __vite_glob_0_64, + "./Pages/Help/AccountHelpPage.jsx": __vite_glob_0_65, + "./Pages/Help/AuthHelpPage.jsx": __vite_glob_0_66, + "./Pages/Help/CardsHelpPage.jsx": __vite_glob_0_67, + "./Pages/Help/HelpCenterPage.jsx": __vite_glob_0_68, + "./Pages/Help/ProfileHelpPage.jsx": __vite_glob_0_69, + "./Pages/Help/StudioHelpPage.jsx": __vite_glob_0_70, + "./Pages/Help/TroubleshootingHelpPage.jsx": __vite_glob_0_71, + "./Pages/Help/UploadHelpPage.jsx": __vite_glob_0_72, + "./Pages/Help/WorldsHelpPage.jsx": __vite_glob_0_73, + "./Pages/Leaderboard/LeaderboardPage.jsx": __vite_glob_0_74, + "./Pages/Messages/Index.jsx": __vite_glob_0_75, + "./Pages/Moderation/AiBiographyAdmin.jsx": __vite_glob_0_76, + "./Pages/Moderation/ArtworkMaturityQueue.jsx": __vite_glob_0_77, + "./Pages/News/NewsComments.jsx": __vite_glob_0_78, + "./Pages/Profile/ProfileGallery.jsx": __vite_glob_0_79, + "./Pages/Profile/ProfileShow.jsx": __vite_glob_0_80, + "./Pages/Settings/ProfileEdit.jsx": __vite_glob_0_81, + "./Pages/Studio/StudioActivity.jsx": __vite_glob_0_82, + "./Pages/Studio/StudioAnalytics.jsx": __vite_glob_0_83, + "./Pages/Studio/StudioArchived.jsx": __vite_glob_0_84, + "./Pages/Studio/StudioArtworkAnalytics.jsx": __vite_glob_0_85, + "./Pages/Studio/StudioArtworkEdit.jsx": __vite_glob_0_86, + "./Pages/Studio/StudioArtworks.jsx": __vite_glob_0_87, + "./Pages/Studio/StudioAssets.jsx": __vite_glob_0_88, + "./Pages/Studio/StudioCalendar.jsx": __vite_glob_0_89, + "./Pages/Studio/StudioCardAnalytics.jsx": __vite_glob_0_90, + "./Pages/Studio/StudioCardEditor.jsx": __vite_glob_0_91, + "./Pages/Studio/StudioCardsIndex.jsx": __vite_glob_0_92, + "./Pages/Studio/StudioChallenges.jsx": __vite_glob_0_93, + "./Pages/Studio/StudioCollections.jsx": __vite_glob_0_94, + "./Pages/Studio/StudioComments.jsx": __vite_glob_0_95, + "./Pages/Studio/StudioContentIndex.jsx": __vite_glob_0_96, + "./Pages/Studio/StudioDashboard.jsx": __vite_glob_0_97, + "./Pages/Studio/StudioDrafts.jsx": __vite_glob_0_98, + "./Pages/Studio/StudioFeatured.jsx": __vite_glob_0_99, + "./Pages/Studio/StudioFollowers.jsx": __vite_glob_0_100, + "./Pages/Studio/StudioGroupActivity.jsx": __vite_glob_0_101, + "./Pages/Studio/StudioGroupArtworks.jsx": __vite_glob_0_102, + "./Pages/Studio/StudioGroupAssets.jsx": __vite_glob_0_103, + "./Pages/Studio/StudioGroupChallengeEditor.jsx": __vite_glob_0_104, + "./Pages/Studio/StudioGroupChallenges.jsx": __vite_glob_0_105, + "./Pages/Studio/StudioGroupCollections.jsx": __vite_glob_0_106, + "./Pages/Studio/StudioGroupCreate.jsx": __vite_glob_0_107, + "./Pages/Studio/StudioGroupDashboard.jsx": __vite_glob_0_108, + "./Pages/Studio/StudioGroupEventEditor.jsx": __vite_glob_0_109, + "./Pages/Studio/StudioGroupEvents.jsx": __vite_glob_0_110, + "./Pages/Studio/StudioGroupInvitations.jsx": __vite_glob_0_111, + "./Pages/Studio/StudioGroupJoinRequests.jsx": __vite_glob_0_112, + "./Pages/Studio/StudioGroupMembers.jsx": __vite_glob_0_113, + "./Pages/Studio/StudioGroupPostEditor.jsx": __vite_glob_0_114, + "./Pages/Studio/StudioGroupPosts.jsx": __vite_glob_0_115, + "./Pages/Studio/StudioGroupProjectEditor.jsx": __vite_glob_0_116, + "./Pages/Studio/StudioGroupProjects.jsx": __vite_glob_0_117, + "./Pages/Studio/StudioGroupRecruitment.jsx": __vite_glob_0_118, + "./Pages/Studio/StudioGroupReleaseEditor.jsx": __vite_glob_0_119, + "./Pages/Studio/StudioGroupReleases.jsx": __vite_glob_0_120, + "./Pages/Studio/StudioGroupReputation.jsx": __vite_glob_0_121, + "./Pages/Studio/StudioGroupReviewQueue.jsx": __vite_glob_0_122, + "./Pages/Studio/StudioGroupSettings.jsx": __vite_glob_0_123, + "./Pages/Studio/StudioGroupsIndex.jsx": __vite_glob_0_124, + "./Pages/Studio/StudioGrowth.jsx": __vite_glob_0_125, + "./Pages/Studio/StudioInbox.jsx": __vite_glob_0_126, + "./Pages/Studio/StudioNewsEditor.jsx": __vite_glob_0_127, + "./Pages/Studio/StudioNewsIndex.jsx": __vite_glob_0_128, + "./Pages/Studio/StudioNewsTaxonomies.jsx": __vite_glob_0_129, + "./Pages/Studio/StudioPreferences.jsx": __vite_glob_0_130, + "./Pages/Studio/StudioProfile.jsx": __vite_glob_0_131, + "./Pages/Studio/StudioScheduled.jsx": __vite_glob_0_132, + "./Pages/Studio/StudioSearch.jsx": __vite_glob_0_133, + "./Pages/Studio/StudioSettings.jsx": __vite_glob_0_134, + "./Pages/Studio/StudioStories.jsx": __vite_glob_0_135, + "./Pages/Studio/StudioUploadQueue.jsx": __vite_glob_0_136, + "./Pages/Studio/StudioWorldEditor.jsx": __vite_glob_0_137, + "./Pages/Studio/StudioWorldsIndex.jsx": __vite_glob_0_138, + "./Pages/Upload/Index.jsx": __vite_glob_0_139, + "./Pages/World/WorldIndex.jsx": __vite_glob_0_140, + "./Pages/World/WorldShow.jsx": __vite_glob_0_141 +}); const ClientOnlyPlaceholder = () => null; d( (page) => W({ diff --git a/config/horizon.php b/config/horizon.php index 7851a78c..e2ef0503 100644 --- a/config/horizon.php +++ b/config/horizon.php @@ -209,7 +209,10 @@ return [ 'maxJobs' => 0, 'memory' => 128, 'tries' => 1, - 'timeout' => 60, + // Long-running recommendation rebuild jobs declare timeouts up to 900s. + // Keep the worker timeout above that ceiling so Horizon does not kill + // healthy jobs before Laravel can enforce the job-level timeout. + 'timeout' => 960, 'nice' => 0, ], 'supervisor-messaging' => [ diff --git a/config/registration.php b/config/registration.php index e25e71cd..a26317ff 100644 --- a/config/registration.php +++ b/config/registration.php @@ -6,7 +6,7 @@ return [ 'email_per_minute_limit' => (int) env('REGISTRATION_EMAIL_PER_MINUTE_LIMIT', 6), 'email_cooldown_minutes' => (int) env('REGISTRATION_EMAIL_COOLDOWN_MINUTES', 30), 'verify_token_ttl_hours' => (int) env('REGISTRATION_VERIFY_TOKEN_TTL_HOURS', 24), - 'enable_turnstile' => (bool) env('REGISTRATION_ENABLE_TURNSTILE', true), + 'enable_turnstile' => (bool) env('TURNSTILE_ENABLED', env('REGISTRATION_ENABLE_TURNSTILE', false)), 'disposable_domains_enabled' => (bool) env('REGISTRATION_DISPOSABLE_DOMAINS_ENABLED', true), 'turnstile_suspicious_attempts' => (int) env('REGISTRATION_TURNSTILE_SUSPICIOUS_ATTEMPTS', 2), 'turnstile_attempt_window_minutes' => (int) env('REGISTRATION_TURNSTILE_ATTEMPT_WINDOW_MINUTES', 30), diff --git a/config/services.php b/config/services.php index b2c15a0d..65ad858a 100644 --- a/config/services.php +++ b/config/services.php @@ -58,8 +58,10 @@ return [ ], 'turnstile' => [ + 'enabled' => env('TURNSTILE_ENABLED', false), 'site_key' => env('TURNSTILE_SITE_KEY'), 'secret_key' => env('TURNSTILE_SECRET_KEY'), + 'fail_open' => env('TURNSTILE_FAIL_OPEN', false), 'script_url' => env('TURNSTILE_SCRIPT_URL', 'https://challenges.cloudflare.com/turnstile/v0/api.js'), 'verify_url' => env('TURNSTILE_VERIFY_URL', 'https://challenges.cloudflare.com/turnstile/v0/siteverify'), 'timeout' => (int) env('TURNSTILE_TIMEOUT', 5), diff --git a/database/seeders/AcademyDemoSeeder.php b/database/seeders/AcademyDemoSeeder.php index b502770f..07f981bd 100644 --- a/database/seeders/AcademyDemoSeeder.php +++ b/database/seeders/AcademyDemoSeeder.php @@ -8,6 +8,7 @@ use App\Models\AcademyBadge; use App\Models\AcademyCategory; use App\Models\AcademyChallenge; use App\Models\AcademyLesson; +use App\Models\AcademyLessonBlock; use App\Models\AcademyPromptPack; use App\Models\AcademyPromptPackItem; use App\Models\AcademyPromptTemplate; @@ -114,7 +115,7 @@ class AcademyDemoSeeder extends Seeder ]; foreach ($lessons as $index => $lesson) { - AcademyLesson::query()->updateOrCreate( + $academyLesson = AcademyLesson::query()->updateOrCreate( ['slug' => $lesson['slug']], [ 'category_id' => $categories->get($lesson['category_slug'])?->id, @@ -129,6 +130,35 @@ class AcademyDemoSeeder extends Seeder 'published_at' => now()->subDays(8 - $index), ], ); + + if ($lesson['slug'] === 'what-is-ai-assisted-digital-art') { + AcademyLessonBlock::query()->updateOrCreate( + [ + 'lesson_id' => $academyLesson->id, + 'type' => 'ai_comparison', + 'sort_order' => 0, + ], + [ + 'title' => 'Same Prompt, Different AI Models', + 'payload' => [ + 'title' => 'Same Prompt, Different AI Models', + 'intro' => 'We used the same fantasy forest prompt in different AI image tools to compare how each model handles mood, composition, detail, lighting, and wallpaper quality.', + 'prompt' => 'A peaceful fantasy forest wallpaper, glowing blue flowers, soft morning light, gentle mist, wide cinematic composition, detailed digital painting, calm mood, high-resolution wallpaper, no text, no watermark.', + 'negative_prompt' => 'text, watermark, blurry pixels, distorted objects, bad anatomy, modern UI', + 'aspect_ratio' => '16:9', + 'criteria' => [ + 'Composition', + 'Lighting', + 'Wallpaper quality', + 'Prompt accuracy', + 'Detail quality', + 'Beginner friendliness', + ], + ], + 'active' => true, + ], + ); + } } $prompts = [ @@ -419,4 +449,4 @@ class AcademyDemoSeeder extends Seeder app(AcademyCacheService::class)->clearAll(); } -} \ No newline at end of file +} diff --git a/package-lock.json b/package-lock.json index f1560c3d..aa928445 100644 --- a/package-lock.json +++ b/package-lock.json @@ -6,6 +6,7 @@ "": { "dependencies": { "@emoji-mart/data": "^1.2.1", + "@floating-ui/dom": "^1.7.6", "@inertiajs/core": "^1.0.4", "@inertiajs/react": "^1.0.4", "@tiptap/extension-code-block-lowlight": "^3.20.0", @@ -13,6 +14,10 @@ "@tiptap/extension-link": "^3.20.0", "@tiptap/extension-mention": "^3.20.0", "@tiptap/extension-placeholder": "^3.20.0", + "@tiptap/extension-table": "^3.22.5", + "@tiptap/extension-table-cell": "^3.22.5", + "@tiptap/extension-table-header": "^3.22.5", + "@tiptap/extension-table-row": "^3.22.5", "@tiptap/extension-underline": "^3.20.0", "@tiptap/react": "^3.20.0", "@tiptap/starter-kit": "^3.20.0", @@ -680,17 +685,26 @@ "resolved": "https://registry.npmjs.org/@floating-ui/core/-/core-1.7.5.tgz", "integrity": "sha512-1Ih4WTWyw0+lKyFMcBHGbb5U5FtuHJuujoyyr5zTaWS5EYMeT6Jb2AuDeftsCsEuchO+mM2ij5+q9crhydzLhQ==", "license": "MIT", - "optional": true, "dependencies": { "@floating-ui/utils": "^0.2.11" } }, + "node_modules/@floating-ui/dom": { + "version": "1.7.6", + "resolved": "https://registry.npmjs.org/@floating-ui/dom/-/dom-1.7.6.tgz", + "integrity": "sha512-9gZSAI5XM36880PPMm//9dfiEngYoC6Am2izES1FF406YFsjvyBMmeJ2g4SAju3xWwtuynNRFL2s9hgxpLI5SQ==", + "license": "MIT", + "peer": true, + "dependencies": { + "@floating-ui/core": "^1.7.5", + "@floating-ui/utils": "^0.2.11" + } + }, "node_modules/@floating-ui/utils": { "version": "0.2.11", "resolved": "https://registry.npmjs.org/@floating-ui/utils/-/utils-0.2.11.tgz", "integrity": "sha512-RiB/yIh78pcIxl6lLMG0CgBXAZ2Y0eVHqMPYugu+9U0AeT6YBeiJpf7lbdJNIugFP5SIjwNRgo4DhR1Qxi26Gg==", - "license": "MIT", - "optional": true + "license": "MIT" }, "node_modules/@inertiajs/core": { "version": "1.3.0", @@ -1141,12 +1155,6 @@ "url": "https://opencollective.com/popperjs" } }, - "node_modules/@remirror/core-constants": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/@remirror/core-constants/-/core-constants-3.0.0.tgz", - "integrity": "sha512-42aWfPrimMfDKDi4YegyS7x+/0tlzaqwPQCULLanv3DMIlu96KTJR0fM5isWX2UViOqlGnX6YFgqWepcX+XMNg==", - "license": "MIT" - }, "node_modules/@rollup/rollup-android-arm-eabi": { "version": "4.60.1", "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm-eabi/-/rollup-android-arm-eabi-4.60.1.tgz", @@ -1866,9 +1874,9 @@ } }, "node_modules/@tiptap/core": { - "version": "3.22.1", - "resolved": "https://registry.npmjs.org/@tiptap/core/-/core-3.22.1.tgz", - "integrity": "sha512-6wPNhkdLIGYiKAGqepDCRtR0TYGJxV40SwOEN2vlPhsXqAgzmyG37UyREj5pGH5xTekugqMCgCnyRg7m5nYoYQ==", + "version": "3.22.5", + "resolved": "https://registry.npmjs.org/@tiptap/core/-/core-3.22.5.tgz", + "integrity": "sha512-L1lhWz6ujGny8LduTJ7MBWYhzigwOvfUJUrJ7IzOJSuy3+OAzisdGDD1GV7LEO/hU0Hr2Mkm1wajRIHExvS9HQ==", "license": "MIT", "peer": true, "funding": { @@ -1876,7 +1884,7 @@ "url": "https://github.com/sponsors/ueberdosis" }, "peerDependencies": { - "@tiptap/pm": "^3.22.1" + "@tiptap/pm": "3.22.5" } }, "node_modules/@tiptap/extension-blockquote": { @@ -2227,6 +2235,60 @@ "@tiptap/core": "^3.22.1" } }, + "node_modules/@tiptap/extension-table": { + "version": "3.22.5", + "resolved": "https://registry.npmjs.org/@tiptap/extension-table/-/extension-table-3.22.5.tgz", + "integrity": "sha512-GMBM07bCwzHx1NK08zXRr2mNTDnP78Hd0VxFsRBIDFddDMZ2qG5jhwKHXN5cHMTrdWokWFUjvnEeJeV3guHoGg==", + "license": "MIT", + "peer": true, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/ueberdosis" + }, + "peerDependencies": { + "@tiptap/core": "3.22.5", + "@tiptap/pm": "3.22.5" + } + }, + "node_modules/@tiptap/extension-table-cell": { + "version": "3.22.5", + "resolved": "https://registry.npmjs.org/@tiptap/extension-table-cell/-/extension-table-cell-3.22.5.tgz", + "integrity": "sha512-Wn4asCgNLfOPH5EOpiMjzOJXTZvv+TTqUT+gzm2fV69ZkleCGNO0BZwuR/TCIDLGIArbvHzyYy2/lJAfG4UCtg==", + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/ueberdosis" + }, + "peerDependencies": { + "@tiptap/extension-table": "3.22.5" + } + }, + "node_modules/@tiptap/extension-table-header": { + "version": "3.22.5", + "resolved": "https://registry.npmjs.org/@tiptap/extension-table-header/-/extension-table-header-3.22.5.tgz", + "integrity": "sha512-aJmbgbO6QbSj0Rw3X4ogGPyd+8FwP6RgG71Dpa3NovzVkqJc3ZUq0wC3XH48U9Hd89F8f4AggFgHjU6/kQAgQQ==", + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/ueberdosis" + }, + "peerDependencies": { + "@tiptap/extension-table": "3.22.5" + } + }, + "node_modules/@tiptap/extension-table-row": { + "version": "3.22.5", + "resolved": "https://registry.npmjs.org/@tiptap/extension-table-row/-/extension-table-row-3.22.5.tgz", + "integrity": "sha512-9A2BdX+R+P71f192Fo74OttMHj1WoFVO0ezaCzFbT8uNVG3nCJ7B5/1UkTlzqDdGOuWh1VpR63pFZP9LFsUv6A==", + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/ueberdosis" + }, + "peerDependencies": { + "@tiptap/extension-table": "3.22.5" + } + }, "node_modules/@tiptap/extension-text": { "version": "3.22.1", "resolved": "https://registry.npmjs.org/@tiptap/extension-text/-/extension-text-3.22.1.tgz", @@ -2269,28 +2331,22 @@ } }, "node_modules/@tiptap/pm": { - "version": "3.22.1", - "resolved": "https://registry.npmjs.org/@tiptap/pm/-/pm-3.22.1.tgz", - "integrity": "sha512-OSqSg2974eLJT5PNKFLM7156lBXCUf/dsKTQXWSzsLTf6HOP4dYP6c0YbAk6lgbNI+BdszsHNClmLVLA8H/L9A==", + "version": "3.22.5", + "resolved": "https://registry.npmjs.org/@tiptap/pm/-/pm-3.22.5.tgz", + "integrity": "sha512-Cr9Mv4igxvI2tKMiahw48sZxva3PfDzypErH8IB82N+9qa9n9ygVMt0BOaDg53hLKxEEVeYr2S/wCcJIVFgBTw==", "license": "MIT", "peer": true, "dependencies": { "prosemirror-changeset": "^2.3.0", - "prosemirror-collab": "^1.3.1", "prosemirror-commands": "^1.6.2", "prosemirror-dropcursor": "^1.8.1", "prosemirror-gapcursor": "^1.3.2", "prosemirror-history": "^1.4.1", - "prosemirror-inputrules": "^1.4.0", "prosemirror-keymap": "^1.2.2", - "prosemirror-markdown": "^1.13.1", - "prosemirror-menu": "^1.2.4", "prosemirror-model": "^1.24.1", - "prosemirror-schema-basic": "^1.2.3", "prosemirror-schema-list": "^1.5.0", "prosemirror-state": "^1.4.3", "prosemirror-tables": "^1.6.4", - "prosemirror-trailing-node": "^3.0.0", "prosemirror-transform": "^1.10.2", "prosemirror-view": "^1.38.1" }, @@ -2417,22 +2473,6 @@ "@types/unist": "*" } }, - "node_modules/@types/linkify-it": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/@types/linkify-it/-/linkify-it-5.0.0.tgz", - "integrity": "sha512-sVDA58zAw4eWAffKOaQH5/5j3XeayukzDk+ewSsnv3p4yJEZHCCzMDiZM8e0OUrRvmpGZ85jf4yDHkHsgBNr9Q==", - "license": "MIT" - }, - "node_modules/@types/markdown-it": { - "version": "14.1.2", - "resolved": "https://registry.npmjs.org/@types/markdown-it/-/markdown-it-14.1.2.tgz", - "integrity": "sha512-promo4eFwuiW+TfGxhi+0x3czqTYJkG8qB17ZUJiVF10Xm7NLVRSLUsfRTU/6h1e24VvRnXCx+hG7li58lkzog==", - "license": "MIT", - "dependencies": { - "@types/linkify-it": "^5", - "@types/mdurl": "^2" - } - }, "node_modules/@types/mdast": { "version": "4.0.4", "resolved": "https://registry.npmjs.org/@types/mdast/-/mdast-4.0.4.tgz", @@ -2442,12 +2482,6 @@ "@types/unist": "*" } }, - "node_modules/@types/mdurl": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/@types/mdurl/-/mdurl-2.0.0.tgz", - "integrity": "sha512-RGdgjQUZba5p6QEFAVx2OGb8rQDL/cPRG7GiedRzMcJ1tYnUANBncjbSB1NRGwbvjcPeikRABz2nshyPk1bhWg==", - "license": "MIT" - }, "node_modules/@types/ms": { "version": "2.1.0", "resolved": "https://registry.npmjs.org/@types/ms/-/ms-2.1.0.tgz", @@ -2682,12 +2716,6 @@ "dev": true, "license": "MIT" }, - "node_modules/argparse": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/argparse/-/argparse-2.0.1.tgz", - "integrity": "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==", - "license": "Python-2.0" - }, "node_modules/aria-query": { "version": "5.3.0", "resolved": "https://registry.npmjs.org/aria-query/-/aria-query-5.3.0.tgz", @@ -3131,12 +3159,6 @@ "url": "https://github.com/open-cli-tools/concurrently?sponsor=1" } }, - "node_modules/crelt": { - "version": "1.0.6", - "resolved": "https://registry.npmjs.org/crelt/-/crelt-1.0.6.tgz", - "integrity": "sha512-VQ2MBenTq1fWZUH9DJNGti7kKv6EeAuYr3cLwxUWhIu1baTaXh4Ib5W2CqHVqib4/MqbYGJqiL3Zb8GJZr3l4g==", - "license": "MIT" - }, "node_modules/cssesc": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/cssesc/-/cssesc-3.0.0.tgz", @@ -3517,18 +3539,6 @@ "node": ">=6" } }, - "node_modules/escape-string-regexp": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-4.0.0.tgz", - "integrity": "sha512-TtpcNJ3XAzx3Gq8sWRzJaVajRs0uVxA2YAkdb1jm2YkPz4G6egUFAyA3n5vtEIZefPk5Wa4UXbKuS5fKkJWdgA==", - "license": "MIT", - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, "node_modules/estree-util-is-identifier-name": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/estree-util-is-identifier-name/-/estree-util-is-identifier-name-3.0.0.tgz", @@ -4509,15 +4519,6 @@ "dev": true, "license": "MIT" }, - "node_modules/linkify-it": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/linkify-it/-/linkify-it-5.0.0.tgz", - "integrity": "sha512-5aHCbzQRADcdP+ATqnDuhhJ/MRIqDkZX5pyjFHRRysS8vZ5AbqGEoFIb6pYHPZ+L/OC2Lc+xT8uHVVR5CAK/wQ==", - "license": "MIT", - "dependencies": { - "uc.micro": "^2.0.0" - } - }, "node_modules/linkifyjs": { "version": "4.3.2", "resolved": "https://registry.npmjs.org/linkifyjs/-/linkifyjs-4.3.2.tgz", @@ -4591,35 +4592,6 @@ "@jridgewell/sourcemap-codec": "^1.5.5" } }, - "node_modules/markdown-it": { - "version": "14.1.1", - "resolved": "https://registry.npmjs.org/markdown-it/-/markdown-it-14.1.1.tgz", - "integrity": "sha512-BuU2qnTti9YKgK5N+IeMubp14ZUKUUw7yeJbkjtosvHiP0AZ5c8IAgEMk79D0eC8F23r4Ac/q8cAIFdm2FtyoA==", - "license": "MIT", - "dependencies": { - "argparse": "^2.0.1", - "entities": "^4.4.0", - "linkify-it": "^5.0.0", - "mdurl": "^2.0.0", - "punycode.js": "^2.3.1", - "uc.micro": "^2.1.0" - }, - "bin": { - "markdown-it": "bin/markdown-it.mjs" - } - }, - "node_modules/markdown-it/node_modules/entities": { - "version": "4.5.0", - "resolved": "https://registry.npmjs.org/entities/-/entities-4.5.0.tgz", - "integrity": "sha512-V0hjH4dGPh9Ao5p0MoRY6BVqtwCjhz6vI5LT8AJ55H+4g9/4vbHx1I54fS0XuclLhDHArPQCiMjDxjaL8fPxhw==", - "license": "BSD-2-Clause", - "engines": { - "node": ">=0.12" - }, - "funding": { - "url": "https://github.com/fb55/entities?sponsor=1" - } - }, "node_modules/math-intrinsics": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz", @@ -4782,12 +4754,6 @@ "url": "https://opencollective.com/unified" } }, - "node_modules/mdurl": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/mdurl/-/mdurl-2.0.0.tgz", - "integrity": "sha512-Lf+9+2r+Tdp5wXDXC4PcIBjTDtq4UKjCPMQhKIuzpJNW0b96kVqSwW0bT7FhRSfmAiFYgP+SCRvdrDozfh0U5w==", - "license": "MIT" - }, "node_modules/merge2": { "version": "1.4.1", "resolved": "https://registry.npmjs.org/merge2/-/merge2-1.4.1.tgz", @@ -5772,15 +5738,6 @@ "prosemirror-transform": "^1.0.0" } }, - "node_modules/prosemirror-collab": { - "version": "1.3.1", - "resolved": "https://registry.npmjs.org/prosemirror-collab/-/prosemirror-collab-1.3.1.tgz", - "integrity": "sha512-4SnynYR9TTYaQVXd/ieUvsVV4PDMBzrq2xPUWutHivDuOshZXqQ5rGbZM84HEaXKbLdItse7weMGOUdDVcLKEQ==", - "license": "MIT", - "dependencies": { - "prosemirror-state": "^1.0.0" - } - }, "node_modules/prosemirror-commands": { "version": "1.7.1", "resolved": "https://registry.npmjs.org/prosemirror-commands/-/prosemirror-commands-1.7.1.tgz", @@ -5827,16 +5784,6 @@ "rope-sequence": "^1.3.0" } }, - "node_modules/prosemirror-inputrules": { - "version": "1.5.1", - "resolved": "https://registry.npmjs.org/prosemirror-inputrules/-/prosemirror-inputrules-1.5.1.tgz", - "integrity": "sha512-7wj4uMjKaXWAQ1CDgxNzNtR9AlsuwzHfdFH1ygEHA2KHF2DOEaXl1CJfNPAKCg9qNEh4rum975QLaCiQPyY6Fw==", - "license": "MIT", - "dependencies": { - "prosemirror-state": "^1.0.0", - "prosemirror-transform": "^1.0.0" - } - }, "node_modules/prosemirror-keymap": { "version": "1.2.3", "resolved": "https://registry.npmjs.org/prosemirror-keymap/-/prosemirror-keymap-1.2.3.tgz", @@ -5847,48 +5794,15 @@ "w3c-keyname": "^2.2.0" } }, - "node_modules/prosemirror-markdown": { - "version": "1.13.4", - "resolved": "https://registry.npmjs.org/prosemirror-markdown/-/prosemirror-markdown-1.13.4.tgz", - "integrity": "sha512-D98dm4cQ3Hs6EmjK500TdAOew4Z03EV71ajEFiWra3Upr7diytJsjF4mPV2dW+eK5uNectiRj0xFxYI9NLXDbw==", - "license": "MIT", - "dependencies": { - "@types/markdown-it": "^14.0.0", - "markdown-it": "^14.0.0", - "prosemirror-model": "^1.25.0" - } - }, - "node_modules/prosemirror-menu": { - "version": "1.3.0", - "resolved": "https://registry.npmjs.org/prosemirror-menu/-/prosemirror-menu-1.3.0.tgz", - "integrity": "sha512-TImyPXCHPcDsSka2/lwJ6WjTASr4re/qWq1yoTTuLOqfXucwF6VcRa2LWCkM/EyTD1UO3CUwiH8qURJoWJRxwg==", - "license": "MIT", - "dependencies": { - "crelt": "^1.0.0", - "prosemirror-commands": "^1.0.0", - "prosemirror-history": "^1.0.0", - "prosemirror-state": "^1.0.0" - } - }, "node_modules/prosemirror-model": { "version": "1.25.4", "resolved": "https://registry.npmjs.org/prosemirror-model/-/prosemirror-model-1.25.4.tgz", "integrity": "sha512-PIM7E43PBxKce8OQeezAs9j4TP+5yDpZVbuurd1h5phUxEKIu+G2a+EUZzIC5nS1mJktDJWzbqS23n1tsAf5QA==", "license": "MIT", - "peer": true, "dependencies": { "orderedmap": "^2.0.0" } }, - "node_modules/prosemirror-schema-basic": { - "version": "1.2.4", - "resolved": "https://registry.npmjs.org/prosemirror-schema-basic/-/prosemirror-schema-basic-1.2.4.tgz", - "integrity": "sha512-ELxP4TlX3yr2v5rM7Sb70SqStq5NvI15c0j9j/gjsrO5vaw+fnnpovCLEGIcpeGfifkuqJwl4fon6b+KdrODYQ==", - "license": "MIT", - "dependencies": { - "prosemirror-model": "^1.25.0" - } - }, "node_modules/prosemirror-schema-list": { "version": "1.5.1", "resolved": "https://registry.npmjs.org/prosemirror-schema-list/-/prosemirror-schema-list-1.5.1.tgz", @@ -5905,7 +5819,6 @@ "resolved": "https://registry.npmjs.org/prosemirror-state/-/prosemirror-state-1.4.4.tgz", "integrity": "sha512-6jiYHH2CIGbCfnxdHbXZ12gySFY/fz/ulZE333G6bPqIZ4F+TXo9ifiR86nAHpWnfoNjOb3o5ESi7J8Uz1jXHw==", "license": "MIT", - "peer": true, "dependencies": { "prosemirror-model": "^1.0.0", "prosemirror-transform": "^1.0.0", @@ -5925,21 +5838,6 @@ "prosemirror-view": "^1.41.4" } }, - "node_modules/prosemirror-trailing-node": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/prosemirror-trailing-node/-/prosemirror-trailing-node-3.0.0.tgz", - "integrity": "sha512-xiun5/3q0w5eRnGYfNlW1uU9W6x5MoFKWwq/0TIRgt09lv7Hcser2QYV8t4muXbEr+Fwo0geYn79Xs4GKywrRQ==", - "license": "MIT", - "dependencies": { - "@remirror/core-constants": "3.0.0", - "escape-string-regexp": "^4.0.0" - }, - "peerDependencies": { - "prosemirror-model": "^1.22.1", - "prosemirror-state": "^1.4.2", - "prosemirror-view": "^1.33.8" - } - }, "node_modules/prosemirror-transform": { "version": "1.12.0", "resolved": "https://registry.npmjs.org/prosemirror-transform/-/prosemirror-transform-1.12.0.tgz", @@ -5954,7 +5852,6 @@ "resolved": "https://registry.npmjs.org/prosemirror-view/-/prosemirror-view-1.41.8.tgz", "integrity": "sha512-TnKDdohEatgyZNGCDWIdccOHXhYloJwbwU+phw/a23KBvJIR9lWQWW7WHHK3vBdOLDNuF7TaX98GObUZOWkOnA==", "license": "MIT", - "peer": true, "dependencies": { "prosemirror-model": "^1.20.0", "prosemirror-state": "^1.0.0", @@ -5980,15 +5877,6 @@ "node": ">=6" } }, - "node_modules/punycode.js": { - "version": "2.3.1", - "resolved": "https://registry.npmjs.org/punycode.js/-/punycode.js-2.3.1.tgz", - "integrity": "sha512-uxFIHU0YlHYhDQtV4R9J6a52SLx28BCjT+4ieh7IGbgwVJWO+km431c4yRlREUAsAmt/uMjQUyQHNEPf0M39CA==", - "license": "MIT", - "engines": { - "node": ">=6" - } - }, "node_modules/pusher-js": { "version": "8.5.0", "resolved": "https://registry.npmjs.org/pusher-js/-/pusher-js-8.5.0.tgz", @@ -6933,12 +6821,6 @@ "integrity": "sha512-6rt+RN7aOi1nGMyC4Xa5DdYiukl2UWCbcJft7YhxReBGQD7OAM8Pbxw6YMo4r2diNEA8FEmu32YOn9rhaiE5yw==", "license": "Unlicense" }, - "node_modules/uc.micro": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/uc.micro/-/uc.micro-2.1.0.tgz", - "integrity": "sha512-ARDJmphmdvUk6Glw7y9DQ2bFkKBHwQHLi2lsaH6PPmz/Ka9sFOBsBluozhDltWmnv9u/cF6Rt87znRTPV+yp/A==", - "license": "MIT" - }, "node_modules/unified": { "version": "11.0.5", "resolved": "https://registry.npmjs.org/unified/-/unified-11.0.5.tgz", diff --git a/package.json b/package.json index 201898c1..dd639fda 100644 --- a/package.json +++ b/package.json @@ -34,6 +34,7 @@ }, "dependencies": { "@emoji-mart/data": "^1.2.1", + "@floating-ui/dom": "^1.7.6", "@inertiajs/core": "^1.0.4", "@inertiajs/react": "^1.0.4", "@tiptap/extension-code-block-lowlight": "^3.20.0", @@ -41,6 +42,10 @@ "@tiptap/extension-link": "^3.20.0", "@tiptap/extension-mention": "^3.20.0", "@tiptap/extension-placeholder": "^3.20.0", + "@tiptap/extension-table": "^3.22.5", + "@tiptap/extension-table-cell": "^3.22.5", + "@tiptap/extension-table-header": "^3.22.5", + "@tiptap/extension-table-row": "^3.22.5", "@tiptap/extension-underline": "^3.20.0", "@tiptap/react": "^3.20.0", "@tiptap/starter-kit": "^3.20.0", diff --git a/resources/css/app.css b/resources/css/app.css index 66b4e9b2..d8e2e5fe 100644 --- a/resources/css/app.css +++ b/resources/css/app.css @@ -458,6 +458,420 @@ -webkit-user-select: text; user-select: text; cursor: text; + font-size: 1.05rem; + line-height: 1.85; +} + +.news-rich-text-editor .ProseMirror { + color: rgb(226 232 240 / 0.92); + font-family: 'Libre Franklin', 'Inter', sans-serif; + font-size: 1.02rem; + line-height: 1.9; +} + +.news-rich-text-editor .ProseMirror p { + padding-top: 0.18rem; + padding-bottom: 0.3rem; +} + +.news-rich-text-editor .ProseMirror p:empty { + display: none; +} + +.news-rich-text-editor .ProseMirror p + p { + margin-top: 1.5rem; +} + +.news-rich-text-editor .ProseMirror h2, +.news-rich-text-editor .ProseMirror h3, +.news-rich-text-editor .ProseMirror h4, +.news-rich-text-editor .ProseMirror h5, +.news-rich-text-editor .ProseMirror h6 { + color: rgb(255 255 255); + font-weight: 600; + letter-spacing: -0.03em; +} + +.news-rich-text-editor .ProseMirror h2 { + margin-top: 2.5rem; + margin-bottom: 1rem; + font-size: clamp(1.65rem, 1.2rem + 1vw, 2rem); +} + +.news-rich-text-editor .ProseMirror h3 { + margin-top: 2rem; + margin-bottom: 0.75rem; + font-size: clamp(1.35rem, 1.05rem + 0.8vw, 1.6rem); +} + +.news-rich-text-editor .ProseMirror h4, +.news-rich-text-editor .ProseMirror h5, +.news-rich-text-editor .ProseMirror h6 { + margin-top: 1.5rem; + margin-bottom: 0.6rem; +} + +.news-rich-text-editor .ProseMirror ul, +.news-rich-text-editor .ProseMirror ol { + margin: 1.5rem 0; + padding-left: 1.5rem; +} + +.news-rich-text-editor .ProseMirror ul { + list-style-type: disc; +} + +.news-rich-text-editor .ProseMirror ol { + list-style-type: decimal; +} + +.news-rich-text-editor .ProseMirror li { + color: rgb(255 255 255 / 0.72); + margin-bottom: 0.5rem; +} + +.news-rich-text-editor .ProseMirror li::marker { + color: rgb(255 255 255 / 0.45); +} + +.news-rich-text-editor .ProseMirror blockquote { + margin: 2rem 0; + border-left: 3px solid rgb(14 165 233 / 0.7); + background: rgb(255 255 255 / 0.03); + padding: 0.6rem 0 0.6rem 1.25rem; + color: rgb(255 255 255 / 0.68); +} + +.news-rich-text-editor .ProseMirror hr { + margin: 2rem 0; +} + +.rich-text-editor-viewport { + overflow-y: auto; + overscroll-behavior: contain; + border-bottom-left-radius: 0.75rem; + border-bottom-right-radius: 0.75rem; + box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.02); +} + +.rich-text-editor-viewport .ProseMirror { + min-height: 100%; +} + +.rich-text-editor-viewport .ProseMirror:focus { + outline: none; +} + +.rich-text-editor-viewport .ProseMirror > :first-child { + margin-top: 0; +} + +.rich-text-editor-viewport .ProseMirror > :last-child { + margin-bottom: 0; +} + +.rich-text-editor-viewport::-webkit-scrollbar { + width: 10px; +} + +.rich-text-editor-viewport::-webkit-scrollbar-track { + background: rgba(15, 23, 42, 0.34); +} + +.rich-text-editor-viewport::-webkit-scrollbar-thumb { + background: linear-gradient(180deg, rgba(56, 189, 248, 0.22), rgba(125, 211, 252, 0.35)); + border: 2px solid rgba(15, 23, 42, 0.48); + border-radius: 999px; +} + +.rich-text-editor-viewport::-webkit-scrollbar-thumb:hover { + background: linear-gradient(180deg, rgba(56, 189, 248, 0.36), rgba(125, 211, 252, 0.5)); +} + +.rich-text-editor-viewport::-webkit-scrollbar-corner { + background: transparent; +} + +.tiptap .ProseMirror :is(p, div, h2, h3, hr) { + margin-bottom: 1.05em; +} + +.tiptap .ProseMirror p { + font-size: 1.02rem; + line-height: 1.9; +} + +.tiptap .ProseMirror h2 { + font-size: 1.75rem; + line-height: 1.18; + margin-top: 1.8em; + margin-bottom: 0.95em; +} + +.tiptap .ProseMirror h3 { + font-size: 1.35rem; + line-height: 1.22; + margin-top: 1.5em; + margin-bottom: 0.85em; +} + +.tiptap .ProseMirror hr { + margin-top: 1.75em; + margin-bottom: 1.75em; +} + +.rich-image-node { + position: relative; + display: flex; + flex-direction: column; + gap: 0.75rem; + margin: 1.75rem auto; + max-width: 100%; + outline: none; +} + +.rich-image-node.is-selected .rich-image-node__frame { + box-shadow: 0 0 0 1px rgba(125, 211, 252, 0.45), 0 0 0 6px rgba(14, 165, 233, 0.12); +} + +.rich-image-node__frame { + position: relative; + display: inline-flex; + max-width: 100%; + margin: 0 auto; + border-radius: 1.25rem; +} + +.rich-image-node__img { + display: block; + width: 100%; + max-width: 100%; + height: auto; + border-radius: 1.25rem; + object-fit: contain; +} + +.rich-image-node__drag-handle, +.rich-image-node__resize-handle { + position: absolute; + display: inline-flex; + align-items: center; + justify-content: center; + width: 2rem; + height: 2rem; + border: 1px solid rgba(255, 255, 255, 0.12); + border-radius: 999px; + background: rgba(8, 12, 20, 0.9); + color: rgb(241 245 249 / 0.95); + box-shadow: 0 12px 32px rgba(0, 0, 0, 0.38); + cursor: grab; +} + +.rich-image-node__drag-handle { + top: 0.75rem; + left: 0.75rem; +} + +.rich-image-node__resize-handle { + right: 0.75rem; + bottom: 0.75rem; + cursor: nwse-resize; +} + +.rich-image-node__caption { + max-width: min(100%, 46rem); + margin: 0 auto; + color: rgb(148 163 184 / 0.9); + font-size: 0.9rem; + line-height: 1.7; + text-align: center; +} + +.rich-image-node__editor { + display: grid; + gap: 0.9rem; + padding: 0.9rem; + border: 1px solid rgba(255, 255, 255, 0.08); + border-radius: 1.1rem; + background: rgba(8, 12, 20, 0.92); +} + +.rich-image-node.is-selected .rich-image-node__editor { + margin-inline: auto; + width: min(100%, 52rem); +} + +.rich-compare-node { + position: relative; + display: flex; + flex-direction: column; + gap: 0.8rem; + margin: 1.75rem auto; + max-width: 100%; + outline: none; +} + +.rich-compare-node.is-selected { + border-radius: 1.25rem; +} + +.rich-compare-node.is-selected .rich-compare-node__grid, +.ProseMirror-selectednode.rich-compare-node .rich-compare-node__grid { + box-shadow: 0 0 0 1px rgba(125, 211, 252, 0.45), 0 0 0 6px rgba(14, 165, 233, 0.12); +} + +.rich-compare-node__grid { + display: grid; + grid-template-columns: repeat(2, minmax(0, 1fr)); + gap: 0.75rem; + width: 100%; +} + +.rich-compare-node__tile { + position: relative; + overflow: hidden; + border-radius: 1.25rem; + border: 1px solid rgba(255, 255, 255, 0.08); + background: rgba(8, 12, 20, 0.92); + box-shadow: 0 18px 42px rgba(0, 0, 0, 0.18); +} + +.rich-compare-node__img { + display: block; + width: 100%; + height: auto; + object-fit: contain; +} + +.rich-compare-node__badge { + position: absolute; + left: 0.75rem; + top: 0.75rem; + z-index: 1; + border: 1px solid rgba(255, 255, 255, 0.12); + border-radius: 999px; + background: rgba(8, 12, 20, 0.92); + color: rgb(226 232 240 / 0.9); + font-size: 0.68rem; + font-weight: 700; + letter-spacing: 0.12em; + line-height: 1; + padding: 0.45rem 0.65rem; + text-transform: uppercase; +} + +.rich-compare-node__subtitle { + max-width: min(100%, 52rem); + margin: 0 auto; + color: rgb(148 163 184 / 0.9); + font-size: 0.92rem; + line-height: 1.7; + text-align: center; +} + +.rich-compare-node__editor { + display: grid; + gap: 0.9rem; + padding: 0.9rem; + border: 1px solid rgba(255, 255, 255, 0.08); + border-radius: 1.1rem; + background: rgba(8, 12, 20, 0.92); +} + +.rich-compare-node.is-selected .rich-compare-node__editor { + margin-inline: auto; + width: min(100%, 72rem); +} + +.ProseMirror-selectednode.rich-image-node, +.rich-image-node.is-selected { + border-radius: 1.25rem; +} + +.ProseMirror-selectednode.rich-image-node .rich-image-node__img { + outline: 2px solid rgba(125, 211, 252, 0.55); + outline-offset: 4px; +} + +.tiptap .tableWrapper, +.rich-text-editor-viewport .tableWrapper { + margin: 1.5rem 0; + overflow-x: auto; + padding: 0.35rem; + border: 1px solid rgba(125, 211, 252, 0.3); + border-radius: 1rem; + background: rgba(8, 12, 20, 0.72); + box-shadow: inset 0 0 0 1px rgba(255, 255, 255, 0.03), 0 16px 42px rgba(2, 6, 23, 0.22); +} + +.tiptap table.rich-table, +.rich-text-editor-viewport .tableWrapper table { + width: 100%; + min-width: 100%; + border-collapse: separate; + border-spacing: 0; + table-layout: fixed; + overflow: hidden; + border: 1px solid rgba(125, 211, 252, 0.38); + border-radius: 0.8rem; +} + +.tiptap table.rich-table th, +.tiptap table.rich-table td, +.rich-text-editor-viewport .tableWrapper th, +.rich-text-editor-viewport .tableWrapper td { + position: relative; + min-width: 120px; + padding: 0.85rem 0.95rem; + border: 1px solid rgba(148, 163, 184, 0.3) !important; + vertical-align: top; + background: rgba(255, 255, 255, 0.03); +} + +.tiptap table.rich-table th, +.rich-text-editor-viewport .tableWrapper th { + background: rgba(14, 165, 233, 0.16); + color: rgb(241 245 249); + font-weight: 700; +} + +.tiptap table.rich-table td p, +.tiptap table.rich-table th p, +.rich-text-editor-viewport .tableWrapper td p, +.rich-text-editor-viewport .tableWrapper th p { + margin: 0; + line-height: 1.65; +} + +.tiptap table.rich-table .selectedCell, +.rich-text-editor-viewport .tableWrapper .selectedCell { + position: relative; +} + +.tiptap table.rich-table .selectedCell::after, +.rich-text-editor-viewport .tableWrapper .selectedCell::after { + content: ''; + position: absolute; + inset: 0; + background: rgba(56, 189, 248, 0.14); + pointer-events: none; +} + +.tiptap table.rich-table .column-resize-handle, +.rich-text-editor-viewport .tableWrapper .column-resize-handle { + position: absolute; + top: 0; + right: -2px; + width: 4px; + height: 100%; + background: rgba(125, 211, 252, 0.82); + pointer-events: none; + box-shadow: 0 0 0 1px rgba(15, 23, 42, 0.45); +} + +.tiptap table.rich-table tr:nth-child(even) td, +.rich-text-editor-viewport .tableWrapper tr:nth-child(even) td { + background: rgba(255, 255, 255, 0.035); } .tiptap p.is-editor-empty:first-child::before { @@ -483,6 +897,73 @@ overflow-x: auto; } +.forum-code-block { + position: relative; + max-width: 100%; + overflow-x: auto; + overflow-y: hidden; + margin: 1.4rem 0; + border: 1px solid rgba(56, 189, 248, 0.16); + border-radius: 1.15rem; + background: + linear-gradient(180deg, rgba(15, 23, 42, 0.98) 0, rgba(15, 23, 42, 0.98) 3rem, rgba(2, 6, 23, 0.98) 3rem, rgba(2, 6, 23, 0.98) 100%); + box-shadow: + 0 22px 58px rgba(2, 6, 23, 0.42), + inset 0 1px 0 rgba(56, 189, 248, 0.1); + scrollbar-width: thin; + scrollbar-color: rgba(255,255,255,0.14) transparent; +} + +.forum-code-block::-webkit-scrollbar { + height: 8px; +} + +.forum-code-block::-webkit-scrollbar-track { + background: transparent; +} + +.forum-code-block::-webkit-scrollbar-thumb { + background-color: rgba(255,255,255,0.16); + border-radius: 999px; +} + +.forum-code-block::-webkit-scrollbar-thumb:hover { + background-color: rgba(255,255,255,0.28); +} + +.forum-code-block code { + display: block; + min-width: max-content; + padding: 3.75rem 1.25rem 1.25rem; + color: rgb(226 232 240); + font-family: 'JetBrains Mono', 'SFMono-Regular', 'Consolas', 'Liberation Mono', monospace; + font-size: 0.92rem; + line-height: 1.75; + tab-size: 2; +} + +.forum-code-block::before { + content: 'Code'; + position: absolute; + top: 0.82rem; + left: 1.1rem; + z-index: 1; + border: 1px solid rgba(56, 189, 248, 0.2); + border-radius: 999px; + background: rgba(15, 23, 42, 0.92); + padding: 0.2rem 0.55rem; + color: rgb(125 211 252); + font-size: 0.7rem; + font-weight: 700; + letter-spacing: 0.09em; + text-transform: uppercase; +} + +.forum-code-block .story-code-copy-button { + top: 0.78rem; + right: 1.05rem; +} + .tiptap pre code { display: block; background: none; @@ -621,7 +1102,8 @@ .story-prose pre { position: relative; - overflow: hidden; + overflow-x: auto; + overflow-y: hidden; border-color: rgba(51, 65, 85, 0.95) !important; background: linear-gradient(180deg, rgba(15, 23, 42, 0.98) 0, rgba(15, 23, 42, 0.98) 3rem, rgba(2, 6, 23, 0.98) 3rem, rgba(2, 6, 23, 0.98) 100%) !important; @@ -629,6 +1111,30 @@ 0 26px 75px rgba(2, 6, 23, 0.5), inset 0 1px 0 rgba(56, 189, 248, 0.08); padding: 4rem 1.5rem 1.5rem !important; + scrollbar-width: thin; + scrollbar-color: rgba(125, 211, 252, 0.34) rgba(15, 23, 42, 0.25); +} + +.story-prose pre::-webkit-scrollbar { + height: 10px; +} + +.story-prose pre::-webkit-scrollbar-track { + background: rgba(15, 23, 42, 0.24); +} + +.story-prose pre::-webkit-scrollbar-thumb { + border: 2px solid rgba(15, 23, 42, 0.28); + border-radius: 999px; + background: linear-gradient(90deg, rgba(56, 189, 248, 0.28), rgba(125, 211, 252, 0.48)); +} + +.story-prose pre::-webkit-scrollbar-thumb:hover { + background: linear-gradient(90deg, rgba(56, 189, 248, 0.42), rgba(125, 211, 252, 0.58)); +} + +.story-prose pre::-webkit-scrollbar-corner { + background: transparent; } .story-prose p { @@ -737,12 +1243,14 @@ .story-prose figure iframe { display: block; width: 100%; - min-width: 100%; + max-width: 100%; + height: auto; aspect-ratio: 16 / 9; } .news-rich-text-editor .news-embed, .story-prose .news-embed { + width: 100%; margin: 1.75rem 0; overflow: hidden; border: 1px solid rgba(148, 163, 184, 0.18); @@ -798,10 +1306,377 @@ .story-prose .news-embed-video iframe { display: block; width: 100%; + max-width: 100%; + height: auto; border: 0; aspect-ratio: 16 / 9; } +.academy-lesson-prose { + color: rgb(226 232 240 / 0.9); + font-family: 'Libre Franklin', 'Inter', sans-serif; + font-size: calc(clamp(0.88rem, 1.02rem + 0.28vw, 1.2rem) * var(--academy-lesson-font-scale, 1)); + line-height: 1.74; +} + +.academy-lesson-prose > :first-child { + margin-top: 0; +} + +.academy-lesson-prose > :last-child { + margin-bottom: 0; +} + +.academy-lesson-prose :is(p, li) { + color: rgb(226 232 240 / 0.9); + font-size: inherit; + line-height: inherit; +} + +.academy-lesson-prose p { + margin-top: 0; + margin-bottom: 1.0rem; + text-wrap: pretty; +} + +.academy-lesson-prose p + p { + margin-top: 0; +} + +.academy-lesson-prose h2, +.academy-lesson-prose h3 { + position: relative; + text-wrap: balance; + scroll-margin-top: 7rem; +} + +.academy-lesson-prose h2 { + margin-top: 3.35rem; + margin-bottom: 1.05rem; + font-size: clamp(2.08rem, 1.56rem + 1.12vw, 2.8rem); + line-height: 1.06; + font-weight: 800; + letter-spacing: -0.045em; + color: rgb(255 255 255); +} + +.academy-lesson-prose h2::before { + content: ''; + display: block; + width: 3.25rem; + height: 2px; + margin-bottom: 1rem; + border-radius: 999px; + background: linear-gradient(90deg, rgba(125, 211, 252, 0.95), rgba(125, 211, 252, 0.12)); +} + +.academy-lesson-prose h3 { + margin-top: 2.45rem; + margin-bottom: 0.9rem; + font-size: clamp(1.48rem, 1.22rem + 0.66vw, 1.9rem); + line-height: 1.18; + font-weight: 750; + letter-spacing: -0.03em; + color: rgb(248 250 252); +} + +.academy-lesson-prose ul, +.academy-lesson-prose ol { + margin: 1rem 0 1.15rem; + padding-left: 0; +} + +.academy-lesson-prose ul { + list-style: none; +} + +.academy-lesson-prose ol { + list-style: none; + counter-reset: lesson-ordered-list; +} + +.academy-lesson-prose ul li, +.academy-lesson-prose ol li { + position: relative; + margin: 0; + padding-left: 1.95rem; + line-height: 1.64; +} + +.academy-lesson-prose ul li + li, +.academy-lesson-prose ol li + li { + margin-top: 0.14rem; +} + +.academy-lesson-prose ul li::before { + content: ''; + position: absolute; + top: 0.82em; + left: 0.2rem; + width: 0.55rem; + height: 0.55rem; + border-radius: 999px; + background: linear-gradient(180deg, rgba(125, 211, 252, 0.95), rgba(56, 189, 248, 0.65)); + box-shadow: 0 0 0 4px rgba(56, 189, 248, 0.08); +} + +.academy-lesson-prose ol li::before { + counter-increment: lesson-ordered-list; + content: counter(lesson-ordered-list); + position: absolute; + top: 0.16rem; + left: 0; + display: inline-flex; + align-items: center; + justify-content: center; + width: 1.2rem; + height: 1.2rem; + border: 1px solid rgba(125, 211, 252, 0.24); + border-radius: 999px; + background: rgba(56, 189, 248, 0.09); + color: rgb(224 242 254); + font-size: 0.72rem; + font-weight: 700; + line-height: 1; +} + +.academy-lesson-prose li > p:last-child { + margin-bottom: 0; +} + +.academy-lesson-prose li > p:first-child { + margin-top: 0; +} + +.academy-lesson-prose li > p + p { + margin-top: 0.25rem; +} + +.academy-lesson-prose hr { + position: relative; + height: 1px; + margin: 2.9rem 0; + border: 0; + background: linear-gradient(90deg, rgba(148, 163, 184, 0), rgba(148, 163, 184, 0.34), rgba(148, 163, 184, 0)); +} + +.academy-lesson-prose hr::after { + content: ''; + position: absolute; + left: 50%; + top: 50%; + width: 0.7rem; + height: 0.7rem; + transform: translate(-50%, -50%) rotate(45deg); + border: 1px solid rgba(125, 211, 252, 0.3); + background: rgba(15, 23, 42, 0.9); + box-shadow: 0 0 0 8px rgba(15, 23, 42, 0.9); +} + +.academy-lesson-prose table { + width: 100%; + margin: 2rem 0; + border-collapse: separate; + border-spacing: 0; + border: 1px solid rgba(125, 211, 252, 0.28); + border-radius: 1rem; + overflow: hidden; + background: rgba(8, 12, 20, 0.72); + box-shadow: inset 0 0 0 1px rgba(255, 255, 255, 0.03), 0 16px 42px rgba(2, 6, 23, 0.2); +} + +.academy-lesson-prose th, +.academy-lesson-prose td { + min-width: 120px; + padding: 0.9rem 1rem; + border: 1px solid rgba(148, 163, 184, 0.28); + vertical-align: top; + background: rgba(255, 255, 255, 0.03); +} + +.academy-lesson-prose th { + background: rgba(14, 165, 233, 0.14); + color: rgb(248 250 252); + font-weight: 700; +} + +.academy-lesson-prose td p, +.academy-lesson-prose th p { + margin: 0; + line-height: 1.65; +} + +.academy-lesson-prose tbody tr:nth-child(even) td { + background: rgba(255, 255, 255, 0.02); +} + +.academy-lesson-prose pre { + margin: .4rem 0; + padding: 0.5rem !important; + border-color: rgba(56, 189, 248, 0.16) !important; + background: + linear-gradient(180deg, rgba(15, 23, 42, 0.98) 0, rgba(15, 23, 42, 0.98) 3rem, rgba(2, 6, 23, 0.98) 3rem, rgba(2, 6, 23, 0.98) 100%) !important; + box-shadow: + 0 28px 78px rgba(2, 6, 23, 0.56), + inset 0 1px 0 rgba(56, 189, 248, 0.1); +} + +.academy-lesson-prose pre code, +.academy-lesson-prose pre code.hljs, +.academy-lesson-prose pre code[class*='language-'] { + color: rgb(226 232 240); + font-size: 0.92rem; + line-height: 1.8; + tab-size: 2; +} + +.academy-lesson-prose pre::after { + inset: 3rem 0 auto 0; + background: linear-gradient(90deg, rgba(56, 189, 248, 0), rgba(56, 189, 248, 0.26), rgba(56, 189, 248, 0)); +} + +.academy-lesson-prose pre[data-language]::before { + top: 0.8rem; + left: 1.2rem; +} + +.academy-lesson-prose > img, +.academy-lesson-prose figure, +.academy-lesson-prose video, +.academy-lesson-prose iframe { + display: block; + width: 100%; + margin: 2.15rem 0; +} + +.academy-lesson-prose > img, +.academy-lesson-prose figure img, +.academy-lesson-prose video, +.academy-lesson-prose iframe { + overflow: hidden; + border: 1px solid rgba(148, 163, 184, 0.12); + border-radius: 1.5rem; + background: linear-gradient(180deg, rgba(15, 23, 42, 0.94), rgba(2, 6, 23, 0.96)); + box-shadow: 0 24px 55px rgba(2, 6, 23, 0.34); +} + +.academy-lesson-prose iframe, +.academy-lesson-prose video, +.academy-lesson-prose figure iframe, +.academy-lesson-prose figure video { + aspect-ratio: 16 / 9; +} + +.academy-code-copy-button { + top: 0.78rem; + right: 1.1rem; +} + +.academy-lesson-prose figure { + overflow: hidden; + border: 1px solid rgba(148, 163, 184, 0.12); + border-radius: 1.75rem; + background: rgba(15, 23, 42, 0.72); + padding: 0.55rem; +} + +.academy-lesson-prose figure img, +.academy-lesson-prose figure iframe, +.academy-lesson-prose figure video { + margin: 0; +} + +.academy-lesson-prose figcaption { + padding: 0.9rem 0.45rem 0.25rem; + color: rgb(148 163 184 / 0.92); + font-size: 0.92rem; + line-height: 1.7; + text-align: center; +} + +.academy-lesson-prose a { + color: rgb(125 211 252); + text-decoration-thickness: 1.5px; + text-underline-offset: 0.18em; +} + +.academy-lesson-toc-link { + display: flex; + align-items: flex-start; + gap: 0.8rem; + border-radius: 1rem; + padding: 0.8rem 0.9rem; + color: rgb(226 232 240 / 0.88); + font-size: 0.96rem; + line-height: 1.55; + text-decoration: none; + transition: background-color 140ms ease, color 140ms ease, border-color 140ms ease, transform 140ms ease; +} + +.academy-lesson-toc-link:hover { + background: rgba(255, 255, 255, 0.05); + color: rgb(255 255 255); +} + +.academy-lesson-toc-link-active { + background: rgba(56, 189, 248, 0.12); + color: rgb(255 255 255); + box-shadow: inset 0 0 0 1px rgba(125, 211, 252, 0.18); +} + +.academy-lesson-toc-link-active .academy-lesson-toc-link-indicator { + background: linear-gradient(180deg, rgba(125, 211, 252, 1), rgba(56, 189, 248, 0.9)); + box-shadow: 0 0 0 4px rgba(56, 189, 248, 0.12); +} + +.academy-lesson-toc-link-subtle { + padding-left: 1.55rem; + color: rgb(148 163 184 / 0.95); + font-size: 0.9rem; +} + +.academy-lesson-toc-link-indicator { + width: 0.45rem; + height: 0.45rem; + margin-top: 0.48rem; + flex: 0 0 auto; + border-radius: 999px; + background: linear-gradient(180deg, rgba(125, 211, 252, 0.95), rgba(56, 189, 248, 0.68)); + box-shadow: 0 0 0 4px rgba(56, 189, 248, 0.08); +} + +.academy-lesson-toc-link-subtle .academy-lesson-toc-link-indicator { + width: 0.35rem; + height: 0.35rem; + margin-top: 0.56rem; + background: rgba(148, 163, 184, 0.72); + box-shadow: none; +} + +.academy-lesson-prose strong { + color: rgb(255 255 255); + font-weight: 750; +} + +.academy-lesson-prose em { + color: rgb(226 232 240 / 0.94); +} + +@media (max-width: 768px) { + .academy-lesson-prose { + font-size: calc(clamp(1.02rem, 0.98rem + 0.18vw, 1.1rem) * var(--academy-lesson-font-scale, 1)); + line-height: 1.78; + } + + .academy-lesson-prose h2 { + margin-top: 2.8rem; + } + + .academy-lesson-prose h3 { + margin-top: 2.15rem; + } +} + .news-editor-outline .ProseMirror :is(p, div, figure, blockquote, ul, ol, li, h2, h3, pre, hr) { position: relative; outline: 1px dashed rgba(56, 189, 248, 0.24); @@ -821,7 +1696,7 @@ .news-editor-outline .ProseMirror hr::before { position: absolute; top: -0.55rem; - left: 0.1rem; + right: 0.1rem; z-index: 2; border: 1px solid rgba(148, 163, 184, 0.16); border-radius: 0.35rem; @@ -968,6 +1843,7 @@ .story-prose pre code.hljs, .story-prose pre code[class*='language-'] { display: block; + min-width: max-content; overflow-x: auto; background: transparent; padding: 0; diff --git a/resources/js/Layouts/AdminLayout.jsx b/resources/js/Layouts/AdminLayout.jsx index 7c0ff2d9..55b30288 100644 --- a/resources/js/Layouts/AdminLayout.jsx +++ b/resources/js/Layouts/AdminLayout.jsx @@ -7,6 +7,7 @@ const buildAdminNavGroups = (isAdmin) => [ items: [ { label: 'Dashboard', href: '/moderation', icon: 'fa-solid fa-gauge-high', exact: true }, { label: 'Daily Activity', href: '/moderation/activity', icon: 'fa-solid fa-calendar-day' }, + { label: 'Online Users', href: '/moderation/traffic/online', icon: 'fa-solid fa-user-check' }, ], }, { @@ -22,10 +23,6 @@ const buildAdminNavGroups = (isAdmin) => [ items: [ { label: 'Stories', href: '/moderation/stories', icon: 'fa-solid fa-feather-pointed' }, { label: 'Artworks', href: '/moderation/artworks', icon: 'fa-solid fa-images' }, - { label: 'Academy Dashboard', href: '/moderation/academy/dashboard', icon: 'fa-solid fa-graduation-cap' }, - { label: 'Academy Lessons', href: '/moderation/academy/lessons', icon: 'fa-solid fa-book-open' }, - { label: 'Academy Prompts', href: '/moderation/academy/prompts', icon: 'fa-solid fa-wand-magic-sparkles' }, - { label: 'Academy Challenges', href: '/moderation/academy/challenges', icon: 'fa-solid fa-trophy' }, { label: 'Featured Artworks', href: '/moderation/artworks/featured', icon: 'fa-solid fa-star' }, { label: 'Homepage Announcements', href: '/moderation/homepage/announcements', icon: 'fa-solid fa-bullhorn' }, { label: 'Upload Queue', href: '/moderation/uploads', icon: 'fa-solid fa-cloud-arrow-up' }, @@ -33,6 +30,15 @@ const buildAdminNavGroups = (isAdmin) => [ { label: 'AI Biography', href: '/moderation/ai-biography', icon: 'fa-solid fa-wand-magic-sparkles' }, ], }, + { + label: 'Academy', + items: [ + { label: 'Academy Dashboard', href: '/moderation/academy/dashboard', icon: 'fa-solid fa-graduation-cap' }, + { label: 'Academy Lessons', href: '/moderation/academy/lessons', icon: 'fa-solid fa-book-open' }, + { label: 'Academy Prompts', href: '/moderation/academy/prompts', icon: 'fa-solid fa-wand-magic-sparkles' }, + { label: 'Academy Challenges', href: '/moderation/academy/challenges', icon: 'fa-solid fa-trophy' }, + ], + }, { label: 'System', items: [ @@ -49,6 +55,18 @@ function NavLink({ item, active }) { : 'text-slate-400 hover:text-white hover:bg-white/5' }` + // For some moderation surfaces (traffic/online) we prefer a full-page + // navigation so the server-rendered blade view opens as its own page + // instead of being handled by Inertia or opened inline. + if (item.href === '/moderation/traffic/online') { + return ( + + + {item.label} + + ) + } + return ( @@ -66,7 +84,7 @@ function Sidebar({ pathname, isAdmin }) { } return ( -