added pricing, orgs
tests / ci (push) Canceled after 0s

This commit is contained in:
2026-10-04 20:34:19 -07:00
parent 999d5ad28d
commit 2ca3860557
52 changed files with 3467 additions and 47 deletions
@@ -28,6 +28,9 @@
<flux:sidebar.item icon="users" :href="route('admin.notes-limits')" :current="request()->routeIs('admin.notes-limits')" wire:navigate>
{{ __('Notes limits') }}
</flux:sidebar.item>
<flux:sidebar.item icon="currency-dollar" :href="route('admin.plan-pricing')" :current="request()->routeIs('admin.plan-pricing')" wire:navigate>
{{ __('Plan pricing') }}
</flux:sidebar.item>
</flux:sidebar.group>
@endif
</flux:sidebar.nav>
@@ -0,0 +1,44 @@
<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}" class="dark">
<head>
@include('partials.head')
</head>
<body class="min-h-screen bg-white antialiased dark:bg-linear-to-b dark:from-neutral-950 dark:to-neutral-900">
<div class="flex min-h-svh flex-col">
<header class="border-b border-zinc-200 px-6 py-4 dark:border-white/10">
<div class="mx-auto flex w-full max-w-5xl items-center justify-between">
<a href="{{ route('home') }}" class="flex items-center gap-2 font-medium" wire:navigate>
<x-app-logo-icon class="size-8 fill-current text-zinc-900 dark:text-white" />
<span class="text-sm font-semibold text-zinc-900 dark:text-white">{{ config('app.name', 'Laravel') }}</span>
</a>
<nav class="flex items-center gap-4 text-sm">
@auth
<flux:link :href="route('dashboard')" wire:navigate>{{ __('Dashboard') }}</flux:link>
@else
<flux:link :href="route('login')" wire:navigate>{{ __('Log in') }}</flux:link>
@if (Route::has('register'))
<flux:button :href="route('register')" variant="primary" size="sm" wire:navigate>
{{ __('Sign up') }}
</flux:button>
@endif
@endauth
</nav>
</div>
</header>
<main class="flex flex-1 flex-col items-center px-6 py-12 md:py-16">
{{ $slot }}
</main>
</div>
@persist('toast')
<flux:toast.group>
<flux:toast />
</flux:toast.group>
@endpersist
@fluxScripts
</body>
</html>
@@ -0,0 +1,133 @@
<?php
use App\Models\Organization;
use App\Models\Setting;
use Flux\Flux;
use Illuminate\Support\Collection;
use Livewire\Attributes\Computed;
use Livewire\Attributes\Title;
use Livewire\Component;
new #[Title('Plan pricing')] class extends Component
{
public function mount(): void
{
if (! auth()->user()->isAdmin()) {
abort(403);
}
$this->amounts = $this->plans()
->mapWithKeys(fn (array $plan): array => [
$plan['key'] => self::formatMajorUnits(Organization::planAmount($plan['key'])),
])
->all();
}
/**
* The price of each configured plan, keyed by plan, in major units so that
* it can be edited and shown as an administrator typed it.
*
* @var array<string, string>
*/
public array $amounts = [];
/**
* Get every configured plan, including any that cannot be sold yet, so a
* price can be set before the Stripe price is in place.
*
* @return Collection<string, array{key: string, name: string, interval: string, purchasable: bool}>
*/
#[Computed]
public function plans(): Collection
{
$configured = config('plans.plans');
$available = Organization::availablePlans();
if (! is_array($configured)) {
return collect();
}
return collect($configured)->map(function ($plan, string $key) use ($available): array {
$plan = is_array($plan) ? $plan : [];
return [
'key' => $key,
'name' => is_string($plan['name'] ?? null) ? $plan['name'] : $key,
'interval' => is_string($plan['interval'] ?? null) ? $plan['interval'] : 'month',
'purchasable' => array_key_exists($key, $available),
];
});
}
public function saveAmounts(): void
{
$validated = $this->validate([
'amounts' => ['required', 'array'],
'amounts.*' => ['required', 'numeric', 'min:0', 'decimal:0,2'],
]);
foreach ($validated['amounts'] as $key => $amount) {
Setting::put(Setting::planAmountKey($key), (string) Setting::toMinorUnits((string) $amount));
}
unset($this->plans);
Flux::toast(variant: 'success', text: __('Plan pricing updated.'));
}
/**
* Render a stored amount, in minor units, as the major units an
* administrator edits it in.
*/
protected static function formatMajorUnits(int $amount): string
{
return intdiv($amount, 100).'.'.str_pad((string) ($amount % 100), 2, '0', STR_PAD_LEFT);
}
}; ?>
<div class="flex h-full w-full flex-1 flex-col gap-6">
<div>
<flux:heading size="xl">{{ __('Plan pricing') }}</flux:heading>
<flux:text class="mt-1">{{ __('Set the price shown for each plan on the pricing page and at signup.') }}</flux:text>
</div>
@if ($this->plans->isEmpty())
<flux:callout variant="warning">{{ __('No plans are configured.') }}</flux:callout>
@else
<form wire:submit="saveAmounts" class="flex max-w-2xl flex-col gap-6">
<flux:card class="flex flex-col gap-5">
@foreach ($this->plans as $plan)
<flux:field>
<flux:label>{{ $plan['name'] }}</flux:label>
<flux:input
wire:model="amounts.{{ $plan['key'] }}"
:value="$amounts[$plan['key']] ?? null"
type="number"
step="0.01"
min="0"
inputmode="decimal"
data-test="plan-amount-input-{{ $plan['key'] }}"
/>
<flux:text size="sm" class="text-zinc-500 dark:text-zinc-400">
{{ __('Billed every :interval.', ['interval' => $plan['interval']]) }}
@unless ($plan['purchasable'])
{{ __('This plan is not on sale yet, because it has no Stripe price configured.') }}
@endunless
</flux:text>
<flux:error name="amounts.{{ $plan['key'] }}" />
</flux:field>
@endforeach
</flux:card>
<div class="flex justify-end">
<flux:button type="submit" variant="primary" data-test="save-plan-amounts-button">
{{ __('Save') }}
</flux:button>
</div>
</form>
@endif
</div>
+72 -2
View File
@@ -1,12 +1,82 @@
@php
use App\Models\Organization;
$plans = Organization::availablePlans();
$trialDays = Organization::trialDays();
@endphp
<x-layouts::auth :title="__('Register')">
<div class="flex flex-col gap-6">
<x-auth-header :title="__('Create an account')" :description="__('Enter your details below to create your account')" />
<x-auth-header
:title="__('Create an account')"
:description="$plans !== []
? __('Choose a plan, then enter your details to get started')
: __('Enter your details below to create your account')"
/>
<!-- Session Status -->
<x-auth-session-status class="text-center" :status="session('status')" />
<form method="POST" action="{{ route('register.store') }}" class="flex flex-col gap-6">
@csrf
@if ($plans !== [])
{{-- Plan picker. Plain inputs rather than flux:radio because this form
is server rendered and does not load Livewire's UI runtime. --}}
<fieldset class="flex flex-col gap-2">
<legend class="text-sm font-medium text-zinc-800 dark:text-white">
{{ __('Choose your plan') }}
</legend>
@foreach ($plans as $key => $plan)
<label
@class([
'flex cursor-pointer items-start gap-3 rounded-lg border border-zinc-200 p-3 transition has-[:checked]:border-accent-500 has-[:checked]:bg-zinc-50 dark:border-white/10 dark:has-[:checked]:bg-white/5',
'border-zinc-400 bg-zinc-50 dark:border-zinc-500 dark:bg-white/5' => old('plan', array_key_first($plans)) === $key,
])
data-test="register-plan-{{ $key }}"
>
<input
type="radio"
name="plan"
value="{{ $key }}"
@checked(old('plan', array_key_first($plans)) === $key)
required
class="mt-0.5 size-4 shrink-0 accent-accent-500"
/>
<span class="flex flex-col gap-0.5">
<span class="flex items-baseline justify-between gap-3">
<span class="text-sm font-medium text-zinc-800 dark:text-white">
{{ $plan['name'] }}
</span>
<span
class="text-sm font-semibold text-zinc-900 dark:text-white"
data-test="register-plan-{{ $key }}-amount"
>
{{ Organization::formatAmount($plan['amount']) }}
</span>
</span>
<span class="text-xs text-zinc-500 dark:text-zinc-400">
{{ $trialDays > 0
? __('Free for :days days, then billed every :interval', [
'days' => $trialDays,
'interval' => $plan['interval'],
])
: __('Billed every :interval', ['interval' => $plan['interval']]) }}
</span>
</span>
</label>
@endforeach
@error('plan')
<flux:error name="plan" />
@enderror
</fieldset>
@endif
<!-- Name -->
<flux:input
name="name"
@@ -56,7 +126,7 @@
<div class="flex items-center justify-end">
<flux:button type="submit" variant="primary" class="w-full" data-test="register-user-button">
{{ __('Create account') }}
{{ $plans !== [] ? __('Continue to payment') : __('Create account') }}
</flux:button>
</div>
</form>
@@ -4,6 +4,7 @@
<flux:navlist.item :href="route('profile.edit')" wire:navigate>{{ __('Profile') }}</flux:navlist.item>
<flux:navlist.item :href="route('security.edit')" wire:navigate>{{ __('Security') }}</flux:navlist.item>
<flux:navlist.item :href="route('appearance.edit')" wire:navigate>{{ __('Appearance') }}</flux:navlist.item>
<flux:navlist.item :href="route('billing.edit')" wire:navigate data-test="billing-nav-link">{{ __('Billing') }}</flux:navlist.item>
</flux:navlist>
</div>
@@ -0,0 +1,151 @@
<?php
use Illuminate\Support\Facades\Auth;
use Livewire\Attributes\Computed;
use Livewire\Attributes\Title;
use Livewire\Component;
new #[Title('Billing settings')]
class extends Component
{
/**
* Get the organization that holds the subscription being managed.
*/
#[Computed]
public function organization()
{
return Auth::user()?->currentOrganization()->first();
}
/**
* Get the current subscription, if there is one.
*/
#[Computed]
public function subscription()
{
return $this->organization?->currentSubscription();
}
/**
* Get the plan the organization is on, falling back to a description built
* from the raw Stripe status for states that are not a plan.
*
* @return array{name: string, price: string, interval: string}|null
*/
#[Computed]
public function plan(): ?array
{
return $this->organization?->currentPlan();
}
/**
* Get a human readable label for the subscription status.
*/
#[Computed]
public function status(): string
{
$subscription = $this->subscription;
if ($subscription === null) {
return __('No subscription');
}
return match ($subscription->stripe_status) {
'active' => __('Active'),
'trialing' => __('Free trial'),
'past_due' => __('Past due'),
'canceled' => __('Canceled'),
'unpaid' => __('Unpaid'),
'incomplete' => __('Incomplete'),
'incomplete_expired' => __('Expired'),
default => ucfirst((string) $subscription->stripe_status),
};
}
/**
* Describe the state of the current subscription in a single sentence.
*/
#[Computed]
public function summary(): string
{
$subscription = $this->subscription;
if ($this->organization?->hasLifetimeAccess() === true) {
return __('Lifetime access. No subscription is required.');
}
if ($subscription === null) {
return __('You are on the free plan and cannot use your workspace until you subscribe.');
}
if ($subscription->ends_at !== null && $subscription->ends_at->isFuture()) {
return __('Your plan stays active until :date. Subscribe again to keep your access after that.', [
'date' => $subscription->ends_at->toFormattedDateString(),
]);
}
if ($subscription->trial_ends_at !== null && $subscription->trial_ends_at->isFuture()) {
return __('Your free trial ends on :date.', [
'date' => $subscription->trial_ends_at->toFormattedDateString(),
]);
}
return __('Your subscription renews automatically.');
}
/**
* Determine whether the customer portal button should be shown. The portal
* only exists once Stripe knows about the organization as a customer.
*/
#[Computed]
public function canManagePaymentMethod(): bool
{
return $this->organization?->hasStripeId() === true;
}
}; ?>
<section class="w-full">
@include('partials.settings-heading')
<flux:heading level="2" class="sr-only">{{ __('Billing settings') }}</flux:heading>
<x-pages::settings.layout :heading="__('Billing')" :subheading="__('Manage your plan and payment details')">
<div class="space-y-6" data-test="billing-overview">
<flux:card class="space-y-3">
<div class="flex items-center justify-between gap-4">
<div>
<flux:heading size="sm">{{ $this->plan['name'] ?? __('Free') }}</flux:heading>
<flux:text size="sm" class="text-zinc-500 dark:text-zinc-400">
{{ $this->status }}
</flux:text>
</div>
<flux:badge :color="$this->organization?->isEntitled() ? 'green' : 'red'" size="sm">
{{ $this->organization?->isEntitled() ? __('Active') : __('Inactive') }}
</flux:badge>
</div>
<flux:text size="sm">{{ $this->summary }}</flux:text>
</flux:card>
<div class="flex flex-wrap items-center gap-3">
@if ($this->organization?->isEntitled() !== true)
<flux:button :href="route('pricing')" variant="primary" wire:navigate data-test="subscribe-button">
{{ __('Subscribe') }}
</flux:button>
@endif
@if ($this->canManagePaymentMethod)
<form method="POST" action="{{ route('billing.portal') }}">
@csrf
<flux:button type="submit" variant="ghost" data-test="billing-portal-button">
{{ __('Manage payment method') }}
</flux:button>
</form>
@endif
</div>
</div>
</x-pages::settings.layout>
</section>
+35 -18
View File
@@ -266,10 +266,10 @@ new #[Title('Dashboard')] class extends Component
{
$this->todoForUser($todoId);
$ids = $this->filteredTodoQuery()->priority()->pluck('id')->all();
$ids = $this->orderedTodoIds;
$currentIndex = array_search($todoId, $ids, true);
if ($currentIndex === false || $ids === []) {
if ($currentIndex === false) {
return;
}
@@ -279,40 +279,57 @@ new #[Title('Dashboard')] class extends Component
return;
}
$this->reorderTodo($todoId, $ids, $target);
$this->reorderTodo($todoId, $target);
}
public function handleSort(int $todoId, int $position): void
{
$this->todoForUser($todoId);
$ids = $this->filteredTodoQuery()->priority()->pluck('id')->all();
$currentIndex = array_search($todoId, $ids, true);
if ($currentIndex === false || $ids === []) {
return;
}
$offset = ($this->todos->currentPage() - 1) * self::PER_PAGE;
$this->reorderTodo($todoId, $ids, $offset + $position);
$this->reorderTodo($todoId, $offset + $position);
}
/**
* @param array<int, int> $ids
* Move a todo to the given index of the currently visible order. The
* reordered todos are written back into the slots they already occupy in
* the user's full priority order, so reordering under an active filter
* permutes the visible todos without renumbering them from zero and
* colliding with the todos the filter hides.
*/
private function reorderTodo(int $todoId, array $ids, int $newIndex): void
private function reorderTodo(int $todoId, int $newIndex): void
{
unset($ids[array_search($todoId, $ids, true)]);
$ids = array_values($ids);
$visibleIds = $this->orderedTodoIds;
$currentIndex = array_search($todoId, $visibleIds, true);
$newIndex = max(0, min($newIndex, count($ids)));
if ($currentIndex === false) {
return;
}
array_splice($ids, $newIndex, 0, $todoId);
$newIndex = max(0, min($newIndex, count($visibleIds) - 1));
if ($newIndex === $currentIndex) {
return;
}
$visibleOrder = $visibleIds;
unset($visibleOrder[$currentIndex]);
array_splice($visibleOrder, $newIndex, 0, $todoId);
$ids = Todo::query()->forUser(auth()->id())->priority()->pluck('id')->all();
$slots = array_keys(array_intersect($ids, $visibleIds));
foreach ($slots as $visibleSlot => $slot) {
$ids[$slot] = $visibleOrder[$visibleSlot];
}
foreach ($ids as $position => $id) {
Todo::query()->forUser(auth()->id())->whereKey($id)->update(['position' => $position]);
}
unset($this->todos, $this->orderedTodoIds);
}
/**
@@ -493,7 +510,7 @@ new #[Title('Dashboard')] class extends Component
@forelse ($this->todos as $todo)
<flux:table.row :key="$todo->id" wire:sort:item="{{ $todo->id }}" data-test="todo-row">
<flux:table.cell class="py-0 text-zinc-300 dark:text-zinc-600">
<div wire:sort:handle class="inline-flex cursor-grab" :title="__('Reorder')">
<div wire:sort:handle class="inline-flex cursor-grab" title="{{ __('Reorder') }}">
<flux:icon.chevrons-up-down variant="micro" />
</div>
</flux:table.cell>
+1 -1
View File
@@ -472,7 +472,7 @@ new #[Title('Folders')] class extends Component
:class="dragging && 'opacity-40'"
@dragstart="dragging = true; window.__mtFolderDrag = { folderId: {{ $node['folder']->id }} }; $dispatch('folder-drag-start')"
@dragend="dragging = false; window.__mtFolderDrag = null; $dispatch('folder-drag-end')"
:title="__('Drag to move this folder')"
title="{{ __('Drag to move this folder') }}"
data-test="drag-folder-{{ $node['folder']->id }}"
>
<flux:icon.chevrons-up-down variant="micro" />
+163
View File
@@ -0,0 +1,163 @@
<?php
use App\Models\Organization;
use Illuminate\Http\RedirectResponse;
use Illuminate\Support\Facades\Auth;
use Illuminate\Validation\Rule;
use Livewire\Attributes\Computed;
use Livewire\Attributes\Layout;
use Livewire\Attributes\Title;
use Livewire\Component;
new #[Layout('layouts::marketing')]
#[Title('Pricing')]
class extends Component
{
/**
* The plan key the visitor chose. Held as state so the server can validate
* it against the configured plans rather than trusting the button.
*/
public string $plan = '';
/**
* The trial length configured for new subscriptions.
*/
public function trialDays(): int
{
return Organization::trialDays();
}
/**
* Determine whether the signed-in user already has access, in which case
* there is nothing to sell them.
*/
#[Computed]
public function isSubscribed(): bool
{
return Auth::user()?->hasActiveSubscription() ?? false;
}
/**
* Get the plans that are configured and available to purchase.
*
* @return array<string, array{name: string, price: string, interval: string}>
*/
#[Computed]
public function plans(): array
{
return Organization::availablePlans();
}
/**
* Start a Stripe Checkout session for the given plan.
*/
public function subscribe(string $plan): RedirectResponse
{
abort_if(Auth::guest(), 403);
$this->plan = $plan;
$this->validate([
'plan' => ['required', Rule::in(array_keys(Organization::availablePlans()))],
], [
'plan.in' => __('That plan is not available.'),
]);
$organization = Auth::user()->currentOrganization()->first();
abort_if($organization === null, 403);
return $organization->checkoutForPlan($this->plan)->redirect();
}
}; ?>
<section class="flex w-full max-w-5xl flex-col gap-10">
<div class="flex flex-col items-center gap-3 text-center">
<flux:heading size="xl" level="1">{{ __('Plans and pricing') }}</flux:heading>
@if (session('billing.checkout_failed'))
<flux:callout variant="danger" class="w-full" data-test="pricing-status">
{{ session('billing.checkout_failed') }}
</flux:callout>
@endif
@if ($this->isSubscribed)
<flux:subheading>{{ __('Your workspace already has an active subscription.') }}</flux:subheading>
@else
<flux:subheading class="max-w-2xl text-center">
{{ __('Subscribe to unlock your todos, folders and notes.') }}
</flux:subheading>
@endif
</div>
@if ($this->isSubscribed)
<flux:button :href="route('billing.edit')" variant="primary" wire:navigate data-test="manage-subscription-button">
{{ __('Manage your subscription') }}
</flux:button>
@elseif (count($this->plans) === 0)
<flux:callout variant="warning" class="mx-auto max-w-2xl">
{{ __('No plans are available right now. Please check back soon.') }}
</flux:callout>
@else
<div class="grid w-full gap-6 md:grid-cols-2 lg:grid-cols-3">
@foreach ($this->plans as $key => $plan)
<flux:card class="flex flex-col gap-5" data-test="plan-{{ $key }}">
<div class="flex flex-col gap-1">
<flux:heading size="lg">{{ $plan['name'] }}</flux:heading>
<p class="text-2xl font-semibold text-zinc-900 dark:text-white" data-test="plan-{{ $key }}-amount">
{{ Organization::formatAmount($plan['amount']) }}
</p>
<flux:text size="sm" class="text-zinc-500 dark:text-zinc-400">
{{ __('Billed every :interval', ['interval' => $plan['interval']]) }}
</flux:text>
</div>
<ul class="flex flex-1 flex-col gap-2 text-sm">
<li class="flex items-center gap-2">
<flux:icon.check class="size-4 shrink-0" />
<span>{{ __('Unlimited todos and folders') }}</span>
</li>
<li class="flex items-center gap-2">
<flux:icon.check class="size-4 shrink-0" />
<span>{{ __('Notes on every todo') }}</span>
</li>
<li class="flex items-center gap-2">
<flux:icon.check class="size-4 shrink-0" />
<span>{{ __('Status, due dates and priorities') }}</span>
</li>
</ul>
@auth
<flux:button
wire:click="subscribe('{{ $key }}')"
variant="primary"
class="w-full"
data-test="subscribe-{{ $key }}-button"
>
{{ $this->trialDays() > 0
? __('Start :days-day free trial', ['days' => $this->trialDays()])
: __('Subscribe') }}
</flux:button>
@else
<flux:button :href="route('register')" variant="primary" class="w-full" wire:navigate>
{{ __('Create an account') }}
</flux:button>
@endauth
</flux:card>
@endforeach
</div>
@if ($this->trialDays() > 0)
<flux:text size="sm" class="text-center text-zinc-500 dark:text-zinc-400">
{{ __('Your trial ends after :days days and you can cancel at any time.', ['days' => $this->trialDays()]) }}
</flux:text>
@endif
@endif
@error('plan')
<flux:error name="plan" />
@enderror
</section>
@@ -0,0 +1,96 @@
<?php
use Illuminate\Support\Facades\Auth;
use Livewire\Attributes\Computed;
use Livewire\Attributes\Layout;
use Livewire\Attributes\Title;
use Livewire\Attributes\Url;
use Livewire\Component;
new #[Layout('layouts::marketing')]
#[Title('Confirming your subscription')]
class extends Component
{
/**
* How long to keep polling for the webhook before giving up.
*/
private const TIMEOUT_SECONDS = 30;
/**
* The Stripe Checkout session id, used only to correlate the page with
* the checkout that just completed.
*/
#[Url(as: 'session_id', except: '')]
public string $sessionId = '';
/**
* Seconds spent waiting so far.
*/
public int $waitedSeconds = 0;
public bool $timedOut = false;
/**
* Confirm the subscription arrived. Cashier 16 has no checkout session
* lookup, so the webhook is polled against the local subscription row.
*/
public function confirm(): void
{
if ($this->hasSubscription) {
$this->redirect(route('dashboard'), navigate: true);
return;
}
$this->waitedSeconds += 1;
if ($this->waitedSeconds >= self::TIMEOUT_SECONDS) {
$this->timedOut = true;
}
}
#[Computed]
public function hasSubscription(): bool
{
return Auth::user()?->hasActiveSubscription() ?? false;
}
}; ?>
<section class="flex w-full max-w-xl flex-col items-center gap-6 text-center"
@if (! $timedOut)
wire:poll.2s="confirm"
@endif
>
@if ($this->hasSubscription)
<flux:icon.check class="size-12 text-green-500" />
<flux:heading size="xl" level="1">{{ __('Your subscription is active') }}</flux:heading>
<flux:subheading>{{ __('Welcome aboard. Taking you to your todos now.') }}</flux:subheading>
<flux:button :href="route('dashboard')" variant="primary" wire:navigate data-test="go-to-dashboard-button">
{{ __('Go to my todos') }}
</flux:button>
@elseif ($timedOut)
<flux:icon.clock class="size-12 text-zinc-500" />
<flux:heading size="xl" level="1">{{ __('Still confirming your payment') }}</flux:heading>
<flux:subheading>
{{ __('Your payment went through, but we have not heard from Stripe yet. Your access will turn on automatically as soon as it does.') }}
</flux:subheading>
<flux:button :href="route('pricing')" variant="primary" wire:navigate data-test="back-to-pricing-button">
{{ __('Back to plans') }}
</flux:button>
@else
<div
class="size-12 animate-spin rounded-full border-4 border-zinc-200 border-t-zinc-500 dark:border-white/10 dark:border-t-zinc-300"
role="status"
></div>
<flux:heading size="xl" level="1">{{ __('Confirming your subscription') }}</flux:heading>
<flux:subheading>{{ __('This usually takes a few seconds. Please do not close this page.') }}</flux:subheading>
@endif
</section>
+34 -17
View File
@@ -248,7 +248,7 @@ new #[Title('Todos')] class extends Component
$ids = $this->orderedTodoIds;
$currentIndex = array_search($todoId, $ids, true);
if ($currentIndex === false || $ids === []) {
if ($currentIndex === false) {
return;
}
@@ -258,38 +258,55 @@ new #[Title('Todos')] class extends Component
return;
}
$this->reorderTodo($todoId, $ids, $target);
$this->reorderTodo($todoId, $target);
}
public function handleSort(int $todoId, int $position): void
{
$this->todoForUser($todoId);
$ids = $this->orderedTodoIds;
$currentIndex = array_search($todoId, $ids, true);
if ($currentIndex === false || $ids === []) {
return;
}
$this->reorderTodo($todoId, $ids, $position);
$this->reorderTodo($todoId, $position);
}
/**
* @param array<int, int> $ids
* Move a todo to the given index of the currently visible order. The
* reordered todos are written back into the slots they already occupy in
* the user's full priority order, so reordering under an active filter
* permutes the visible todos without renumbering them from zero and
* colliding with the todos the filter hides.
*/
private function reorderTodo(int $todoId, array $ids, int $newIndex): void
private function reorderTodo(int $todoId, int $newIndex): void
{
unset($ids[array_search($todoId, $ids, true)]);
$ids = array_values($ids);
$visibleIds = $this->orderedTodoIds;
$currentIndex = array_search($todoId, $visibleIds, true);
$newIndex = max(0, min($newIndex, count($ids)));
if ($currentIndex === false) {
return;
}
array_splice($ids, $newIndex, 0, $todoId);
$newIndex = max(0, min($newIndex, count($visibleIds) - 1));
if ($newIndex === $currentIndex) {
return;
}
$visibleOrder = $visibleIds;
unset($visibleOrder[$currentIndex]);
array_splice($visibleOrder, $newIndex, 0, $todoId);
$ids = Todo::query()->forUser(auth()->id())->priority()->pluck('id')->all();
$slots = array_keys(array_intersect($ids, $visibleIds));
foreach ($slots as $visibleSlot => $slot) {
$ids[$slot] = $visibleOrder[$visibleSlot];
}
foreach ($ids as $position => $id) {
Todo::query()->forUser(auth()->id())->whereKey($id)->update(['position' => $position]);
}
unset($this->todos, $this->orderedTodoIds);
}
/**
@@ -407,7 +424,7 @@ new #[Title('Todos')] class extends Component
@forelse ($this->todos as $todo)
<flux:table.row :key="$todo->id" wire:sort:item="{{ $todo->id }}" data-test="todo-row">
<flux:table.cell class="py-0 text-zinc-300 dark:text-zinc-600">
<div wire:sort:handle class="inline-flex cursor-grab" :title="__('Reorder')">
<div wire:sort:handle class="inline-flex cursor-grab" title="{{ __('Reorder') }}">
<flux:icon.chevrons-up-down variant="micro" />
</div>
</flux:table.cell>