13 Commits
28 changed files with 1645 additions and 1615 deletions
+53
View File
@@ -2,6 +2,59 @@
All notable changes to this project will be documented in this file. This project adheres to [Semantic Versioning](http://semver.org/). All notable changes to this project will be documented in this file. This project adheres to [Semantic Versioning](http://semver.org/).
## [1.0.6] - 2026-07-28
### Added
- WebUI version is now displayed when hovering over the logo.
### Changed
### Fixed
- Properly serialize `date` filters when applying them to the list filter.
## [1.0.5] - 2026-06-21
### Added
### Changed
### Fixed
- Redirect to `/login` when there is no refresh token.
- Include required JMAP capabilities in `using`.
- Default scopes omit `offline_access`.
## [1.0.4] - 2026-05-11
### Added
### Changed
### Fixed
- Align `base32` alphabet with the server.
## [1.0.3] - 2026-05-05
### Added
### Changed
### Fixed
- Broken "Delivery History" link on OSS/Community editions.
- Resolve object ids in map keys.
## [1.0.2] - 2026-04-30
### Added
- OIDC:
- Include `email` and `profile` scopes in OIDC authentication requests.
- TOTP:
- Add "Copy Secret" button to TOTP setup flow.
### Changed
### Fixed
- Display validation errors returned by the server.
## [1.0.1] - 2026-04-25 ## [1.0.1] - 2026-04-25
### Added ### Added
+1 -1
View File
@@ -4,7 +4,7 @@
<head> <head>
<meta charset="UTF-8" /> <meta charset="UTF-8" />
<base href="/" /> <base href="/" />
<link rel="icon" type="image/svg+xml" href="favicon.svg" /> <link rel="icon" type="image/x-icon" href="favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Portal</title> <title>Portal</title>
</head> </head>
+975 -1380
View File
File diff suppressed because it is too large Load Diff
+41 -41
View File
@@ -1,7 +1,7 @@
{ {
"name": "stalwart-webui", "name": "stalwart-webui",
"private": true, "private": true,
"version": "1.0.1", "version": "1.0.6",
"description": "Stalwart WebUI", "description": "Stalwart WebUI",
"type": "module", "type": "module",
"scripts": { "scripts": {
@@ -16,55 +16,55 @@
"format:check": "prettier --check src/" "format:check": "prettier --check src/"
}, },
"dependencies": { "dependencies": {
"@radix-ui/react-alert-dialog": "^1.1.15", "@radix-ui/react-alert-dialog": "^1.1.23",
"@radix-ui/react-checkbox": "^1.3.3", "@radix-ui/react-checkbox": "^1.3.11",
"@radix-ui/react-collapsible": "^1.1.12", "@radix-ui/react-collapsible": "^1.1.20",
"@radix-ui/react-dialog": "^1.1.15", "@radix-ui/react-dialog": "^1.1.23",
"@radix-ui/react-dropdown-menu": "^2.1.16", "@radix-ui/react-dropdown-menu": "^2.1.24",
"@radix-ui/react-label": "^2.1.8", "@radix-ui/react-label": "^2.1.15",
"@radix-ui/react-popover": "^1.1.15", "@radix-ui/react-popover": "^1.1.23",
"@radix-ui/react-scroll-area": "^1.2.10", "@radix-ui/react-scroll-area": "^1.2.18",
"@radix-ui/react-select": "^2.2.6", "@radix-ui/react-select": "^2.3.7",
"@radix-ui/react-separator": "^1.1.8", "@radix-ui/react-separator": "^1.1.15",
"@radix-ui/react-slot": "^1.2.4", "@radix-ui/react-slot": "^1.3.3",
"@radix-ui/react-switch": "^1.2.6", "@radix-ui/react-switch": "^1.3.7",
"@radix-ui/react-tabs": "^1.1.13", "@radix-ui/react-tabs": "^1.1.21",
"@radix-ui/react-tooltip": "^1.2.8", "@radix-ui/react-tooltip": "^1.2.16",
"@types/qrcode": "^1.5.6", "@types/qrcode": "^1.5.6",
"class-variance-authority": "^0.7.1", "class-variance-authority": "^0.7.1",
"clsx": "^2.1.1", "clsx": "^2.1.1",
"cmdk": "^1.1.1", "cmdk": "^1.1.1",
"i18next": "^26.0.4", "i18next": "^26.3.6",
"lucide-react": "^1.8.0", "lucide-react": "^1.27.0",
"otpauth": "^9.5.0", "otpauth": "^9.5.1",
"qrcode": "^1.5.4", "qrcode": "^1.5.4",
"react": "^19.2.4", "react": "^19.2.8",
"react-dom": "^19.2.4", "react-dom": "^19.2.8",
"react-i18next": "^17.0.2", "react-i18next": "^17.0.11",
"react-markdown": "^10.1.0", "react-markdown": "^10.1.0",
"react-router-dom": "^7.14.0", "react-router-dom": "^7.18.1",
"recharts": "^3.8.1", "recharts": "^3.10.1",
"tailwind-merge": "^3.5.0", "tailwind-merge": "^3.6.0",
"zustand": "^5.0.12" "zustand": "^5.0.14"
}, },
"devDependencies": { "devDependencies": {
"@eslint/js": "^9.39.4", "@eslint/js": "^10.0.1",
"@tailwindcss/vite": "^4.2.2", "@tailwindcss/vite": "^4.3.3",
"@types/node": "^24.12.2", "@types/node": "^26.1.2",
"@types/react": "^19.2.14", "@types/react": "^19.2.17",
"@types/react-dom": "^19.2.3", "@types/react-dom": "^19.2.3",
"@vitejs/plugin-react": "^6.0.1", "@vitejs/plugin-react": "^6.0.4",
"eslint": "^9.39.4", "eslint": "^10.8.0",
"eslint-config-prettier": "^10.1.8", "eslint-config-prettier": "^10.1.8",
"eslint-plugin-react-hooks": "^7.0.1", "eslint-plugin-react-hooks": "^7.1.1",
"eslint-plugin-react-refresh": "^0.5.2", "eslint-plugin-react-refresh": "^0.5.3",
"globals": "^17.4.0", "globals": "^17.8.0",
"happy-dom": "^20.9.0", "happy-dom": "^20.11.1",
"prettier": "^3.8.2", "prettier": "^3.9.6",
"tailwindcss": "^4.2.2", "tailwindcss": "^4.3.3",
"typescript": "~6.0.2", "typescript": "~6.0.3",
"typescript-eslint": "^8.58.0", "typescript-eslint": "^8.65.0",
"vite": "^8.0.4", "vite": "^8.1.5",
"vitest": "^4.1.4" "vitest": "^4.1.10"
} }
} }

Before

Width:  |  Height:  |  Size: 15 KiB

After

Width:  |  Height:  |  Size: 15 KiB

+3 -15
View File
@@ -19,7 +19,7 @@ import { toast } from '@/hooks/use-toast';
import { resolveObject, resolveSchema, resolveForm, buildCreateDefaults, deepMerge } from '@/lib/schemaResolver'; import { resolveObject, resolveSchema, resolveForm, buildCreateDefaults, deepMerge } from '@/lib/schemaResolver';
import { calculateJmapPatch } from '@/lib/jmapPatch'; import { calculateJmapPatch } from '@/lib/jmapPatch';
import { jmapGet, jmapSet, getAccountId } from '@/services/jmap/client'; import { jmapGet, jmapSet, getAccountId } from '@/services/jmap/client';
import { friendlySetError } from '@/lib/jmapErrors'; import { friendlySetError, validationErrorMessage } from '@/lib/jmapErrors';
import type { Field, Fields, Form, FormField } from '@/types/schema'; import type { Field, Fields, Form, FormField } from '@/types/schema';
import type { JmapSetError, JmapSetResponse } from '@/types/jmap'; import type { JmapSetError, JmapSetResponse } from '@/types/jmap';
@@ -88,9 +88,9 @@ export function BootstrapWizard() {
const { obj, sch } = resolved; const { obj, sch } = resolved;
const ctrl = new AbortController(); const ctrl = new AbortController();
setLoading(true);
(async () => { (async () => {
setLoading(true);
try { try {
const accountId = getAccountId(obj.objectName); const accountId = getAccountId(obj.objectName);
const responses = await jmapGet(obj.objectName, accountId, ['singleton'], fetchProperties, ctrl.signal); const responses = await jmapGet(obj.objectName, accountId, ['singleton'], fetchProperties, ctrl.signal);
@@ -181,19 +181,7 @@ export function BootstrapWizard() {
for (const ve of error.validationErrors) { for (const ve of error.validationErrors) {
const top = ve.property?.split('/')[0] ?? ''; const top = ve.property?.split('/')[0] ?? '';
if (!top) continue; if (!top) continue;
const msg = record(top, validationErrorMessage(ve));
ve.type === 'Required'
? t('form.required', 'This field is required.')
: ve.type === 'MaxLength'
? t('form.maxLengthIs', 'Maximum length is {{max}}.', { max: ve.required })
: ve.type === 'MinLength'
? t('form.minLengthIs', 'Minimum length is {{min}}.', { min: ve.required })
: ve.type === 'MaxValue'
? t('form.maxValueIs', 'Maximum value is {{max}}.', { max: ve.required })
: ve.type === 'MinValue'
? t('form.minValueIs', 'Minimum value is {{min}}.', { min: ve.required })
: t('form.invalidValue', 'Invalid value.');
record(top, msg);
} }
} }
@@ -4,8 +4,9 @@
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL * SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
*/ */
import { useState, useEffect } from 'react'; import { useState } from 'react';
import { useTranslation } from 'react-i18next'; import { useTranslation } from 'react-i18next';
import { useBufferedValue } from '@/hooks/useBufferedValue';
import { Input } from '@/components/ui/input'; import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button'; import { Button } from '@/components/ui/button';
@@ -21,11 +22,7 @@ function BufferedExprInput({
React.InputHTMLAttributes<HTMLInputElement>, React.InputHTMLAttributes<HTMLInputElement>,
'onChange' | 'value' 'onChange' | 'value'
>) { >) {
const [local, setLocal] = useState(value); const [local, setLocal] = useBufferedValue(value);
useEffect(() => {
setLocal(value);
}, [value]);
const commit = () => { const commit = () => {
if (local !== value) onCommit(local); if (local !== value) onCommit(local);
+25 -38
View File
@@ -5,6 +5,7 @@
*/ */
import { useState, useEffect, useCallback, useMemo } from 'react'; import { useState, useEffect, useCallback, useMemo } from 'react';
import { flushSync } from 'react-dom';
import { useNavigate, useBlocker } from 'react-router-dom'; import { useNavigate, useBlocker } from 'react-router-dom';
import { useTranslation } from 'react-i18next'; import { useTranslation } from 'react-i18next';
import { Button } from '@/components/ui/button'; import { Button } from '@/components/ui/button';
@@ -46,7 +47,7 @@ import {
} from '@/lib/schemaResolver'; } from '@/lib/schemaResolver';
import { jmapGet, jmapSet, jmapRequest, getAccountId } from '@/services/jmap/client'; import { jmapGet, jmapSet, jmapRequest, getAccountId } from '@/services/jmap/client';
import { calculateJmapPatch } from '@/lib/jmapPatch'; import { calculateJmapPatch } from '@/lib/jmapPatch';
import { friendlySetError } from '@/lib/jmapErrors'; import { friendlySetError, validationErrorMessage } from '@/lib/jmapErrors';
import { coerceLabel } from '@/lib/objectOptions'; import { coerceLabel } from '@/lib/objectOptions';
import { SECRET_MASK } from '@/lib/jmapUtils'; import { SECRET_MASK } from '@/lib/jmapUtils';
import { toast } from '@/hooks/use-toast'; import { toast } from '@/hooks/use-toast';
@@ -166,11 +167,11 @@ export function DynamicForm({ viewName, objectId }: DynamicFormProps) {
return Array.from(set); return Array.from(set);
}, [schema, resolved, viewName]); }, [schema, resolved, viewName]);
useEffect(() => { const [prevCreateInitKey, setPrevCreateInitKey] = useState<typeof resolved | undefined>(undefined);
if (!schema || !resolved) return; if (isCreate && schema && resolved) {
if (resolved !== prevCreateInitKey) {
setPrevCreateInitKey(resolved);
const { obj, sch } = resolved; const { obj, sch } = resolved;
if (isCreate) {
const staticFilters = resolved.list?.filtersStatic; const staticFilters = resolved.list?.filtersStatic;
if (sch.type === 'multiple') { if (sch.type === 'multiple') {
const variantFromFilter = typeof staticFilters?.['@type'] === 'string' ? staticFilters['@type'] : undefined; const variantFromFilter = typeof staticFilters?.['@type'] === 'string' ? staticFilters['@type'] : undefined;
@@ -184,13 +185,19 @@ export function DynamicForm({ viewName, objectId }: DynamicFormProps) {
setFormData(defaults); setFormData(defaults);
setOriginalData(defaults); setOriginalData(defaults);
} }
return; }
} else if (prevCreateInitKey !== undefined) {
setPrevCreateInitKey(undefined);
} }
useEffect(() => {
if (!schema || !resolved || isCreate) return;
const { obj, sch } = resolved;
const ctrl = new AbortController(); const ctrl = new AbortController();
setLoading(true);
(async () => { (async () => {
setLoading(true);
try { try {
const accountId = getAccountId(obj.objectName); const accountId = getAccountId(obj.objectName);
const ids = isSingleton ? ['singleton'] : [objectId]; const ids = isSingleton ? ['singleton'] : [objectId];
@@ -251,13 +258,14 @@ export function DynamicForm({ viewName, objectId }: DynamicFormProps) {
const blocker = useBlocker(isDirty && !saving); const blocker = useBlocker(isDirty && !saving);
const [pendingNavAfterCreate, setPendingNavAfterCreate] = useState(false); const navigateAfterCreate = useCallback(() => {
useEffect(() => { flushSync(() => {
if (!pendingNavAfterCreate) return; setOriginalData({ ...formData });
setPendingNavAfterCreate(false); setServerCreatedProps(null);
});
const section = viewToSection[viewName] ?? ''; const section = viewToSection[viewName] ?? '';
navigate(`/${section}/${viewName}`); navigate(`/${section}/${viewName}`);
}, [pendingNavAfterCreate, viewName, viewToSection, navigate]); }, [formData, viewToSection, viewName, navigate]);
const handleFieldChange = useCallback((fieldName: string, value: unknown) => { const handleFieldChange = useCallback((fieldName: string, value: unknown) => {
setFormData((prev) => ({ ...prev, [fieldName]: value })); setFormData((prev) => ({ ...prev, [fieldName]: value }));
@@ -347,21 +355,10 @@ export function DynamicForm({ viewName, objectId }: DynamicFormProps) {
if (error.validationErrors && error.validationErrors.length > 0) { if (error.validationErrors && error.validationErrors.length > 0) {
for (const ve of error.validationErrors) { for (const ve of error.validationErrors) {
if (ve.property && currentFields?.properties[ve.property]) { if (ve.property && currentFields?.properties[ve.property]) {
const msg = newFieldErrors[ve.property] = validationErrorMessage(ve);
ve.type === 'Required'
? t('form.required', 'This field is required.')
: ve.type === 'MaxLength'
? t('form.maxLengthIs', 'Maximum length is {{max}}.', { max: ve.required })
: ve.type === 'MinLength'
? t('form.minLengthIs', 'Minimum length is {{min}}.', { min: ve.required })
: ve.type === 'MaxValue'
? t('form.maxValueIs', 'Maximum value is {{max}}.', { max: ve.required })
: ve.type === 'MinValue'
? t('form.minValueIs', 'Minimum value is {{min}}.', { min: ve.required })
: t('form.invalidValue', 'Invalid value.');
newFieldErrors[ve.property] = msg;
} else if (ve.property) { } else if (ve.property) {
setGeneralError((prev) => (prev ? `${prev}\n${ve.property}: ${ve.type}` : `${ve.property}: ${ve.type}`)); const detail = ve.value && ve.value.length > 0 ? ve.value : ve.type;
setGeneralError((prev) => (prev ? `${prev}\n${ve.property}: ${detail}` : `${ve.property}: ${detail}`));
} }
} }
} }
@@ -939,9 +936,7 @@ export function DynamicForm({ viewName, objectId }: DynamicFormProps) {
open={serverCreatedProps !== null && createdObjectId !== null} open={serverCreatedProps !== null && createdObjectId !== null}
onOpenChange={(open) => { onOpenChange={(open) => {
if (!open) { if (!open) {
setOriginalData({ ...formData }); navigateAfterCreate();
setServerCreatedProps(null);
setPendingNavAfterCreate(true);
} }
}} }}
> >
@@ -974,15 +969,7 @@ export function DynamicForm({ viewName, objectId }: DynamicFormProps) {
})()} })()}
</div> </div>
<DialogFooter> <DialogFooter>
<Button <Button onClick={navigateAfterCreate}>{t('common.continue', 'Continue')}</Button>
onClick={() => {
setOriginalData({ ...formData });
setServerCreatedProps(null);
setPendingNavAfterCreate(true);
}}
>
{t('common.continue', 'Continue')}
</Button>
</DialogFooter> </DialogFooter>
</DialogContent> </DialogContent>
</Dialog> </Dialog>
+46 -53
View File
@@ -6,6 +6,7 @@
import { useState, useEffect, type KeyboardEvent } from 'react'; import { useState, useEffect, type KeyboardEvent } from 'react';
import { useTranslation } from 'react-i18next'; import { useTranslation } from 'react-i18next';
import { useBufferedValue, useResetOnChange } from '@/hooks/useBufferedValue';
import ReactMarkdown from 'react-markdown'; import ReactMarkdown from 'react-markdown';
import { Input } from '@/components/ui/input'; import { Input } from '@/components/ui/input';
@@ -243,11 +244,7 @@ interface BufferedInputProps extends Omit<React.InputHTMLAttributes<HTMLInputEle
} }
function BufferedInput({ value, onCommit, onBlur, onKeyDown, ...rest }: BufferedInputProps) { function BufferedInput({ value, onCommit, onBlur, onKeyDown, ...rest }: BufferedInputProps) {
const [local, setLocal] = useState(value); const [local, setLocal] = useBufferedValue(value);
useEffect(() => {
setLocal(value);
}, [value]);
const commit = () => { const commit = () => {
if (local !== value) onCommit(local); if (local !== value) onCommit(local);
@@ -278,11 +275,7 @@ interface BufferedTextareaProps extends Omit<React.TextareaHTMLAttributes<HTMLTe
} }
function BufferedTextarea({ value, onCommit, onBlur, ...rest }: BufferedTextareaProps) { function BufferedTextarea({ value, onCommit, onBlur, ...rest }: BufferedTextareaProps) {
const [local, setLocal] = useState(value); const [local, setLocal] = useBufferedValue(value);
useEffect(() => {
setLocal(value);
}, [value]);
return ( return (
<Textarea <Textarea
@@ -463,8 +456,7 @@ function SecretInput({ value, onChange, readOnly, placeholder, minLength, maxLen
const [localValue, setLocalValue] = useState(() => (value === SECRET_MASK || value === '' ? '' : value)); const [localValue, setLocalValue] = useState(() => (value === SECRET_MASK || value === '' ? '' : value));
const [isMasked, setIsMasked] = useState(() => value === SECRET_MASK); const [isMasked, setIsMasked] = useState(() => value === SECRET_MASK);
/* eslint-disable react-hooks/set-state-in-effect */ useResetOnChange(value, () => {
useEffect(() => {
if (value === SECRET_MASK || value === '') { if (value === SECRET_MASK || value === '') {
setLocalValue(''); setLocalValue('');
setIsMasked(value === SECRET_MASK); setIsMasked(value === SECRET_MASK);
@@ -472,8 +464,7 @@ function SecretInput({ value, onChange, readOnly, placeholder, minLength, maxLen
setLocalValue(value); setLocalValue(value);
setIsMasked(false); setIsMasked(false);
} }
}, [value]); });
/* eslint-enable react-hooks/set-state-in-effect */
const handleLocalChange = (v: string) => { const handleLocalChange = (v: string) => {
setLocalValue(v); setLocalValue(v);
@@ -513,6 +504,10 @@ function SecretInput({ value, onChange, readOnly, placeholder, minLength, maxLen
minLength={minLength} minLength={minLength}
maxLength={maxLength} maxLength={maxLength}
rows={4} rows={4}
autoComplete="off"
data-1p-ignore
data-lpignore="true"
data-bwignore
className={visible ? '' : 'tracking-widest'} className={visible ? '' : 'tracking-widest'}
style={visible ? undefined : ({ WebkitTextSecurity: 'disc' } as React.CSSProperties)} style={visible ? undefined : ({ WebkitTextSecurity: 'disc' } as React.CSSProperties)}
/> />
@@ -535,6 +530,10 @@ function SecretInput({ value, onChange, readOnly, placeholder, minLength, maxLen
placeholder={displayPlaceholder} placeholder={displayPlaceholder}
minLength={minLength} minLength={minLength}
maxLength={maxLength} maxLength={maxLength}
autoComplete="off"
data-1p-ignore
data-lpignore="true"
data-bwignore
className="flex-1" className="flex-1"
/> />
{toggleBtn} {toggleBtn}
@@ -607,13 +606,7 @@ function BufferedNumberInput({
disabled, disabled,
onCommit, onCommit,
}: BufferedNumberInputProps) { }: BufferedNumberInputProps) {
const [local, setLocal] = useState<string>(value != null ? String(value) : ''); const [local, setLocal] = useBufferedValue(value, (v) => (v != null ? String(v) : ''));
/* eslint-disable react-hooks/set-state-in-effect */
useEffect(() => {
setLocal(value != null ? String(value) : '');
}, [value]);
/* eslint-enable react-hooks/set-state-in-effect */
const commit = () => { const commit = () => {
if (local === '') { if (local === '') {
@@ -666,13 +659,11 @@ function SizeInputEditable({ value, onChange, nullable }: Omit<SizeInputProps, '
const [unit, setUnit] = useState(initHuman.unit); const [unit, setUnit] = useState(initHuman.unit);
const [localStr, setLocalStr] = useState<string>(isNull ? '' : String(initHuman.value)); const [localStr, setLocalStr] = useState<string>(isNull ? '' : String(initHuman.value));
/* eslint-disable react-hooks/set-state-in-effect */ useResetOnChange(value, () => {
useEffect(() => {
const h = bytesToHuman(typeof value === 'number' ? value : 0); const h = bytesToHuman(typeof value === 'number' ? value : 0);
setUnit(h.unit); setUnit(h.unit);
setLocalStr(value == null ? '' : String(h.value)); setLocalStr(value == null ? '' : String(h.value));
}, [value]); });
/* eslint-enable react-hooks/set-state-in-effect */
const commit = () => { const commit = () => {
if (localStr === '') { if (localStr === '') {
@@ -771,13 +762,11 @@ function DurationInputEditable({ value, onChange, nullable }: Omit<DurationInput
const [unit, setUnit] = useState(initHuman.unit); const [unit, setUnit] = useState(initHuman.unit);
const [localStr, setLocalStr] = useState<string>(isNull ? '' : String(initHuman.value)); const [localStr, setLocalStr] = useState<string>(isNull ? '' : String(initHuman.value));
/* eslint-disable react-hooks/set-state-in-effect */ useResetOnChange(value, () => {
useEffect(() => {
const h = msToHuman(typeof value === 'number' ? value : 0); const h = msToHuman(typeof value === 'number' ? value : 0);
setUnit(h.unit); setUnit(h.unit);
setLocalStr(value == null ? '' : String(h.value)); setLocalStr(value == null ? '' : String(h.value));
}, [value]); });
/* eslint-enable react-hooks/set-state-in-effect */
const commit = () => { const commit = () => {
if (localStr === '') { if (localStr === '') {
@@ -862,13 +851,7 @@ function DateTimeField({ value, onChange, readOnly, nullable }: DateTimeFieldPro
return new Date(local).toISOString(); return new Date(local).toISOString();
}; };
const [local, setLocal] = useState(() => toLocal(strValue)); const [local, setLocal] = useBufferedValue(strValue, toLocal);
/* eslint-disable react-hooks/set-state-in-effect */
useEffect(() => {
setLocal(toLocal(strValue));
}, [strValue]);
/* eslint-enable react-hooks/set-state-in-effect */
const commit = () => { const commit = () => {
const iso = toIso(local); const iso = toIso(local);
@@ -1005,9 +988,9 @@ function BlobField({ value, onChange, readOnly }: BlobFieldProps) {
if (!blobId || loaded) return; if (!blobId || loaded) return;
let cancelled = false; let cancelled = false;
setLoading(true);
(async () => { (async () => {
setLoading(true);
try { try {
const accountId = getAccountId('x:Blob'); const accountId = getAccountId('x:Blob');
const responses = await jmapGet('Blob', accountId, [blobId], ['data:asText']); const responses = await jmapGet('Blob', accountId, [blobId], ['data:asText']);
@@ -1253,12 +1236,8 @@ function RateField({ value, onChange, readOnly, nullable }: RateFieldProps) {
const [localCount, setLocalCount] = useState(String(count)); const [localCount, setLocalCount] = useState(String(count));
const [localPeriod, setLocalPeriod] = useState(String(human.value)); const [localPeriod, setLocalPeriod] = useState(String(human.value));
useEffect(() => { useResetOnChange(count, () => setLocalCount(String(count)));
setLocalCount(String(count)); useResetOnChange(human.value, () => setLocalPeriod(String(human.value)));
}, [count]);
useEffect(() => {
setLocalPeriod(String(human.value));
}, [human.value]);
const commitCount = () => { const commitCount = () => {
const n = parseInt(localCount, 10); const n = parseInt(localCount, 10);
@@ -1979,6 +1958,29 @@ function ObjectIdMultiSelectPill({
); );
} }
function MapEntryKeyLabel({ keyClass, keyValue, schema }: { keyClass: ScalarType; keyValue: string; schema: Schema }) {
if (keyClass.type === 'enum') {
const variants = schema.enums[keyClass.enumName] ?? [];
const variant = variants.find((v) => v.name === keyValue);
return <>{variant?.label ?? keyValue}</>;
}
if (keyClass.type === 'objectId') {
return <ObjectIdKeyLabel objectName={keyClass.objectName} keyValue={keyValue} schema={schema} />;
}
return <>{keyValue}</>;
}
function ObjectIdKeyLabel({ objectName, keyValue, schema }: { objectName: string; keyValue: string; schema: Schema }) {
const list = useObjectList(objectName, schema);
const fromList = list.options.find((o) => o.id === keyValue)?.label;
const { label: cheapLabel, loading } = useObjectLabel(objectName, fromList ? null : keyValue, schema);
const display = fromList ?? cheapLabel;
if (loading && !display) {
return <Loader2 className="h-3 w-3 animate-spin text-muted-foreground" />;
}
return <>{display ?? keyValue}</>;
}
interface MapFieldProps { interface MapFieldProps {
keyClass: ScalarType; keyClass: ScalarType;
valueClass: MapValueType; valueClass: MapValueType;
@@ -2038,15 +2040,6 @@ function MapField({ keyClass, valueClass, value, onChange, readOnly, schema, min
} }
}; };
const getKeyLabel = (key: string): string => {
if (keyClass.type === 'enum') {
const variants = schema.enums[keyClass.enumName] ?? [];
const variant = variants.find((v) => v.name === key);
if (variant) return variant.label;
}
return key;
};
const existingKeys = new Set(Object.keys(mapValue)); const existingKeys = new Set(Object.keys(mapValue));
return ( return (
@@ -2063,7 +2056,7 @@ function MapField({ keyClass, valueClass, value, onChange, readOnly, schema, min
className="flex flex-1 items-center gap-2 p-3 text-sm font-medium hover:bg-accent/50 rounded-t-md transition-colors [&[data-state=closed]>svg]:rotate-0 [&[data-state=open]>svg]:rotate-90" className="flex flex-1 items-center gap-2 p-3 text-sm font-medium hover:bg-accent/50 rounded-t-md transition-colors [&[data-state=closed]>svg]:rotate-0 [&[data-state=open]>svg]:rotate-90"
> >
<ChevronRight className="h-4 w-4 shrink-0 transition-transform duration-200" /> <ChevronRight className="h-4 w-4 shrink-0 transition-transform duration-200" />
{getKeyLabel(key)} <MapEntryKeyLabel keyClass={keyClass} keyValue={key} schema={schema} />
</button> </button>
</CollapsibleTrigger> </CollapsibleTrigger>
{!readOnly && ( {!readOnly && (
+48 -1
View File
@@ -8,11 +8,12 @@ import { useEffect, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next'; import { useTranslation } from 'react-i18next';
import * as OTPAuth from 'otpauth'; import * as OTPAuth from 'otpauth';
import QRCode from 'qrcode'; import QRCode from 'qrcode';
import { Loader2, ShieldCheck, ShieldOff } from 'lucide-react'; import { Check, Copy, Loader2, ShieldCheck, ShieldOff } from 'lucide-react';
import { Button } from '@/components/ui/button'; import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input'; import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label'; import { Label } from '@/components/ui/label';
import { toast } from '@/hooks/use-toast';
import { SECRET_MASK } from '@/lib/jmapUtils'; import { SECRET_MASK } from '@/lib/jmapUtils';
interface OtpAuthValue { interface OtpAuthValue {
@@ -56,6 +57,27 @@ export function OtpAuthField({ value, onChange, readOnly }: OtpAuthFieldProps) {
const [qrDataUrl, setQrDataUrl] = useState<string | null>(null); const [qrDataUrl, setQrDataUrl] = useState<string | null>(null);
const [setupCode, setSetupCode] = useState(''); const [setupCode, setSetupCode] = useState('');
const [setupError, setSetupError] = useState<string | null>(null); const [setupError, setSetupError] = useState<string | null>(null);
const [secretCopied, setSecretCopied] = useState(false);
const setupSecret = useMemo(() => {
if (!setupTotp) return null;
return setupTotp.secret.base32.replace(/(.{4})/g, '$1 ').trim();
}, [setupTotp]);
const copySecret = async () => {
if (!setupTotp) return;
try {
await navigator.clipboard.writeText(setupTotp.secret.base32);
setSecretCopied(true);
setTimeout(() => setSecretCopied(false), 1500);
} catch {
toast({
title: t('otp.copyFailed', 'Copy failed'),
description: t('otp.clipboardBlocked', 'Your browser blocked clipboard access.'),
variant: 'destructive',
});
}
};
useEffect(() => { useEffect(() => {
if (!setupUrl) return; if (!setupUrl) return;
@@ -96,6 +118,7 @@ export function OtpAuthField({ value, onChange, readOnly }: OtpAuthFieldProps) {
setSetupTotp(null); setSetupTotp(null);
setSetupUrl(null); setSetupUrl(null);
setSetupCode(''); setSetupCode('');
setSecretCopied(false);
}; };
const cancelSetup = () => { const cancelSetup = () => {
@@ -103,6 +126,7 @@ export function OtpAuthField({ value, onChange, readOnly }: OtpAuthFieldProps) {
setSetupUrl(null); setSetupUrl(null);
setSetupCode(''); setSetupCode('');
setSetupError(null); setSetupError(null);
setSecretCopied(false);
}; };
const otpCodeValue = useMemo( const otpCodeValue = useMemo(
@@ -155,6 +179,29 @@ export function OtpAuthField({ value, onChange, readOnly }: OtpAuthFieldProps) {
</div> </div>
)} )}
</div> </div>
{setupSecret && (
<div className="space-y-1.5">
<Label className="text-sm font-medium">{t('otp.manualEntryLabel', 'Or enter this code manually')}</Label>
<p className="text-xs text-muted-foreground">
{t(
'otp.manualEntryDescription',
'If you cannot scan the QR code, enter this secret into your authenticator app instead.',
)}
</p>
<div className="flex gap-2">
<code className="flex-1 rounded bg-muted p-2 text-sm font-mono break-all select-all">{setupSecret}</code>
<Button
type="button"
variant="outline"
size="sm"
onClick={copySecret}
aria-label={t('otp.copySecret', 'Copy secret')}
>
{secretCopied ? <Check className="h-4 w-4" /> : <Copy className="h-4 w-4" />}
</Button>
</div>
</div>
)}
<div className="space-y-1.5"> <div className="space-y-1.5">
<Label className="text-sm font-medium">{t('otp.confirmationCodeLabel', 'Confirmation code')}</Label> <Label className="text-sm font-medium">{t('otp.confirmationCodeLabel', 'Confirmation code')}</Label>
<Input <Input
+2 -2
View File
@@ -8,10 +8,10 @@ import { Navigate, useLocation } from 'react-router-dom';
import { useAuthStore } from '@/stores/authStore'; import { useAuthStore } from '@/stores/authStore';
export function ProtectedRoute({ children }: { children: React.ReactNode }) { export function ProtectedRoute({ children }: { children: React.ReactNode }) {
const accessToken = useAuthStore((s) => s.accessToken); const authenticated = useAuthStore((s) => s.isAuthenticated());
const bypassToken = import.meta.env.VITE_ACCESS_TOKEN; const bypassToken = import.meta.env.VITE_ACCESS_TOKEN;
const location = useLocation(); const location = useLocation();
if (!accessToken && !bypassToken) { if (!authenticated && !bypassToken) {
const originalPath = location.pathname + location.search; const originalPath = location.pathname + location.search;
return <Navigate to="/login" replace state={{ from: originalPath }} />; return <Navigate to="/login" replace state={{ from: originalPath }} />;
} }
+10
View File
@@ -21,6 +21,7 @@ import {
DropdownMenuTrigger, DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu'; } from '@/components/ui/dropdown-menu';
import Logo from '@/components/common/Logo'; import Logo from '@/components/common/Logo';
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip';
import { EnterpriseUpsell } from '@/components/common/EnterpriseUpsell'; import { EnterpriseUpsell } from '@/components/common/EnterpriseUpsell';
import { findFirstAccessibleLinkInLayout, findFirstVisibleLinkInLayout, visibleLayouts } from '@/lib/layout'; import { findFirstAccessibleLinkInLayout, findFirstVisibleLinkInLayout, visibleLayouts } from '@/lib/layout';
import { useUIStore } from '@/stores/uiStore'; import { useUIStore } from '@/stores/uiStore';
@@ -66,9 +67,18 @@ export function TopBar() {
<Menu className="h-4 w-4" /> <Menu className="h-4 w-4" />
</Button> </Button>
<TooltipProvider>
<Tooltip>
<TooltipTrigger asChild>
<Link to="/" className="flex shrink-0 items-center"> <Link to="/" className="flex shrink-0 items-center">
<Logo /> <Logo />
</Link> </Link>
</TooltipTrigger>
<TooltipContent side="bottom">
{t('version.label', 'Stalwart WebUI v{{version}}', { version: __APP_VERSION__ })}
</TooltipContent>
</Tooltip>
</TooltipProvider>
<div className="hidden min-w-0 flex-1 items-center justify-center px-4 md:flex"> <div className="hidden min-w-0 flex-1 items-center justify-center px-4 md:flex">
<GlobalSearch /> <GlobalSearch />
+58 -47
View File
@@ -17,6 +17,7 @@ import {
ArrowUpDown, ArrowUpDown,
Filter, Filter,
Loader2, Loader2,
Lock,
Search, Search,
RotateCcw, RotateCcw,
} from 'lucide-react'; } from 'lucide-react';
@@ -46,9 +47,12 @@ import {
} from '@/components/ui/alert-dialog'; } from '@/components/ui/alert-dialog';
import { Collapsible, CollapsibleTrigger, CollapsibleContent } from '@/components/ui/collapsible'; import { Collapsible, CollapsibleTrigger, CollapsibleContent } from '@/components/ui/collapsible';
import { ObjectPicker } from '@/components/common/ObjectPicker'; import { ObjectPicker } from '@/components/common/ObjectPicker';
import { EnterpriseUpsell } from '@/components/common/EnterpriseUpsell';
import { toast } from '@/hooks/use-toast'; import { toast } from '@/hooks/use-toast';
import { friendlySetError } from '@/lib/jmapErrors'; import { friendlySetError } from '@/lib/jmapErrors';
import { coerceLabel } from '@/lib/objectOptions'; import { coerceLabel } from '@/lib/objectOptions';
import { buildJmapFilter } from '@/lib/listFilter';
import { useResetOnChange } from '@/hooks/useBufferedValue';
import { useSchemaStore } from '@/stores/schemaStore'; import { useSchemaStore } from '@/stores/schemaStore';
import { useAuthStore } from '@/stores/authStore'; import { useAuthStore } from '@/stores/authStore';
@@ -302,6 +306,24 @@ interface SortState {
ascending: boolean; ascending: boolean;
} }
function readUrlFilters(): Record<string, string> {
const params = new URLSearchParams(window.location.search);
const filters: Record<string, string> = {};
params.forEach((value, key) => {
if (key.startsWith('f.')) {
filters[key.slice(2)] = value;
}
});
return filters;
}
function readUrlSort(): SortState | null {
const params = new URLSearchParams(window.location.search);
const sortParam = params.get('sort');
const sortDir = params.get('sortDir');
return sortParam ? { field: sortParam, ascending: sortDir !== 'desc' } : null;
}
interface ConfirmAction { interface ConfirmAction {
label: string; label: string;
onConfirm: () => void; onConfirm: () => void;
@@ -319,6 +341,8 @@ export function DynamicList({ viewName }: DynamicListProps) {
const schema = useSchemaStore((s) => s.schema); const schema = useSchemaStore((s) => s.schema);
const viewToSection = useSchemaStore((s) => s.viewToSection); const viewToSection = useSchemaStore((s) => s.viewToSection);
const hasObjectPermission = useAccountStore((s) => s.hasObjectPermission); const hasObjectPermission = useAccountStore((s) => s.hasObjectPermission);
const edition = useAccountStore((s) => s.edition);
const [upsellOpen, setUpsellOpen] = useState(false);
const resolved = useMemo(() => { const resolved = useMemo(() => {
if (!schema) return null; if (!schema) return null;
@@ -347,15 +371,15 @@ export function DynamicList({ viewName }: DynamicListProps) {
const [selectedIds, setSelectedIds] = useState<Set<string>>(new Set()); const [selectedIds, setSelectedIds] = useState<Set<string>>(new Set());
const [selectAllMode, setSelectAllMode] = useState(false); const [selectAllMode, setSelectAllMode] = useState(false);
const [filtersOpen, setFiltersOpen] = useState(false); const [filtersOpen, setFiltersOpen] = useState(() => Object.keys(readUrlFilters()).length > 0);
const [filterValues, setFilterValues] = useState<Record<string, string>>({}); const [filterValues, setFilterValues] = useState<Record<string, string>>(readUrlFilters);
const [appliedFilters, setAppliedFilters] = useState<Record<string, string>>({}); const [appliedFilters, setAppliedFilters] = useState<Record<string, string>>(readUrlFilters);
const [sort, setSort] = useState<SortState | null>(null); const [sort, setSort] = useState<SortState | null>(readUrlSort);
const [confirmAction, setConfirmAction] = useState<ConfirmAction | null>(null); const [confirmAction, setConfirmAction] = useState<ConfirmAction | null>(null);
useEffect(() => { useResetOnChange(viewName, () => {
setItems([]); setItems([]);
setTotal(null); setTotal(null);
setAnchorStack([]); setAnchorStack([]);
@@ -364,44 +388,22 @@ export function DynamicList({ viewName }: DynamicListProps) {
setSelectAllMode(false); setSelectAllMode(false);
setError(null); setError(null);
const params = new URLSearchParams(window.location.search); const initialFilters = readUrlFilters();
const initialFilters: Record<string, string> = {};
params.forEach((value, key) => {
if (key.startsWith('f.')) {
initialFilters[key.slice(2)] = value;
}
});
setFilterValues(initialFilters); setFilterValues(initialFilters);
setAppliedFilters(initialFilters); setAppliedFilters(initialFilters);
setFiltersOpen(Object.keys(initialFilters).length > 0); setFiltersOpen(Object.keys(initialFilters).length > 0);
setSort(readUrlSort());
});
const sortParam = params.get('sort'); const objectName = resolved?.obj.objectName;
const sortDir = params.get('sortDir');
setSort(sortParam ? { field: sortParam, ascending: sortDir !== 'desc' } : null);
}, [viewName]);
const buildFilter = useCallback((): Record<string, unknown> => { const buildFilter = useCallback((): Record<string, unknown> => {
const filter: Record<string, unknown> = {}; return buildJmapFilter({
const list = resolved?.list; appliedFilters,
if (list?.filtersStatic) { filters: resolved?.list?.filters,
Object.assign(filter, list.filtersStatic); filtersStatic: resolved?.list?.filtersStatic,
} isXPrefixed: objectName?.startsWith('x:') ?? false,
const opSuffix: Record<string, string> = { });
eq: '', }, [appliedFilters, resolved?.list, objectName]);
gt: 'IsGreaterThan',
gte: 'IsGreaterThanOrEqual',
lt: 'IsLessThan',
lte: 'IsLessThanOrEqual',
};
for (const [key, val] of Object.entries(appliedFilters)) {
if (val === '' || val == null) continue;
if (key.endsWith('Op')) continue;
const op = appliedFilters[`${key}Op`];
const suffix = op ? (opSuffix[op] ?? '') : '';
filter[`${key}${suffix}`] = val;
}
return filter;
}, [appliedFilters, resolved?.list]);
const buildSort = useCallback((): Record<string, unknown>[] | undefined => { const buildSort = useCallback((): Record<string, unknown>[] | undefined => {
if (!sort) return undefined; if (!sort) return undefined;
@@ -473,6 +475,7 @@ export function DynamicList({ viewName }: DynamicListProps) {
useEffect(() => { useEffect(() => {
if (!resolved?.list) return; if (!resolved?.list) return;
// eslint-disable-next-line react-hooks/set-state-in-effect
setAnchorStack([]); setAnchorStack([]);
setCurrentAnchor(null); setCurrentAnchor(null);
fetchData(null); fetchData(null);
@@ -1020,17 +1023,20 @@ export function DynamicList({ viewName }: DynamicListProps) {
function renderItemActions(item: Record<string, unknown>): React.ReactNode { function renderItemActions(item: Record<string, unknown>): React.ReactNode {
if (!hasItemActions || !list.itemActions) return null; if (!hasItemActions || !list.itemActions) return null;
const filteredActions = list.itemActions.filter((action) => { const filteredActions = list.itemActions.flatMap((action): { action: ItemAction; locked: boolean }[] => {
if (action.type === 'separator') return true; if (action.type === 'separator') return [{ action, locked: false }];
if (action.type === 'delete') return canDelete; if (action.type === 'delete') return canDelete ? [{ action, locked: false }] : [];
if (action.type === 'setProperty') return canUpdate; if (action.type === 'setProperty') return canUpdate ? [{ action, locked: false }] : [];
if (action.type === 'view' || action.type === 'query') { if (action.type === 'view' || action.type === 'query') {
const targetObj = resolveObject(schema!, action.objectName); const targetObj = resolveObject(schema!, action.objectName);
if (targetObj && !hasObjectPermission(targetObj.permissionPrefix, 'Get')) { if (!targetObj) return [];
return false; if (targetObj.enterprise) {
if (edition === 'oss') return [];
if (edition === 'community') return [{ action, locked: true }];
} }
if (!hasObjectPermission(targetObj.permissionPrefix, 'Get')) return [];
} }
return true; return [{ action, locked: false }];
}); });
if (filteredActions.length === 0) return null; if (filteredActions.length === 0) return null;
@@ -1043,7 +1049,7 @@ export function DynamicList({ viewName }: DynamicListProps) {
</Button> </Button>
</DropdownMenuTrigger> </DropdownMenuTrigger>
<DropdownMenuContent align="end"> <DropdownMenuContent align="end">
{filteredActions.map((action, idx) => { {filteredActions.map(({ action, locked }, idx) => {
if (action.type === 'separator') { if (action.type === 'separator') {
return <DropdownMenuSeparator key={`sep-${idx}`} />; return <DropdownMenuSeparator key={`sep-${idx}`} />;
} }
@@ -1057,7 +1063,9 @@ export function DynamicList({ viewName }: DynamicListProps) {
className={isDestructive ? 'text-destructive' : undefined} className={isDestructive ? 'text-destructive' : undefined}
onClick={(e) => { onClick={(e) => {
e.stopPropagation(); e.stopPropagation();
if (needsConfirmation) { if (locked) {
setUpsellOpen(true);
} else if (needsConfirmation) {
setConfirmAction({ setConfirmAction({
label: action.label, label: action.label,
onConfirm: () => executeItemAction(action, item), onConfirm: () => executeItemAction(action, item),
@@ -1068,6 +1076,7 @@ export function DynamicList({ viewName }: DynamicListProps) {
}} }}
> >
{action.label} {action.label}
{locked && <Lock className="ml-auto h-3 w-3 text-muted-foreground" />}
</DropdownMenuItem> </DropdownMenuItem>
); );
})} })}
@@ -1352,6 +1361,8 @@ export function DynamicList({ viewName }: DynamicListProps) {
</AlertDialogFooter> </AlertDialogFooter>
</AlertDialogContent> </AlertDialogContent>
</AlertDialog> </AlertDialog>
<EnterpriseUpsell open={upsellOpen} onClose={() => setUpsellOpen(false)} />
</div> </div>
); );
} }
+28 -9
View File
@@ -6,15 +6,16 @@
import { useMemo } from 'react'; import { useMemo } from 'react';
import ReactMarkdown from 'react-markdown'; import ReactMarkdown from 'react-markdown';
import { Check, X, HelpCircle, ChevronRight } from 'lucide-react'; import { Check, X, HelpCircle, ChevronRight, Loader2 } from 'lucide-react';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'; import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { jmapMapToArray, SECRET_MASK } from '@/lib/jmapUtils'; import { jmapMapToArray, SECRET_MASK } from '@/lib/jmapUtils';
import { Badge } from '@/components/ui/badge'; import { Badge } from '@/components/ui/badge';
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip'; import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip';
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from '@/components/ui/collapsible'; import { Collapsible, CollapsibleContent, CollapsibleTrigger } from '@/components/ui/collapsible';
import { resolveSchema, resolveVariantForm, resolveForm } from '@/lib/schemaResolver'; import { resolveSchema, resolveVariantForm, resolveForm } from '@/lib/schemaResolver';
import { useObjectList, useObjectLabel } from '@/lib/objectOptions';
import { formatSize, formatDuration } from '@/lib/durationFormat'; import { formatSize, formatDuration } from '@/lib/durationFormat';
import type { Schema, Field, FieldType, FormField, Form, Fields, EnumVariant } from '@/types/schema'; import type { Schema, Field, FieldType, FormField, Form, Fields, EnumVariant, ScalarType } from '@/types/schema';
export interface DynamicViewProps { export interface DynamicViewProps {
schema: Schema; schema: Schema;
@@ -401,7 +402,7 @@ function MapValue({
schema, schema,
}: { }: {
value: unknown; value: unknown;
keyClass: { type: string; enumName?: string }; keyClass: ScalarType;
valueClass: { type: string; objectName?: string }; valueClass: { type: string; objectName?: string };
schema: Schema; schema: Schema;
}) { }) {
@@ -417,12 +418,7 @@ function MapValue({
return ( return (
<div className="space-y-2"> <div className="space-y-2">
{entries.map(([k, v]) => { {entries.map(([k, v]) => {
let keyLabel = k; const keyLabel = <MapKeyLabel keyClass={keyClass} keyValue={k} schema={schema} />;
if (keyClass.type === 'enum' && keyClass.enumName) {
const variants = schema.enums[keyClass.enumName] ?? [];
const variant = variants.find((e: EnumVariant) => e.name === k);
if (variant) keyLabel = variant.label;
}
if (valueClass.type === 'object' && valueClass.objectName) { if (valueClass.type === 'object' && valueClass.objectName) {
return ( return (
@@ -446,6 +442,29 @@ function MapValue({
); );
} }
function MapKeyLabel({ keyClass, keyValue, schema }: { keyClass: ScalarType; keyValue: string; schema: Schema }) {
if (keyClass.type === 'enum') {
const variants = schema.enums[keyClass.enumName] ?? [];
const variant = variants.find((e: EnumVariant) => e.name === keyValue);
return <>{variant?.label ?? keyValue}</>;
}
if (keyClass.type === 'objectId') {
return <ObjectIdKeyLabel objectName={keyClass.objectName} keyValue={keyValue} schema={schema} />;
}
return <>{keyValue}</>;
}
function ObjectIdKeyLabel({ objectName, keyValue, schema }: { objectName: string; keyValue: string; schema: Schema }) {
const list = useObjectList(objectName, schema);
const fromList = list.options.find((o) => o.id === keyValue)?.label;
const { label: cheapLabel, loading } = useObjectLabel(objectName, fromList ? null : keyValue, schema);
const display = fromList ?? cheapLabel;
if (loading && !display) {
return <Loader2 className="h-3 w-3 animate-spin text-muted-foreground" />;
}
return <>{display ?? keyValue}</>;
}
function FieldTooltip({ description }: { description: string }) { function FieldTooltip({ description }: { description: string }) {
return ( return (
<TooltipProvider> <TooltipProvider>
@@ -11,7 +11,7 @@ import { CircleDot, CircleX, Clock } from 'lucide-react';
import { useSchemaStore } from '@/stores/schemaStore'; import { useSchemaStore } from '@/stores/schemaStore';
import type { TraceEvent, TraceKeyValue, TraceValue } from '../types'; import type { TraceEvent, TraceKeyValue, TraceValue } from '../types';
const BASE32_ALPHABET = 'abcdefghijklmnopqrstuvwxyz234567'; const BASE32_ALPHABET = 'abcdefghijklmnopqrstuvwxyz792013';
function intToBase32(input: number | string): string { function intToBase32(input: number | string): string {
let n: bigint; let n: bigint;
+28
View File
@@ -0,0 +1,28 @@
/*
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
*
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
*/
import { useState, type Dispatch, type SetStateAction } from 'react';
export function useBufferedValue<T, S = T>(
value: T,
transform: (v: T) => S = (v) => v as unknown as S,
): [S, Dispatch<SetStateAction<S>>] {
const [prev, setPrev] = useState(value);
const [local, setLocal] = useState<S>(() => transform(value));
if (!Object.is(value, prev)) {
setPrev(value);
setLocal(transform(value));
}
return [local, setLocal];
}
export function useResetOnChange<K>(key: K, reset: () => void): void {
const [prev, setPrev] = useState(key);
if (!Object.is(key, prev)) {
setPrev(key);
reset();
}
}
+8
View File
@@ -294,6 +294,9 @@
"stalwartAlt": "Stalwart Logo" "stalwartAlt": "Stalwart Logo"
}, },
"logout": "Logout", "logout": "Logout",
"version": {
"label": "Stalwart WebUI v{{version}}"
},
"oauth": { "oauth": {
"backToLogin": "Back to login", "backToLogin": "Back to login",
"discoveryFailed": "Discovery failed for \"{{username}}\": {{status}} {{statusText}}", "discoveryFailed": "Discovery failed for \"{{username}}\": {{status}} {{statusText}}",
@@ -305,12 +308,17 @@
"tokenExchangeFailed": "Token exchange failed: {{status}} {{statusText}}" "tokenExchangeFailed": "Token exchange failed: {{status}} {{statusText}}"
}, },
"otp": { "otp": {
"clipboardBlocked": "Your browser blocked clipboard access.",
"codeIncorrect": "That code is incorrect. Make sure your authenticator clock is in sync.", "codeIncorrect": "That code is incorrect. Make sure your authenticator clock is in sync.",
"confirmationCodeLabel": "Confirmation code", "confirmationCodeLabel": "Confirmation code",
"copyFailed": "Copy failed",
"copySecret": "Copy secret",
"currentCodeLabel": "Current code", "currentCodeLabel": "Current code",
"currentCodePrompt": "Enter your current 6-digit code to authorise any change to this account (including disabling two-factor authentication).", "currentCodePrompt": "Enter your current 6-digit code to authorise any change to this account (including disabling two-factor authentication).",
"disable": "Disable", "disable": "Disable",
"enterCodePrompt": "Enter the code shown in your authenticator.", "enterCodePrompt": "Enter the code shown in your authenticator.",
"manualEntryDescription": "If you cannot scan the QR code, enter this secret into your authenticator app instead.",
"manualEntryLabel": "Or enter this code manually",
"qrCodeAlt": "TOTP QR code", "qrCodeAlt": "TOTP QR code",
"scanDescription": "Scan the QR code below with Google Authenticator, 1Password, Authy, or any other TOTP app, then enter the 6-digit code it shows to confirm setup.", "scanDescription": "Scan the QR code below with Google Authenticator, 1Password, Authy, or any other TOTP app, then enter the 6-digit code it shows to confirm setup.",
"scanPrompt": "Scan with your authenticator app", "scanPrompt": "Scan with your authenticator app",
+19 -1
View File
@@ -4,9 +4,27 @@
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL * SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
*/ */
import type { JmapSetError } from '@/types/jmap'; import type { JmapSetError, ValidationError } from '@/types/jmap';
import i18n from '@/i18n'; import i18n from '@/i18n';
export function validationErrorMessage(ve: ValidationError): string {
switch (ve.type) {
case 'Required':
return i18n.t('form.required', 'This field is required.');
case 'MaxLength':
return i18n.t('form.maxLengthIs', 'Maximum length is {{max}}.', { max: ve.required });
case 'MinLength':
return i18n.t('form.minLengthIs', 'Minimum length is {{min}}.', { min: ve.required });
case 'MaxValue':
return i18n.t('form.maxValueIs', 'Maximum value is {{max}}.', { max: ve.required });
case 'MinValue':
return i18n.t('form.minValueIs', 'Minimum value is {{min}}.', { min: ve.required });
default:
if (ve.value && ve.value.length > 0) return ve.value;
return i18n.t('form.invalidValue', 'Invalid value.');
}
}
export function friendlySetError(err: JmapSetError): string { export function friendlySetError(err: JmapSetError): string {
if (err.description) return err.description; if (err.description) return err.description;
switch (err.type) { switch (err.type) {
+155
View File
@@ -0,0 +1,155 @@
/*
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
*
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
*/
import { describe, it, expect } from 'vitest';
import { buildJmapFilter } from './listFilter';
import type { Filter } from '@/types/schema';
const dateFilter: Filter = { type: 'date', field: 'timestamp', label: 'Date' };
const textFilter: Filter = { type: 'text', field: 'text', label: 'Text' };
const intFilter: Filter = { type: 'integer', field: 'size', label: 'Size' };
describe('buildJmapFilter', () => {
it('returns an empty object when nothing is applied', () => {
expect(buildJmapFilter({ appliedFilters: {}, isXPrefixed: true })).toEqual({});
});
it('merges filtersStatic', () => {
const filter = buildJmapFilter({
appliedFilters: {},
filtersStatic: { hasErrors: true },
isXPrefixed: true,
});
expect(filter).toEqual({ hasErrors: true });
});
it('skips empty and Op-only keys', () => {
const filter = buildJmapFilter({
appliedFilters: { text: '', textOp: 'eq' },
filters: [textFilter],
isXPrefixed: true,
});
expect(filter).toEqual({});
});
it('passes text filters through verbatim', () => {
const filter = buildJmapFilter({
appliedFilters: { text: 'hello' },
filters: [textFilter],
isXPrefixed: true,
});
expect(filter).toEqual({ text: 'hello' });
});
it('applies the operator suffix for integer filters', () => {
const filter = buildJmapFilter({
appliedFilters: { size: '1024', sizeOp: 'gt' },
filters: [intFilter],
isXPrefixed: true,
});
expect(filter).toEqual({ sizeIsGreaterThan: '1024' });
});
describe('date filters (x-prefixed, with operator UI)', () => {
it('expands a default date-only equality into a full-day range', () => {
const filter = buildJmapFilter({
appliedFilters: { timestamp: '2026-06-17' },
filters: [dateFilter],
isXPrefixed: true,
});
expect(filter).toEqual({
timestampIsGreaterThanOrEqual: '2026-06-17T00:00:00Z',
timestampIsLessThan: '2026-06-18T00:00:00Z',
});
});
it('treats an explicit eq operator the same as the default', () => {
const filter = buildJmapFilter({
appliedFilters: { timestamp: '2026-06-17', timestampOp: 'eq' },
filters: [dateFilter],
isXPrefixed: true,
});
expect(filter).toEqual({
timestampIsGreaterThanOrEqual: '2026-06-17T00:00:00Z',
timestampIsLessThan: '2026-06-18T00:00:00Z',
});
});
it('appends midnight UTC for the After (gt) operator', () => {
const filter = buildJmapFilter({
appliedFilters: { timestamp: '2026-06-17', timestampOp: 'gt' },
filters: [dateFilter],
isXPrefixed: true,
});
expect(filter).toEqual({ timestampIsGreaterThan: '2026-06-17T00:00:00Z' });
});
it('appends midnight UTC for the Before (lt) operator', () => {
const filter = buildJmapFilter({
appliedFilters: { timestamp: '2026-06-17', timestampOp: 'lt' },
filters: [dateFilter],
isXPrefixed: true,
});
expect(filter).toEqual({ timestampIsLessThan: '2026-06-17T00:00:00Z' });
});
it('rolls over month boundaries', () => {
const filter = buildJmapFilter({
appliedFilters: { timestamp: '2026-06-30' },
filters: [dateFilter],
isXPrefixed: true,
});
expect(filter).toEqual({
timestampIsGreaterThanOrEqual: '2026-06-30T00:00:00Z',
timestampIsLessThan: '2026-07-01T00:00:00Z',
});
});
it('rolls over year boundaries', () => {
const filter = buildJmapFilter({
appliedFilters: { timestamp: '2026-12-31' },
filters: [dateFilter],
isXPrefixed: true,
});
expect(filter).toEqual({
timestampIsGreaterThanOrEqual: '2026-12-31T00:00:00Z',
timestampIsLessThan: '2027-01-01T00:00:00Z',
});
});
it('handles leap-year February', () => {
const filter = buildJmapFilter({
appliedFilters: { timestamp: '2028-02-28' },
filters: [dateFilter],
isXPrefixed: true,
});
expect(filter).toEqual({
timestampIsGreaterThanOrEqual: '2028-02-28T00:00:00Z',
timestampIsLessThan: '2028-02-29T00:00:00Z',
});
});
it('passes a full datetime through with only the operator suffix applied', () => {
const filter = buildJmapFilter({
appliedFilters: { timestamp: '2026-06-17T08:30:00Z', timestampOp: 'gt' },
filters: [dateFilter],
isXPrefixed: true,
});
expect(filter).toEqual({ timestampIsGreaterThan: '2026-06-17T08:30:00Z' });
});
});
describe('date filters (non-x-prefixed, no operator UI)', () => {
it('appends midnight UTC as an exact match without range expansion', () => {
const filter = buildJmapFilter({
appliedFilters: { timestamp: '2026-06-17' },
filters: [dateFilter],
isXPrefixed: false,
});
expect(filter).toEqual({ timestamp: '2026-06-17T00:00:00Z' });
});
});
});
+97
View File
@@ -0,0 +1,97 @@
/*
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
*
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
*/
import type { Filter } from '@/types/schema';
const OP_SUFFIX: Record<string, string> = {
eq: '',
gt: 'IsGreaterThan',
gte: 'IsGreaterThanOrEqual',
lt: 'IsLessThan',
lte: 'IsLessThanOrEqual',
};
const DATE_ONLY = /^\d{4}-\d{2}-\d{2}$/;
function utcDayStart(date: string): string {
return `${date}T00:00:00Z`;
}
function utcNextDayStart(date: string): string {
const dt = new Date(`${date}T00:00:00Z`);
dt.setUTCDate(dt.getUTCDate() + 1);
const y = dt.getUTCFullYear();
const m = String(dt.getUTCMonth() + 1).padStart(2, '0');
const d = String(dt.getUTCDate()).padStart(2, '0');
return `${y}-${m}-${d}T00:00:00Z`;
}
function applyDateFilter(
filter: Record<string, unknown>,
field: string,
value: string,
op: string | undefined,
isXPrefixed: boolean,
): void {
if (!DATE_ONLY.test(value)) {
const suffix = isXPrefixed && op ? (OP_SUFFIX[op] ?? '') : '';
filter[`${field}${suffix}`] = value;
return;
}
if (!isXPrefixed) {
filter[field] = utcDayStart(value);
return;
}
const effectiveOp = op ?? 'eq';
if (effectiveOp === 'eq') {
filter[`${field}IsGreaterThanOrEqual`] = utcDayStart(value);
filter[`${field}IsLessThan`] = utcNextDayStart(value);
return;
}
const suffix = OP_SUFFIX[effectiveOp] ?? '';
filter[`${field}${suffix}`] = utcDayStart(value);
}
export interface BuildJmapFilterArgs {
appliedFilters: Record<string, string>;
filters?: Filter[];
filtersStatic?: Record<string, unknown>;
isXPrefixed: boolean;
}
export function buildJmapFilter({
appliedFilters,
filters,
filtersStatic,
isXPrefixed,
}: BuildJmapFilterArgs): Record<string, unknown> {
const filter: Record<string, unknown> = {};
if (filtersStatic) {
Object.assign(filter, filtersStatic);
}
const dateFields = new Set((filters ?? []).filter((f) => f.type === 'date').map((f) => f.field));
for (const [key, val] of Object.entries(appliedFilters)) {
if (val === '' || val == null) continue;
if (key.endsWith('Op')) continue;
const op = appliedFilters[`${key}Op`];
if (dateFields.has(key)) {
applyDateFilter(filter, key, val, op, isXPrefixed);
continue;
}
const suffix = op ? (OP_SUFFIX[op] ?? '') : '';
filter[`${key}${suffix}`] = val;
}
return filter;
}
+1 -1
View File
@@ -97,7 +97,7 @@ async function fetchObjectList(viewOrObjectName: string, schema: Schema): Promis
const accountId = getAccountId(objectName); const accountId = getAccountId(objectName);
const displayProp = getDisplayProperty(schema, viewOrObjectName); const displayProp = getDisplayProperty(schema, viewOrObjectName);
let items: Array<Record<string, unknown>> = []; let items: Array<Record<string, unknown>>;
try { try {
const result = await jmapQueryAllAndGet( const result = await jmapQueryAllAndGet(
objectName, objectName,
+7 -1
View File
@@ -107,13 +107,19 @@ export async function apiFetch(path: string, options?: RequestInit): Promise<Res
let response = await makeRequest(); let response = await makeRequest();
if (response.status === 401 && useAuthStore.getState().refreshToken) { if (response.status === 401) {
if (useAuthStore.getState().refreshToken) {
try { try {
await refreshAccessToken(); await refreshAccessToken();
response = await makeRequest(); response = await makeRequest();
} catch { } catch {
throw new ApiError(401, 'Unauthorized', null); throw new ApiError(401, 'Unauthorized', null);
} }
} else {
useAuthStore.getState().logout();
window.location.href = `${getBasePath()}/login`;
throw new ApiError(401, 'Unauthorized', null);
}
} }
if (!response.ok) { if (!response.ok) {
+9 -8
View File
@@ -125,8 +125,7 @@ function getRedirectUri(): string {
} }
export async function startAuthFlow(username: string, returnUrl?: string | null): Promise<void> { export async function startAuthFlow(username: string, returnUrl?: string | null): Promise<void> {
const { authorization_endpoint, token_endpoint, end_session_endpoint, scopes_supported } = const { authorization_endpoint, token_endpoint, end_session_endpoint, scopes_supported } = await discover(username);
await discover(username);
const codeVerifier = generateCodeVerifier(); const codeVerifier = generateCodeVerifier();
const { challenge: codeChallenge, method: codeChallengeMethod } = await generateCodeChallenge(codeVerifier); const { challenge: codeChallenge, method: codeChallengeMethod } = await generateCodeChallenge(codeVerifier);
@@ -163,12 +162,14 @@ export async function startAuthFlow(username: string, returnUrl?: string | null)
prompt: 'login', prompt: 'login',
}); });
const scope = let scope: string;
SCOPES && SCOPES.length > 0 if (SCOPES && SCOPES.length > 0) {
? SCOPES scope = SCOPES;
: scopes_supported?.includes('openid') } else if (scopes_supported?.includes('openid')) {
? 'openid' scope = ['openid', 'email', 'profile', 'offline_access'].filter((s) => scopes_supported.includes(s)).join(' ');
: ''; } else {
scope = '';
}
if (scope) { if (scope) {
params.set('scope', scope); params.set('scope', scope);
} }
+11 -1
View File
@@ -10,7 +10,17 @@ import { logJmapExchange } from '@/lib/debug';
import type { JmapMethodCall, JmapMethodResponse, JmapQueryResponse, JmapResponse } from '@/types/jmap'; import type { JmapMethodCall, JmapMethodResponse, JmapQueryResponse, JmapResponse } from '@/types/jmap';
import type { Schema } from '@/types/schema'; import type { Schema } from '@/types/schema';
const JMAP_USING = ['urn:ietf:params:jmap:core', 'urn:stalwart:jmap']; const JMAP_USING = [
'urn:ietf:params:jmap:core',
'urn:stalwart:jmap',
'urn:ietf:params:jmap:blob',
'urn:ietf:params:jmap:mail',
'urn:ietf:params:jmap:calendars',
'urn:ietf:params:jmap:contacts',
'urn:ietf:params:jmap:principals',
'urn:ietf:params:jmap:sieve',
'urn:ietf:params:jmap:vacationresponse',
];
export function getAccountId(objectType: string): string { export function getAccountId(objectType: string): string {
const { primaryAccountId, activeAccountId } = useAuthStore.getState(); const { primaryAccountId, activeAccountId } = useAuthStore.getState();
+1 -1
View File
@@ -60,6 +60,6 @@ export interface JmapSetError {
export interface ValidationError { export interface ValidationError {
type: 'Invalid' | 'Required' | 'MaxLength' | 'MinLength' | 'MaxValue' | 'MinValue'; type: 'Invalid' | 'Required' | 'MaxLength' | 'MinLength' | 'MaxValue' | 'MinValue';
property: string; property: string;
value?: unknown; value?: string;
required?: number; required?: number;
} }
+2
View File
@@ -18,3 +18,5 @@ interface ImportMetaEnv {
interface ImportMeta { interface ImportMeta {
readonly env: ImportMetaEnv; readonly env: ImportMetaEnv;
} }
declare const __APP_VERSION__: string;
+1
View File
@@ -10,6 +10,7 @@
/* Bundler mode */ /* Bundler mode */
"moduleResolution": "bundler", "moduleResolution": "bundler",
"allowImportingTsExtensions": true, "allowImportingTsExtensions": true,
"resolveJsonModule": true,
"verbatimModuleSyntax": true, "verbatimModuleSyntax": true,
"moduleDetection": "force", "moduleDetection": "force",
"noEmit": true, "noEmit": true,
+4
View File
@@ -3,9 +3,13 @@ import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react' import react from '@vitejs/plugin-react'
import tailwindcss from '@tailwindcss/vite' import tailwindcss from '@tailwindcss/vite'
import path from 'path' import path from 'path'
import { version } from './package.json'
export default defineConfig({ export default defineConfig({
base: './', base: './',
define: {
__APP_VERSION__: JSON.stringify(version),
},
plugins: [react(), tailwindcss()], plugins: [react(), tailwindcss()],
resolve: { resolve: {
alias: { alias: {