Files
accounted/components/settings/LogoUpload.tsx
T
Jakob Wennberg 6d9846b1e7 feat(settings): Fönster redesign - flat rows, ? help, dirty save bar (#1193)
* feat(settings): Fönster redesign - flat rows, help behind ?, dirty save bar

Founder-approved concept (2026-07-25) applied to the whole settings
surface, modal and full-page variants alike:

- New primitives in components/settings/SettingsRows.tsx: section header
  (serif title + one-line intro), eyebrow groups, hairline label/control
  rows, flat inputs/selects/textareas, segmented control, animated
  reveal for gated settings, danger zone.
- Every static explanation paragraph moved behind a "?" popover
  (HelpPopover) at row or group level; dynamic status stays visible.
- Modal chrome: company kicker over serif title, fixed 920x680 window.
- SettingsFormWrapper: save is a sticky bar that appears only when the
  form is dirty; collapses to zero height when clean.
- All 11 sections converted (Konto, Abonnemang, Företag, Bokföring,
  Skatt, Löner, Fakturering, Mallar, Bank incl. Enable Banking-panel,
  Assistenten, API) with handlers, validation, role/entitlement/sandbox
  gates and i18n keys preserved; checkboxes became switches, cards
  dissolved into groups.
- Fix: Escape with an open help popover closed the whole settings
  modal; it now closes the popover first.
- New i18n keys: settings_intro.*, group labels, wrapper_unsaved
  (sv+en).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(settings): founder feedback round 1 on the Fönster redesign

- Abonnemang paying state: status and manage split into two rows so the
  row no longer wraps awkwardly; the included-features list now shows
  for paying companies too.
- Logos where the counterpart has one: BankID mark on the security row
  and on the Koppla BankID button, Skatteverket mark on the connection
  rows.
- Buttons are unmistakably buttons: 27 text-labeled row actions went
  from ghost to outline pills; icon-only actions stay quiet.
- The agent-knowledge view (Regler & profil: Dina regler, Momsprofil,
  Konventioner) converted to the flat row language; it was the last
  old-style surface inside settings. Descriptions moved behind "?",
  rules render as hairline rows, the per-row "Regel" chip demoted to
  muted text.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(settings): address review-bot findings on the Fönster redesign

- SettingsFormWrapper marks the form dirty on switch clicks too: Radix
  Switch is a button and fires no input event, so switch-only changes
  (f-skatt, KU, ROT/RUT, OSS...) never revealed the save bar.
- i18n: the migrated hardcoded strings got keys in both locales
  (fiscal-period start date/range/months, security set-password trio);
  dates in ApiKeysPanel/OAuthClientsPanel/CalendarFeedSettings now pass
  the active locale to formatDateLong.
- A11y: member remove/revoke buttons and the invite role select got
  correct accessible names; BankNameCombobox accepts aria-label wired
  from its row; the pinned-fact icon exposes role img.
- BankIdSettings: explicit Avbryt under the QR block so a cancelled
  BankID flow cannot strand isLinking.
- VoucherSeriesManager: clear the skeleton when no company is resolved.

Verified end to end in sandbox: switch-only dirty bar, PUT /api/settings
200 for text and switch saves, persistence across hard reload.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-07-25 23:55:08 +02:00

181 lines
5.6 KiB
TypeScript

'use client'
import { useState, useRef } from 'react'
import { useTranslations } from 'next-intl'
import { Button } from '@/components/ui/button'
import { useToast } from '@/components/ui/use-toast'
import { Loader2, Upload, Trash2 } from 'lucide-react'
import {
SettingsGroup,
SettingsRow,
} from '@/components/settings/SettingsRows'
import { getErrorMessage as getUserErrorMessage } from '@/lib/errors/get-error-message'
import { LOGO_UPLOAD_MAX_BYTES } from '@/lib/invoices/branding-constants'
interface LogoUploadProps {
logoUrl: string | null
onUpdate: (logoUrl: string | null) => void
}
export function LogoUpload({ logoUrl, onUpdate }: LogoUploadProps) {
const t = useTranslations('settings_company')
const { toast } = useToast()
const [isUploading, setIsUploading] = useState(false)
const [isDeleting, setIsDeleting] = useState(false)
const [preview, setPreview] = useState<string | null>(logoUrl)
const [isDragging, setIsDragging] = useState(false)
const inputRef = useRef<HTMLInputElement>(null)
const ALLOWED_TYPES = ['image/png', 'image/jpeg', 'image/svg+xml', 'image/webp']
function validateAndUpload(file: File) {
if (!ALLOWED_TYPES.includes(file.type)) {
toast({ title: t('logo_disallowed_type_title'), description: t('logo_disallowed_type_description'), variant: 'destructive' })
return
}
if (file.size > LOGO_UPLOAD_MAX_BYTES) {
toast({ title: t('logo_too_large'), variant: 'destructive' })
return
}
handleUpload(file)
}
async function handleUpload(file: File) {
setIsUploading(true)
const formData = new FormData()
formData.append('file', file)
try {
const response = await fetch('/api/settings/logo', {
method: 'POST',
body: formData,
})
const result = await response.json()
if (!response.ok) {
throw new Error(result.error || t('logo_upload_failed_default'))
}
setPreview(result.data.logo_url)
onUpdate(result.data.logo_url)
} catch (error) {
toast({
title: t('logo_upload_failed_title'),
description: error instanceof Error ? getUserErrorMessage(error) : t('logo_try_again'),
variant: 'destructive',
})
}
setIsUploading(false)
}
async function handleDelete() {
setIsDeleting(true)
try {
const response = await fetch('/api/settings/logo', { method: 'DELETE' })
if (!response.ok) throw new Error()
setPreview(null)
onUpdate(null)
if (inputRef.current) inputRef.current.value = ''
} catch {
toast({ title: t('logo_delete_failed'), variant: 'destructive' })
}
setIsDeleting(false)
}
function handleFileChange(e: React.ChangeEvent<HTMLInputElement>) {
const file = e.target.files?.[0]
if (!file) return
validateAndUpload(file)
}
function handleDrop(e: React.DragEvent<HTMLButtonElement>) {
e.preventDefault()
setIsDragging(false)
const file = e.dataTransfer.files?.[0]
if (file) validateAndUpload(file)
}
function handleDragOver(e: React.DragEvent<HTMLButtonElement>) {
e.preventDefault()
setIsDragging(true)
}
function handleDragLeave(e: React.DragEvent<HTMLButtonElement>) {
e.preventDefault()
setIsDragging(false)
}
return (
<SettingsGroup>
<SettingsRow label={t('logo_heading')} help={t('logo_help')}>
{preview ? (
<>
<span className="inline-flex rounded-lg border border-border bg-muted/30 p-2">
{/* eslint-disable-next-line @next/next/no-img-element */}
<img
src={preview}
alt={t('logo_alt')}
className="max-h-10 max-w-32 object-contain"
/>
</span>
<Button
variant="ghost"
size="sm"
onClick={() => inputRef.current?.click()}
disabled={isUploading}
className="text-muted-foreground hover:text-foreground"
>
{isUploading ? <Loader2 className="mr-2 h-3.5 w-3.5 animate-spin" /> : null}
{t('logo_change')}
</Button>
<Button
variant="outline"
size="sm"
onClick={handleDelete}
disabled={isDeleting}
className="text-muted-foreground hover:text-destructive"
>
{isDeleting ? <Loader2 className="mr-2 h-3.5 w-3.5 animate-spin" /> : <Trash2 className="mr-2 h-3.5 w-3.5" />}
{t('logo_remove')}
</Button>
</>
) : (
<button
type="button"
onClick={() => inputRef.current?.click()}
onDrop={handleDrop}
onDragOver={handleDragOver}
onDragEnter={handleDragOver}
onDragLeave={handleDragLeave}
disabled={isUploading}
className={`inline-flex min-h-10 items-center gap-2 rounded-lg border border-dashed px-4 py-2 text-sm text-muted-foreground transition-colors duration-150 disabled:opacity-50 ${
isDragging ? 'border-foreground bg-muted/40' : 'border-border hover:bg-muted/20'
}`}
>
{isUploading ? (
<Loader2 className="h-4 w-4 animate-spin" />
) : (
<Upload className="h-4 w-4 text-muted-foreground/60" />
)}
{isUploading ? t('logo_uploading') : t('logo_pick_or_drop')}
</button>
)}
</SettingsRow>
<input
ref={inputRef}
type="file"
accept="image/png,image/jpeg,image/svg+xml,image/webp"
className="hidden"
onChange={handleFileChange}
/>
</SettingsGroup>
)
}