Cars: drag the tabs into order, and a lock for every arrangement

Two things, both about layouts you arrange by dragging.

A car's tab bar now takes a drag: the tabs reorder as the pointer crosses
them and the arrangement saves on drop — or on dragend, since a tab
released in the gap beside the bar never produces a drop and would
otherwise revert on the next load. Same native drag events as the garage
and the Information rows, so also pointer-only, and it needs write access.

The order belongs to the car, like the choice of which tabs show at all,
so everyone it is shared with sees the same bar. It is stored as the full
list of keys, hidden tabs included, so a tab switched off and back on
returns to where it was rather than to the end; a key the stored
arrangement doesn't mention — a tab added in a later release — follows
the arranged ones. Information is arrangeable although it cannot be
switched off, which is why the validation needs arrangeableCarTabs rather
than reusing hideableCarTabs; it is derived from that set so the two
cannot drift as tabs are added. tabOrder rides on the existing PUT
/api/cars/{id}/view, so a tab drag never has to resend what is hidden.
Where the page opens is unchanged: Information, wherever it now sits.

And a padlock in the sidebar, above the theme toggle, holds every
arrangement in the app still at once — the garage, a car's tabs, its
Information rows, the provider's readings. It is a guard against nudging
a layout while reading it, not a permission: it is the user's own setting
and says nothing about what anybody may edit, so locking hides your own
drag handles rather than stopping a co-owner rearranging a shared car.
Stored as dragLocked on the profile, like the theme it sits above, so a
locked account is still locked on the next device — where a folded
provider card stays one browser's reading habit. Unlocked by default, so
nothing changes until it is clicked, and while locked the grab cursor and
the drag hints go with the drag.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
tajniak81
2026-08-17 22:43:54 +02:00
co-authored by Claude Opus 5
parent 6191160f14
commit cc1dafa9f7
17 changed files with 302 additions and 48 deletions
+3 -3
View File
@@ -149,7 +149,7 @@ GET /api/auth/validate
GET /api/auth/me
GET /api/identity
# current user (profile / appearance / garage order / avatar / data /
# current user (profile / appearance / drag lock / garage order / avatar / data /
# account lifecycle)
GET /api/me PATCH /api/me DELETE /api/me
POST /api/me/password
@@ -193,8 +193,8 @@ POST /api/vehicle-providers/{provider}/import
# which PATCH /api/me {carOrder} sets)
GET /api/cars POST /api/cars
GET /api/cars/{id} PATCH /api/cars/{id} DELETE /api/cars/{id}
PUT /api/cars/{id}/view # which tabs + Information rows this car shows,
# and the order of the rows and the provider readings
PUT /api/cars/{id}/view # which tabs + Information rows this car shows, and
# the order of the tabs, the rows and the provider readings
GET /api/cars/{id}/provider POST /api/cars/{id}/provider
POST /api/cars/{id}/provider/sync
GET /api/cars/{id}/service-records GET /api/cars/{id}/technical-checks
+31 -5
View File
@@ -248,6 +248,19 @@ var hideableCarTabs = map[string]bool{
"fuel": true, "charging": true, "documents": true, "parts": true, "reminders": true,
}
// arrangeableCarTabs are the tabs a car's page can be rearranged into, which is
// the hideable ones plus Information: it cannot be switched off, but there is no
// reason it has to stay at the front. Derived from hideableCarTabs so the two
// sets cannot drift as tabs are added.
var arrangeableCarTabs = func() map[string]bool {
out := make(map[string]bool, len(hideableCarTabs)+1)
for key := range hideableCarTabs {
out[key] = true
}
out["info"] = true
return out
}()
// hideableCarFields are the Information rows that can be switched off — every
// one of them, since unlike the tabs there is no row the page needs to keep.
// Mirrors the car.info.* labels the web app renders.
@@ -295,11 +308,11 @@ func normalizeKeys(in []string, allowed map[string]bool, what string) ([]string,
}
// PUT /api/cars/{id}/view — choose what this car's page shows: which tabs, which
// rows of the Information tab, and the order the Information rows and the
// connected service's headline readings are laid out in. Body: {hiddenTabs?:
// [...], hiddenFields?: [...], fieldOrder?: [...], metricOrder?: [...]}; only the
// lists present are written, so a client can rearrange one group without
// resending the others. Its own endpoint rather than fields on the car edit, so an ordinary
// rows of the Information tab, and the order the tabs, the Information rows and
// the connected service's headline readings are laid out in. Body: {hiddenTabs?:
// [...], hiddenFields?: [...], tabOrder?: [...], fieldOrder?: [...],
// metricOrder?: [...]}; only the lists present are written, so a client can
// rearrange one group without resending the others. Its own endpoint rather than fields on the car edit, so an ordinary
// save of the car form — which sends every other field — can never reveal
// something somebody deliberately switched off. Needs write access: the choice
// belongs to the car, so it is the same permission as editing it.
@@ -307,6 +320,7 @@ func (s *Server) updateCarView(w http.ResponseWriter, r *http.Request) {
var in struct {
HiddenTabs *[]string `json:"hiddenTabs"`
HiddenFields *[]string `json:"hiddenFields"`
TabOrder *[]string `json:"tabOrder"`
FieldOrder *[]string `json:"fieldOrder"`
MetricOrder *[]string `json:"metricOrder"`
}
@@ -341,6 +355,18 @@ func (s *Server) updateCarView(w http.ResponseWriter, r *http.Request) {
}
payload["hidden_fields"] = fields
}
if in.TabOrder != nil {
// A wider set than the hidden tabs: Information is arrangeable although it
// cannot be switched off. A partial list is accepted, and the tabs it
// leaves out follow the arranged ones — which is what puts a tab added in
// a later release at the end rather than in the middle of somebody's bar.
order, err := normalizeKeys(*in.TabOrder, arrangeableCarTabs, "tab")
if err != nil {
writeError(w, http.StatusBadRequest, err.Error())
return
}
payload["tab_order"] = order
}
if in.FieldOrder != nil {
// The same key set as the hidden fields, since every Information row can
// be moved. A partial list is accepted rather than demanding all 14: the
+32
View File
@@ -77,6 +77,38 @@ func TestNormalizeHiddenFields(t *testing.T) {
}
}
// The tabs arrange against a wider set than they hide against: Information
// cannot be switched off, but it can be moved off the front of the bar.
func TestNormalizeTabOrder(t *testing.T) {
got, err := normalizeKeys([]string{"reminders", "info", "fuel"}, arrangeableCarTabs, "tab")
if err != nil {
t.Fatalf("normalizeKeys: %v", err)
}
assertKeys(t, got, []string{"reminders", "info", "fuel"})
// Everything the bar renders has to be arrangeable — the hideable tabs plus
// Information, and nothing else.
for key := range hideableCarTabs {
if !arrangeableCarTabs[key] {
t.Errorf("tab %q should be arrangeable", key)
}
}
if !arrangeableCarTabs["info"] {
t.Error("the info tab should be arrangeable even though it cannot be hidden")
}
if len(arrangeableCarTabs) != len(hideableCarTabs)+1 {
t.Errorf("arrangeableCarTabs has %d entries, want the hideable tabs plus Information", len(arrangeableCarTabs))
}
// A field key is not a tab key, and an invented tab is still an error.
if _, err := normalizeKeys([]string{"vin"}, arrangeableCarTabs, "tab"); err == nil {
t.Error("normalizeKeys accepted a field key as a tab, want an error")
}
if _, err := normalizeKeys([]string{"info", "nonsense"}, arrangeableCarTabs, "tab"); err == nil {
t.Error("normalizeKeys accepted an unknown tab in an arrangement, want an error")
}
}
// The arrangement of the Information rows shares the field key set — every row
// can be moved — but not the meaning: here the order of the list is the point,
// so it has to survive validation exactly as it was sent.
+8
View File
@@ -31,6 +31,7 @@ type userRecord struct {
DateFormat string `json:"date_format"`
Currency string `json:"currency"`
FontSize string `json:"font_size"`
DragLocked bool `json:"drag_locked"`
DeletionRequestedAt string `json:"deletion_requested_at"`
Role string `json:"role"`
Organization string `json:"organization"`
@@ -72,6 +73,7 @@ func (rec userRecord) toModel() models.User {
DateFormat: orDefault(rec.DateFormat, "YMD"),
Currency: orDefault(rec.Currency, "USD"),
FontSize: orDefault(rec.FontSize, "medium"),
DragLocked: rec.DragLocked,
Role: orDefault(rec.Role, "user"),
Created: rec.Created,
@@ -132,6 +134,7 @@ type updateMeRequest struct {
DateFormat *string `json:"dateFormat"`
Currency *string `json:"currency"`
FontSize *string `json:"fontSize"`
DragLocked *bool `json:"dragLocked"`
CarOrder *[]string `json:"carOrder"`
}
@@ -240,6 +243,11 @@ func (s *Server) handleUpdateMe(w http.ResponseWriter, r *http.Request) {
}
payload["font_size"] = *in.FontSize
}
if in.DragLocked != nil {
// No value to validate — either the arrangements on this account's pages
// are held still or they are not.
payload["drag_locked"] = *in.DragLocked
}
if in.CarOrder != nil {
ids, err := normalizeCarOrder(*in.CarOrder)
if err != nil {
+5 -3
View File
@@ -69,11 +69,12 @@ type carRecord struct {
Updated string `json:"updated"`
// Switched-off tabs and Information fields, plus the arrangements of the
// Information rows and the connected service's readings. Raw because
// PocketBase hands back whatever a json field holds — null on a car nobody
// has configured — which is not a []string.
// tabs, the Information rows and the connected service's readings. Raw
// because PocketBase hands back whatever a json field holds — null on a car
// nobody has configured — which is not a []string.
HiddenTabs json.RawMessage `json:"hidden_tabs"`
HiddenFields json.RawMessage `json:"hidden_fields"`
TabOrder json.RawMessage `json:"tab_order"`
FieldOrder json.RawMessage `json:"field_order"`
MetricOrder json.RawMessage `json:"metric_order"`
}
@@ -104,6 +105,7 @@ func (rec carRecord) toModel() models.Car {
ProviderVehicleID: rec.ProviderVehicleID,
HiddenTabs: decodeStringList(rec.HiddenTabs),
HiddenFields: decodeStringList(rec.HiddenFields),
TabOrder: decodeStringList(rec.TabOrder),
FieldOrder: decodeStringList(rec.FieldOrder),
MetricOrder: decodeStringList(rec.MetricOrder),
Owner: rec.Owner,
+8 -3
View File
@@ -46,9 +46,10 @@ var collectionsSchema = map[string][]fieldDef{
// release is on by default. Keys are validated in internal/api/cars.go.
fJSON("hidden_tabs", 2000),
fJSON("hidden_fields", 2000),
// The order the Information rows are laid out in, as field keys, and the
// same for the connected service's headline readings. Empty means the
// page's own default order.
// The order the tabs are laid out in, as tab keys, the same for the
// Information rows, and the same for the connected service's headline
// readings. Empty means the page's own default order.
fJSON("tab_order", 2000),
fJSON("field_order", 2000),
fJSON("metric_order", 2000),
// Owner of this car. Non-cascading: deleting a user must not wipe their cars.
@@ -191,6 +192,10 @@ var collectionsSchema = map[string][]fieldDef{
"TRY", "UAH", "USD", "CAD", "AUD", "JPY",
}, false),
fSelect("font_size", []string{"small", "medium", "large"}, false),
// Holds every arrangement on this user's pages still — the garage, a
// car's tabs and Information rows, the provider's readings — so reading a
// page cannot nudge its layout. Per user, like the garage order.
fBool("drag_locked"),
fDate("deletion_requested_at", false),
// Access role. Empty value is treated as "user" by the API.
fSelect("role", []string{"user", "admin", "superadmin"}, false),
+13
View File
@@ -89,6 +89,12 @@ type Car struct {
// list, and joins the end when it does turn up.
MetricOrder []string `json:"metricOrder"`
// TabOrder is the order of the tabs themselves, as tab keys. It covers the
// hidden tabs too, like FieldOrder, so a tab switched back on returns to
// where it was, and it includes "info" — Information cannot be switched off
// but it can be moved off the front.
TabOrder []string `json:"tabOrder"`
// Owner is the user id that owns this car. Access is the requesting user's
// permission on it — "owner", "write", or "read" — computed by the API at
// read time and never persisted (omitempty; not part of the write payload).
@@ -427,6 +433,13 @@ type User struct {
FontSize string `json:"fontSize"` // small | medium | large
Role string `json:"role"` // user | admin
// DragLocked holds every arrangement on this account's pages still: the
// garage, a car's tabs, its Information rows, the provider's readings. A
// guard against nudging a layout while reading it, not a permission — it is
// the user's own setting and says nothing about what they may edit. False
// (draggable) on an account that has never set it.
DragLocked bool `json:"dragLocked"`
// Organization membership. Empty when the user belongs to no organization —
// the clients use that to offer creating one (which makes them its admin).
Organization string `json:"organization"`
+10 -4
View File
@@ -279,10 +279,12 @@ const DESIRED = {
// default. Keys are validated in internal/api/cars.go.
F.json("hidden_tabs", 2000),
F.json("hidden_fields", 2000),
// The order the Information rows are laid out in, as field keys — the
// hidden ones included, so a row switched back on returns to where it was.
// Empty means the page's own default order. metric_order is the same for
// the headline readings on the connected service's tab.
// The order the tabs are laid out in, as tab keys, and the order the
// Information rows are laid out in, as field keys — the hidden ones
// included in both, so one switched back on returns to where it was. Empty
// means the page's own default order. metric_order is the same for the
// headline readings on the connected service's tab.
F.json("tab_order", 2000),
F.json("field_order", 2000),
F.json("metric_order", 2000),
// Owner of this car. Non-cascading on purpose: deleting a user must not
@@ -464,6 +466,10 @@ const DESIRED = {
"TRY", "UAH", "USD", "CAD", "AUD", "JPY",
]),
F.select("font_size", ["small", "medium", "large"]),
// Holds every arrangement on this user's pages still — the garage, a car's
// tabs and Information rows, the provider's readings — so reading a page
// cannot nudge its layout. Per user, like car_order.
F.bool("drag_locked"),
F.date("deletion_requested_at"),
// Access role. Empty value is treated as "user" by the API.
F.select("role", ["user", "admin", "superadmin"]),
+13
View File
@@ -101,6 +101,19 @@ Config (`server/.env`, copy from `.env.example`):
the same page; setting it needs write access. Stored as the *hidden* sets, so
anything added in a later release is on by default, and the Information tab
itself can't be switched off.
- **Locking the layout** — the padlock in the sidebar, above the theme toggle,
holds every arrangement still at once: the garage, a car's tabs, its
Information rows, the provider's readings. It is a guard against nudging a
layout while reading it, not a permission — it is the user's own setting
(`dragLocked` on the profile, so it follows them to the next device) and says
nothing about what they may edit. Unlocked by default; while locked the drag
cursor and the hints go too.
- **Arranging the tabs** — the tabs themselves drag into any order, saved on
drop. A property of the car like the choice of which tabs show, so everyone it
is shared with sees the same bar, and it needs write access. It covers the
hidden tabs too, so switching one back on returns it to where it was, and
Information is arrangeable even though it can't be switched off. Where the
page opens is unchanged: Information, wherever it now sits in the bar.
- **Arranging the Information rows** — the rows on a car's Information tab drag
into any order, saved on drop. Also a property of the car, and it covers the
hidden rows too, so switching one back on returns it to where it was. Same
+25 -1
View File
@@ -28,6 +28,18 @@ function toggleTheme() {
if (isAuthenticated.value) api.updateMe({ theme: next }).catch(() => {});
}
// Drag lock (on ⇄ off), the same shape as the theme toggle: applies instantly
// and persists to the profile, so a locked account stays locked on the next
// device. It holds every arrangement still — the garage, a car's tabs, its
// Information rows, the provider's readings — which is a guard against nudging
// a layout while reading it, not a permission: what a user may edit is
// unchanged.
function toggleDragLock() {
const next = !prefs.dragLocked;
prefs.dragLocked = next;
if (isAuthenticated.value) api.updateMe({ dragLocked: next }).catch(() => {});
}
const userInitial = computed(() =>
(state.user?.name || state.user?.email || "?").charAt(0).toUpperCase()
);
@@ -90,8 +102,20 @@ onBeforeUnmount(() => themeObserver?.disconnect());
</RouterLink>
</nav>
<!-- Footer: theme toggle + user + logout -->
<!-- Footer: drag lock + theme toggle + user + logout -->
<div class="mt-auto flex flex-col gap-2 border-t border-white/10 pt-3">
<button
class="flex items-center gap-3 rounded-control px-2.5 py-2 text-[15px] font-medium transition-colors hover:bg-white/5 hover:text-white md:px-3"
:class="prefs.dragLocked ? 'text-white/80' : 'text-white/60'"
:title="t('nav.dragLockHint')"
@click="toggleDragLock"
>
<!-- closed padlock while locked, open one while things can be dragged -->
<svg v-if="prefs.dragLocked" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" class="h-5 w-5 shrink-0"><rect x="4" y="10.5" width="16" height="10.5" rx="2"/><path stroke-linecap="round" d="M8 10.5V7a4 4 0 0 1 8 0v3.5"/></svg>
<svg v-else viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" class="h-5 w-5 shrink-0"><rect x="4" y="10.5" width="16" height="10.5" rx="2"/><path stroke-linecap="round" d="M8 10.5V7a4 4 0 0 1 7.7-1.5"/></svg>
<span class="hidden md:inline">{{ prefs.dragLocked ? t("nav.unlockDrag") : t("nav.lockDrag") }}</span>
</button>
<button
class="flex items-center gap-3 rounded-control px-2.5 py-2 text-[15px] font-medium text-white/60 transition-colors hover:bg-white/5 hover:text-white md:px-3"
@click="toggleTheme"
+6 -1
View File
@@ -11,6 +11,7 @@
// change to this file.
import { ref, computed, watch, onMounted } from "vue";
import { api } from "../api";
import { prefs } from "../prefs";
import { t } from "../i18n";
import { formatDateTime, formatKm } from "../lib/format.js";
@@ -207,7 +208,11 @@ watch(
// Same native drag events as the garage and the Information rows, so also
// pointer-only, and it needs write access like every other choice on the car.
const canArrangeMetrics = computed(() => props.canWrite && metrics.value.length > 1);
// The rail's lock holds these still too — it covers every arrangement at once,
// which is the point of putting it in the rail rather than on each page.
const canArrangeMetrics = computed(
() => props.canWrite && !prefs.dragLocked && metrics.value.length > 1
);
const dragMetric = ref(""); // reading being dragged
const dropMetric = ref(""); // reading it is currently hovering over
let metricsMoved = false; // the row changed during this drag and isn't saved yet
+5 -1
View File
@@ -26,6 +26,9 @@
"garage": "Garage",
"charging": "Opladning",
"settings": "Indstillinger",
"lockDrag": "Lås layout",
"unlockDrag": "Lås layout op",
"dragLockHint": "Fastholder alle rækkefølger — garagen, bilens faner, dens oplysninger og aflæsninger.",
"lightMode": "Lys tilstand",
"darkMode": "Mørk tilstand",
"signedIn": "Logget ind",
@@ -273,7 +276,8 @@
"charging": "Opladningsudgifter",
"documents": "Dokumenter",
"parts": "Reservedelskatalog",
"reminders": "Påmindelser"
"reminders": "Påmindelser",
"dragHint": "Træk en fane for at ændre rækkefølgen af bilens faner."
},
"viewPicker": {
+5 -1
View File
@@ -26,6 +26,9 @@
"garage": "Garage",
"charging": "Charging",
"settings": "Settings",
"lockDrag": "Lock layout",
"unlockDrag": "Unlock layout",
"dragLockHint": "Hold every arrangement still — the garage, a car's tabs, its information and readings.",
"lightMode": "Light mode",
"darkMode": "Dark mode",
"signedIn": "Signed in",
@@ -348,7 +351,8 @@
"charging": "Charging cost",
"documents": "Documents",
"parts": "Parts catalog",
"reminders": "Reminders"
"reminders": "Reminders",
"dragHint": "Drag a tab to rearrange this car's tabs."
},
"viewPicker": {
+5 -1
View File
@@ -26,6 +26,9 @@
"garage": "Garaż",
"charging": "Ładowanie",
"settings": "Ustawienia",
"lockDrag": "Zablokuj układ",
"unlockDrag": "Odblokuj układ",
"dragLockHint": "Utrzymuje wszystkie układy — garaż, karty samochodu, jego informacje i odczyty.",
"lightMode": "Tryb jasny",
"darkMode": "Tryb ciemny",
"signedIn": "Zalogowano",
@@ -277,7 +280,8 @@
"charging": "Koszty ładowania",
"documents": "Dokumenty",
"parts": "Katalog części",
"reminders": "Przypomnienia"
"reminders": "Przypomnienia",
"dragHint": "Przeciągnij kartę, aby zmienić kolejność kart tego samochodu."
},
"viewPicker": {
+5
View File
@@ -8,6 +8,10 @@ export const prefs = reactive({
dateFormat: "YMD", // YMD | DMY | MDY
currency: "USD", // ISO 4217 code
fontSize: "medium", // small | medium | large
// Holds every arrangement still: the garage, a car's tabs, its Information
// rows, the provider's readings. Nothing to apply to the document — the views
// read it to decide whether their elements are draggable at all.
dragLocked: false,
});
const FONT_SCALE = { small: "93.75%", medium: "100%", large: "112.5%" };
@@ -44,6 +48,7 @@ export function applyProfilePrefs(profile) {
prefs.dateFormat = profile.dateFormat || "YMD";
prefs.currency = profile.currency || "USD";
prefs.fontSize = profile.fontSize || "medium";
prefs.dragLocked = !!profile.dragLocked;
applyTheme();
applyFontSize();
}
+117 -21
View File
@@ -2,6 +2,7 @@
import { ref, onMounted, computed, watch } from "vue";
import { useRouter } from "vue-router";
import { api } from "../api";
import { prefs } from "../prefs";
import {
formatDate,
formatKm,
@@ -86,9 +87,10 @@ const isReadOnly = computed(() => car.value?.access === "read");
const activeTab = ref("info");
// Connected-service tab. It leads the bar — ahead of Information — because for a
// car imported from a manufacturer account that is the live view of the car,
// while everything to its right is the record the user keeps by hand.
// Connected-service tab. It leads the bar by default — ahead of Information —
// because for a car imported from a manufacturer account that is the live view
// of the car, while everything to its right is the record the user keeps by
// hand. Like every tab it can be dragged elsewhere.
//
// It shows for a linked car (labelled with the service, "MyToyota") and also for
// an unlinked one as long as the user has some account connected, where it offers
@@ -119,19 +121,39 @@ const dueReminders = computed(
// activeTab, so a hidden tab's content is unreachable rather than unlabelled.
const hiddenTabs = computed(() => car.value?.hiddenTabs || []);
const hiddenFields = computed(() => car.value?.hiddenFields || []);
// The tabs in their default order. Information sits second because the
// connected service, when there is one, is what you came to look at.
const ALL_TAB_KEYS = [
"provider", "info", "services", "technical", "maintenance", "fuel",
"charging", "documents", "parts", "reminders",
];
// The arrangement of the bar: the full list of tab keys, hidden ones and the
// connected-service tab included, so a tab switched back on — or a provider
// linked later — returns to where it was put rather than to the end. Its own
// ref rather than read off the car, because a drag rearranges it live and only
// saves on drop. Rebuilt whenever the car is (re)loaded.
const tabKeys = ref([...ALL_TAB_KEYS]);
watch(
() => car.value?.tabOrder,
(order) => {
const arranged = [];
for (const key of order || []) {
if (ALL_TAB_KEYS.includes(key) && !arranged.includes(key)) arranged.push(key);
}
// A tab the stored arrangement doesn't mention — one added in a later
// release — follows the arranged ones, the same rule the Information rows
// and the garage use.
tabKeys.value = [...arranged, ...ALL_TAB_KEYS.filter((k) => !arranged.includes(k))];
},
{ immediate: true }
);
const TABS = computed(() =>
[
...(showProviderTab.value ? [{ key: "provider", label: providerLabel.value }] : []),
{ key: "info", label: t("car.tabs.info") },
{ key: "services", label: t("car.tabs.services") },
{ key: "technical", label: t("car.tabs.technical") },
{ key: "maintenance", label: t("car.tabs.maintenance") },
{ key: "fuel", label: t("car.tabs.fuel") },
{ key: "charging", label: t("car.tabs.charging") },
{ key: "documents", label: t("car.tabs.documents") },
{ key: "parts", label: t("car.tabs.parts") },
{ key: "reminders", label: t("car.tabs.reminders") },
].filter((tab) => !hiddenTabs.value.includes(tab.key))
tabKeys.value
.filter((key) => !hiddenTabs.value.includes(key))
.filter((key) => key !== "provider" || showProviderTab.value)
.map((key) => ({ key, label: tabPickerLabel(key) }))
);
// Switching a tab off while standing on it (or landing on a car whose provider
@@ -143,6 +165,64 @@ watch(TABS, (tabs) => {
}
});
// Dragging a tab, on the same native drag events as the Information rows and the
// garage — so pointer-only, as touch browsers don't fire these. Needs write
// access, since the arrangement belongs to the car; a bar with one tab left has
// nothing to rearrange; and the rail's lock holds it still for a user who would
// rather not nudge the bar on the way to a tab.
const canArrangeTabs = computed(
() => canWrite.value && !prefs.dragLocked && TABS.value.length > 1
);
const dragTab = ref(""); // tab being dragged
const dropTab = ref(""); // tab it is currently hovering over
const tabOrderError = ref("");
let tabsMoved = false; // the bar changed during this drag and isn't saved yet
function onTabDragStart(key, e) {
dragTab.value = key;
tabsMoved = false;
e.dataTransfer.effectAllowed = "move";
// Firefox only starts a drag once something is on the transfer.
e.dataTransfer.setData("text/plain", key);
}
// Reorder live as the pointer crosses tabs, so the bar shows the arrangement you
// are about to get. dragenter fires again for every child element inside the
// same button — the reminder count badge — so the tab being hovered is
// remembered and only a genuinely new one moves anything. The splice works on
// the full list, hidden tabs included, which keeps a hidden tab anchored between
// the same two visible neighbours.
function onTabDragEnter(key) {
if (!dragTab.value || key === dragTab.value || dropTab.value === key) return;
dropTab.value = key;
const list = tabKeys.value;
const from = list.indexOf(dragTab.value);
const to = list.indexOf(key);
if (from < 0 || to < 0) return;
list.splice(to, 0, ...list.splice(from, 1));
tabsMoved = true;
}
// Save whatever the bar now shows. Called from both drop and dragend: a tab
// released over the gap beside the bar never produces a drop, and leaving that
// arrangement unsaved would quietly undo itself on the next load.
async function commitTabOrder() {
dragTab.value = "";
dropTab.value = "";
if (!tabsMoved) return;
tabsMoved = false;
tabOrderError.value = "";
try {
const updated = await api.updateCarView(props.id, { tabOrder: tabKeys.value });
car.value = { ...updated, access: car.value.access };
} catch (e) {
// The arrangement didn't stick; say so and put the stored one back rather
// than leaving the page showing an order the server doesn't have.
tabOrderError.value = e.message;
await load();
}
}
// --- What this car's page shows (write access; owner or write-shared) ---
//
// Two hidden sets, both properties of the car: the tabs, and the rows of the
@@ -238,7 +318,9 @@ watch(
// rather than a drag library, which does mean it is pointer-only, as touch
// browsers don't fire these. Needs write access, and there is nothing to
// rearrange with a single row showing.
const canArrangeFields = computed(() => canWrite.value && infoFields.value.length > 1);
const canArrangeFields = computed(
() => canWrite.value && !prefs.dragLocked && infoFields.value.length > 1
);
const dragField = ref(""); // row being dragged
const dropField = ref(""); // row it is currently hovering over
const fieldOrderError = ref("");
@@ -744,16 +826,30 @@ onMounted(load);
</div>
</div>
<!-- Tabs -->
<!-- Tabs. They can be dragged into any order with write access; the
arrangement belongs to the car, like which tabs show at all. -->
<p v-if="tabOrderError" class="mb-4 rounded-control bg-danger-soft px-4 py-3 text-sm font-medium text-danger">{{ tabOrderError }}</p>
<div class="mb-6 flex flex-wrap gap-1 border-b border-subtle">
<button
v-for="tab in TABS"
:key="tab.key"
:draggable="canArrangeTabs"
:title="canArrangeTabs ? t('car.tabs.dragHint') : ''"
class="-mb-px flex items-center gap-1.5 border-b-2 px-4 py-2.5 text-sm font-semibold transition-colors"
:class="activeTab === tab.key
? 'border-accent text-brandtext'
: 'border-transparent text-muted hover:text-strong'"
@click="activeTab = tab.key">
:class="[
activeTab === tab.key
? 'border-accent text-brandtext'
: 'border-transparent text-muted hover:text-strong',
canArrangeTabs ? 'cursor-grab active:cursor-grabbing' : '',
dragTab === tab.key ? 'opacity-50' : '',
dropTab === tab.key ? 'bg-sunken rounded-t-control' : '',
]"
@click="activeTab = tab.key"
@dragstart="onTabDragStart(tab.key, $event)"
@dragenter.prevent="onTabDragEnter(tab.key)"
@dragover.prevent
@drop.prevent="commitTabOrder"
@dragend="commitTabOrder">
{{ tab.label }}
<span
v-if="tab.key === 'reminders' && dueReminders"
+11 -4
View File
@@ -1,7 +1,8 @@
<script setup>
import { ref, onMounted } from "vue";
import { ref, computed, onMounted } from "vue";
import { useRouter } from "vue-router";
import { api } from "../api";
import { prefs } from "../prefs";
import { formatDate, formatKm, serviceStatus } from "../lib/format.js";
import { t, tSplit } from "../i18n";
import CarFormModal from "../components/CarFormModal.vue";
@@ -46,6 +47,11 @@ async function load() {
// Hand-rolled on the native HTML5 drag events rather than pulling in a drag
// library for one screen — which does mean it is pointer-only, as touch
// browsers don't fire these.
//
// The rail's lock holds the garage still, for the reader who keeps nudging a
// card while scrolling. It is that user's own setting, so it hides the cursor
// and the hint as well as the drag itself.
const canArrangeCars = computed(() => !prefs.dragLocked && cars.value.length > 1);
const dragId = ref(""); // card being dragged
const dropId = ref(""); // card it is currently hovering over
const orderError = ref("");
@@ -173,10 +179,11 @@ onMounted(() => {
v-for="car in cars"
:key="car.id"
:to="{ name: 'car', params: { id: car.id } }"
:draggable="cars.length > 1"
:title="cars.length > 1 ? t('dashboard.dragHint') : ''"
class="dh-card group block cursor-grab p-5 transition-shadow duration-150 hover:shadow-pop active:cursor-grabbing"
:draggable="canArrangeCars"
:title="canArrangeCars ? t('dashboard.dragHint') : ''"
class="dh-card group block p-5 transition-shadow duration-150 hover:shadow-pop"
:class="[
canArrangeCars ? 'cursor-grab active:cursor-grabbing' : '',
dragId === car.id ? 'opacity-50' : '',
dropId === car.id ? 'ring-2 ring-accent' : '',
]"