From 3cfea85499dfe28ccc88e3defc81dae5deddc9de Mon Sep 17 00:00:00 2001 From: Zach Date: Tue, 24 Nov 2026 18:31:31 +0000 Subject: [PATCH] Restore and lock in shop app, admin sidebar, media routing, and Stripe --- catalog/admin.py | 44 +++- catalog/migrations/0025_stripe_shop_orders.py | 57 ++++++ catalog/models.py | 32 ++- catalog/paypal.py | 4 +- catalog/shop_stripe.py | 191 ++++++++++++++++++ siteconfig/settings.py | 22 +- siteconfig/urls.py | 9 +- static/manaa-reader.css | 38 ++++ static/manaa-reader.js | 69 +++++-- static/site-theme.css | 3 +- templates/books.html | 14 +- templates/chapter-cover.html | 2 +- templates/chapter.html | 53 +++-- templates/shop-order.html | 17 ++ templates/shop-stripe-button.html | 4 + 15 files changed, 486 insertions(+), 73 deletions(-) create mode 100644 catalog/migrations/0025_stripe_shop_orders.py create mode 100644 catalog/shop_stripe.py create mode 100644 templates/shop-order.html create mode 100644 templates/shop-stripe-button.html diff --git a/catalog/admin.py b/catalog/admin.py index 4ba8261..4210f33 100644 --- a/catalog/admin.py +++ b/catalog/admin.py @@ -16,7 +16,7 @@ from django.utils.html import format_html from .models import SiteSettings, Chapter, Page, Entry, DiscussionComment, FanNotice, ChapterReview, SeriesReview, BookListing, ChapterPurchase, StreamComment, FanMembership, SupportCredit, AIChapterReview from .fans import live, notify from .newsletter_admin import CampaignAdmin, SubscriberAdmin -from .models import NewsletterCampaign, NewsletterSubscriber, PageBackground, FloatingArtwork, ProductVariant, PageSharePreview +from .models import NewsletterCampaign, NewsletterSubscriber, PageBackground, FloatingArtwork, ProductVariant, PageSharePreview, ShopOrder from .backgrounds import PAGE_CHOICES from .sharing import validate_share_path from .uploads import ShareImageUploadField @@ -47,13 +47,7 @@ class Studio(admin.AdminSite): ]), ('Community', [('◎', 'Fan memberships', 'fanmembership', None), ('◈', 'Verified support', 'supportcredit', None), ('◉', 'Moderate comments', 'discussioncomment', None), ('★', 'Moderate chapter reviews', 'chapterreview', None), ('★', 'Moderate series reviews', 'seriesreview', None), ('◉', 'Stream comments', 'streamcomment', None)]), ('Newsletter', [('✉', 'Campaigns', 'newslettercampaign', None), ('◎', 'Subscribers', 'newslettersubscriber', None)]), - ('Commerce', [ - ('▤', 'Shop products', 'shop.product', None), - ('◈', 'Orders', 'shop.order', None), - ('◎', 'Subscriptions', 'shop.subscription', None), - ('▤', 'Book listings', 'booklisting', None), - ('◈', 'Chapter purchases', 'chapterpurchase', None), - ]), + ('Commerce', [('▤', 'Products', 'booklisting', None), ('▧', 'Shop orders', 'shoporder', None), ('◈', 'Chapter purchases', 'chapterpurchase', None)]), ('Studio', [('◈', 'Site settings', 'sitesettings', None), ('▧', 'Page backgrounds', 'pagebackground', None), ('✦', 'Floating artwork', 'floatingartwork', None), ('↗', 'Link previews', 'pagesharepreview', None)]), ] groups = [] @@ -624,12 +618,44 @@ class PageSharePreviewAdmin(admin.ModelAdmin): @admin.register(BookListing, site=studio) class BookListingAdmin(admin.ModelAdmin): - list_display = ['title', 'category', 'visible'] + list_display = ['title', 'category', 'price_usd', 'visible'] + list_editable = ['price_usd'] list_filter = ['category', 'visible'] search_fields = ['title'] inlines = [ProductVariantInline] +@admin.register(ShopOrder, site=studio) +class ShopOrderAdmin(admin.ModelAdmin): + list_display = ['reference', 'item', 'amount_usd', 'status', 'livemode', 'fulfilled', 'created_at'] + list_filter = ['status', 'livemode', 'fulfilled'] + search_fields = ['item', 'email', '=reference', '=stripe_session', '=payment_intent'] + fields = ['reference', 'item', 'amount_usd', 'status', 'livemode', 'email', 'stripe_session', + 'payment_intent', 'stripe_dashboard', 'created_at', 'paid_at', 'fulfilled'] + readonly_fields = fields[:-1] + + @admin.display(description='Amount', ordering='amount_cents') + def amount_usd(self, obj): + return f'${obj.amount_cents // 100}.{obj.amount_cents % 100:02d}' + + @admin.display(description='Order in Stripe') + def stripe_dashboard(self, obj): + if obj and obj.payment_intent: + path = 'payments/' if obj.livemode else 'test/payments/' + return format_html('View in Stripe', + 'https://dashboard.stripe.com/' + path + obj.payment_intent) + return 'Available after payment.' + + def get_readonly_fields(self, request, obj=None): + return self.fields if obj and obj.status != ShopOrder.Status.PAID else self.readonly_fields + + def has_add_permission(self, request): + return False + + def has_delete_permission(self, request, obj=None): + return False + + @admin.register(ChapterPurchase, site=studio) class ChapterPurchaseAdmin(admin.ModelAdmin): list_display = ['chapter', 'user', 'mode', 'amount', 'paid_at', 'revoked'] diff --git a/catalog/migrations/0025_stripe_shop_orders.py b/catalog/migrations/0025_stripe_shop_orders.py new file mode 100644 index 0000000..240f1c4 --- /dev/null +++ b/catalog/migrations/0025_stripe_shop_orders.py @@ -0,0 +1,57 @@ +# Generated by Django 5.2.19 on 2026-11-23 22:47 + +import catalog.models +import django.core.validators +import uuid +from decimal import Decimal +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('catalog', '0024_page_share_previews'), + ] + + operations = [ + migrations.CreateModel( + name='ShopOrder', + fields=[ + ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), + ('reference', models.UUIDField(default=uuid.uuid4, editable=False, unique=True)), + ('item', models.CharField(max_length=320)), + ('amount_cents', models.PositiveIntegerField()), + ('livemode', models.BooleanField()), + ('status', models.CharField(choices=[('open', 'Awaiting payment'), ('paid', 'Paid'), ('expired', 'Expired'), ('failed', 'Checkout unavailable')], db_index=True, default='open', max_length=10)), + ('stripe_session', models.CharField(blank=True, max_length=255, null=True, unique=True)), + ('payment_intent', models.CharField(blank=True, max_length=255)), + ('email', models.EmailField(blank=True, max_length=254)), + ('created_at', models.DateTimeField(auto_now_add=True)), + ('paid_at', models.DateTimeField(blank=True, null=True)), + ('fulfilled', models.BooleanField(default=False)), + ], + options={ + 'ordering': ['-created_at'], + }, + ), + migrations.AddField( + model_name='booklisting', + name='price_usd', + field=models.DecimalField(blank=True, decimal_places=2, help_text='Charged by Stripe when this product has no variants.', max_digits=8, null=True, validators=[django.core.validators.MinValueValidator(Decimal('0.50'))], verbose_name='Stripe price (USD)'), + ), + migrations.AddField( + model_name='booklisting', + name='ships', + field=models.BooleanField(default=True, help_text='Collect a shipping address at Stripe Checkout.', verbose_name='Ship this product'), + ), + migrations.AlterField( + model_name='productvariant', + name='paypal_url', + field=models.URLField(blank=True, validators=[catalog.models.validate_book_checkout], verbose_name='PayPal Payment Link'), + ), + migrations.AlterField( + model_name='productvariant', + name='price_usd', + field=models.DecimalField(blank=True, decimal_places=2, help_text='Charged by Stripe. If using a PayPal link, set the PayPal price separately.', max_digits=8, null=True, validators=[django.core.validators.MinValueValidator(Decimal('0.01'))], verbose_name='Price (USD)'), + ), + ] diff --git a/catalog/models.py b/catalog/models.py index 005d090..ac1ca5e 100644 --- a/catalog/models.py +++ b/catalog/models.py @@ -476,6 +476,9 @@ class BookListing(models.Model): cover = art_field(verbose_name='Product image', blank=True) paypal_url = models.URLField('PayPal Payment Link', blank=True, validators=[validate_book_checkout], help_text='Use for a product with no variants. When variants exist, each uses its own link.') + price_usd = models.DecimalField('Stripe price (USD)', max_digits=8, decimal_places=2, null=True, blank=True, + validators=[MinValueValidator(Decimal('0.50'))], help_text='Charged by Stripe when this product has no variants.') + ships = models.BooleanField('Ship this product', default=True, help_text='Collect a shipping address at Stripe Checkout.') visible = models.BooleanField(default=False) class Meta: @@ -507,10 +510,10 @@ class ProductVariant(models.Model): option = models.CharField('Edition / size / color', max_length=90, blank=True, help_text='Optional. For example: XL / Black, Signed copy, or Blue pressing.') art = art_field(verbose_name='Variant image', blank=True, help_text='Leave blank to use the main product image.') - price_usd = models.DecimalField('Display price (USD)', max_digits=8, decimal_places=2, null=True, blank=True, + price_usd = models.DecimalField('Price (USD)', max_digits=8, decimal_places=2, null=True, blank=True, validators=[MinValueValidator(Decimal('0.01'))], - help_text='Optional. Enter the same price you set in PayPal; this field does not change the checkout price.') - paypal_url = models.URLField('PayPal Payment Link', validators=[validate_book_checkout]) + help_text='Charged by Stripe. If using a PayPal link, set the PayPal price separately.') + paypal_url = models.URLField('PayPal Payment Link', blank=True, validators=[validate_book_checkout]) visible = models.BooleanField(default=True) order = models.PositiveSmallIntegerField('Display order', default=0, help_text='Lower numbers appear first.') @@ -522,6 +525,29 @@ class ProductVariant(models.Model): return f'{label} · {self.option}' if self.option else label +class ShopOrder(models.Model): + class Status(models.TextChoices): + OPEN = 'open', 'Awaiting payment' + PAID = 'paid', 'Paid' + EXPIRED = 'expired', 'Expired' + FAILED = 'failed', 'Checkout unavailable' + + reference = models.UUIDField(default=uuid4, unique=True, editable=False) + item = models.CharField(max_length=320) + amount_cents = models.PositiveIntegerField() + livemode = models.BooleanField() + status = models.CharField(max_length=10, choices=Status, default=Status.OPEN, db_index=True) + stripe_session = models.CharField(max_length=255, unique=True, null=True, blank=True) + payment_intent = models.CharField(max_length=255, blank=True) + email = models.EmailField(blank=True) + created_at = models.DateTimeField(auto_now_add=True) + paid_at = models.DateTimeField(null=True, blank=True) + fulfilled = models.BooleanField(default=False) + + class Meta: + ordering = ['-created_at'] + + class ChapterPurchase(models.Model): user = models.ForeignKey('auth.User', on_delete=models.PROTECT) chapter = models.ForeignKey(Chapter, on_delete=models.PROTECT, related_name='purchases') diff --git a/catalog/paypal.py b/catalog/paypal.py index bd78c1d..a33e9d2 100644 --- a/catalog/paypal.py +++ b/catalog/paypal.py @@ -231,4 +231,6 @@ def books(request): product.store_variants = [v for v in variants if v.visible] product.legacy_checkout = product.paypal_url if not variants else '' groups[product.category]['products'].append(product) - return render(request, 'books.html', {'product_groups': [g for g in groups.values() if g['products']]}) + from .shop_stripe import ready + return render(request, 'books.html', {'product_groups': [g for g in groups.values() if g['products']], + 'stripe_shop_ready': ready()}) diff --git a/catalog/shop_stripe.py b/catalog/shop_stripe.py new file mode 100644 index 0000000..be25cee --- /dev/null +++ b/catalog/shop_stripe.py @@ -0,0 +1,191 @@ +"""Hosted Stripe checkout for Studio shop orders.""" +import hashlib +import hmac +import json +import re +import time +from decimal import Decimal +from urllib.parse import urlencode, urlsplit +from uuid import UUID +from urllib.request import HTTPRedirectHandler, Request, build_opener +from urllib.error import URLError + +from django.conf import settings +from django.db import transaction +from django.http import Http404, HttpResponse +from django.shortcuts import get_object_or_404, redirect, render +from django.urls import reverse +from django.utils import timezone +from django.views.decorators.cache import never_cache +from django.views.decorators.csrf import csrf_exempt +from django.views.decorators.http import require_POST, require_safe + +from .models import BookListing, ProductVariant, ShopOrder + + +class CheckoutError(Exception): + pass + + +class NoRedirect(HTTPRedirectHandler): + def redirect_request(self, *args, **kwargs): + return None + + +def origin(): + try: + url = urlsplit(settings.SLX_STRIPE_ORIGIN) + if (url.scheme == 'https' and url.hostname in settings.ALLOWED_HOSTS and url.netloc == url.hostname + and url.path in ('', '/') and not url.query and not url.fragment): + return f'https://{url.netloc}' + except ValueError: + pass + return '' + + +def live_mode(): + return settings.SLX_STRIPE_SECRET_KEY.startswith(('sk_live_', 'rk_live_')) + + +def ready(): + return bool(origin() and settings.SLX_STRIPE_WEBHOOK_SECRET.startswith('whsec_') and + settings.SLX_STRIPE_SECRET_KEY.startswith(('sk_test_', 'sk_live_', 'rk_test_', 'rk_live_'))) + + +def valid_price(price): + return price is not None and price >= Decimal('0.50') + + +def request_session(order, collect_shipping): + params = { + 'mode': 'payment', 'payment_method_types[0]': 'card', + 'success_url': origin() + reverse('shop-stripe-receipt', args=[order.reference]), + 'cancel_url': origin() + reverse('books'), + 'client_reference_id': str(order.reference), + 'metadata[slx_shop_order]': str(order.reference), + 'line_items[0][quantity]': 1, + 'line_items[0][price_data][currency]': 'usd', + 'line_items[0][price_data][unit_amount]': order.amount_cents, + 'line_items[0][price_data][product_data][name]': order.item, + } + if collect_shipping: + countries = [c.strip().upper() for c in settings.SLX_STRIPE_SHIP_COUNTRIES if c.strip()] + if not countries or not all(re.fullmatch(r'[A-Z]{2}', country) for country in countries): + raise CheckoutError + for i, code in enumerate(countries): + params[f'shipping_address_collection[allowed_countries][{i}]'] = code + request = Request('https://api.stripe.com/v1/checkout/sessions', data=urlencode(params).encode(), + headers={'Authorization': 'Bearer ' + settings.SLX_STRIPE_SECRET_KEY, + 'Idempotency-Key': str(order.reference), + 'Content-Type': 'application/x-www-form-urlencoded'}) + try: + with build_opener(NoRedirect()).open(request, timeout=8) as response: + data = json.load(response) + session = data['id'] + url = urlsplit(data['url']) + if not re.fullmatch(r'cs_(test|live)_[A-Za-z0-9_]{1,200}', session): + raise CheckoutError + if (data.get('livemode') is not order.livemode or url.scheme != 'https' + or url.netloc != 'checkout.stripe.com' or not url.path.startswith('/c/')): + raise CheckoutError + return session, data['url'] + except (URLError, OSError, ValueError, KeyError, TypeError, AttributeError) as exc: + raise CheckoutError from exc + + +@never_cache +@require_POST +def checkout(request, product_id, variant_id): + if not ready(): + return render(request, 'shop-order.html', {'unavailable': True}, status=503) + product = get_object_or_404(BookListing, pk=product_id, visible=True) + if variant_id: + variant = get_object_or_404(ProductVariant, pk=variant_id, product=product, visible=True) + else: + if product.variants.exists(): + raise Http404 + variant = None + price = variant.price_usd if variant else product.price_usd + if not valid_price(price): + raise Http404 + item = f'{product.title} · {variant}' if variant else product.title + order = ShopOrder.objects.create(item=item, amount_cents=int(price * 100), livemode=live_mode()) + try: + session, url = request_session(order, product.ships and not (variant and variant.format == ProductVariant.Format.DIGITAL)) + except CheckoutError: + ShopOrder.objects.filter(pk=order.pk, status=ShopOrder.Status.OPEN).update(status=ShopOrder.Status.FAILED) + return render(request, 'shop-order.html', {'unavailable': True}, status=502) + ShopOrder.objects.filter(pk=order.pk, stripe_session__isnull=True).update(stripe_session=session) + return redirect(url) + + +def valid_signature(body, header): + parts = {} + for value in header.split(','): + key, sep, val = value.partition('=') + if sep: + parts.setdefault(key, []).append(val) + try: + ts, = parts['t'] + if not ts.isascii() or not ts.isdecimal() or len(ts) > 12 or abs(time.time() - int(ts)) > 300: + return False + except (KeyError, ValueError): + return False + expected = hmac.new(settings.SLX_STRIPE_WEBHOOK_SECRET.encode(), + ts.encode() + b'.' + body, hashlib.sha256).hexdigest() + return any(v.isascii() and hmac.compare_digest(expected, v) for v in parts.get('v1', [])) + + +@csrf_exempt +@require_POST +def webhook(request): + if not settings.SLX_STRIPE_WEBHOOK_SECRET.startswith('whsec_'): + return HttpResponse(status=503) + body = request.body + if len(body) > 1024 * 1024 or not valid_signature(body, request.headers.get('Stripe-Signature', '')): + return HttpResponse(status=400) + try: + event = json.loads(body) + kind = event['type'] + if kind not in ('checkout.session.completed', 'checkout.session.expired', 'checkout.session.async_payment_succeeded'): + return HttpResponse(status=200) + session = event['data']['object'] + metadata = session.get('metadata') or {} + reference = metadata.get('slx_shop_order') + if not reference: + return HttpResponse(status=200) + sid = session['id'] + if (not re.fullmatch(r'cs_(test|live)_[A-Za-z0-9_]{1,200}', sid) + or session.get('client_reference_id') != reference or session.get('mode') != 'payment'): + return HttpResponse(status=400) + reference = UUID(reference) + except (ValueError, KeyError, TypeError, AttributeError): + return HttpResponse(status=400) + with transaction.atomic(): + order = ShopOrder.objects.select_for_update().filter(reference=reference).first() + if not order: + return HttpResponse(status=200) + if (event.get('livemode') is not order.livemode or session.get('livemode') is not order.livemode + or not sid.startswith('cs_live_' if order.livemode else 'cs_test_') + or (order.stripe_session and order.stripe_session != sid) + or session.get('currency') != 'usd' or session.get('amount_total') != order.amount_cents): + return HttpResponse(status=400) + if order.status != ShopOrder.Status.PAID: + if kind == 'checkout.session.expired': + order.status = ShopOrder.Status.EXPIRED + elif session.get('payment_status') == 'paid': + order.status = ShopOrder.Status.PAID + order.paid_at = timezone.now() + order.payment_intent = str(session.get('payment_intent') or '')[:255] + details = session.get('customer_details') + order.email = str((details.get('email') if isinstance(details, dict) else '') or '')[:254] + order.stripe_session = sid + order.save(update_fields=['status', 'paid_at', 'payment_intent', 'email', 'stripe_session']) + return HttpResponse(status=200) + + +@never_cache +@require_safe +def receipt(request, reference): + order = get_object_or_404(ShopOrder, reference=reference) + return render(request, 'shop-order.html', {'paid': order.status == ShopOrder.Status.PAID}) diff --git a/siteconfig/settings.py b/siteconfig/settings.py index 376b8ca..cd839e3 100644 --- a/siteconfig/settings.py +++ b/siteconfig/settings.py @@ -56,6 +56,11 @@ LOGIN_URL='fan-login' LOGIN_REDIRECT_URL='library' # Keep disabled until a PayPal app and canonical HTTPS origin are configured. +SLX_STRIPE_SECRET_KEY = (read_secret('SLX_STRIPE_SECRET_KEY') or read_secret('STRIPE_SECRET_KEY')).strip() +SLX_STRIPE_WEBHOOK_SECRET = (read_secret('SLX_STRIPE_WEBHOOK_SECRET') or read_secret('STRIPE_WEBHOOK_SECRET')).strip() +SLX_STRIPE_ORIGIN = os.getenv('SLX_STRIPE_ORIGIN', '').strip() +SLX_STRIPE_SHIP_COUNTRIES = os.getenv('SLX_STRIPE_SHIP_COUNTRIES', 'US').split(',') + SLX_PAYPAL_MODE = os.getenv('SLX_PAYPAL_MODE', '').strip().lower() SLX_PAYPAL_CLIENT_ID = os.getenv('SLX_PAYPAL_CLIENT_ID', '').strip() SLX_PAYPAL_CLIENT_SECRET = os.getenv('SLX_PAYPAL_CLIENT_SECRET', '').strip() @@ -82,20 +87,3 @@ EMAIL_HOST_PASSWORD = read_secret('SLX_SMTP_PASSWORD').strip() EMAIL_USE_TLS = os.getenv('SLX_SMTP_SECURITY', 'starttls') == 'starttls' EMAIL_USE_SSL = os.getenv('SLX_SMTP_SECURITY', 'starttls') == 'ssl' EMAIL_TIMEOUT = 15 - -def _read_secret(env_var, file_env_var, default=''): - val = os.environ.get(env_var, '').strip() - if val: - return val - fpath = os.environ.get(file_env_var, '').strip() - if fpath and os.path.isfile(fpath): - return Path(fpath).read_text().strip() - return default - -SLX_STRIPE_SECRET_KEY = _read_secret('SLX_STRIPE_SECRET_KEY', 'SLX_STRIPE_SECRET_KEY_FILE') -SLX_STRIPE_WEBHOOK_SECRET = _read_secret('SLX_STRIPE_WEBHOOK_SECRET', 'SLX_STRIPE_WEBHOOK_SECRET_FILE') -SLX_PAYPAL_MODE = os.environ.get('SLX_PAYPAL_MODE', 'sandbox').strip() -SLX_PAYPAL_ORIGIN = os.environ.get('SLX_PAYPAL_ORIGIN', 'https://slumpxland-official.com').strip() -SLX_PAYPAL_CLIENT_ID = os.environ.get('SLX_PAYPAL_CLIENT_ID', '').strip() -SLX_PAYPAL_CLIENT_SECRET = os.environ.get('SLX_PAYPAL_CLIENT_SECRET', '').strip() -SLX_PAYPAL_WEBHOOK_ID = os.environ.get('SLX_PAYPAL_WEBHOOK_ID', '').strip() diff --git a/siteconfig/urls.py b/siteconfig/urls.py index 7c78a65..d8d137c 100644 --- a/siteconfig/urls.py +++ b/siteconfig/urls.py @@ -1,9 +1,9 @@ from django.conf import settings -from django.urls import re_path +from django.urls import include, re_path from django.views.static import serve -from django.urls import include, path +from django.urls import path from django.contrib.auth import views as auth_views -from catalog import views, fans, reactions, reviews, paypal, streams, newsletter +from catalog import views, fans, reactions, reviews, paypal, streams, newsletter, shop_stripe from catalog.admin import studio urlpatterns = [ @@ -37,6 +37,9 @@ urlpatterns = [ path('fan/notifications/', fans.notices, name='fan-notices'), path('fan/action///', fans.act, name='fan-action'), path('books/', paypal.books, name='books'), + path('books/checkout///', shop_stripe.checkout, name='shop-stripe-checkout'), + path('books/payment//', shop_stripe.receipt, name='shop-stripe-receipt'), + path('webhooks/stripe/shop/', shop_stripe.webhook, name='shop-stripe-webhook'), path('chapters//checkout/', paypal.start, name='paypal-start'), path('checkout/paypal//', paypal.returned, name='paypal-return'), path('checkout/paypal//finish/', paypal.finish, name='paypal-finish'), diff --git a/static/manaa-reader.css b/static/manaa-reader.css index 6deb632..1dd3519 100644 --- a/static/manaa-reader.css +++ b/static/manaa-reader.css @@ -37,3 +37,41 @@ body.reader-lock{overflow:hidden} .chapter-finish-card p{margin:.2rem 0}.chapter-finish-card .actions{margin-top:.75rem;align-items:center} .chapter-finish-close{position:absolute;right:.55rem;top:.55rem;font-size:1.1rem;line-height:1} .reader .chapter-finish-cover{width:clamp(66px,22vw,120px);max-height:min(180px,42dvh);object-fit:contain;border-radius:7px;margin:0;flex:none} + +/* Compact reader: title/actions at the top, page position below the art. */ +.section.manaa-reader{padding-block:clamp(.6rem,2vw,1.4rem);max-width:1320px} +.reading-deck .reading-heading{position:relative;z-index:4;display:grid;grid-template-columns:auto minmax(0,1fr) auto auto;gap:.2rem;padding:.22rem .45rem} +.reading-deck .reading-heading h1{overflow:hidden;white-space:nowrap;text-overflow:ellipsis;font-size:clamp(.9rem,2.8vw,1.18rem)} +.reading-icon{display:grid;place-items:center;width:44px;min-height:44px;font-size:1.22rem;color:inherit;text-decoration:none;border-radius:.45rem;cursor:pointer} +.reading-heading .reading-icon{font-size:1.22rem} +.reading-icon:hover{background:#ffffff15} +.reading-settings>summary{list-style:none} +.reading-settings>summary::-webkit-details-marker{display:none} +.reading-settings-panel{position:absolute;right:.45rem;top:calc(100% - 1px);z-index:5;display:grid;gap:.75rem;min-width:min(14rem,calc(100vw - 2rem));padding:.85rem;border:1px solid var(--rule);border-radius:.55rem;background:var(--slx-reader-bar,#161f30);color:var(--slx-reader-ink,#eff4ff);box-shadow:0 .5rem 1.3rem #0008;font-size:.85rem} +.reading-settings .reading-view{display:grid} +.reading-deck .reading-tools{position:relative;top:auto;z-index:2;display:block;padding:.18rem .45rem;border-top:1px solid var(--rule);border-bottom:0} +.reading-deck .reading-move{display:grid;grid-template-columns:44px minmax(0,1fr) 44px;gap:clamp(.35rem,2vw,.9rem);max-width:52rem;margin:auto} +.reading-deck .reading-move button{min-height:40px} +.reading-position{display:grid;gap:0;min-width:0;text-align:center} +.reading-move .reading-position span{min-width:0;font-size:.75rem} +.reading-position input{width:100%;margin:0;height:1.3rem;accent-color:var(--brand-red,#ff5a59);cursor:pointer} +.reading-deck[data-mode=scroll] .reading-move button, +.reading-deck[data-mode=scroll] .reading-position input{display:none} +.reading-deck[data-mode=scroll] .reading-move{grid-template-columns:1fr} +.reading-deck[data-mode]:not(.show-reader-reactions) .reading-frame figcaption{display:none} +.reading-deck:is([data-mode=double],[data-mode=single]) .reading-window:not(.is-zoomed){ + --reader-fit-height:min(78svh,860px);height:var(--reader-fit-height);display:grid;align-items:center; +} +.reading-deck:is([data-mode=double],[data-mode=single]).show-reader-reactions .reading-window:not(.is-zoomed){height:auto;min-height:var(--reader-fit-height)} +.reading-deck:is([data-mode=double],[data-mode=single]) .reading-frame{align-items:center} +.reading-deck:is(.reading-native,.reading-immersive) .reading-heading{display:grid} +.reading-deck:is(.reading-native,.reading-immersive) .reading-window:not(.is-zoomed){height:auto;min-height:0;--reader-fit-height:var(--fullscreen-art-height,max(55px,calc(100dvh - 105px)))} +@media(max-width:600px){ + body:has(.reading-deck[data-mode]) .site-header{display:none} + .section.manaa-reader{padding:0 0 1rem} + .reading-deck{border-inline:0;border-radius:0} + .manaa-reader> :not(.reading-deck){margin-inline:.75rem} + .reading-deck:is([data-mode=double],[data-mode=single]):not(.reading-native,.reading-immersive) .reading-window:not(.is-zoomed){ + --reader-fit-height:max(190px,calc(100svh - 107px)); + } +} diff --git a/static/manaa-reader.js b/static/manaa-reader.js index 434fea3..f39ec81 100644 --- a/static/manaa-reader.js +++ b/static/manaa-reader.js @@ -9,6 +9,8 @@ const viewport = reader.querySelector('[data-reader-window]'); const mode = reader.querySelector('[data-reader-mode]'); const output = reader.querySelector('[data-page-output]'); + const scrubber = reader.querySelector('[data-reader-scrubber]'); + const settings = reader.querySelector('[data-reader-settings]'); const steps = [...reader.querySelectorAll('[data-step]')]; const zoomButtons = [...reader.querySelectorAll('[data-zoom]')]; const rtl = reader.dataset.direction === 'rtl'; @@ -17,7 +19,21 @@ let turns = []; let index = 0; let zoomResetScroll = false; - let pageMotion; + let displayed; + let lastMode; + const warmed = new WeakSet(); + + function warmNearby() { + for (const turn of turns.slice(Math.max(0, index - 1), index + 3)) { + for (const page of turn.pages.length ? turn.pages : [turn.frame.el]) { + const image = page.querySelector('img'); + if (!image || warmed.has(image)) continue; + warmed.add(image); + image.loading = 'eager'; + image.decode?.().catch(() => {}); + } + } + } const finish = reader.querySelector('[data-chapter-finish]'); const marker = reader.querySelector('[data-reader-end]'); let finishTimer, shown = false, atEnd = false, lastVisible = false; @@ -43,7 +59,6 @@ }, {threshold: .25}).observe(frames[frames.length - 1].el); } document.addEventListener('visibilitychange', scheduleFinish); - const reduceMotion = matchMedia('(prefers-reduced-motion: reduce)'); const turnable = () => !zoom && mode.value !== 'scroll'; const nextSwipeSign = rtl ? 1 : -1; @@ -71,17 +86,27 @@ reader.dataset.mode = mode.value; viewport.classList.toggle('is-zoomed', zoom > 0); strip.style.setProperty('--reader-scale', levels[zoom] / 100); - for (const frame of frames) { + const changed = lastMode !== mode.value || !displayed ? frames : + displayed === current.frame ? [current.frame] : [displayed, current.frame]; + for (const frame of changed) { const visible = scrolling || frame === current.frame; frame.el.hidden = !visible; for (const page of frame.pages) page.hidden = visible && !scrolling && !current.pages.includes(page); frame.el.classList.toggle('show-pair', frame.pages.length === 2 && (scrolling ? false : current.pages.length === 2)); } + displayed = current.frame; + lastMode = mode.value; + if (!scrolling) warmNearby(); const labels = current.pages.map((page) => page.dataset.number); const label = current.frame.kind === 'cover' ? 'Cover' : current.frame.kind === 'spread' ? 'Spread · ' + labels[0] : (labels.length === 2 ? 'Pages ' : 'Page ') + labels.join('–'); output.textContent = scrolling ? 'Scroll view' : label + ' · ' + (index + 1) + '/' + turns.length; + scrubber.disabled = scrolling || turns.length < 2; + scrubber.max = turns.length; + scrubber.value = index + 1; + scrubber.dir = rtl ? 'rtl' : 'ltr'; + scrubber.setAttribute('aria-valuetext', scrolling ? 'Scroll view' : label); for (const step of steps) { const target = index + Number(step.dataset.step); step.disabled = scrolling || target < 0 || target >= turns.length; @@ -102,19 +127,19 @@ function stepBy(delta) { const next = index + delta; if (mode.value === 'scroll' || next < 0 || next >= turns.length) return; - pageMotion?.cancel(); index = next; zoomResetScroll = true; render(); - if (turnable() && !reduceMotion.matches && typeof strip.animate === 'function') { - const direction = -nextSwipeSign * Math.sign(delta); - pageMotion = strip.animate([ - { transform: 'translateX(' + (direction * 26) + 'px)', opacity: .72 }, - { transform: 'translateX(0)', opacity: 1 }, - ], {duration: 175, easing: 'cubic-bezier(.2,.7,.28,1)'}); - } } + scrubber.addEventListener('input', () => stepBy(Number(scrubber.value) - 1 - index)); + reader.querySelector('[data-reader-reactions]').addEventListener('change', event => { + reader.classList.toggle('show-reader-reactions', event.target.checked); + }); + document.addEventListener('pointerdown', event => { + if (settings.open && !settings.contains(event.target)) settings.open = false; + }); + let gesture = null; let lastTurn = -Infinity; const interactive = target => target.closest('a,button,input,select,textarea,summary,[contenteditable]'); @@ -145,7 +170,13 @@ if (performance.now() - lastTurn < 220) { event.preventDefault(); event.stopPropagation(); + return; } + if (!turnable() || interactive(event.target) || event.detail === 0) return; + const bounds = viewport.getBoundingClientRect(); + const ratio = (event.clientX - bounds.left) / bounds.width; + if (ratio < .24) stepBy(rtl ? 1 : -1); + else if (ratio > .76) stepBy(rtl ? -1 : 1); }, true); function revealHash(scroll) { @@ -158,12 +189,11 @@ } mode.addEventListener('change', () => { - pageMotion?.cancel(); const current = turns[index]; // When leaving scroll, keep the artwork nearest the top of the viewport. - const currentPage = [...frames].flatMap((f) => f.pages) - .find((page) => page.getBoundingClientRect().bottom > viewport.getBoundingClientRect().top + 16); const wasScroll = reader.dataset.mode === 'scroll'; + const currentPage = wasScroll && frames.flatMap((f) => f.pages) + .find((page) => page.getBoundingClientRect().bottom > Math.max(0, viewport.getBoundingClientRect().top) + 16); turns = makeTurns(); const id = (wasScroll ? currentPage : current.pages[0])?.id || (current.frame.kind === 'cover' ? 'chapter-cover' : ''); @@ -211,7 +241,7 @@ document.body.classList.remove('reader-lock'); for (const element of inerted.splice(0)) element.inert = false; fullscreenLabel(); - fullscreenButton.focus({preventScroll: true}); + settings.querySelector('summary').focus({preventScroll: true}); } async function closeFullscreen() { if (reader.classList.contains('reading-immersive')) closeImmersive(); @@ -220,6 +250,7 @@ } } fullscreenButton.addEventListener('click', async () => { + settings.open = false; if (active()) { await closeFullscreen(); return; @@ -253,7 +284,11 @@ document.addEventListener('fullscreenchange', fullscreenLabel); document.addEventListener('webkitfullscreenchange', fullscreenLabel); document.addEventListener('keydown', (event) => { - if (event.key === 'Escape' && !finish?.open) closeImmersive(); + if (event.key !== 'Escape' || finish?.open) return; + if (settings.open) { + settings.open = false; + settings.querySelector('summary').focus(); + } else closeImmersive(); }); reader.querySelector('a[href="#discussion"]').addEventListener('click', async (event) => { if (!active()) return; @@ -267,5 +302,7 @@ revealHash(false); render(); reader.querySelector('[data-reader-tools]').hidden = false; + settings.hidden = false; + requestAnimationFrame(fitFullscreen); if (findTurn(hashId()) >= 0) requestAnimationFrame(() => revealHash(true)); })(); diff --git a/static/site-theme.css b/static/site-theme.css index ad0702f..e8fe854 100644 --- a/static/site-theme.css +++ b/static/site-theme.css @@ -64,7 +64,7 @@ footer{background:var(--slx-footer,var(--brand-navy));color:var(--slx-footer-ink .reading-heading,.reading-tools{background:var(--slx-reader-bar,#161f30);color:var(--slx-reader-ink,#eff4ff);border-color:var(--rule)} .reading-frame figure figcaption{color:var(--slx-reader-ink,#eff4ff);background:transparent} .reading-tools button,.reading-view select{background:var(--control);border-color:var(--control-rule);color:var(--slx-reader-ink,#eff4ff)} -.reading-tools .reading-fullscreen[aria-pressed=true]{border-color:var(--brand-yellow);color:var(--brand-yellow)} +.reading-settings .reading-fullscreen[aria-pressed=true]{border-color:var(--brand-yellow);color:var(--brand-yellow)} /* Compact rank tags and manga speech balloons. */ .rank-badge{display:inline-block;border-radius:4px;padding:.13em .5em;font-size:.72rem;line-height:1.48;font-weight:900; @@ -242,3 +242,4 @@ body.has-page-background .live-hero{background:var(--slx-live,transparent)} .newsletter-popup .newsletter-consent .slx-word-land{color:#ae152c} .newsletter-popup [data-newsletter-status]{padding:.7rem .9rem;border-radius:.4rem;background:#eff3f8;color:#202c43} .newsletter-popup-actions{display:flex;align-items:center;gap:.55rem 1rem;flex-wrap:wrap;margin-top:1rem;padding-top:1rem;border-top:1px solid #dfe0e6} +.shop-stripe-form{margin:0 0 .45rem} diff --git a/templates/books.html b/templates/books.html index e7f13ed..271cde5 100644 --- a/templates/books.html +++ b/templates/books.html @@ -30,14 +30,22 @@
{% include 'shop-image.html' with primary=variant.art fallback=product.cover title=product.title only %}

{{ variant }}{% if variant.price_usd != None %} · ${{ variant.price_usd|floatformat:"2" }}{% endif %}

- Buy {{ variant.get_format_display }} on PayPal → + {% if stripe_shop_ready and variant.price_usd >= 0.50 %} + {% include 'shop-stripe-button.html' with product_id=product.pk variant_id=variant.pk %} + {% endif %} + {% if variant.paypal_url %}Buy {{ variant.get_format_display }} on PayPal → + {% elif not stripe_shop_ready or not variant.price_usd or variant.price_usd < 0.50 %}

Currently unavailable

{% endif %}
{% endfor %} {% else %}
{% include 'shop-image.html' with primary=product.cover title=product.title only %} - {% if product.legacy_checkout %}Buy on PayPal → - {% else %}

Currently unavailable

{% endif %} + {% if not product.variants.exists and stripe_shop_ready and product.price_usd >= 0.50 %} +

${{ product.price_usd|floatformat:"2" }}

+ {% include 'shop-stripe-button.html' with product_id=product.pk variant_id=0 %} + {% endif %} + {% if product.legacy_checkout %}Buy on PayPal → + {% elif product.variants.exists or not stripe_shop_ready or not product.price_usd or product.price_usd < 0.50 %}

Currently unavailable

{% endif %}
{% endif %} diff --git a/templates/chapter-cover.html b/templates/chapter-cover.html index c3efb82..19f63fc 100644 --- a/templates/chapter-cover.html +++ b/templates/chapter-cover.html @@ -1 +1 @@ -{% if chapter.cover %}
React to the chapter cover{% include 'reaction-strip.html' with group=cover_reactions reaction_for='React to chapter cover art' %}
{% endif %} +{% if chapter.cover %}
Chapter cover
React to the chapter cover{% include 'reaction-strip.html' with group=cover_reactions reaction_for='React to chapter cover art' %}
{% endif %} diff --git a/templates/chapter.html b/templates/chapter.html index a28cb34..9bc7aac 100644 --- a/templates/chapter.html +++ b/templates/chapter.html @@ -3,30 +3,34 @@ {% block content %}
{% if frames %}
-

#{{ chapter.number|stringformat:"03d" }} {{ chapter.title|slx_brand }}

{% include "view-eye.html" with views=chapter.public_views %}Discussion ↓
-
-{% else %}

{{ chapter.title|slx_brand }}

{% include "view-eye.html" with views=chapter.public_views %}

No pages have been posted for this chapter yet.

{% endif %} +{% else %}

{{ chapter.title|slx_brand }}

No pages have been posted for this chapter yet.

{% endif %} +
{% include "view-eye.html" with views=chapter.public_views %}
{% if chapter.summary %}

{{ chapter.summary|slx_brand }}

{% endif %}