mirror of
https://github.com/stalwartlabs/webui.git
synced 2026-12-06 16:04:38 +00:00
v2.1.0
This commit is contained in:
1 parent
6b8ad61b57
commit
7e77ffc073
87 files changed
+6591
-596
No files matched your search
@@ -2,6 +2,30 @@
|
||||
|
||||
All notable changes to this project will be documented in this file. This project adheres to [Semantic Versioning](http://semver.org/).
|
||||
|
||||
## [2.1.0] - 2026-11-18
|
||||
|
||||
### Added
|
||||
- Mail Rules editor under Account > Filters & Auto-Replies:
|
||||
- Rules listed as readable sentences, with an enable switch and reordering by drag and drop, keyboard or menu.
|
||||
- Rule builder with "all / any" conditions, exceptions and actions on compact rows.
|
||||
- Blocked senders and Safe senders pages under Account > Filters & Auto-Replies.
|
||||
- Vacation Response page with a date range picker.
|
||||
- Weekly schedule editor for working hours (Account > Calendars > Settings) and mail rule schedules.
|
||||
- Searchable time zone picker that shows UTC offsets and offers the browser's time zone.
|
||||
- Local time and local date fields, with a time input that follows the 12-hour or 24-hour clock of the user's locale.
|
||||
- Pasting several values at once into list fields, with duplicate and invalid entry reporting.
|
||||
|
||||
### Changed
|
||||
- Map entries use the value format their key declares in the schema, so the maximum disk space quota is entered with the size field (unit selector) and shown with units.
|
||||
- Account pages follow the account selected in the top bar, including management settings.
|
||||
- Forms check required fields and minimum item counts inside nested lists before saving.
|
||||
|
||||
### Fixed
|
||||
- Lists below their minimum number of entries are reported on the field before saving.
|
||||
- On phones, select menus no longer cut off long labels, popovers keep a margin from the screen edge, and object pickers no longer show an empty row.
|
||||
- Search boxes use a clear button that matches the theme.
|
||||
- Switching an object to another variant (for example an MTA route from Local to MX) no longer fails with "name: required": unchanged immutable fields are now sent with the new variant.
|
||||
|
||||
## [2.0.6] - 2026-11-13
|
||||
|
||||
### Fixed
|
||||
|
||||
Generated
+58
-2
@@ -1,14 +1,17 @@
|
||||
{
|
||||
"name": "stalwart-webui",
|
||||
"version": "2.0.4",
|
||||
"version": "2.1.0",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "stalwart-webui",
|
||||
"version": "2.0.4",
|
||||
"version": "2.1.0",
|
||||
"dependencies": {
|
||||
"@daypicker/react": "^10.0.2",
|
||||
"@dnd-kit/core": "^6.3.1",
|
||||
"@dnd-kit/sortable": "^10.0.0",
|
||||
"@dnd-kit/utilities": "^3.2.2",
|
||||
"@fontsource-variable/inter": "^5.3.0",
|
||||
"@fontsource-variable/jetbrains-mono": "^5.3.0",
|
||||
"@fontsource-variable/plus-jakarta-sans": "^5.3.0",
|
||||
@@ -387,6 +390,59 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"node_modules/@dnd-kit/accessibility": {
|
||||
"version": "3.1.1",
|
||||
"resolved": "https://registry.npmjs.org/@dnd-kit/accessibility/-/accessibility-3.1.1.tgz",
|
||||
"integrity": "sha512-2P+YgaXF+gRsIihwwY1gCsQSYnu9Zyj2py8kY5fFvUM1qm2WA2u639R6YNVfU4GWr+ZM5mqEsfHZZLoRONbemw==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"tslib": "^2.0.0"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"react": ">=16.8.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@dnd-kit/core": {
|
||||
"version": "6.3.1",
|
||||
"resolved": "https://registry.npmjs.org/@dnd-kit/core/-/core-6.3.1.tgz",
|
||||
"integrity": "sha512-xkGBRQQab4RLwgXxoqETICr6S5JlogafbhNsidmrkVv2YRs5MLwpjoF2qpiGjQt8S9AoxtIV603s0GIUpY5eYQ==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@dnd-kit/accessibility": "^3.1.1",
|
||||
"@dnd-kit/utilities": "^3.2.2",
|
||||
"tslib": "^2.0.0"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"react": ">=16.8.0",
|
||||
"react-dom": ">=16.8.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@dnd-kit/sortable": {
|
||||
"version": "10.0.0",
|
||||
"resolved": "https://registry.npmjs.org/@dnd-kit/sortable/-/sortable-10.0.0.tgz",
|
||||
"integrity": "sha512-+xqhmIIzvAYMGfBYYnbKuNicfSsk4RksY2XdmJhT+HAC01nix6fHCztU68jooFiMUB01Ky3F0FyOvhG/BZrWkg==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@dnd-kit/utilities": "^3.2.2",
|
||||
"tslib": "^2.0.0"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@dnd-kit/core": "^6.3.0",
|
||||
"react": ">=16.8.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@dnd-kit/utilities": {
|
||||
"version": "3.2.2",
|
||||
"resolved": "https://registry.npmjs.org/@dnd-kit/utilities/-/utilities-3.2.2.tgz",
|
||||
"integrity": "sha512-+MKAJEOfaBe5SmV6t34p80MMKhjvUz0vRrvVJbPT0WElzaOJ/1xs+D+KDv+tD/NE5ujfrChEcshd4fLn0wpiqg==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"tslib": "^2.0.0"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"react": ">=16.8.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@emnapi/core": {
|
||||
"version": "1.11.1",
|
||||
"resolved": "https://registry.npmjs.org/@emnapi/core/-/core-1.11.1.tgz",
|
||||
|
||||
+5
-2
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "stalwart-webui",
|
||||
"private": true,
|
||||
"version": "2.0.6",
|
||||
"version": "2.1.0",
|
||||
"stalwart": {
|
||||
"minServerVersion": "1.0.0"
|
||||
},
|
||||
@@ -18,6 +18,9 @@
|
||||
},
|
||||
"dependencies": {
|
||||
"@daypicker/react": "^10.0.2",
|
||||
"@dnd-kit/core": "^6.3.1",
|
||||
"@dnd-kit/sortable": "^10.0.0",
|
||||
"@dnd-kit/utilities": "^3.2.2",
|
||||
"@fontsource-variable/inter": "^5.3.0",
|
||||
"@fontsource-variable/jetbrains-mono": "^5.3.0",
|
||||
"@fontsource-variable/plus-jakarta-sans": "^5.3.0",
|
||||
@@ -78,4 +81,4 @@
|
||||
"typescript-eslint": "^8.71.2",
|
||||
"vite": "^8.3.4"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -36,9 +36,12 @@ export function ObjectPicker({ schema, objectName, label, value, onChange, onCle
|
||||
const noPermissionMessage = useNoPermissionMessage(schema, objectName);
|
||||
|
||||
return (
|
||||
<ObjectFieldFrame disabled={!!noPermissionMessage}>
|
||||
<ObjectFieldFrame disabled={!!noPermissionMessage} single>
|
||||
{value && (
|
||||
<Badge variant="secondary" className="h-7 max-w-xs gap-1 pl-3 pr-1 text-[13px] font-medium">
|
||||
<Badge
|
||||
variant="secondary"
|
||||
className="h-7 min-w-0 max-w-full gap-1 sm:max-w-xs pl-3 pr-1 text-[13px] font-medium"
|
||||
>
|
||||
{labelLoading ? (
|
||||
<Loader2 className="h-3 w-3 animate-spin" aria-hidden="true" />
|
||||
) : (
|
||||
|
||||
@@ -30,12 +30,21 @@ export interface ObjectSearchPopoverProps {
|
||||
placeholder?: string;
|
||||
}
|
||||
|
||||
export function ObjectFieldFrame({ disabled, children }: { disabled?: boolean; children: ReactNode }) {
|
||||
export function ObjectFieldFrame({
|
||||
disabled,
|
||||
single,
|
||||
children,
|
||||
}: {
|
||||
disabled?: boolean;
|
||||
single?: boolean;
|
||||
children: ReactNode;
|
||||
}) {
|
||||
return (
|
||||
<div
|
||||
data-slot="object-field"
|
||||
className={cn(
|
||||
'field-surface flex min-h-9 w-full flex-wrap items-center gap-1.5 rounded-lg p-1',
|
||||
'field-surface flex min-h-9 w-full items-center gap-1.5 rounded-lg p-1',
|
||||
single ? 'flex-nowrap' : 'flex-wrap',
|
||||
disabled && 'opacity-60',
|
||||
)}
|
||||
>
|
||||
@@ -45,7 +54,11 @@ export function ObjectFieldFrame({ disabled, children }: { disabled?: boolean; c
|
||||
}
|
||||
|
||||
const INLINE_TRIGGER =
|
||||
'h-7 min-w-[6rem] flex-1 justify-between gap-2 rounded-md px-2 text-sm font-normal text-dim shadow-none hover:bg-transparent hover:text-foreground focus-visible:ring-0 focus-visible:ring-offset-0';
|
||||
'h-7 flex-1 justify-between gap-2 rounded-md px-2 text-sm font-normal text-dim shadow-none hover:bg-transparent hover:text-foreground focus-visible:ring-0 focus-visible:ring-offset-0';
|
||||
|
||||
function inlineTrigger(placeholder: string): string {
|
||||
return cn(INLINE_TRIGGER, placeholder ? 'min-w-[6rem]' : 'min-w-8 justify-end');
|
||||
}
|
||||
|
||||
export function ObjectSearchPopover({
|
||||
options,
|
||||
@@ -74,7 +87,7 @@ export function ObjectSearchPopover({
|
||||
size={placeholder === undefined ? 'icon' : 'sm'}
|
||||
className={cn(
|
||||
'cursor-not-allowed',
|
||||
placeholder === undefined ? 'h-8 w-8 bg-muted opacity-60' : INLINE_TRIGGER,
|
||||
placeholder === undefined ? 'h-8 w-8 bg-muted opacity-60' : inlineTrigger(placeholder),
|
||||
)}
|
||||
aria-label={label}
|
||||
aria-disabled="true"
|
||||
@@ -109,7 +122,7 @@ export function ObjectSearchPopover({
|
||||
className={
|
||||
placeholder === undefined
|
||||
? 'h-8 w-8 bg-muted hover:bg-highlight hover:text-highlight-foreground'
|
||||
: INLINE_TRIGGER
|
||||
: inlineTrigger(placeholder)
|
||||
}
|
||||
aria-label={label}
|
||||
disabled={disabled}
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
/*
|
||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
import { useRef, type ComponentProps } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Search, X } from 'lucide-react';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
type SearchInputProps = Omit<ComponentProps<typeof Input>, 'type' | 'value' | 'onChange'> & {
|
||||
value: string;
|
||||
onValueChange: (value: string) => void;
|
||||
icon?: boolean;
|
||||
};
|
||||
|
||||
export function SearchInput({ value, onValueChange, icon = false, className, ...props }: SearchInputProps) {
|
||||
const { t } = useTranslation();
|
||||
const input = useRef<HTMLInputElement>(null);
|
||||
const clear = () => {
|
||||
onValueChange('');
|
||||
input.current?.focus();
|
||||
};
|
||||
return (
|
||||
<div data-slot="search-input" className="relative w-full">
|
||||
{icon && (
|
||||
<Search
|
||||
className="pointer-events-none absolute left-3 top-1/2 size-4 -translate-y-1/2 text-dim"
|
||||
aria-hidden="true"
|
||||
/>
|
||||
)}
|
||||
<Input
|
||||
{...props}
|
||||
ref={input}
|
||||
type="search"
|
||||
value={value}
|
||||
onChange={(event) => onValueChange(event.target.value)}
|
||||
className={cn(
|
||||
'[&::-webkit-search-cancel-button]:appearance-none',
|
||||
icon && 'pl-9',
|
||||
value !== '' && 'pr-9',
|
||||
className,
|
||||
)}
|
||||
/>
|
||||
{value !== '' && !props.disabled && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={clear}
|
||||
aria-label={t('common.clearSearch', 'Clear search')}
|
||||
className="absolute right-1.5 top-1/2 grid size-6 -translate-y-1/2 place-items-center rounded-md text-dim transition-colors hover:bg-muted hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
|
||||
>
|
||||
<X className="size-3.5" aria-hidden="true" />
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -4,7 +4,7 @@
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
import { useEffect, useId, useState, useSyncExternalStore } from 'react';
|
||||
import { useEffect, useId, useState, useSyncExternalStore, type ComponentType } from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { ArrowLeft, Check, Loader2, RefreshCw, Trash2 } from 'lucide-react';
|
||||
@@ -19,15 +19,21 @@ import { FormProvider } from '@/components/forms/FormProvider';
|
||||
import { FormSections } from '@/components/forms/FormSections';
|
||||
import { UnsavedChangesDialog } from '@/components/forms/UnsavedChangesDialog';
|
||||
import { formFieldLabels } from '@/components/forms/formLogic';
|
||||
import { useDynamicForm, type DynamicFormModel } from '@/components/forms/useDynamicForm';
|
||||
import type { RenderableSection } from '@/components/forms/formLogic';
|
||||
import { useDynamicForm, type DynamicFormModel, type DynamicFormOptions } from '@/components/forms/useDynamicForm';
|
||||
import type { FieldValues, RenderableSection } from '@/components/forms/formLogic';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
const SECTION_INDEX_MIN = 3;
|
||||
|
||||
interface DynamicFormProps {
|
||||
export interface AfterSectionsProps {
|
||||
data: FieldValues;
|
||||
readOnly: boolean;
|
||||
}
|
||||
|
||||
interface DynamicFormProps extends DynamicFormOptions {
|
||||
viewName: string;
|
||||
objectId: string | null;
|
||||
afterSections?: ComponentType<AfterSectionsProps>;
|
||||
}
|
||||
|
||||
function capitalize(text: string): string {
|
||||
@@ -132,12 +138,19 @@ function Loading({ label }: { label: string }) {
|
||||
);
|
||||
}
|
||||
|
||||
export function DynamicForm({ viewName, objectId }: DynamicFormProps) {
|
||||
export function DynamicForm({
|
||||
viewName,
|
||||
objectId,
|
||||
accountId,
|
||||
fieldOverrides,
|
||||
createValues,
|
||||
afterSections: AfterSections,
|
||||
}: DynamicFormProps) {
|
||||
const { t } = useTranslation();
|
||||
const navigate = useNavigate();
|
||||
const canUpdate = useCanAccess(viewName, 'Update');
|
||||
const canDestroy = useCanAccess(viewName, 'Destroy');
|
||||
const model = useDynamicForm(viewName, objectId);
|
||||
const model = useDynamicForm(viewName, objectId, { accountId, fieldOverrides, createValues });
|
||||
const { schema, resolved, mode, isSingleton, state, isDirty, saving, loading, loadError } = model;
|
||||
const [deleteConfirmOpen, setDeleteConfirmOpen] = useState(false);
|
||||
const title = useFormTitle(model);
|
||||
@@ -223,12 +236,14 @@ export function DynamicForm({ viewName, objectId }: DynamicFormProps) {
|
||||
errors={state.fieldErrors}
|
||||
readOnly={readOnly}
|
||||
onFieldChange={model.setField}
|
||||
renderers={fieldOverrides?.render}
|
||||
variant={
|
||||
sch.type === 'multiple'
|
||||
? { variants: sch.variants, value: state.variant, onChange: model.setVariant }
|
||||
: undefined
|
||||
}
|
||||
/>
|
||||
{AfterSections && <AfterSections data={state.data} readOnly={readOnly} />}
|
||||
</FormProvider>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -11,10 +11,9 @@ import { Label } from '@/components/ui/label';
|
||||
import { Markdown } from '@/components/common/Markdown';
|
||||
import { HelpTooltip } from '@/components/common/HelpTooltip';
|
||||
import { FieldValue } from '@/components/values/FieldValue';
|
||||
import { SievepadButton } from '@/components/forms/SievepadButton';
|
||||
import { FieldScopeProvider } from '@/components/forms/FormProvider';
|
||||
import { FieldControl } from '@/components/forms/widgets/FieldControl';
|
||||
import { widgetTraits } from '@/components/forms/widgets/registry';
|
||||
import { resolveWidget } from '@/extensions/widgets';
|
||||
import { fieldIds, isEnterpriseLockedIn, useFieldScope, useFormContext } from '@/components/forms/formContext';
|
||||
import { requiredMarker } from '@/components/forms/formLogic';
|
||||
import { resolveObject } from '@/lib/schemaResolver';
|
||||
@@ -94,7 +93,7 @@ export function FieldRow({ field, formField, value, onChange, error, readOnly: f
|
||||
referencesLocked ||
|
||||
field.update === 'serverSet' ||
|
||||
(topLevel && ctx.mode === 'edit' && field.update === 'immutable');
|
||||
const traits = widgetTraits(ft);
|
||||
const { traits, RowAddon } = resolveWidget(ft);
|
||||
const asValue = readOnly && traits.readOnlyAsValue;
|
||||
const marker = requiredMarker(field, readOnly);
|
||||
const describedBy =
|
||||
@@ -107,19 +106,12 @@ export function FieldRow({ field, formField, value, onChange, error, readOnly: f
|
||||
'aria-required': marker === 'required' && ARIA_REQUIRED_TYPES.has(ft.type) ? true : undefined,
|
||||
};
|
||||
|
||||
const widgetProps = { type: ft, field, formField, value, onChange, readOnly, control, error };
|
||||
let body: ReactNode = asValue ? (
|
||||
<FieldValue schema={ctx.schema} type={ft} value={value} />
|
||||
) : (
|
||||
<FieldScopeProvider name={formField.name} readOnly={readOnly}>
|
||||
<FieldControl
|
||||
type={ft}
|
||||
field={field}
|
||||
formField={formField}
|
||||
value={value}
|
||||
onChange={onChange}
|
||||
readOnly={readOnly}
|
||||
control={control}
|
||||
/>
|
||||
<FieldControl {...widgetProps} />
|
||||
</FieldScopeProvider>
|
||||
);
|
||||
if (!asValue && traits.labelMode === 'group') {
|
||||
@@ -134,6 +126,7 @@ export function FieldRow({ field, formField, value, onChange, error, readOnly: f
|
||||
return (
|
||||
<div data-slot="field-row" className="space-y-1.5 py-4">
|
||||
{body}
|
||||
{RowAddon && <RowAddon {...widgetProps} />}
|
||||
<FieldError id={ids.errorId} error={error} />
|
||||
</div>
|
||||
);
|
||||
@@ -165,9 +158,7 @@ export function FieldRow({ field, formField, value, onChange, error, readOnly: f
|
||||
</div>
|
||||
<div className={cn('min-w-0 space-y-1.5', layout === 'inline' && 'pt-0.5', asValue && '@xl:pt-2')}>
|
||||
<div className={cn(locked && 'opacity-60')}>{body}</div>
|
||||
{ft.type === 'string' && ft.format === 'sieve' && (
|
||||
<SievepadButton scriptName={ctx.recordLabel} source={typeof value === 'string' ? value : ''} />
|
||||
)}
|
||||
{RowAddon && <RowAddon {...widgetProps} />}
|
||||
{layout !== 'inline' && <FieldError id={ids.errorId} error={error} />}
|
||||
</div>
|
||||
{layout === 'inline' && error && (
|
||||
|
||||
@@ -10,6 +10,7 @@ import { VariantSelect } from '@/components/forms/VariantSelect';
|
||||
import type { EmbeddedVariant } from '@/lib/embeddedSchema';
|
||||
import { cn } from '@/lib/utils';
|
||||
import type { FieldErrors, FieldValues, RenderableSection } from '@/components/forms/formLogic';
|
||||
import type { FieldOverrides } from '@/components/forms/useDynamicForm';
|
||||
|
||||
interface VariantControl {
|
||||
variants: readonly EmbeddedVariant[];
|
||||
@@ -25,6 +26,7 @@ interface FormSectionsProps {
|
||||
readOnly: boolean;
|
||||
onFieldChange: (name: string, value: unknown) => void;
|
||||
variant?: VariantControl;
|
||||
renderers?: FieldOverrides['render'];
|
||||
}
|
||||
|
||||
export function FormSections({
|
||||
@@ -35,6 +37,7 @@ export function FormSections({
|
||||
readOnly,
|
||||
onFieldChange,
|
||||
variant,
|
||||
renderers,
|
||||
}: FormSectionsProps) {
|
||||
return (
|
||||
<>
|
||||
@@ -54,6 +57,20 @@ export function FormSections({
|
||||
/>
|
||||
);
|
||||
}
|
||||
const Render = renderers && Object.hasOwn(renderers, formField.name) ? renderers[formField.name] : null;
|
||||
if (Render) {
|
||||
return (
|
||||
<Render
|
||||
key={formField.name}
|
||||
field={field}
|
||||
formField={formField}
|
||||
data={data}
|
||||
errors={errors}
|
||||
readOnly={readOnly}
|
||||
onFieldChange={onFieldChange}
|
||||
/>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<FieldRow
|
||||
key={formField.name}
|
||||
|
||||
@@ -14,6 +14,8 @@ import { Label } from '@/components/ui/label';
|
||||
import { ConfirmDialog } from '@/components/common/ConfirmDialog';
|
||||
import { toast } from '@/hooks/use-toast';
|
||||
import { dismissSievepadWarning, isSievepadWarningDismissed, openInSievepad } from '@/lib/sievepad';
|
||||
import { useFormContext } from '@/components/forms/formContext';
|
||||
import type { WidgetProps } from '@/components/forms/widgets/types';
|
||||
|
||||
interface SievepadButtonProps {
|
||||
scriptName: string;
|
||||
@@ -78,3 +80,8 @@ export function SievepadButton({ scriptName, source }: SievepadButtonProps) {
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export function SievepadRowAddon({ value }: WidgetProps) {
|
||||
const { recordLabel } = useFormContext();
|
||||
return <SievepadButton scriptName={recordLabel} source={typeof value === 'string' ? value : ''} />;
|
||||
}
|
||||
@@ -32,6 +32,8 @@ export const FieldScopeContext = createContext<FieldScope>({ path: [], readOnly:
|
||||
|
||||
export const PanelContext = createContext(false);
|
||||
|
||||
export const EnclosingSchemaContext = createContext<string | null>(null);
|
||||
|
||||
export function useFormContext(): FormContextValue {
|
||||
const ctx = useContext(FormContext);
|
||||
if (!ctx) throw new Error('Form widgets must be rendered inside a FormProvider');
|
||||
@@ -46,6 +48,10 @@ export function useInPanel(): boolean {
|
||||
return useContext(PanelContext);
|
||||
}
|
||||
|
||||
export function useEnclosingSchema(): string | null {
|
||||
return useContext(EnclosingSchemaContext);
|
||||
}
|
||||
|
||||
export function isEnterpriseLockedIn(ctx: FormContextValue, enterprise: boolean | undefined): boolean {
|
||||
return !!enterprise && ctx.isCommunity;
|
||||
}
|
||||
|
||||
@@ -9,10 +9,22 @@ import { deepMerge, resolveForm, resolveObject, type ResolvedView } from '@/lib/
|
||||
import { SECRET_MASK } from '@/lib/jmapUtils';
|
||||
import { embeddedEntries, isRecord, resolveEmbedded } from '@/lib/embeddedSchema';
|
||||
import { isMissingValue, isRequiredField, isUnchangedSecret } from '@/lib/fieldRules';
|
||||
import { widgetTraits } from '@/components/forms/widgets/registry';
|
||||
import { parseLocalDate, parseLocalTime } from '@/lib/localDateTime';
|
||||
import { WORKING_HOURS_SLOT, isScheduleInvalid, scheduleRules } from '@/lib/weeklySchedule';
|
||||
import { widgetTraits } from '@/extensions/widgets';
|
||||
import type { BlobUpload } from '@/services/jmap/client';
|
||||
import type { JmapSetError, ValidationError } from '@/types/jmap';
|
||||
import type { Field, FieldType, Fields, Form, FormField, Schema } from '@/types/schema';
|
||||
import type {
|
||||
Field,
|
||||
FieldType,
|
||||
Fields,
|
||||
Form,
|
||||
FormField,
|
||||
MapValueType,
|
||||
ScalarType,
|
||||
Schema,
|
||||
StringFormat,
|
||||
} from '@/types/schema';
|
||||
import type { FormMode } from '@/components/forms/formContext';
|
||||
|
||||
export type FieldValues = Record<string, unknown>;
|
||||
@@ -68,40 +80,180 @@ export function requiredMarker(field: Field, readOnly: boolean): 'required' | 'o
|
||||
return isNullable(field.type) ? 'optional' : 'required';
|
||||
}
|
||||
|
||||
function itemCount(value: unknown): number {
|
||||
return isRecord(value) ? Object.keys(value).length : 0;
|
||||
}
|
||||
|
||||
function isMissingNestedValue(schema: Schema, field: Field, value: unknown): boolean {
|
||||
if (field.update === 'serverSet') return false;
|
||||
if (isRequiredField(field) && isMissingValue(value)) return true;
|
||||
const { type } = field;
|
||||
switch (type.type) {
|
||||
case 'object':
|
||||
return hasMissingNested(schema, type.objectName, value);
|
||||
case 'objectList':
|
||||
return (
|
||||
(type.minItems != null && itemCount(value) < type.minItems) ||
|
||||
(isRecord(value) && Object.values(value).some((item) => hasMissingNested(schema, type.objectName, item)))
|
||||
);
|
||||
case 'set':
|
||||
return type.minItems != null && itemCount(value) < type.minItems;
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
export function missingNestedFields(schema: Schema, objectName: string, value: unknown): string[] {
|
||||
if (!isRecord(value)) return [];
|
||||
const resolved = resolveEmbedded(schema, objectName, value);
|
||||
if (!resolved) return [];
|
||||
return embeddedEntries(resolved)
|
||||
.filter(({ formField, field }) => isMissingNestedValue(schema, field, value[formField.name]))
|
||||
.map(({ formField }) => formField.name);
|
||||
}
|
||||
|
||||
function hasMissingNested(schema: Schema, objectName: string, value: unknown): boolean {
|
||||
if (!isRecord(value)) return false;
|
||||
const resolved = resolveEmbedded(schema, objectName, value);
|
||||
if (!resolved) return false;
|
||||
for (const { formField, field } of embeddedEntries(resolved)) {
|
||||
if (field.update === 'serverSet') continue;
|
||||
const nested = value[formField.name];
|
||||
if (isRequiredField(field) && isMissingValue(nested)) return true;
|
||||
if (field.type.type === 'object' && hasMissingNested(schema, field.type.objectName, nested)) return true;
|
||||
}
|
||||
return false;
|
||||
return embeddedEntries(resolved).some(({ formField, field }) =>
|
||||
isMissingNestedValue(schema, field, value[formField.name]),
|
||||
);
|
||||
}
|
||||
|
||||
export function mergeFieldErrors(required: FieldErrors, custom: FieldErrors, format: FieldErrors): FieldErrors {
|
||||
return { ...required, ...custom, ...format };
|
||||
}
|
||||
|
||||
export interface RequiredMessages {
|
||||
required: string;
|
||||
minItems: (count: number) => string;
|
||||
}
|
||||
|
||||
function tooFewItems(type: FieldType, value: unknown): number | null {
|
||||
if (type.type !== 'set' && type.type !== 'objectList') return null;
|
||||
return type.minItems != null && itemCount(value) < type.minItems ? type.minItems : null;
|
||||
}
|
||||
|
||||
export function validateRequired(
|
||||
data: FieldValues,
|
||||
fields: Fields,
|
||||
mode: FormMode,
|
||||
message: string,
|
||||
messages: RequiredMessages | string,
|
||||
visible?: ReadonlySet<string>,
|
||||
schema?: Schema,
|
||||
): FieldErrors {
|
||||
const required = typeof messages === 'string' ? messages : messages.required;
|
||||
const errors: FieldErrors = {};
|
||||
for (const [name, field] of Object.entries(fields.properties)) {
|
||||
if (visible && !visible.has(name)) continue;
|
||||
const value = data[name];
|
||||
if (isRequiredField(field, mode) && isMissingValue(value)) {
|
||||
errors[name] = required;
|
||||
continue;
|
||||
}
|
||||
if (!schema || field.update === 'serverSet' || (mode === 'edit' && field.update === 'immutable')) continue;
|
||||
const { type } = field;
|
||||
const minItems = tooFewItems(type, value);
|
||||
if (minItems !== null) {
|
||||
errors[name] = typeof messages === 'string' ? messages : messages.minItems(minItems);
|
||||
} else if ((type.type === 'object' || type.type === 'objectList') && isMissingNestedValue(schema, field, value)) {
|
||||
errors[name] = required;
|
||||
}
|
||||
}
|
||||
return errors;
|
||||
}
|
||||
|
||||
export type ValidatedFormat = Extract<StringFormat, 'localTime' | 'localDate'> | 'weeklySchedule';
|
||||
export type FormatMessages = Record<ValidatedFormat, string>;
|
||||
|
||||
function invalidString(format: StringFormat, value: unknown): ValidatedFormat | null {
|
||||
if (typeof value !== 'string' || value === '') return null;
|
||||
switch (format) {
|
||||
case 'localTime':
|
||||
return parseLocalTime(value) === null ? format : null;
|
||||
case 'localDate':
|
||||
return parseLocalDate(value) === null ? format : null;
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function invalidScalar(type: ScalarType | MapValueType, value: unknown): ValidatedFormat | null {
|
||||
return type.type === 'string' ? invalidString(type.format, value) : null;
|
||||
}
|
||||
|
||||
function invalidNested(schema: Schema, objectName: string, value: unknown): ValidatedFormat | null {
|
||||
if (!isRecord(value)) return null;
|
||||
const resolved = resolveEmbedded(schema, objectName, value);
|
||||
if (!resolved) return null;
|
||||
for (const { formField, field } of embeddedEntries(resolved)) {
|
||||
if (field.update === 'serverSet') continue;
|
||||
const invalid = invalidValue(schema, field.type, value[formField.name], resolved.schemaName);
|
||||
if (invalid) return invalid;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function invalidValue(
|
||||
schema: Schema,
|
||||
type: FieldType,
|
||||
value: unknown,
|
||||
container: string | null,
|
||||
): ValidatedFormat | null {
|
||||
switch (type.type) {
|
||||
case 'string':
|
||||
return invalidString(type.format, value);
|
||||
case 'object':
|
||||
return invalidNested(schema, type.objectName, value);
|
||||
case 'objectList':
|
||||
if (!isRecord(value)) return null;
|
||||
if (type.objectName === WORKING_HOURS_SLOT && isScheduleInvalid(value, scheduleRules(container), type.minItems)) {
|
||||
return 'weeklySchedule';
|
||||
}
|
||||
for (const item of Object.values(value)) {
|
||||
const invalid = invalidNested(schema, type.objectName, item);
|
||||
if (invalid) return invalid;
|
||||
}
|
||||
return null;
|
||||
case 'set':
|
||||
if (!isRecord(value)) return null;
|
||||
for (const key of Object.keys(value)) {
|
||||
const invalid = invalidScalar(type.class, key);
|
||||
if (invalid) return invalid;
|
||||
}
|
||||
return null;
|
||||
case 'map': {
|
||||
if (!isRecord(value)) return null;
|
||||
const { keyClass, valueClass } = type;
|
||||
for (const [key, item] of Object.entries(value)) {
|
||||
const invalid =
|
||||
invalidScalar(keyClass, key) ??
|
||||
(valueClass.type === 'object'
|
||||
? invalidNested(schema, valueClass.objectName, item)
|
||||
: invalidScalar(valueClass, item));
|
||||
if (invalid) return invalid;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export function validateFormat(
|
||||
data: FieldValues,
|
||||
fields: Fields,
|
||||
schema: Schema,
|
||||
messages: FormatMessages,
|
||||
visible?: ReadonlySet<string>,
|
||||
): FieldErrors {
|
||||
const errors: FieldErrors = {};
|
||||
for (const [name, field] of Object.entries(fields.properties)) {
|
||||
if (visible && !visible.has(name)) continue;
|
||||
if (isRequiredField(field, mode) && isMissingValue(data[name])) errors[name] = message;
|
||||
else if (
|
||||
schema &&
|
||||
field.type.type === 'object' &&
|
||||
field.update !== 'serverSet' &&
|
||||
!(mode === 'edit' && field.update === 'immutable') &&
|
||||
hasMissingNested(schema, field.type.objectName, data[name])
|
||||
) {
|
||||
errors[name] = message;
|
||||
}
|
||||
if (field.update === 'serverSet') continue;
|
||||
const invalid = invalidValue(schema, field.type, data[name], null);
|
||||
if (invalid) errors[name] = messages[invalid];
|
||||
}
|
||||
return errors;
|
||||
}
|
||||
@@ -153,7 +305,6 @@ export function buildUpdatePatch(original: FieldValues, data: FieldValues, field
|
||||
if (key === 'id') continue;
|
||||
const field = fields?.properties[key];
|
||||
if (field?.update === 'serverSet') continue;
|
||||
if (field?.update === 'immutable' && valuesEqual(original[key], value)) continue;
|
||||
if (field && isUnchangedSecret(field, value)) continue;
|
||||
patch[key] = value === undefined ? null : withoutMaskedSecrets(value);
|
||||
}
|
||||
@@ -202,9 +353,11 @@ export function mapSetError(
|
||||
): { general: string; fieldErrors: FieldErrors } {
|
||||
const fieldErrors: FieldErrors = {};
|
||||
const extra: string[] = [];
|
||||
const validated = new Set(error.validationErrors?.map((ve) => ve.property));
|
||||
for (const prop of error.properties ?? []) {
|
||||
const top = prop.split('/')[0];
|
||||
if (top && knownFields.has(top)) fieldErrors[top] = error.description ?? messages.invalidValue;
|
||||
else if (!validated.has(prop)) extra.push(`${prop}: ${messages.invalidValue}`);
|
||||
}
|
||||
for (const ve of error.validationErrors ?? []) {
|
||||
if (!ve.property) continue;
|
||||
@@ -228,6 +381,17 @@ export function combineForms(parent: Form | null, variant: Form | null): Form |
|
||||
};
|
||||
}
|
||||
|
||||
export function validatedFieldNames(
|
||||
formNames: ReadonlySet<string>,
|
||||
fields: Fields,
|
||||
hidden: ReadonlySet<string>,
|
||||
): ReadonlySet<string> | undefined {
|
||||
if (hidden.size === 0) return formNames.size > 0 ? formNames : undefined;
|
||||
const names = new Set(formNames.size > 0 ? formNames : Object.keys(fields.properties));
|
||||
for (const name of hidden) names.delete(name);
|
||||
return names;
|
||||
}
|
||||
|
||||
export function formFieldNames(...forms: (Form | null | undefined)[]): Set<string> {
|
||||
const names = new Set<string>();
|
||||
for (const form of forms) {
|
||||
@@ -297,13 +461,20 @@ export interface RenderableSection {
|
||||
fields: RenderableField[];
|
||||
}
|
||||
|
||||
export function buildSections(form: Form | null, fields: Fields | null, mode: FormMode): RenderableSection[] {
|
||||
const NO_HIDDEN_FIELDS: ReadonlySet<string> = new Set();
|
||||
|
||||
export function buildSections(
|
||||
form: Form | null,
|
||||
fields: Fields | null,
|
||||
mode: FormMode,
|
||||
hidden: ReadonlySet<string> = NO_HIDDEN_FIELDS,
|
||||
): RenderableSection[] {
|
||||
const visible = (field: Field) =>
|
||||
mode === 'create' ? field.update !== 'serverSet' : !widgetTraits(field.type).createOnly;
|
||||
if (!form) {
|
||||
if (!fields) return [];
|
||||
const all = Object.entries(fields.properties)
|
||||
.filter(([, field]) => visible(field))
|
||||
.filter(([name, field]) => !hidden.has(name) && visible(field))
|
||||
.map(([name, field]) => ({ formField: { name, label: name }, field }));
|
||||
return all.length > 0 ? [{ key: 'section-0', fields: all }] : [];
|
||||
}
|
||||
@@ -315,6 +486,7 @@ export function buildSections(form: Form | null, fields: Fields | null, mode: Fo
|
||||
rendered.push({ formField: ff, field: null });
|
||||
continue;
|
||||
}
|
||||
if (hidden.has(ff.name)) continue;
|
||||
const field = fields?.properties[ff.name];
|
||||
if (field && visible(field)) rendered.push({ formField: ff, field });
|
||||
}
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
import { useEffect, useReducer } from 'react';
|
||||
import { useEffect, useReducer, type ComponentType } from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { useSchemaStore } from '@/stores/schemaStore';
|
||||
@@ -14,6 +14,7 @@ import { toast } from '@/hooks/use-toast';
|
||||
import {
|
||||
buildCreateDefaults,
|
||||
buildEmbeddedDefaults,
|
||||
deepMerge,
|
||||
getDisplayProperty,
|
||||
resolveForm,
|
||||
resolveVariantForm,
|
||||
@@ -37,21 +38,31 @@ import {
|
||||
formFieldNames,
|
||||
isOtpAuthValid,
|
||||
mapSetError,
|
||||
mergeFieldErrors,
|
||||
validateFormat,
|
||||
validateRequired,
|
||||
validatedFieldNames,
|
||||
VARIANT_FIELD,
|
||||
type FieldErrors,
|
||||
type FieldValues,
|
||||
} from '@/components/forms/formLogic';
|
||||
import { formReducer, initialFormState, isFormDirty, type FormState } from '@/components/forms/formReducer';
|
||||
import { useUnsavedChangesGuard } from '@/components/forms/useUnsavedChangesGuard';
|
||||
import type { FormMode } from '@/components/forms/formContext';
|
||||
import type { JmapSetError } from '@/types/jmap';
|
||||
import type { Fields, Form, Schema } from '@/types/schema';
|
||||
import type { Field, Fields, Form, FormField, Schema } from '@/types/schema';
|
||||
|
||||
const CREATE_ID = 'new-0';
|
||||
const NOISY_CREATED_KEYS = new Set(['id', 'blobId']);
|
||||
|
||||
function createDefaults(schema: Schema, view: ResolvedView, variant: string | undefined): FieldValues {
|
||||
const data = buildCreateDefaults(schema, view.object, view.resolvedSchema, variant, view.list?.filtersStatic);
|
||||
function createDefaults(
|
||||
schema: Schema,
|
||||
view: ResolvedView,
|
||||
variant: string | undefined,
|
||||
createValues: FieldValues | undefined,
|
||||
): FieldValues {
|
||||
const defaults = buildCreateDefaults(schema, view.object, view.resolvedSchema, variant, view.list?.filtersStatic);
|
||||
const data = createValues ? deepMerge(defaults, createValues) : defaults;
|
||||
if (variant) data[VARIANT_FIELD] = variant;
|
||||
return data;
|
||||
}
|
||||
@@ -63,10 +74,15 @@ function initialCreateVariant(view: ResolvedView): string | undefined {
|
||||
return typeof fromFilter === 'string' ? fromFilter : (resolvedSchema.variants[0]?.name ?? '');
|
||||
}
|
||||
|
||||
function initialState(schema: Schema | null, view: ResolvedView | null, mode: FormMode): FormState {
|
||||
function initialState(
|
||||
schema: Schema | null,
|
||||
view: ResolvedView | null,
|
||||
mode: FormMode,
|
||||
createValues: FieldValues | undefined,
|
||||
): FormState {
|
||||
if (mode !== 'create' || !schema || !view) return initialFormState();
|
||||
const variant = initialCreateVariant(view);
|
||||
return initialFormState(createDefaults(schema, view, variant), variant ?? '', view);
|
||||
return initialFormState(createDefaults(schema, view, variant, createValues), variant ?? '', view);
|
||||
}
|
||||
|
||||
function loadedVariant(view: ResolvedView, data: FieldValues): string {
|
||||
@@ -75,7 +91,32 @@ function loadedVariant(view: ResolvedView, data: FieldValues): string {
|
||||
return typeof type === 'string' ? type : (view.resolvedSchema.variants[0]?.name ?? '');
|
||||
}
|
||||
|
||||
export function useDynamicForm(viewName: string, objectId: string | null) {
|
||||
export interface FieldRenderProps {
|
||||
field: Field;
|
||||
formField: FormField;
|
||||
data: FieldValues;
|
||||
errors: FieldErrors;
|
||||
readOnly: boolean;
|
||||
onFieldChange: (name: string, value: unknown) => void;
|
||||
}
|
||||
|
||||
export interface FieldOverrides {
|
||||
hidden?: readonly string[];
|
||||
render?: Readonly<Record<string, ComponentType<FieldRenderProps>>>;
|
||||
validate?: (data: FieldValues) => FieldErrors;
|
||||
}
|
||||
|
||||
export interface DynamicFormOptions {
|
||||
accountId?: string;
|
||||
fieldOverrides?: FieldOverrides;
|
||||
createValues?: FieldValues;
|
||||
}
|
||||
|
||||
export function useDynamicForm(
|
||||
viewName: string,
|
||||
objectId: string | null,
|
||||
{ accountId, fieldOverrides, createValues }: DynamicFormOptions = {},
|
||||
) {
|
||||
const { t } = useTranslation();
|
||||
const navigate = useNavigate();
|
||||
const schema = useSchemaStore((s) => s.schema);
|
||||
@@ -86,14 +127,14 @@ export function useDynamicForm(viewName: string, objectId: string | null) {
|
||||
const isSingleton = resolved?.object.objectType.type === 'singleton';
|
||||
const objectName = resolved?.object.objectName;
|
||||
|
||||
const [state, dispatch] = useReducer(formReducer, null, () => initialState(schema, resolved, mode));
|
||||
const [state, dispatch] = useReducer(formReducer, null, () => initialState(schema, resolved, mode, createValues));
|
||||
const isDirty = isFormDirty(state);
|
||||
|
||||
if (mode === 'create' && schema && resolved && state.source !== resolved) {
|
||||
const variant = initialCreateVariant(resolved);
|
||||
dispatch({
|
||||
type: 'load',
|
||||
data: createDefaults(schema, resolved, variant),
|
||||
data: createDefaults(schema, resolved, variant, createValues),
|
||||
variant: variant ?? '',
|
||||
source: resolved,
|
||||
});
|
||||
@@ -103,7 +144,7 @@ export function useDynamicForm(viewName: string, objectId: string | null) {
|
||||
objectName,
|
||||
mode === 'create' ? null : isSingleton ? 'singleton' : objectId,
|
||||
schema && resolved ? collectFetchProperties(schema, resolved, viewName) : ['id'],
|
||||
{ staleTime: 0, refetchOnMount: 'always' },
|
||||
{ staleTime: 0, refetchOnMount: 'always', accountId },
|
||||
);
|
||||
if (objectQuery.data && objectQuery.data !== state.source && !isDirty && resolved) {
|
||||
dispatch({
|
||||
@@ -140,7 +181,8 @@ export function useDynamicForm(viewName: string, objectId: string | null) {
|
||||
}
|
||||
}
|
||||
const form = sch?.type === 'multiple' ? combineForms(parentForm, variantForm) : variantForm;
|
||||
const sections = buildSections(form, fields, mode);
|
||||
const hidden = new Set(fieldOverrides?.hidden);
|
||||
const sections = buildSections(form, fields, mode, hidden);
|
||||
|
||||
const loading = mode === 'edit' && objectQuery.fetchStatus !== 'idle' && !objectQuery.isFetchedAfterMount;
|
||||
const loadError =
|
||||
@@ -165,7 +207,9 @@ export function useDynamicForm(viewName: string, objectId: string | null) {
|
||||
};
|
||||
|
||||
const applySetError = (error: JmapSetError) => {
|
||||
const { general, fieldErrors } = mapSetError(error, new Set(Object.keys(fields?.properties ?? {})), {
|
||||
const known = new Set(Object.keys(fields?.properties ?? {}));
|
||||
for (const name of hidden) known.delete(name);
|
||||
const { general, fieldErrors } = mapSetError(error, known, {
|
||||
general: friendlySetError(error),
|
||||
invalidValue: t('form.invalidValue', 'Invalid value.'),
|
||||
validation: validationErrorMessage,
|
||||
@@ -183,7 +227,7 @@ export function useDynamicForm(viewName: string, objectId: string | null) {
|
||||
const { variants } = resolved.resolvedSchema;
|
||||
const defaults =
|
||||
mode === 'create'
|
||||
? createDefaults(schema, resolved, next)
|
||||
? createDefaults(schema, resolved, next, createValues)
|
||||
: buildEmbeddedDefaults(schema, resolved.object.objectName, {}, next);
|
||||
const data = switchVariantValues(
|
||||
variants.find((v) => v.name === state.variant)?.fields,
|
||||
@@ -198,14 +242,33 @@ export function useDynamicForm(viewName: string, objectId: string | null) {
|
||||
const save = async () => {
|
||||
if (!resolved || saving) return;
|
||||
if (fields) {
|
||||
const visible = formFieldNames(parentForm, variantForm);
|
||||
const errors = validateRequired(
|
||||
state.data,
|
||||
fields,
|
||||
mode,
|
||||
t('form.required', 'This field is required.'),
|
||||
visible.size > 0 ? visible : undefined,
|
||||
schema ?? undefined,
|
||||
const visibleNames = validatedFieldNames(formFieldNames(parentForm, variantForm), fields, hidden);
|
||||
const errors = mergeFieldErrors(
|
||||
validateRequired(
|
||||
state.data,
|
||||
fields,
|
||||
mode,
|
||||
{
|
||||
required: t('form.required', 'This field is required.'),
|
||||
minItems: (count) => t('form.minItems', 'Add at least {{count}} entries.', { count }),
|
||||
},
|
||||
visibleNames,
|
||||
schema ?? undefined,
|
||||
),
|
||||
fieldOverrides?.validate?.(state.data) ?? {},
|
||||
schema
|
||||
? validateFormat(
|
||||
state.data,
|
||||
fields,
|
||||
schema,
|
||||
{
|
||||
localTime: t('form.invalidLocalTime', 'Enter a valid time.'),
|
||||
localDate: t('form.invalidLocalDate', 'Enter a valid date as YYYY-MM-DD.'),
|
||||
weeklySchedule: t('form.invalidWeeklySchedule', 'Correct the intervals in this schedule.'),
|
||||
},
|
||||
visibleNames,
|
||||
)
|
||||
: {},
|
||||
);
|
||||
if (Object.keys(errors).length > 0) {
|
||||
dispatch({
|
||||
@@ -234,7 +297,7 @@ export function useDynamicForm(viewName: string, objectId: string | null) {
|
||||
}),
|
||||
fields,
|
||||
);
|
||||
const result = await setMutation.mutateAsync({ create: { [CREATE_ID]: payload }, blobs });
|
||||
const result = await setMutation.mutateAsync({ create: { [CREATE_ID]: payload }, blobs, accountId });
|
||||
const created = result.created?.[CREATE_ID];
|
||||
if (created) {
|
||||
const extras: FieldValues = {};
|
||||
@@ -263,7 +326,7 @@ export function useDynamicForm(viewName: string, objectId: string | null) {
|
||||
}
|
||||
const { blobs, payload } = collectBlobUploads(patch, fields, state.original);
|
||||
const updateId = isSingleton ? 'singleton' : objectId!;
|
||||
const result = await setMutation.mutateAsync({ update: { [updateId]: payload }, blobs });
|
||||
const result = await setMutation.mutateAsync({ update: { [updateId]: payload }, blobs, accountId });
|
||||
if (result.updated && updateId in result.updated) {
|
||||
toast({ title: t('form.savedSuccess', 'Saved successfully'), variant: 'success' });
|
||||
dispatch({ type: 'commit' });
|
||||
@@ -282,7 +345,7 @@ export function useDynamicForm(viewName: string, objectId: string | null) {
|
||||
if (!resolved || !objectId) return;
|
||||
dispatch({ type: 'setErrors', generalError: null });
|
||||
try {
|
||||
const result = await setMutation.mutateAsync({ destroy: [objectId] });
|
||||
const result = await setMutation.mutateAsync({ destroy: [objectId], accountId });
|
||||
if (result.destroyed?.includes(objectId)) {
|
||||
const label = resolved.list?.singularName ?? resolved.object.objectType.description;
|
||||
toast({
|
||||
|
||||
@@ -15,9 +15,9 @@ import { cn } from '@/lib/utils';
|
||||
import type { WidgetProps } from '@/components/forms/widgets/types';
|
||||
import type { FieldTypeUtcDateTime } from '@/types/schema';
|
||||
|
||||
const Calendar = lazy(() => import('@/components/ui/calendar').then((m) => ({ default: m.Calendar })));
|
||||
export const Calendar = lazy(() => import('@/components/ui/calendar').then((m) => ({ default: m.Calendar })));
|
||||
|
||||
function CalendarFallback() {
|
||||
export function CalendarFallback() {
|
||||
return (
|
||||
<div className="flex h-72 w-64 items-center justify-center" role="status">
|
||||
<Loader2 className="h-5 w-5 animate-spin text-brand-text" aria-hidden="true" />
|
||||
|
||||
@@ -8,7 +8,7 @@ import { useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { FieldRow } from '@/components/forms/FieldRow';
|
||||
import { VariantSelect } from '@/components/forms/VariantSelect';
|
||||
import { PanelContext, useFormContext, useInPanel } from '@/components/forms/formContext';
|
||||
import { EnclosingSchemaContext, PanelContext, useFormContext, useInPanel } from '@/components/forms/formContext';
|
||||
import { buildEmbeddedDefaults } from '@/lib/schemaResolver';
|
||||
import { embeddedEntries, isRecord, resolveEmbedded, switchVariantValues } from '@/lib/embeddedSchema';
|
||||
import type { ControlProps, WidgetProps } from '@/components/forms/widgets/types';
|
||||
@@ -83,15 +83,17 @@ export function EmbeddedObjectEditor({
|
||||
)}
|
||||
{entries.length > 0 && (
|
||||
<div className={cn('divide-y divide-border', frame === 'rule' && '[&>[data-slot=field-row]]:py-3')}>
|
||||
{entries.map(({ formField, field }) => (
|
||||
<FieldRow
|
||||
key={formField.name}
|
||||
field={field}
|
||||
formField={formField}
|
||||
value={obj[formField.name]}
|
||||
onChange={(v) => onChange({ ...obj, [formField.name]: v })}
|
||||
/>
|
||||
))}
|
||||
<EnclosingSchemaContext value={resolved.schemaName}>
|
||||
{entries.map(({ formField, field }) => (
|
||||
<FieldRow
|
||||
key={formField.name}
|
||||
field={field}
|
||||
formField={formField}
|
||||
value={obj[formField.name]}
|
||||
onChange={(v) => onChange({ ...obj, [formField.name]: v })}
|
||||
/>
|
||||
))}
|
||||
</EnclosingSchemaContext>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
@@ -4,104 +4,10 @@
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
import { lazy, Suspense } from 'react';
|
||||
import { ColorWidget, MultilineWidget, SecretWidget, TextWidget } from '@/components/forms/widgets/StringWidgets';
|
||||
import { DurationWidget, NumberWidget, SizeWidget } from '@/components/forms/widgets/NumberWidgets';
|
||||
import { DateTimeWidget } from '@/components/forms/widgets/DateTimeWidget';
|
||||
import { BooleanWidget } from '@/components/forms/widgets/BooleanWidget';
|
||||
import { EnumWidget } from '@/components/forms/widgets/EnumWidgets';
|
||||
import { BlobWidget } from '@/components/forms/widgets/BlobWidget';
|
||||
import { ObjectIdWidget } from '@/components/forms/widgets/ObjectIdWidgets';
|
||||
import { SetWidget } from '@/components/forms/widgets/SetWidget';
|
||||
import { EmbeddedObjectWidget } from '@/components/forms/widgets/EmbeddedObjectWidget';
|
||||
import { ObjectListWidget } from '@/components/forms/widgets/ObjectListWidget';
|
||||
import { MapWidget } from '@/components/forms/widgets/MapWidget';
|
||||
import { RateWidget } from '@/components/forms/widgets/RateWidget';
|
||||
import { ExpressionWidget } from '@/components/forms/widgets/ExpressionWidget';
|
||||
import { UnsupportedWidget } from '@/components/forms/widgets/UnsupportedWidget';
|
||||
import { widgetKey } from '@/components/forms/widgets/registry';
|
||||
import { resolveWidget } from '@/extensions/widgets';
|
||||
import type { WidgetProps } from '@/components/forms/widgets/types';
|
||||
import type {
|
||||
FieldType,
|
||||
FieldTypeBlobId,
|
||||
FieldTypeBoolean,
|
||||
FieldTypeEnum,
|
||||
FieldTypeMap,
|
||||
FieldTypeNumber,
|
||||
FieldTypeObject,
|
||||
FieldTypeObjectId,
|
||||
FieldTypeObjectList,
|
||||
FieldTypeSet,
|
||||
FieldTypeString,
|
||||
FieldTypeUtcDateTime,
|
||||
} from '@/types/schema';
|
||||
|
||||
const OtpAuthField = lazy(() =>
|
||||
import('@/components/forms/widgets/OtpAuthField').then((m) => ({ default: m.OtpAuthField })),
|
||||
);
|
||||
|
||||
const PasskeyRegistrationField = lazy(() =>
|
||||
import('@/components/forms/widgets/PasskeyRegistrationField').then((m) => ({
|
||||
default: m.PasskeyRegistrationField,
|
||||
})),
|
||||
);
|
||||
|
||||
function narrow<T extends FieldType>(props: WidgetProps): WidgetProps<T> {
|
||||
return props as WidgetProps<T>;
|
||||
}
|
||||
|
||||
export function FieldControl(props: WidgetProps) {
|
||||
switch (widgetKey(props.type)) {
|
||||
case 'string':
|
||||
return <TextWidget {...narrow<FieldTypeString>(props)} />;
|
||||
case 'string:secret':
|
||||
return <SecretWidget {...narrow<FieldTypeString>(props)} />;
|
||||
case 'string:multiline':
|
||||
return <MultilineWidget {...narrow<FieldTypeString>(props)} />;
|
||||
case 'string:color':
|
||||
return <ColorWidget {...narrow<FieldTypeString>(props)} />;
|
||||
case 'number':
|
||||
return <NumberWidget {...narrow<FieldTypeNumber>(props)} />;
|
||||
case 'number:size':
|
||||
return <SizeWidget {...narrow<FieldTypeNumber>(props)} />;
|
||||
case 'number:duration':
|
||||
return <DurationWidget {...narrow<FieldTypeNumber>(props)} />;
|
||||
case 'utcDateTime':
|
||||
return <DateTimeWidget {...narrow<FieldTypeUtcDateTime>(props)} />;
|
||||
case 'boolean':
|
||||
return <BooleanWidget {...narrow<FieldTypeBoolean>(props)} />;
|
||||
case 'enum':
|
||||
return <EnumWidget {...narrow<FieldTypeEnum>(props)} />;
|
||||
case 'blobId':
|
||||
return <BlobWidget {...narrow<FieldTypeBlobId>(props)} />;
|
||||
case 'objectId':
|
||||
return <ObjectIdWidget {...narrow<FieldTypeObjectId>(props)} />;
|
||||
case 'object':
|
||||
return <EmbeddedObjectWidget {...narrow<FieldTypeObject>(props)} />;
|
||||
case 'object:x:Expression':
|
||||
return <ExpressionWidget {...narrow<FieldTypeObject>(props)} />;
|
||||
case 'object:x:Rate':
|
||||
return <RateWidget {...narrow<FieldTypeObject>(props)} />;
|
||||
case 'object:x:OtpAuth':
|
||||
return (
|
||||
<Suspense fallback={null}>
|
||||
<OtpAuthField {...narrow<FieldTypeObject>(props)} />
|
||||
</Suspense>
|
||||
);
|
||||
case 'object:x:PasskeyRegistration':
|
||||
return (
|
||||
<Suspense fallback={null}>
|
||||
<PasskeyRegistrationField {...narrow<FieldTypeObject>(props)} />
|
||||
</Suspense>
|
||||
);
|
||||
case 'objectList':
|
||||
return <ObjectListWidget {...narrow<FieldTypeObjectList>(props)} />;
|
||||
case 'set':
|
||||
case 'set:enum':
|
||||
return <SetWidget {...narrow<FieldTypeSet>(props)} />;
|
||||
case 'map':
|
||||
return <MapWidget {...narrow<FieldTypeMap>(props)} />;
|
||||
case 'unsupported':
|
||||
return <UnsupportedWidget {...props} />;
|
||||
}
|
||||
const { Edit } = resolveWidget(props.type);
|
||||
return <Edit {...props} />;
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
/*
|
||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
import { lazy, Suspense } from 'react';
|
||||
import type { WidgetProps } from '@/components/forms/widgets/types';
|
||||
import type { FieldTypeObject } from '@/types/schema';
|
||||
|
||||
const OtpAuthField = lazy(() =>
|
||||
import('@/components/forms/widgets/OtpAuthField').then((m) => ({ default: m.OtpAuthField })),
|
||||
);
|
||||
|
||||
const PasskeyRegistrationField = lazy(() =>
|
||||
import('@/components/forms/widgets/PasskeyRegistrationField').then((m) => ({
|
||||
default: m.PasskeyRegistrationField,
|
||||
})),
|
||||
);
|
||||
|
||||
export function OtpAuthWidget(props: WidgetProps<FieldTypeObject>) {
|
||||
return (
|
||||
<Suspense fallback={null}>
|
||||
<OtpAuthField {...props} />
|
||||
</Suspense>
|
||||
);
|
||||
}
|
||||
|
||||
export function PasskeyRegistrationWidget(props: WidgetProps<FieldTypeObject>) {
|
||||
return (
|
||||
<Suspense fallback={null}>
|
||||
<PasskeyRegistrationField {...props} />
|
||||
</Suspense>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
/*
|
||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
import { Suspense, useRef, useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Calendar as CalendarIcon, X } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
|
||||
import { formatLocalDate } from '@/lib/format';
|
||||
import {
|
||||
formatLocalDateValue,
|
||||
localDateFromCalendarDate,
|
||||
localDateToCalendarDate,
|
||||
parseLocalDate,
|
||||
} from '@/lib/localDateTime';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { Calendar, CalendarFallback } from '@/components/forms/widgets/DateTimeWidget';
|
||||
import type { ControlProps } from '@/components/forms/widgets/types';
|
||||
|
||||
export interface LocalDateInputProps extends ControlProps {
|
||||
value: string | null | undefined;
|
||||
onChange: (value: string | null) => void;
|
||||
clearable?: boolean;
|
||||
disabled?: boolean;
|
||||
placeholder?: string;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
export function LocalDateInput({
|
||||
value,
|
||||
onChange,
|
||||
clearable = false,
|
||||
disabled = false,
|
||||
placeholder,
|
||||
className,
|
||||
...control
|
||||
}: LocalDateInputProps) {
|
||||
const { t } = useTranslation();
|
||||
const [open, setOpen] = useState(false);
|
||||
const triggerRef = useRef<HTMLButtonElement>(null);
|
||||
const parsed = parseLocalDate(value);
|
||||
const selected = parsed ? localDateToCalendarDate(parsed) : undefined;
|
||||
const hasValue = typeof value === 'string' && value !== '';
|
||||
|
||||
return (
|
||||
<div className={cn('flex items-center gap-2', className)}>
|
||||
<Popover open={open} onOpenChange={setOpen}>
|
||||
<PopoverTrigger asChild>
|
||||
<Button
|
||||
{...control}
|
||||
ref={triggerRef}
|
||||
type="button"
|
||||
variant="field"
|
||||
disabled={disabled}
|
||||
className={cn('flex-1 justify-start px-3 text-left', !hasValue && 'text-dim')}
|
||||
>
|
||||
<CalendarIcon className="text-dim" aria-hidden="true" />
|
||||
{hasValue ? formatLocalDate(value) : (placeholder ?? t('field.pickDate', 'Pick a date'))}
|
||||
</Button>
|
||||
</PopoverTrigger>
|
||||
<PopoverContent className="w-auto overflow-hidden p-0" align="start">
|
||||
<Suspense fallback={<CalendarFallback />}>
|
||||
<Calendar
|
||||
mode="single"
|
||||
selected={selected}
|
||||
defaultMonth={selected}
|
||||
autoFocus
|
||||
onSelect={(day) => {
|
||||
if (day) onChange(formatLocalDateValue(localDateFromCalendarDate(day)));
|
||||
setOpen(false);
|
||||
}}
|
||||
/>
|
||||
</Suspense>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
{clearable && hasValue && !disabled && (
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="h-9 w-9 shrink-0"
|
||||
onClick={() => {
|
||||
onChange(null);
|
||||
triggerRef.current?.focus();
|
||||
}}
|
||||
aria-label={t('common.clear', 'Clear')}
|
||||
>
|
||||
<X aria-hidden="true" />
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
/*
|
||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
import { LocalDateInput } from '@/components/forms/widgets/LocalDateInput';
|
||||
import { LocalTimeInput } from '@/components/forms/widgets/LocalTimeInput';
|
||||
import { formatLocalDate, formatLocalTime } from '@/lib/format';
|
||||
import type { WidgetProps } from '@/components/forms/widgets/types';
|
||||
import type { ValueProps } from '@/extensions/types';
|
||||
import type { FieldTypeString } from '@/types/schema';
|
||||
|
||||
function stringOrNull(value: unknown): string | null {
|
||||
return typeof value === 'string' && value !== '' ? value : null;
|
||||
}
|
||||
|
||||
export function LocalTimeWidget({ type, value, onChange, readOnly, control }: WidgetProps<FieldTypeString>) {
|
||||
return (
|
||||
<LocalTimeInput
|
||||
{...control}
|
||||
value={stringOrNull(value)}
|
||||
onChange={onChange}
|
||||
allowEndOfDay
|
||||
clearable={!!type.nullable}
|
||||
disabled={readOnly}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export function LocalDateWidget({ type, formField, value, onChange, readOnly, control }: WidgetProps<FieldTypeString>) {
|
||||
return (
|
||||
<LocalDateInput
|
||||
{...control}
|
||||
value={stringOrNull(value)}
|
||||
onChange={onChange}
|
||||
clearable={!!type.nullable}
|
||||
disabled={readOnly}
|
||||
placeholder={formField.placeholder}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export function LocalTimeValue({ value }: ValueProps) {
|
||||
return <span className="text-sm tabular-nums">{formatLocalTime(value)}</span>;
|
||||
}
|
||||
|
||||
export function LocalDateValue({ value }: ValueProps) {
|
||||
return <span className="text-sm">{formatLocalDate(value)}</span>;
|
||||
}
|
||||
@@ -0,0 +1,468 @@
|
||||
/*
|
||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
import { Fragment, useId, useRef, useState, type ChangeEvent, type KeyboardEvent, type ReactNode } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Clock, X } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
|
||||
import { formatLocalTime, localeClock, type LocaleClock } from '@/lib/format';
|
||||
import {
|
||||
HOURS_PER_HALF_DAY,
|
||||
MINUTES_PER_DAY,
|
||||
MINUTES_PER_HOUR,
|
||||
hour12Of,
|
||||
hours24From,
|
||||
localTimeFromMinutes,
|
||||
meridiemOf,
|
||||
parseLocalTime,
|
||||
type Meridiem,
|
||||
} from '@/lib/localDateTime';
|
||||
import { useAccountStore } from '@/stores/accountStore';
|
||||
import { cn } from '@/lib/utils';
|
||||
import type { ControlProps } from '@/components/forms/widgets/types';
|
||||
|
||||
export interface LocalTimeInputProps extends ControlProps {
|
||||
value: string | null | undefined;
|
||||
onChange: (value: string | null) => void;
|
||||
allowEndOfDay?: boolean;
|
||||
clearable?: boolean;
|
||||
disabled?: boolean;
|
||||
pickerStep?: 15 | 30;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
type Segment = 'hours' | 'minutes' | 'meridiem';
|
||||
|
||||
interface PendingDigit {
|
||||
segment: Segment;
|
||||
digit: number;
|
||||
}
|
||||
|
||||
type PickerMove = 'left' | 'right' | 'up' | 'down' | 'first' | 'last';
|
||||
|
||||
const LAST_MINUTE = MINUTES_PER_HOUR - 1;
|
||||
const END_OF_DAY_HOUR = MINUTES_PER_DAY / MINUTES_PER_HOUR;
|
||||
const DIGIT = /^\d$/;
|
||||
const SEGMENT_CLASS =
|
||||
'rounded-sm bg-transparent text-center tabular-nums outline-none placeholder:text-dim focus:bg-highlight focus:text-highlight-foreground disabled:cursor-not-allowed';
|
||||
const PICKER_COLUMNS_24H = 4;
|
||||
const PICKER_COLUMNS_12H = 3;
|
||||
const PICKER_KEYS = new Map<string, PickerMove>([
|
||||
['ArrowLeft', 'left'],
|
||||
['ArrowRight', 'right'],
|
||||
['ArrowUp', 'up'],
|
||||
['ArrowDown', 'down'],
|
||||
['Home', 'first'],
|
||||
['End', 'last'],
|
||||
]);
|
||||
|
||||
function twoDigits(value: number | null): string {
|
||||
return value === null ? '' : String(value).padStart(2, '0');
|
||||
}
|
||||
|
||||
function wrap(value: number, max: number): number {
|
||||
return ((value % (max + 1)) + max + 1) % (max + 1);
|
||||
}
|
||||
|
||||
function meridiemForKey(key: string, clock: LocaleClock): Meridiem | null {
|
||||
const typed = key.toLocaleLowerCase();
|
||||
const am = clock.am.charAt(0).toLocaleLowerCase();
|
||||
const pm = clock.pm.charAt(0).toLocaleLowerCase();
|
||||
if (am !== pm) {
|
||||
if (typed === am) return 'am';
|
||||
if (typed === pm) return 'pm';
|
||||
}
|
||||
return typed === 'a' ? 'am' : typed === 'p' ? 'pm' : null;
|
||||
}
|
||||
|
||||
export function LocalTimeInput({
|
||||
value,
|
||||
onChange,
|
||||
allowEndOfDay = false,
|
||||
clearable = false,
|
||||
disabled = false,
|
||||
pickerStep = 30,
|
||||
className,
|
||||
id,
|
||||
'aria-label': ariaLabel,
|
||||
'aria-labelledby': ariaLabelledBy,
|
||||
'aria-describedby': ariaDescribedBy,
|
||||
'aria-invalid': ariaInvalid,
|
||||
'aria-required': ariaRequired,
|
||||
}: LocalTimeInputProps) {
|
||||
const { t } = useTranslation();
|
||||
useAccountStore((s) => s.locale);
|
||||
const [pending, setPending] = useState<PendingDigit | null>(null);
|
||||
const [pickerOpen, setPickerOpen] = useState(false);
|
||||
const hoursRef = useRef<HTMLInputElement>(null);
|
||||
const minutesRef = useRef<HTMLInputElement>(null);
|
||||
const meridiemRef = useRef<HTMLInputElement>(null);
|
||||
const pickerRef = useRef<HTMLDivElement>(null);
|
||||
const segmentLabelId = useId();
|
||||
|
||||
const clock = localeClock();
|
||||
const twelve = clock.hour12;
|
||||
const total = parseLocalTime(value);
|
||||
const hours = total === null ? null : Math.floor(total / MINUTES_PER_HOUR);
|
||||
const minutes = total === null ? null : total % MINUTES_PER_HOUR;
|
||||
const atEndOfDay = hours === END_OF_DAY_HOUR;
|
||||
const maxHour = allowEndOfDay || atEndOfDay ? END_OF_DAY_HOUR : END_OF_DAY_HOUR - 1;
|
||||
const meridiem: Meridiem | null = hours === null ? null : atEndOfDay ? 'am' : meridiemOf(hours);
|
||||
const hourMin = twelve ? 1 : 0;
|
||||
const hourMax = twelve ? HOURS_PER_HALF_DAY : maxHour;
|
||||
const shownHour = hours === null ? null : twelve ? hour12Of(hours) : hours;
|
||||
const endOfDayText = twelve && atEndOfDay ? t('field.endOfDay', 'End of day') : null;
|
||||
const order: readonly Segment[] = !twelve
|
||||
? ['hours', 'minutes']
|
||||
: clock.meridiemFirst
|
||||
? ['meridiem', 'hours', 'minutes']
|
||||
: ['hours', 'minutes', 'meridiem'];
|
||||
|
||||
const refFor = (segment: Segment) =>
|
||||
segment === 'hours' ? hoursRef : segment === 'minutes' ? minutesRef : meridiemRef;
|
||||
const neighbour = (segment: Segment, delta: number): Segment | undefined => order[order.indexOf(segment) + delta];
|
||||
const focusAfter = (segment: Segment) => {
|
||||
const next = neighbour(segment, 1);
|
||||
if (next) refFor(next).current?.focus();
|
||||
};
|
||||
|
||||
const emit = (h: number, m: number) => onChange(localTimeFromMinutes(h * MINUTES_PER_HOUR + m));
|
||||
const setHours = (h: number) => emit(h, h === END_OF_DAY_HOUR ? 0 : (minutes ?? 0));
|
||||
const setShownHour = (h: number) => setHours(twelve ? hours24From(h, meridiem ?? 'am') : h);
|
||||
const setMinutes = (m: number) => {
|
||||
if (!atEndOfDay) emit(hours ?? 0, m);
|
||||
};
|
||||
const setMeridiem = (next: Meridiem) => {
|
||||
const hour12 = hours === null || atEndOfDay ? HOURS_PER_HALF_DAY : hour12Of(hours);
|
||||
emit(hours24From(hour12, next), atEndOfDay ? 0 : (minutes ?? 0));
|
||||
};
|
||||
|
||||
const typeDigit = (segment: Segment, digit: number) => {
|
||||
const previous = pending?.segment === segment ? pending.digit : null;
|
||||
if (segment === 'hours') {
|
||||
const combined = previous === null ? null : previous * 10 + digit;
|
||||
if (combined !== null && combined >= hourMin && combined <= hourMax) {
|
||||
setShownHour(combined);
|
||||
setPending(null);
|
||||
focusAfter('hours');
|
||||
} else if (digit * 10 > hourMax) {
|
||||
setShownHour(digit);
|
||||
setPending(null);
|
||||
focusAfter('hours');
|
||||
} else {
|
||||
if (digit >= hourMin) setShownHour(digit);
|
||||
setPending({ segment, digit });
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (segment !== 'minutes' || atEndOfDay) return;
|
||||
if (previous !== null) {
|
||||
setMinutes(previous * 10 + digit);
|
||||
setPending(null);
|
||||
focusAfter('minutes');
|
||||
} else if (digit * 10 > LAST_MINUTE) {
|
||||
setMinutes(digit);
|
||||
setPending(null);
|
||||
focusAfter('minutes');
|
||||
} else {
|
||||
setMinutes(digit);
|
||||
setPending({ segment, digit });
|
||||
}
|
||||
};
|
||||
|
||||
const step = (segment: Segment, delta: number) => {
|
||||
setPending(null);
|
||||
if (segment === 'hours') {
|
||||
if (twelve && atEndOfDay) {
|
||||
setHours(delta > 0 ? 0 : END_OF_DAY_HOUR - 1);
|
||||
} else if (twelve && allowEndOfDay && hours === (delta > 0 ? END_OF_DAY_HOUR - 1 : 0)) {
|
||||
setHours(END_OF_DAY_HOUR);
|
||||
} else if (twelve) {
|
||||
setShownHour(
|
||||
shownHour === null
|
||||
? delta > 0
|
||||
? hourMin
|
||||
: hourMax
|
||||
: wrap(shownHour - 1 + delta, HOURS_PER_HALF_DAY - 1) + 1,
|
||||
);
|
||||
} else {
|
||||
setHours(hours === null ? (delta > 0 ? 0 : maxHour) : wrap(hours + delta, maxHour));
|
||||
}
|
||||
} else if (segment === 'minutes') {
|
||||
setMinutes(minutes === null ? (delta > 0 ? 0 : LAST_MINUTE) : wrap(minutes + delta, LAST_MINUTE));
|
||||
} else {
|
||||
setMeridiem(meridiem === 'am' ? 'pm' : 'am');
|
||||
}
|
||||
};
|
||||
|
||||
const clear = () => {
|
||||
setPending(null);
|
||||
if (clearable) onChange(null);
|
||||
};
|
||||
|
||||
const onSegmentChange = (segment: Segment) => (e: ChangeEvent<HTMLInputElement>) => {
|
||||
const inputType = (e.nativeEvent as Partial<InputEvent>).inputType ?? '';
|
||||
if (inputType.startsWith('delete')) {
|
||||
clear();
|
||||
return;
|
||||
}
|
||||
const text = e.target.value;
|
||||
const typed = text.charAt((e.target.selectionStart ?? text.length) - 1);
|
||||
if (segment === 'meridiem') {
|
||||
const next = meridiemForKey(typed, clock);
|
||||
if (next) {
|
||||
setMeridiem(next);
|
||||
focusAfter('meridiem');
|
||||
}
|
||||
} else if (DIGIT.test(typed)) {
|
||||
typeDigit(segment, Number(typed));
|
||||
}
|
||||
};
|
||||
|
||||
const onSegmentKeyDown = (segment: Segment) => (e: KeyboardEvent<HTMLInputElement>) => {
|
||||
switch (e.key) {
|
||||
case 'ArrowUp':
|
||||
step(segment, 1);
|
||||
break;
|
||||
case 'ArrowDown':
|
||||
step(segment, -1);
|
||||
break;
|
||||
case 'Home':
|
||||
case 'End': {
|
||||
setPending(null);
|
||||
const first = e.key === 'Home';
|
||||
if (segment === 'hours') {
|
||||
if (twelve && allowEndOfDay && !first) setHours(END_OF_DAY_HOUR);
|
||||
else setShownHour(first ? hourMin : hourMax);
|
||||
} else if (segment === 'minutes') setMinutes(first ? 0 : LAST_MINUTE);
|
||||
else setMeridiem(first ? 'am' : 'pm');
|
||||
break;
|
||||
}
|
||||
case 'Backspace':
|
||||
case 'Delete':
|
||||
clear();
|
||||
break;
|
||||
case ':':
|
||||
case '.':
|
||||
if (segment !== 'hours') return;
|
||||
minutesRef.current?.focus();
|
||||
break;
|
||||
case 'ArrowRight':
|
||||
case 'ArrowLeft': {
|
||||
const target = neighbour(segment, e.key === 'ArrowRight' ? 1 : -1);
|
||||
if (!target) return;
|
||||
refFor(target).current?.focus();
|
||||
break;
|
||||
}
|
||||
default: {
|
||||
const next = segment === 'meridiem' ? meridiemForKey(e.key, clock) : null;
|
||||
if (next) {
|
||||
setMeridiem(next);
|
||||
focusAfter('meridiem');
|
||||
} else if (endOfDayText !== null && segment === 'hours' && DIGIT.test(e.key)) {
|
||||
typeDigit('hours', Number(e.key));
|
||||
} else {
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
e.preventDefault();
|
||||
};
|
||||
|
||||
const segmentLabel = (segment: Segment) =>
|
||||
segment === 'hours'
|
||||
? t('field.hours', 'Hours')
|
||||
: segment === 'minutes'
|
||||
? t('field.minutes', 'Minutes')
|
||||
: t('field.dayPeriod', 'AM/PM');
|
||||
|
||||
const segmentName = (segment: Segment) => {
|
||||
if (ariaLabelledBy) return { 'aria-labelledby': `${ariaLabelledBy} ${segmentLabelId}-${segment}` };
|
||||
if (ariaLabel) {
|
||||
return {
|
||||
'aria-label': t('field.segmentOf', '{{field}}, {{segment}}', {
|
||||
field: ariaLabel,
|
||||
segment: segmentLabel(segment),
|
||||
}),
|
||||
};
|
||||
}
|
||||
return { 'aria-label': segmentLabel(segment) };
|
||||
};
|
||||
|
||||
const segmentProps = (segment: Segment, current: number | null, min: number, max: number, text: string) => ({
|
||||
...segmentName(segment),
|
||||
type: 'text',
|
||||
inputMode: segment === 'meridiem' ? ('text' as const) : ('numeric' as const),
|
||||
role: 'spinbutton',
|
||||
autoComplete: 'off',
|
||||
disabled,
|
||||
placeholder: '--',
|
||||
value: text,
|
||||
'aria-valuemin': min,
|
||||
'aria-valuemax': max,
|
||||
'aria-valuenow': current ?? undefined,
|
||||
'aria-valuetext': current === null ? t('field.notSet', 'Not set') : text,
|
||||
'aria-invalid': ariaInvalid,
|
||||
'aria-required': ariaRequired,
|
||||
'aria-describedby': ariaDescribedBy,
|
||||
onChange: onSegmentChange(segment),
|
||||
onKeyDown: onSegmentKeyDown(segment),
|
||||
onFocus: (e: { currentTarget: HTMLInputElement }) => e.currentTarget.select(),
|
||||
onBlur: () => setPending(null),
|
||||
className: SEGMENT_CLASS,
|
||||
});
|
||||
|
||||
const meridiemText = meridiem === null ? '' : meridiem === 'am' ? clock.am : clock.pm;
|
||||
const meridiemWidth = `${Math.max(2, clock.am.length, clock.pm.length) + 0.5}ch`;
|
||||
const segments: Record<Segment, ReactNode> = {
|
||||
hours: (
|
||||
<input
|
||||
key="hours"
|
||||
{...segmentProps('hours', shownHour, hourMin, hourMax, endOfDayText ?? twoDigits(shownHour))}
|
||||
ref={hoursRef}
|
||||
id={id}
|
||||
readOnly={endOfDayText !== null}
|
||||
style={{ width: endOfDayText === null ? '2.5ch' : `${endOfDayText.length + 1}ch` }}
|
||||
/>
|
||||
),
|
||||
minutes: endOfDayText === null && (
|
||||
<Fragment key="minutes">
|
||||
<span aria-hidden="true" className="px-0.5 text-dim">
|
||||
:
|
||||
</span>
|
||||
<input
|
||||
{...segmentProps('minutes', minutes, 0, LAST_MINUTE, twoDigits(minutes))}
|
||||
ref={minutesRef}
|
||||
readOnly={atEndOfDay}
|
||||
style={{ width: '2.5ch' }}
|
||||
/>
|
||||
</Fragment>
|
||||
),
|
||||
meridiem: endOfDayText === null && (
|
||||
<input
|
||||
key="meridiem"
|
||||
{...segmentProps('meridiem', meridiem === null ? null : meridiem === 'am' ? 0 : 1, 0, 1, meridiemText)}
|
||||
ref={meridiemRef}
|
||||
className={cn(SEGMENT_CLASS, clock.meridiemFirst ? 'me-1' : 'ms-1')}
|
||||
style={{ width: meridiemWidth }}
|
||||
/>
|
||||
),
|
||||
};
|
||||
|
||||
const options: number[] = [];
|
||||
for (let m = 0; m < MINUTES_PER_DAY; m += pickerStep) options.push(m);
|
||||
if (allowEndOfDay) options.push(MINUTES_PER_DAY);
|
||||
const focusTarget = total !== null && options.includes(total) ? total : options[0];
|
||||
|
||||
const columns = twelve ? PICKER_COLUMNS_12H : PICKER_COLUMNS_24H;
|
||||
const onPickerKeyDown = (e: KeyboardEvent<HTMLDivElement>) => {
|
||||
const move = PICKER_KEYS.get(e.key);
|
||||
const buttons = pickerRef.current?.querySelectorAll<HTMLButtonElement>('button');
|
||||
if (move === undefined || !buttons) return;
|
||||
e.preventDefault();
|
||||
const current = Array.prototype.indexOf.call(buttons, document.activeElement);
|
||||
const delta = move === 'left' ? -1 : move === 'right' ? 1 : move === 'up' ? -columns : columns;
|
||||
const next = move === 'first' ? 0 : move === 'last' ? buttons.length - 1 : current + delta;
|
||||
buttons[Math.min(buttons.length - 1, Math.max(0, next))]?.focus();
|
||||
};
|
||||
|
||||
const pick = (m: number) => {
|
||||
setPending(null);
|
||||
onChange(localTimeFromMinutes(m));
|
||||
setPickerOpen(false);
|
||||
};
|
||||
|
||||
return (
|
||||
<div
|
||||
role={ariaLabelledBy ? undefined : 'group'}
|
||||
aria-label={ariaLabelledBy ? undefined : ariaLabel}
|
||||
aria-describedby={ariaLabelledBy ? undefined : ariaDescribedBy}
|
||||
aria-invalid={ariaInvalid}
|
||||
data-slot="local-time-input"
|
||||
className={cn(
|
||||
'field-surface inline-flex h-9 items-center gap-1 rounded-lg pr-1 pl-3 text-base md:text-sm',
|
||||
disabled && 'opacity-50',
|
||||
className,
|
||||
)}
|
||||
>
|
||||
<div dir="ltr" className="flex items-center">
|
||||
{order.map((segment) => segments[segment])}
|
||||
</div>
|
||||
{ariaLabelledBy && (
|
||||
<span hidden>
|
||||
{order.map((segment) => (
|
||||
<span key={segment} id={`${segmentLabelId}-${segment}`}>
|
||||
{segmentLabel(segment)}
|
||||
</span>
|
||||
))}
|
||||
</span>
|
||||
)}
|
||||
{!disabled && (
|
||||
<div className="ml-auto flex items-center">
|
||||
{clearable && total !== null && (
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="icon-sm"
|
||||
className="h-7 w-7"
|
||||
onClick={() => {
|
||||
clear();
|
||||
hoursRef.current?.focus();
|
||||
}}
|
||||
aria-label={t('common.clear', 'Clear')}
|
||||
>
|
||||
<X aria-hidden="true" />
|
||||
</Button>
|
||||
)}
|
||||
<Popover open={pickerOpen} onOpenChange={setPickerOpen}>
|
||||
<PopoverTrigger asChild>
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="icon-sm"
|
||||
className="h-7 w-7"
|
||||
aria-label={t('field.chooseTime', 'Choose a time')}
|
||||
>
|
||||
<Clock aria-hidden="true" />
|
||||
</Button>
|
||||
</PopoverTrigger>
|
||||
<PopoverContent className="w-64 p-2" align="end">
|
||||
<div
|
||||
ref={pickerRef}
|
||||
className={cn('grid max-h-64 gap-1 overflow-y-auto', twelve ? 'grid-cols-3' : 'grid-cols-4')}
|
||||
dir="ltr"
|
||||
onKeyDown={onPickerKeyDown}
|
||||
>
|
||||
{options.map((m) => (
|
||||
<Button
|
||||
key={m}
|
||||
type="button"
|
||||
variant={m === total ? 'secondary' : 'ghost'}
|
||||
size="sm"
|
||||
className={cn('px-0 tabular-nums', m === MINUTES_PER_DAY && 'col-span-full')}
|
||||
tabIndex={m === focusTarget ? 0 : -1}
|
||||
aria-current={m === total ? 'time' : undefined}
|
||||
autoFocus={m === focusTarget}
|
||||
onClick={() => pick(m)}
|
||||
>
|
||||
{m === MINUTES_PER_DAY
|
||||
? twelve
|
||||
? t('field.endOfDay', 'End of day')
|
||||
: t('field.endOfDayOption', 'End of day (24:00)')
|
||||
: twelve
|
||||
? formatLocalTime(localTimeFromMinutes(m))
|
||||
: localTimeFromMinutes(m)}
|
||||
</Button>
|
||||
))}
|
||||
</div>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -16,10 +16,10 @@ import { PanelContext, useFormContext, useInPanel } from '@/components/forms/for
|
||||
import { FieldControl } from '@/components/forms/widgets/FieldControl';
|
||||
import { EmbeddedObjectEditor } from '@/components/forms/widgets/EmbeddedObjectWidget';
|
||||
import { formatPlaceholder } from '@/components/forms/widgets/placeholders';
|
||||
import { widgetKey } from '@/components/forms/widgets/registry';
|
||||
import { widgetKey, widgetTraits } from '@/extensions/widgets';
|
||||
import { useNoPermissionMessage } from '@/lib/objectOptions';
|
||||
import { useDisplayName, useObjectOptions } from '@/data/objectOptions';
|
||||
import { buildNewObjectValue, getEnum, getEnumVariant } from '@/lib/schemaResolver';
|
||||
import { buildNewObjectValue, getEnum, getEnumVariant, mapEntryValueType } from '@/lib/schemaResolver';
|
||||
import { isRecord } from '@/lib/embeddedSchema';
|
||||
import { cn } from '@/lib/utils';
|
||||
import type { WidgetProps } from '@/components/forms/widgets/types';
|
||||
@@ -82,7 +82,7 @@ export function MapWidget({ type, formField, value, onChange, readOnly }: Widget
|
||||
}
|
||||
};
|
||||
|
||||
const objectValues = valueField.type.type === 'object' && widgetKey(valueField.type) !== 'object:x:Rate';
|
||||
const objectValues = valueField.type.type === 'object' && widgetTraits(valueField.type).layout === 'block';
|
||||
const valueLabel = formField.valueLabel ?? '';
|
||||
const removeButton = (key: string) =>
|
||||
!readOnly && (
|
||||
@@ -111,7 +111,7 @@ export function MapWidget({ type, formField, value, onChange, readOnly }: Widget
|
||||
/>
|
||||
) : (
|
||||
<FieldControl
|
||||
type={valueField.type}
|
||||
type={mapEntryValueType(schema, type.keyClass, type.valueClass, key) as FieldType}
|
||||
field={valueField}
|
||||
formField={{ name: key, label: valueLabel }}
|
||||
value={val}
|
||||
|
||||
@@ -70,7 +70,7 @@ export function ObjectIdWidget({
|
||||
}
|
||||
|
||||
return (
|
||||
<ObjectFieldFrame disabled={!!noPermissionMessage}>
|
||||
<ObjectFieldFrame disabled={!!noPermissionMessage} single>
|
||||
{pill}
|
||||
<ObjectSearchPopover
|
||||
control={control}
|
||||
|
||||
@@ -12,7 +12,7 @@ import { FieldScopeProvider } from '@/components/forms/FormProvider';
|
||||
import { PanelContext, useFormContext, useInPanel } from '@/components/forms/formContext';
|
||||
import { FieldControl } from '@/components/forms/widgets/FieldControl';
|
||||
import { EmbeddedObjectEditor } from '@/components/forms/widgets/EmbeddedObjectWidget';
|
||||
import { widgetKey } from '@/components/forms/widgets/registry';
|
||||
import { widgetKey } from '@/extensions/widgets';
|
||||
import { FieldValue } from '@/components/values/FieldValue';
|
||||
import { buildNewObjectValue } from '@/lib/schemaResolver';
|
||||
import { embeddedSummary, isRecord } from '@/lib/embeddedSchema';
|
||||
|
||||
@@ -22,9 +22,11 @@ export function RemovablePill({ label, onRemove, removeDisabled, children }: Rem
|
||||
return (
|
||||
<Badge
|
||||
variant="secondary"
|
||||
className={cn('h-7 max-w-full gap-1 text-[13px] font-medium', onRemove ? 'pl-3 pr-1' : 'px-3')}
|
||||
className={cn('h-7 min-w-0 max-w-full gap-1 text-[13px] font-medium', onRemove ? 'pl-3 pr-1' : 'px-3')}
|
||||
>
|
||||
{children ?? label}
|
||||
<span className="truncate" title={label}>
|
||||
{children ?? label}
|
||||
</span>
|
||||
{onRemove && (
|
||||
<button
|
||||
type="button"
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
import { useState } from 'react';
|
||||
import { useId, useState, type ClipboardEvent } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Plus } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
@@ -14,8 +14,9 @@ import { ObjectIdMultiSelect } from '@/components/forms/widgets/ObjectIdWidgets'
|
||||
import { RemovablePill } from '@/components/forms/widgets/RemovablePill';
|
||||
import { formatPlaceholder } from '@/components/forms/widgets/placeholders';
|
||||
import { isRecord } from '@/lib/embeddedSchema';
|
||||
import { addSetEntries, joinEntries, splitEntries, type SetEntriesResult } from '@/lib/setEntries';
|
||||
import type { ControlProps, WidgetProps } from '@/components/forms/widgets/types';
|
||||
import type { FieldTypeSet } from '@/types/schema';
|
||||
import type { FieldTypeSet, ScalarTypeString } from '@/types/schema';
|
||||
|
||||
function toSetObject(items: string[]): Record<string, true> {
|
||||
const obj: Record<string, true> = {};
|
||||
@@ -32,6 +33,7 @@ export function SetWidget({ type, formField, value, onChange, readOnly, control
|
||||
case 'string':
|
||||
return (
|
||||
<TagInput
|
||||
type={scalar}
|
||||
label={formField.label}
|
||||
items={items}
|
||||
onChange={commit}
|
||||
@@ -74,6 +76,7 @@ export function SetWidget({ type, formField, value, onChange, readOnly, control
|
||||
}
|
||||
|
||||
interface TagInputProps {
|
||||
type: ScalarTypeString;
|
||||
label: string;
|
||||
items: string[];
|
||||
onChange: (items: string[]) => void;
|
||||
@@ -84,61 +87,142 @@ interface TagInputProps {
|
||||
control: ControlProps;
|
||||
}
|
||||
|
||||
function TagInput({ label, items, onChange, readOnly, minItems, maxItems, placeholder, control }: TagInputProps) {
|
||||
const REPORT_SAMPLE = 5;
|
||||
|
||||
function isNoteworthy(result: SetEntriesResult): boolean {
|
||||
return result.added.length > 1 || result.duplicates.length + result.invalid.length + result.overLimit.length > 0;
|
||||
}
|
||||
|
||||
function TagInput({ type, label, items, onChange, readOnly, minItems, maxItems, placeholder, control }: TagInputProps) {
|
||||
const { t } = useTranslation();
|
||||
const [inputValue, setInputValue] = useState('');
|
||||
const [report, setReport] = useState<SetEntriesResult | null>(null);
|
||||
const statusId = useId();
|
||||
const full = maxItems != null && items.length >= maxItems;
|
||||
|
||||
const addTag = () => {
|
||||
const trimmed = inputValue.trim();
|
||||
if (!trimmed || items.includes(trimmed) || full) return;
|
||||
onChange([...items, trimmed]);
|
||||
setInputValue('');
|
||||
const addEntries = (entries: string[]) => {
|
||||
const result = addSetEntries(items, entries, type, maxItems);
|
||||
if (result.added.length > 0) onChange([...items, ...result.added]);
|
||||
setReport(isNoteworthy(result) ? result : null);
|
||||
return result;
|
||||
};
|
||||
|
||||
const addTyped = () => {
|
||||
const entries = splitEntries(inputValue, type.format);
|
||||
if (entries.length === 0) return;
|
||||
const result = addEntries(entries);
|
||||
setInputValue(joinEntries(result.invalid, type.format) ?? '');
|
||||
};
|
||||
|
||||
const onPaste = (e: ClipboardEvent<HTMLInputElement>) => {
|
||||
const entries = splitEntries(e.clipboardData.getData('text'), type.format);
|
||||
if (entries.length < 2) return;
|
||||
e.preventDefault();
|
||||
const { invalid } = addEntries(entries);
|
||||
const restored = joinEntries(invalid, type.format);
|
||||
if (invalid.length > 0 && restored !== null)
|
||||
setInputValue(inputValue.trim() ? `${inputValue.trim()}, ${restored}` : restored);
|
||||
};
|
||||
|
||||
const sample = (values: string[]) =>
|
||||
values.length > REPORT_SAMPLE
|
||||
? t('field.entriesSample', '{{list}} and {{count}} more', {
|
||||
list: values.slice(0, REPORT_SAMPLE).join(', '),
|
||||
count: values.length - REPORT_SAMPLE,
|
||||
})
|
||||
: values.join(', ');
|
||||
|
||||
return (
|
||||
<div className="space-y-2">
|
||||
{items.length > 0 && (
|
||||
<div className="flex flex-wrap gap-1.5">
|
||||
{items.map((item) => (
|
||||
<RemovablePill
|
||||
key={item}
|
||||
label={item}
|
||||
onRemove={readOnly ? undefined : () => onChange(items.filter((i) => i !== item))}
|
||||
removeDisabled={minItems != null && items.length <= minItems}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
{!readOnly && (
|
||||
<div className="flex items-center gap-2">
|
||||
<Input
|
||||
{...control}
|
||||
value={inputValue}
|
||||
onChange={(e) => setInputValue(e.target.value)}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter') {
|
||||
e.preventDefault();
|
||||
addTag();
|
||||
<div>
|
||||
<div className="space-y-2">
|
||||
{items.length > 0 && (
|
||||
<div className="flex flex-wrap gap-1.5">
|
||||
{items.map((item) => (
|
||||
<RemovablePill
|
||||
key={item}
|
||||
label={item}
|
||||
onRemove={
|
||||
readOnly
|
||||
? undefined
|
||||
: () => {
|
||||
onChange(items.filter((i) => i !== item));
|
||||
setReport(null);
|
||||
}
|
||||
}
|
||||
removeDisabled={minItems != null && items.length <= minItems}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
{!readOnly && (
|
||||
<div className="flex items-center gap-2">
|
||||
<Input
|
||||
{...control}
|
||||
aria-describedby={
|
||||
[control['aria-describedby'], report ? statusId : null].filter(Boolean).join(' ') || undefined
|
||||
}
|
||||
}}
|
||||
disabled={full}
|
||||
placeholder={placeholder ?? t('field.typeAndPressEnter', 'Type and press Enter...')}
|
||||
className="flex-1"
|
||||
/>
|
||||
<Button
|
||||
type="button"
|
||||
variant="secondary"
|
||||
size="icon"
|
||||
className="shrink-0"
|
||||
onClick={addTag}
|
||||
disabled={!inputValue.trim() || full}
|
||||
aria-label={t('field.addValue', 'Add {{name}}', { name: label })}
|
||||
>
|
||||
<Plus aria-hidden="true" />
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
value={inputValue}
|
||||
onChange={(e) => {
|
||||
setInputValue(e.target.value);
|
||||
setReport(null);
|
||||
}}
|
||||
onPaste={onPaste}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter') {
|
||||
e.preventDefault();
|
||||
addTyped();
|
||||
}
|
||||
}}
|
||||
disabled={full}
|
||||
placeholder={placeholder ?? t('field.typeAndPressEnter', 'Type and press Enter...')}
|
||||
className="flex-1"
|
||||
/>
|
||||
<Button
|
||||
type="button"
|
||||
variant="secondary"
|
||||
size="icon"
|
||||
className="shrink-0"
|
||||
onClick={addTyped}
|
||||
disabled={!inputValue.trim() || full}
|
||||
aria-label={t('field.addValue', 'Add {{name}}', { name: label })}
|
||||
>
|
||||
<Plus aria-hidden="true" />
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<div id={statusId} role="status" className="mt-2 space-y-0.5 text-[12.5px] empty:mt-0">
|
||||
{report && report.added.length > 0 && (
|
||||
<p className="text-muted-foreground">
|
||||
{t('field.entriesAdded', 'Added {{count}} values.', { count: report.added.length })}
|
||||
</p>
|
||||
)}
|
||||
{report && report.duplicates.length > 0 && (
|
||||
<p className="text-muted-foreground">
|
||||
{t('field.entriesDuplicate', 'Skipped {{count}} duplicates: {{list}}', {
|
||||
count: report.duplicates.length,
|
||||
list: sample(report.duplicates),
|
||||
})}
|
||||
</p>
|
||||
)}
|
||||
{report && report.invalid.length > 0 && (
|
||||
<p className="text-destructive">
|
||||
{t('field.entriesInvalid', 'Not added, invalid: {{list}}', {
|
||||
count: report.invalid.length,
|
||||
list: sample(report.invalid),
|
||||
})}
|
||||
</p>
|
||||
)}
|
||||
{report && report.overLimit.length > 0 && (
|
||||
<p className="text-destructive">
|
||||
{t('field.entriesOverLimit', 'Not added, the limit is {{max}}: {{list}}', {
|
||||
count: report.overLimit.length,
|
||||
max: maxItems,
|
||||
list: sample(report.overLimit),
|
||||
})}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -72,12 +72,27 @@ export function MultilineWidget(props: WidgetProps<FieldTypeString>) {
|
||||
</div>
|
||||
);
|
||||
}
|
||||
if (type.format === 'sieve') {
|
||||
return <BufferedTextarea {...common} rows={16} spellCheck={false} className="font-mono text-xs" />;
|
||||
}
|
||||
return <BufferedTextarea {...common} rows={4} />;
|
||||
}
|
||||
|
||||
export function SieveWidget(props: WidgetProps<FieldTypeString>) {
|
||||
const { type, formField, value, readOnly, control } = props;
|
||||
return (
|
||||
<BufferedTextarea
|
||||
{...control}
|
||||
value={stringValue(value)}
|
||||
onCommit={stringCommitter(props)}
|
||||
disabled={readOnly}
|
||||
placeholder={formField.placeholder}
|
||||
minLength={type.minLength}
|
||||
maxLength={type.maxLength}
|
||||
rows={16}
|
||||
spellCheck={false}
|
||||
className="font-mono text-xs"
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export function ColorWidget(props: WidgetProps<FieldTypeString>) {
|
||||
const { t } = useTranslation();
|
||||
const { value, readOnly, control } = props;
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
/*
|
||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
import { useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { LocateFixed } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Combobox, type ComboboxOption } from '@/components/ui/combobox';
|
||||
import { useFormContext } from '@/components/forms/formContext';
|
||||
import { formatUtcOffset } from '@/lib/format';
|
||||
import { getEnum } from '@/lib/schemaResolver';
|
||||
import type { WidgetProps } from '@/components/forms/widgets/types';
|
||||
import type { EnumVariant, FieldTypeEnum } from '@/types/schema';
|
||||
|
||||
function browserTimeZone(): string | null {
|
||||
try {
|
||||
return Intl.DateTimeFormat().resolvedOptions().timeZone || null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function zoneOffsets(variants: readonly EnumVariant[], at: Date): ReadonlyMap<string, string> {
|
||||
const offsets = new Map<string, string>();
|
||||
for (const { name } of variants) {
|
||||
const offset = formatUtcOffset(name, at);
|
||||
if (offset) offsets.set(name, offset);
|
||||
}
|
||||
return offsets;
|
||||
}
|
||||
|
||||
export function TimeZoneWidget({ type, value, onChange, readOnly, control }: WidgetProps<FieldTypeEnum>) {
|
||||
const { t } = useTranslation();
|
||||
const { schema } = useFormContext();
|
||||
const variants = getEnum(schema, type.enumName);
|
||||
const [now] = useState(() => new Date());
|
||||
const [offsets, setOffsets] = useState<ReadonlyMap<string, string> | null>(null);
|
||||
const current = typeof value === 'string' ? value : '';
|
||||
const currentOffset = current ? (offsets?.get(current) ?? formatUtcOffset(current, now)) : null;
|
||||
const local = browserTimeZone();
|
||||
const localVariant = local ? variants.find((v) => v.name === local) : undefined;
|
||||
|
||||
const options: ComboboxOption[] = variants.map((v) => {
|
||||
const offset = offsets?.get(v.name);
|
||||
return {
|
||||
value: v.name,
|
||||
label: v.label,
|
||||
description: offset,
|
||||
keywords: offset ? [v.name, offset] : [v.name],
|
||||
};
|
||||
});
|
||||
|
||||
return (
|
||||
<div className="space-y-1.5">
|
||||
<Combobox
|
||||
{...control}
|
||||
options={options}
|
||||
value={current}
|
||||
onValueChange={(v) => onChange(v === '' ? null : v)}
|
||||
onFirstOpen={() => setOffsets(zoneOffsets(variants, now))}
|
||||
placeholder={t('field.selectEllipsis', 'Select...')}
|
||||
searchPlaceholder={t('timeZone.search', 'Search by city, region or offset...')}
|
||||
emptyText={t('field.noMatches', 'No matches')}
|
||||
nullLabel={t('field.none', 'None')}
|
||||
nullable={type.nullable}
|
||||
disabled={readOnly}
|
||||
/>
|
||||
{(currentOffset || (localVariant && local !== current && !readOnly)) && (
|
||||
<div className="flex flex-wrap items-center gap-x-3 gap-y-1">
|
||||
{currentOffset && (
|
||||
<span className="text-[12.5px] text-muted-foreground tabular-nums">
|
||||
{t('timeZone.currentOffset', 'Currently {{offset}}', { offset: currentOffset })}
|
||||
</span>
|
||||
)}
|
||||
{localVariant && local !== current && !readOnly && (
|
||||
<Button
|
||||
type="button"
|
||||
variant="link"
|
||||
size="sm"
|
||||
className="h-auto px-0 py-0.5"
|
||||
onClick={() => onChange(localVariant.name)}
|
||||
>
|
||||
<LocateFixed className="h-3.5 w-3.5" aria-hidden="true" />
|
||||
{t('timeZone.useMine', 'Use my time zone ({{zone}})', { zone: localVariant.label })}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,291 @@
|
||||
/*
|
||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
import { useId } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Plus, Trash2 } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { useEnclosingSchema, useFormContext, useInPanel } from '@/components/forms/formContext';
|
||||
import { LocalTimeInput } from '@/components/forms/widgets/LocalTimeInput';
|
||||
import { WeekChart } from '@/components/values/WeeklyScheduleValue';
|
||||
import { formatSlot, localeWeekdayOrder } from '@/lib/scheduleFormat';
|
||||
import { formatWeekday } from '@/lib/format';
|
||||
import { buildNewObjectValue } from '@/lib/schemaResolver';
|
||||
import { isRecord } from '@/lib/embeddedSchema';
|
||||
import {
|
||||
PRESETS,
|
||||
WORKING_HOURS_SLOT,
|
||||
daysValue,
|
||||
isOvernight,
|
||||
nextSlotKey,
|
||||
parseSlot,
|
||||
presetsFor,
|
||||
scheduleRules,
|
||||
slotEntries,
|
||||
slotIssue,
|
||||
slotsValue,
|
||||
type PresetName,
|
||||
type ScheduleRules,
|
||||
type Slot,
|
||||
type SlotIssue,
|
||||
type Weekday,
|
||||
} from '@/lib/weeklySchedule';
|
||||
import { cn } from '@/lib/utils';
|
||||
import type { WidgetProps } from '@/components/forms/widgets/types';
|
||||
import type { FieldTypeObjectList } from '@/types/schema';
|
||||
|
||||
const FIRST_SLOT_DAYS: readonly Weekday[] = PRESETS.workdays[0].days;
|
||||
|
||||
export interface WeeklyScheduleEditorProps {
|
||||
value: unknown;
|
||||
onChange: (value: Record<string, unknown>) => void;
|
||||
rules: ScheduleRules;
|
||||
readOnly?: boolean;
|
||||
minItems?: number;
|
||||
maxItems?: number;
|
||||
}
|
||||
|
||||
function useIssueMessage(): (issue: SlotIssue) => string {
|
||||
const { t } = useTranslation();
|
||||
return (issue) => {
|
||||
switch (issue) {
|
||||
case 'noDays':
|
||||
return t('schedule.issueNoDays', 'Choose at least one day.');
|
||||
case 'missingTime':
|
||||
return t('schedule.issueMissingTime', 'Enter a start and an end time.');
|
||||
case 'endNotAfterStart':
|
||||
return t(
|
||||
'schedule.issueEndNotAfterStart',
|
||||
'The end must be later than the start. Split hours that cross midnight into two intervals.',
|
||||
);
|
||||
case 'startAtEndOfDay':
|
||||
return t('schedule.issueStartAtEndOfDay', 'The start must be before 24:00.');
|
||||
case 'sameStartEnd':
|
||||
return t('schedule.issueSameStartEnd', 'The start and the end cannot be the same time.');
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
interface DayTogglesProps {
|
||||
days: readonly Weekday[];
|
||||
order: readonly Weekday[];
|
||||
onToggle: (day: Weekday) => void;
|
||||
disabled: boolean;
|
||||
label: string;
|
||||
}
|
||||
|
||||
function DayToggles({ days, order, onToggle, disabled, label }: DayTogglesProps) {
|
||||
const inPanel = useInPanel();
|
||||
return (
|
||||
<div
|
||||
role="group"
|
||||
aria-label={label}
|
||||
className={cn('inline-flex shrink-0 gap-0.5 rounded-full p-1', inPanel ? 'bg-muted' : 'bg-card')}
|
||||
>
|
||||
{order.map((day) => {
|
||||
const on = days.includes(day);
|
||||
const name = formatWeekday(day, 'long');
|
||||
return (
|
||||
<button
|
||||
key={day}
|
||||
type="button"
|
||||
aria-pressed={on}
|
||||
aria-label={name}
|
||||
title={name}
|
||||
disabled={disabled}
|
||||
onClick={() => onToggle(day)}
|
||||
className={cn(
|
||||
'inline-flex h-7 w-7 items-center justify-center rounded-full text-[12.5px] font-semibold outline-none transition-[color,background-color] duration-200 focus-visible:ring-2 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-60',
|
||||
on ? 'bg-primary text-primary-foreground' : 'text-muted-foreground hover:text-foreground',
|
||||
)}
|
||||
>
|
||||
<span aria-hidden="true">{formatWeekday(day, 'narrow')}</span>
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function WeeklyScheduleEditor({
|
||||
value,
|
||||
onChange,
|
||||
rules,
|
||||
readOnly = false,
|
||||
minItems,
|
||||
maxItems,
|
||||
}: WeeklyScheduleEditorProps) {
|
||||
const { t } = useTranslation();
|
||||
const { schema } = useFormContext();
|
||||
const inPanel = useInPanel();
|
||||
const baseId = useId();
|
||||
const issueMessage = useIssueMessage();
|
||||
const order = localeWeekdayOrder();
|
||||
const items = isRecord(value) ? value : {};
|
||||
const raw = slotEntries(items);
|
||||
const entries = raw.map(([key, item]): [string, Slot] => [key, parseSlot(item)]);
|
||||
const canAdd = !readOnly && (maxItems == null || entries.length < maxItems);
|
||||
const canRemove = !readOnly && (minItems == null || entries.length > minItems);
|
||||
const summary = entries.map(([, slot]) => formatSlot(t, slot, order, rules));
|
||||
|
||||
const slotRecord = (key: string): Record<string, unknown> => {
|
||||
const item = items[key];
|
||||
return isRecord(item) ? item : {};
|
||||
};
|
||||
|
||||
const timeValue = (key: string, name: 'start' | 'end'): string | null => {
|
||||
const time = slotRecord(key)[name];
|
||||
return typeof time === 'string' ? time : null;
|
||||
};
|
||||
|
||||
const update = (key: string, patch: Record<string, unknown>) =>
|
||||
onChange({ ...items, [key]: { ...slotRecord(key), ...patch } });
|
||||
|
||||
const toggleDay = (key: string, slot: Slot, day: Weekday) => {
|
||||
const days = slot.days.includes(day) ? slot.days.filter((d) => d !== day) : [...slot.days, day];
|
||||
update(key, { days: daysValue(days) });
|
||||
};
|
||||
|
||||
const addSlot = () => {
|
||||
const last = entries.at(-1)?.[1];
|
||||
const days = last && last.days.length > 0 ? last.days : FIRST_SLOT_DAYS;
|
||||
onChange({
|
||||
...items,
|
||||
[nextSlotKey(raw)]: { ...buildNewObjectValue(schema, WORKING_HOURS_SLOT), days: daysValue(days) },
|
||||
});
|
||||
};
|
||||
|
||||
const removeSlot = (key: string) => {
|
||||
const copy = { ...items };
|
||||
delete copy[key];
|
||||
onChange(copy);
|
||||
};
|
||||
|
||||
const applyPreset = (preset: PresetName) => onChange(slotsValue(PRESETS[preset]));
|
||||
|
||||
return (
|
||||
<div className="space-y-3" data-slot="weekly-schedule">
|
||||
{entries.length > 0 ? (
|
||||
<div className={cn('rounded-xl p-3', inPanel ? 'bg-card shadow-tile' : 'bg-muted')}>
|
||||
<WeekChart entries={entries} rules={rules} order={order} label={summary.join('; ')} />
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-2">
|
||||
<p className="text-sm text-muted-foreground">{t('schedule.empty', 'No intervals yet.')}</p>
|
||||
{!readOnly && (
|
||||
<div className="space-y-1.5">
|
||||
<p className="text-[13px] text-muted-foreground">{t('schedule.startFrom', 'Start from:')}</p>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{presetsFor(rules).map((preset) => (
|
||||
<Button key={preset} type="button" variant="outline" size="sm" onClick={() => applyPreset(preset)}>
|
||||
{preset === 'outsideWorkdays'
|
||||
? t('schedule.presetOutsideWorkdays', 'Evenings, nights and weekends')
|
||||
: formatSlot(t, parseSlot(slotsValue(PRESETS[preset])[0]), order, rules)}
|
||||
</Button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{minItems != null && minItems > 0 && (
|
||||
<p className="text-xs font-medium text-destructive">
|
||||
{t('schedule.issueEmpty', 'Add at least one interval.')}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
{entries.map(([key, slot], position) => {
|
||||
const issue = slotIssue(slot, rules);
|
||||
const slotLabel = t('schedule.interval', 'Interval {{n}}', { n: position + 1 });
|
||||
const issueId = `${baseId}-${key}-issue`;
|
||||
const describedBy = issue ? issueId : undefined;
|
||||
return (
|
||||
<div
|
||||
key={key}
|
||||
role="group"
|
||||
aria-label={slotLabel}
|
||||
data-slot="schedule-slot"
|
||||
className={cn('space-y-2 rounded-xl p-3', inPanel ? 'bg-card shadow-tile' : 'bg-muted')}
|
||||
>
|
||||
<div className="flex items-start gap-2 sm:items-center">
|
||||
<div className="flex min-w-0 flex-1 flex-wrap items-center gap-x-4 gap-y-2">
|
||||
<DayToggles
|
||||
days={slot.days}
|
||||
order={order}
|
||||
onToggle={(day) => toggleDay(key, slot, day)}
|
||||
disabled={readOnly}
|
||||
label={t('schedule.days', 'Days')}
|
||||
/>
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<LocalTimeInput
|
||||
value={timeValue(key, 'start')}
|
||||
onChange={(start) => update(key, { start })}
|
||||
disabled={readOnly}
|
||||
aria-label={t('schedule.start', '{{slot}} start', { slot: slotLabel })}
|
||||
aria-invalid={issue !== null && issue !== 'noDays' ? true : undefined}
|
||||
aria-describedby={describedBy}
|
||||
/>
|
||||
<span className="flex items-center gap-2">
|
||||
<span className="text-[13px] text-muted-foreground">{t('schedule.to', 'to')}</span>
|
||||
<LocalTimeInput
|
||||
value={timeValue(key, 'end')}
|
||||
onChange={(end) => update(key, { end })}
|
||||
allowEndOfDay
|
||||
disabled={readOnly}
|
||||
aria-label={t('schedule.end', '{{slot}} end', { slot: slotLabel })}
|
||||
aria-invalid={issue !== null && issue !== 'noDays' ? true : undefined}
|
||||
aria-describedby={describedBy}
|
||||
/>
|
||||
</span>
|
||||
{isOvernight(slot, rules) && (
|
||||
<span className="text-[12.5px] text-muted-foreground">{t('schedule.nextDay', 'next day')}</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
{!readOnly && (
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost-danger"
|
||||
size="icon-sm"
|
||||
className="mt-0.5 shrink-0 sm:mt-0"
|
||||
onClick={() => removeSlot(key)}
|
||||
disabled={!canRemove}
|
||||
aria-label={t('schedule.remove', 'Remove {{slot}}', { slot: slotLabel })}
|
||||
>
|
||||
<Trash2 className="h-4 w-4" aria-hidden="true" />
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
{issue && (
|
||||
<p id={issueId} className="text-xs font-medium text-destructive">
|
||||
{issueMessage(issue)}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
{canAdd && (
|
||||
<Button type="button" variant="secondary" size="sm" onClick={addSlot}>
|
||||
<Plus className="h-4 w-4" aria-hidden="true" />
|
||||
{t('schedule.add', 'Add interval')}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function WeeklyScheduleWidget({ type, value, onChange, readOnly }: WidgetProps<FieldTypeObjectList>) {
|
||||
const rules = scheduleRules(useEnclosingSchema());
|
||||
return (
|
||||
<WeeklyScheduleEditor
|
||||
value={value}
|
||||
onChange={onChange}
|
||||
rules={rules}
|
||||
readOnly={readOnly}
|
||||
minItems={type.minItems}
|
||||
maxItems={type.maxItems}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -18,6 +18,10 @@ export function formatPlaceholder(format: StringFormat): string | undefined {
|
||||
return 'user@example.com';
|
||||
case 'uri':
|
||||
return 'https://example.com';
|
||||
case 'localTime':
|
||||
return 'HH:MM';
|
||||
case 'localDate':
|
||||
return 'YYYY-MM-DD';
|
||||
default:
|
||||
return undefined;
|
||||
}
|
||||
|
||||
@@ -1,117 +0,0 @@
|
||||
/*
|
||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
import type { FieldType } from '@/types/schema';
|
||||
|
||||
export type LabelMode = 'control' | 'group' | 'none';
|
||||
|
||||
type RowLayout = 'side' | 'block' | 'inline';
|
||||
|
||||
export interface WidgetTraits {
|
||||
labelMode: LabelMode;
|
||||
readOnlyAsValue: boolean;
|
||||
layout: RowLayout;
|
||||
createOnly?: true;
|
||||
}
|
||||
|
||||
export type WidgetKey =
|
||||
| 'string'
|
||||
| 'string:secret'
|
||||
| 'string:multiline'
|
||||
| 'string:color'
|
||||
| 'number'
|
||||
| 'number:size'
|
||||
| 'number:duration'
|
||||
| 'utcDateTime'
|
||||
| 'boolean'
|
||||
| 'enum'
|
||||
| 'blobId'
|
||||
| 'objectId'
|
||||
| 'object'
|
||||
| 'object:x:Expression'
|
||||
| 'object:x:Rate'
|
||||
| 'object:x:OtpAuth'
|
||||
| 'object:x:PasskeyRegistration'
|
||||
| 'objectList'
|
||||
| 'set'
|
||||
| 'set:enum'
|
||||
| 'map'
|
||||
| 'unsupported';
|
||||
|
||||
export function widgetKey(type: FieldType): WidgetKey {
|
||||
switch (type.type) {
|
||||
case 'string':
|
||||
switch (type.format) {
|
||||
case 'secret':
|
||||
case 'secretText':
|
||||
return 'string:secret';
|
||||
case 'text':
|
||||
case 'html':
|
||||
case 'sieve':
|
||||
return 'string:multiline';
|
||||
case 'color':
|
||||
return 'string:color';
|
||||
default:
|
||||
return 'string';
|
||||
}
|
||||
case 'number':
|
||||
return type.format === 'size' ? 'number:size' : type.format === 'duration' ? 'number:duration' : 'number';
|
||||
case 'object':
|
||||
switch (type.objectName) {
|
||||
case 'x:Expression':
|
||||
return 'object:x:Expression';
|
||||
case 'x:Rate':
|
||||
return 'object:x:Rate';
|
||||
case 'x:OtpAuth':
|
||||
return 'object:x:OtpAuth';
|
||||
case 'x:PasskeyRegistration':
|
||||
return 'object:x:PasskeyRegistration';
|
||||
default:
|
||||
return 'object';
|
||||
}
|
||||
case 'set':
|
||||
return type.class.type === 'enum' ? 'set:enum' : 'set';
|
||||
case 'utcDateTime':
|
||||
case 'boolean':
|
||||
case 'enum':
|
||||
case 'blobId':
|
||||
case 'objectId':
|
||||
case 'objectList':
|
||||
case 'map':
|
||||
return type.type;
|
||||
default:
|
||||
return 'unsupported';
|
||||
}
|
||||
}
|
||||
|
||||
const TRAITS: Record<WidgetKey, WidgetTraits> = {
|
||||
string: { labelMode: 'control', readOnlyAsValue: true, layout: 'side' },
|
||||
'string:secret': { labelMode: 'control', readOnlyAsValue: true, layout: 'side' },
|
||||
'string:multiline': { labelMode: 'control', readOnlyAsValue: true, layout: 'block' },
|
||||
'string:color': { labelMode: 'control', readOnlyAsValue: true, layout: 'side' },
|
||||
number: { labelMode: 'control', readOnlyAsValue: true, layout: 'side' },
|
||||
'number:size': { labelMode: 'control', readOnlyAsValue: true, layout: 'side' },
|
||||
'number:duration': { labelMode: 'control', readOnlyAsValue: true, layout: 'side' },
|
||||
utcDateTime: { labelMode: 'control', readOnlyAsValue: true, layout: 'side' },
|
||||
boolean: { labelMode: 'control', readOnlyAsValue: true, layout: 'inline' },
|
||||
enum: { labelMode: 'control', readOnlyAsValue: true, layout: 'side' },
|
||||
blobId: { labelMode: 'control', readOnlyAsValue: false, layout: 'block' },
|
||||
objectId: { labelMode: 'control', readOnlyAsValue: true, layout: 'side' },
|
||||
object: { labelMode: 'group', readOnlyAsValue: false, layout: 'block' },
|
||||
'object:x:Expression': { labelMode: 'group', readOnlyAsValue: false, layout: 'block' },
|
||||
'object:x:Rate': { labelMode: 'control', readOnlyAsValue: false, layout: 'side' },
|
||||
'object:x:OtpAuth': { labelMode: 'none', readOnlyAsValue: false, layout: 'block' },
|
||||
'object:x:PasskeyRegistration': { labelMode: 'none', readOnlyAsValue: false, layout: 'block', createOnly: true },
|
||||
objectList: { labelMode: 'group', readOnlyAsValue: false, layout: 'block' },
|
||||
set: { labelMode: 'control', readOnlyAsValue: true, layout: 'side' },
|
||||
'set:enum': { labelMode: 'group', readOnlyAsValue: true, layout: 'side' },
|
||||
map: { labelMode: 'group', readOnlyAsValue: false, layout: 'block' },
|
||||
unsupported: { labelMode: 'none', readOnlyAsValue: false, layout: 'block' },
|
||||
};
|
||||
|
||||
export function widgetTraits(type: FieldType): WidgetTraits {
|
||||
return TRAITS[widgetKey(type)];
|
||||
}
|
||||
@@ -23,4 +23,5 @@ export interface WidgetProps<T extends FieldType = FieldType> {
|
||||
onChange: (value: unknown) => void;
|
||||
readOnly: boolean;
|
||||
control: ControlProps;
|
||||
error?: string;
|
||||
}
|
||||
@@ -4,49 +4,17 @@
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
import { lazy, Suspense, type ComponentType, type ReactNode } from 'react';
|
||||
import { Suspense, type ReactNode } from 'react';
|
||||
import { useLocation } from 'react-router-dom';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import type { TFunction } from 'i18next';
|
||||
import { useSchemaStore } from '@/stores/schemaStore';
|
||||
import { usePermissionCheckers } from '@/hooks/usePermissions';
|
||||
import { resolveObject } from '@/lib/schemaResolver';
|
||||
import type { PermissionCheckers } from '@/lib/permissions';
|
||||
import { pageObjectId, resolvePage, type PageTarget } from '@/extensions/pages';
|
||||
import { ErrorBoundary } from '@/components/layout/ErrorBoundary';
|
||||
import { DynamicList } from '@/components/lists/DynamicList';
|
||||
import { DynamicForm } from '@/components/forms/DynamicForm';
|
||||
import { DynamicViewPage } from '@/components/views/DynamicViewPage';
|
||||
import { LoadingFallback } from '@/components/common/LoadingFallback';
|
||||
import type { Schema } from '@/types/schema';
|
||||
|
||||
function lazyFeature<M, P>(load: () => Promise<M>, select: (module: M) => ComponentType<P>) {
|
||||
return lazy(() => load().then((module) => ({ default: select(module) })));
|
||||
}
|
||||
|
||||
const DeliveryTracePage = lazyFeature(
|
||||
() => import('@/features/troubleshoot/DeliveryTracePage'),
|
||||
(m) => m.DeliveryTracePage,
|
||||
);
|
||||
// SPDX-SnippetBegin
|
||||
// SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
// SPDX-License-Identifier: LicenseRef-SEL
|
||||
const DashboardView = lazyFeature(
|
||||
() => import('@/features/dashboard/components/DashboardView'),
|
||||
(m) => m.DashboardView,
|
||||
);
|
||||
const LiveTracingPage = lazyFeature(
|
||||
() => import('@/features/tracing/components/LiveTracingPage'),
|
||||
(m) => m.LiveTracingPage,
|
||||
);
|
||||
const TraceDetailView = lazyFeature(
|
||||
() => import('@/features/tracing/components/TraceDetailView'),
|
||||
(m) => m.TraceDetailView,
|
||||
);
|
||||
// SPDX-SnippetEnd
|
||||
const ActionPage = lazyFeature(
|
||||
() => import('@/features/actions/ActionPage'),
|
||||
(m) => m.ActionPage,
|
||||
);
|
||||
|
||||
interface MainContentProps {
|
||||
viewName?: string;
|
||||
@@ -54,104 +22,68 @@ interface MainContentProps {
|
||||
section?: string;
|
||||
}
|
||||
|
||||
export function MainContent({ viewName, id, section }: MainContentProps) {
|
||||
function genericView(viewName: string, target: PageTarget, key: string): ReactNode {
|
||||
switch (target.mode) {
|
||||
case 'list':
|
||||
return <DynamicList key={key} viewName={viewName} />;
|
||||
case 'create':
|
||||
return <DynamicForm key={key} viewName={viewName} objectId={null} />;
|
||||
case 'singleton':
|
||||
return <DynamicForm key={key} viewName={viewName} objectId="singleton" />;
|
||||
case 'edit':
|
||||
return <DynamicForm key={key} viewName={viewName} objectId={target.id} />;
|
||||
case 'detail':
|
||||
return <DynamicViewPage key={key} viewName={viewName} objectId={target.id} />;
|
||||
}
|
||||
}
|
||||
|
||||
export function MainContent({ viewName, id, section = '' }: MainContentProps) {
|
||||
const schema = useSchemaStore((s) => s.schema);
|
||||
const permissions = usePermissionCheckers();
|
||||
const location = useLocation();
|
||||
const { t } = useTranslation();
|
||||
const page = resolvePage(schema, viewName, id, permissions);
|
||||
|
||||
let content: ReactNode;
|
||||
switch (page.kind) {
|
||||
case 'loading':
|
||||
content = <LoadingFallback />;
|
||||
break;
|
||||
case 'unknownComponent':
|
||||
content = (
|
||||
<div className="mt-3 rounded-2xl bg-muted p-10 text-center text-muted-foreground">
|
||||
{t('errors.unknownComponent', 'Unknown component: {{name}}', { name: page.name })}
|
||||
</div>
|
||||
);
|
||||
break;
|
||||
case 'unknownView':
|
||||
content = (
|
||||
<div role="alert" className="mt-3 rounded-xl bg-destructive-soft p-4 text-center text-sm text-destructive">
|
||||
{t('errors.unknownView', 'Unknown view: {{name}}', { name: viewName })}
|
||||
</div>
|
||||
);
|
||||
break;
|
||||
case 'route': {
|
||||
const Page = page.component;
|
||||
content = <Page viewName={page.viewName} objectId={id ?? null} section={section} />;
|
||||
break;
|
||||
}
|
||||
case 'object': {
|
||||
const objectId = pageObjectId(page.target);
|
||||
const key = objectId ? `${page.viewName}/${objectId}` : page.viewName;
|
||||
const Page = page.component;
|
||||
content = Page ? (
|
||||
<Page key={key} viewName={page.viewName} objectId={objectId} section={section} />
|
||||
) : (
|
||||
genericView(page.viewName, page.target, key)
|
||||
);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<ErrorBoundary resetKey={location.pathname}>
|
||||
<Suspense fallback={<LoadingFallback />}>{renderView(t, schema, permissions, viewName, id, section)}</Suspense>
|
||||
<Suspense fallback={<LoadingFallback />}>{content}</Suspense>
|
||||
</ErrorBoundary>
|
||||
);
|
||||
}
|
||||
|
||||
function renderView(
|
||||
t: TFunction,
|
||||
schema: Schema | null,
|
||||
permissions: PermissionCheckers,
|
||||
viewName?: string,
|
||||
id?: string,
|
||||
section?: string,
|
||||
): ReactNode {
|
||||
if (!viewName) {
|
||||
return <LoadingFallback />;
|
||||
}
|
||||
|
||||
// SPDX-SnippetBegin
|
||||
// SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
// SPDX-License-Identifier: LicenseRef-SEL
|
||||
if (viewName.startsWith('Dashboard/')) {
|
||||
const dashboardId = viewName.slice('Dashboard/'.length);
|
||||
return <DashboardView dashboardId={dashboardId} section={section ?? ''} />;
|
||||
}
|
||||
// SPDX-SnippetEnd
|
||||
|
||||
if (viewName.startsWith('CustomComponent/')) {
|
||||
const componentName = viewName.slice('CustomComponent/'.length);
|
||||
// SPDX-SnippetBegin
|
||||
// SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
// SPDX-License-Identifier: LicenseRef-SEL
|
||||
if (componentName === 'Dashboard') {
|
||||
const firstId = schema?.dashboards?.[0]?.id ?? 'overview';
|
||||
return <DashboardView dashboardId={firstId} section={section ?? ''} />;
|
||||
}
|
||||
// SPDX-SnippetEnd
|
||||
if (componentName === 'LiveDelivery') {
|
||||
return <DeliveryTracePage />;
|
||||
}
|
||||
// SPDX-SnippetBegin
|
||||
// SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
// SPDX-License-Identifier: LicenseRef-SEL
|
||||
if (componentName === 'LiveTracing') {
|
||||
return <LiveTracingPage />;
|
||||
}
|
||||
// SPDX-SnippetEnd
|
||||
return (
|
||||
<div className="mt-3 rounded-2xl bg-muted p-10 text-center text-muted-foreground">
|
||||
{t('errors.unknownComponent', 'Unknown component: {{name}}', { name: componentName })}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (!schema) {
|
||||
return <LoadingFallback />;
|
||||
}
|
||||
|
||||
const resolved = resolveObject(schema, viewName);
|
||||
if (!resolved) {
|
||||
return (
|
||||
<div role="alert" className="mt-3 rounded-xl bg-destructive-soft p-4 text-center text-sm text-destructive">
|
||||
{t('errors.unknownView', 'Unknown view: {{name}}', { name: viewName })}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (resolved.objectName === 'x:Action') {
|
||||
return <ActionPage key={viewName} viewName={viewName} />;
|
||||
}
|
||||
|
||||
if (resolved.objectType.type === 'singleton') {
|
||||
return <DynamicForm key={`${viewName}/singleton`} viewName={viewName} objectId="singleton" />;
|
||||
}
|
||||
|
||||
if (id === 'new') {
|
||||
return <DynamicForm key={`${viewName}/new`} viewName={viewName} objectId={null} />;
|
||||
}
|
||||
|
||||
if (id) {
|
||||
// SPDX-SnippetBegin
|
||||
// SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
// SPDX-License-Identifier: LicenseRef-SEL
|
||||
if (resolved.objectName === 'x:Trace') {
|
||||
return <TraceDetailView key={`${viewName}/${id}`} viewName={viewName} objectId={id} />;
|
||||
}
|
||||
// SPDX-SnippetEnd
|
||||
if (!permissions.hasObjectPermission(resolved.permissionPrefix, 'Update')) {
|
||||
return <DynamicViewPage key={`${viewName}/${id}`} viewName={viewName} objectId={id} />;
|
||||
}
|
||||
return <DynamicForm key={`${viewName}/${id}`} viewName={viewName} objectId={id} />;
|
||||
}
|
||||
|
||||
return <DynamicList key={viewName} viewName={viewName} />;
|
||||
}
|
||||
@@ -92,7 +92,7 @@ export function FilterBar({ schema, filters, applied, isXPrefixed, disabled, onA
|
||||
onSubmit={handleSubmit}
|
||||
className="mx-2.5 mb-2.5 rounded-xl bg-muted p-4"
|
||||
>
|
||||
<div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
|
||||
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3">
|
||||
{filters.map((filter) => (
|
||||
<FilterField
|
||||
key={filter.field}
|
||||
|
||||
@@ -11,6 +11,7 @@ import { Input } from '@/components/ui/input';
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
|
||||
import { Combobox } from '@/components/ui/combobox';
|
||||
import { ObjectPicker } from '@/components/common/ObjectPicker';
|
||||
import { SearchInput } from '@/components/common/SearchInput';
|
||||
import { getEnum } from '@/lib/schemaResolver';
|
||||
import type { Filter, FilterDate, FilterEnum, FilterInteger, FilterObjectId, FilterText, Schema } from '@/types/schema';
|
||||
|
||||
@@ -33,7 +34,7 @@ function opField(filter: Filter): string {
|
||||
|
||||
function LabelledField({ id, label, children }: { id: string; label: string; children: ReactNode }) {
|
||||
return (
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<div className="flex min-w-0 flex-col gap-1.5">
|
||||
<label htmlFor={id} className="text-[12.5px] font-semibold text-muted-foreground">
|
||||
{label}
|
||||
</label>
|
||||
@@ -45,7 +46,7 @@ function LabelledField({ id, label, children }: { id: string; label: string; chi
|
||||
function GroupField({ label, children }: { label: string; children: ReactNode }) {
|
||||
const labelId = useId();
|
||||
return (
|
||||
<div role="group" aria-labelledby={labelId} className="flex flex-col gap-1.5">
|
||||
<div role="group" aria-labelledby={labelId} className="flex min-w-0 flex-col gap-1.5">
|
||||
<span id={labelId} className="text-[12.5px] font-semibold text-muted-foreground">
|
||||
{label}
|
||||
</span>
|
||||
@@ -59,12 +60,11 @@ function TextFilter({ filter, values, onChange }: FilterFieldProps<FilterText>)
|
||||
const id = useId();
|
||||
return (
|
||||
<LabelledField id={id} label={filter.label}>
|
||||
<Input
|
||||
<SearchInput
|
||||
id={id}
|
||||
type="search"
|
||||
placeholder={t('list.filterPlaceholder', 'Search {{label}}...', { label: filter.label.toLowerCase() })}
|
||||
value={values[filter.field] ?? ''}
|
||||
onChange={(e) => onChange(filter.field, e.target.value)}
|
||||
onValueChange={(next) => onChange(filter.field, next)}
|
||||
/>
|
||||
</LabelledField>
|
||||
);
|
||||
|
||||
@@ -25,6 +25,7 @@ function PopoverContent({
|
||||
className,
|
||||
align = 'center',
|
||||
sideOffset = 4,
|
||||
collisionPadding = 8,
|
||||
...props
|
||||
}: React.ComponentProps<typeof PopoverPrimitive.Content>) {
|
||||
return (
|
||||
@@ -33,6 +34,7 @@ function PopoverContent({
|
||||
data-slot="popover-content"
|
||||
align={align}
|
||||
sideOffset={sideOffset}
|
||||
collisionPadding={collisionPadding}
|
||||
className={cn(
|
||||
'z-50 w-72 popover-surface p-4 outline-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2',
|
||||
className,
|
||||
|
||||
@@ -32,9 +32,9 @@ function SelectTrigger({
|
||||
<SelectPrimitive.Trigger
|
||||
data-slot="select-trigger"
|
||||
className={cn(
|
||||
'flex items-center justify-between whitespace-nowrap placeholder:text-dim focus:outline-none disabled:cursor-not-allowed disabled:opacity-50 [&>span]:line-clamp-1',
|
||||
'flex items-center justify-between whitespace-nowrap placeholder:text-dim focus:outline-none disabled:cursor-not-allowed disabled:opacity-50 [&>span]:min-w-0 [&>span]:truncate',
|
||||
variant === 'field'
|
||||
? 'field-surface h-9 w-full rounded-lg px-3 py-2 text-sm'
|
||||
? 'field-surface h-9 w-full gap-2 rounded-lg px-3 py-2 text-sm'
|
||||
: 'h-8 w-auto gap-2 rounded-full bg-card px-3.5 text-[13px] font-semibold shadow-tile transition-shadow duration-200 hover:shadow-lift focus-visible:ring-2 focus-visible:ring-ring data-[state=open]:shadow-lift',
|
||||
className,
|
||||
)}
|
||||
@@ -42,7 +42,7 @@ function SelectTrigger({
|
||||
>
|
||||
{children}
|
||||
<SelectPrimitive.Icon asChild>
|
||||
<ChevronDown className="h-4 w-4 opacity-50" />
|
||||
<ChevronDown className="h-4 w-4 shrink-0 opacity-50" />
|
||||
</SelectPrimitive.Icon>
|
||||
</SelectPrimitive.Trigger>
|
||||
);
|
||||
@@ -88,7 +88,7 @@ function SelectContent({
|
||||
className={cn(
|
||||
'relative z-50 max-h-96 min-w-[8rem] overflow-hidden popover-surface data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2',
|
||||
position === 'popper' &&
|
||||
'data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1',
|
||||
'max-w-[var(--radix-select-content-available-width)] data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1',
|
||||
className,
|
||||
)}
|
||||
position={position}
|
||||
|
||||
@@ -12,7 +12,8 @@ import { cn } from '@/lib/utils';
|
||||
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from '@/components/ui/collapsible';
|
||||
import { HelpTooltip } from '@/components/common/HelpTooltip';
|
||||
import { formatDateTime } from '@/lib/format';
|
||||
import { getEnumVariant } from '@/lib/schemaResolver';
|
||||
import { resolveWidget } from '@/extensions/widgets';
|
||||
import { getEnumVariant, mapEntryValueType } from '@/lib/schemaResolver';
|
||||
import {
|
||||
embeddedEntries,
|
||||
embeddedSummary,
|
||||
@@ -50,6 +51,8 @@ export function FieldValue({ schema, type, value, variant = 'full', className }:
|
||||
|
||||
function renderValue(schema: Schema, type: FieldType, value: unknown, variant: ValueVariant): ReactNode {
|
||||
if (isEmptyValue(value)) return <EmptyValue variant={variant} />;
|
||||
const { View } = resolveWidget(type);
|
||||
if (View) return <View schema={schema} type={type} value={value} variant={variant} />;
|
||||
switch (type.type) {
|
||||
case 'string':
|
||||
return <StringValue value={value} format={type.format} variant={variant} />;
|
||||
@@ -176,7 +179,7 @@ function MapValue({
|
||||
key={key}
|
||||
schema={schema}
|
||||
label={<ScalarLabel schema={schema} type={keyClass} value={key} />}
|
||||
type={valueClass as FieldType}
|
||||
type={mapEntryValueType(schema, keyClass, valueClass, key) as FieldType}
|
||||
value={val}
|
||||
/>
|
||||
))}
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
/*
|
||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
import { useState } from 'react';
|
||||
import { formatUtcOffset } from '@/lib/format';
|
||||
import { getEnumVariant } from '@/lib/schemaResolver';
|
||||
import type { ValueProps } from '@/extensions/types';
|
||||
|
||||
export function TimeZoneValue({ schema, type, value, variant }: ValueProps) {
|
||||
const [now] = useState(() => new Date());
|
||||
const name = String(value);
|
||||
const label = (type.type === 'enum' ? getEnumVariant(schema, type.enumName, name)?.label : undefined) ?? name;
|
||||
const offset = variant === 'full' ? formatUtcOffset(name, now) : null;
|
||||
return (
|
||||
<span className="text-sm">
|
||||
{label}
|
||||
{offset && <span className="ms-1.5 text-muted-foreground tabular-nums">({offset})</span>}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
/*
|
||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { useInPanel } from '@/components/forms/formContext';
|
||||
import { formatNumber, formatWeekday } from '@/lib/format';
|
||||
import { MINUTES_PER_DAY, MINUTES_PER_HOUR } from '@/lib/localDateTime';
|
||||
import { formatSlot, localeWeekdayOrder } from '@/lib/scheduleFormat';
|
||||
import {
|
||||
daySegments,
|
||||
parseSlot,
|
||||
slotEntries,
|
||||
weekdayIndex,
|
||||
type ScheduleRules,
|
||||
type Slot,
|
||||
type Weekday,
|
||||
} from '@/lib/weeklySchedule';
|
||||
import { cn } from '@/lib/utils';
|
||||
import type { ValueProps } from '@/extensions/types';
|
||||
|
||||
const AXIS_HOURS = [0, 6, 12, 18, 24] as const;
|
||||
|
||||
interface WeekChartProps {
|
||||
entries: readonly [string, Slot][];
|
||||
rules: ScheduleRules;
|
||||
order: readonly Weekday[];
|
||||
label: string;
|
||||
}
|
||||
|
||||
function percent(minutes: number): string {
|
||||
return `${(minutes / MINUTES_PER_DAY) * 100}%`;
|
||||
}
|
||||
|
||||
export function WeekChart({ entries, rules, order, label }: WeekChartProps) {
|
||||
const inPanel = useInPanel();
|
||||
const segments = daySegments(entries, rules);
|
||||
return (
|
||||
<div role="img" aria-label={label} data-slot="week-chart" className="space-y-1">
|
||||
{order.map((day) => (
|
||||
<div key={day} className="flex items-center gap-2">
|
||||
<span className="w-10 shrink-0 truncate text-[12px] text-muted-foreground" aria-hidden="true">
|
||||
{formatWeekday(day, 'short')}
|
||||
</span>
|
||||
<div className={cn('relative h-4 flex-1 overflow-hidden rounded-full', inPanel ? 'bg-muted' : 'bg-card')}>
|
||||
{AXIS_HOURS.slice(1, -1).map((hour) => (
|
||||
<span
|
||||
key={hour}
|
||||
className="absolute inset-y-0 w-px bg-border"
|
||||
style={{ insetInlineStart: percent(hour * MINUTES_PER_HOUR) }}
|
||||
/>
|
||||
))}
|
||||
{segments[weekdayIndex(day) ?? 0].map((segment) => (
|
||||
<span
|
||||
key={`${segment.key}-${segment.start}`}
|
||||
data-slot="week-chart-bar"
|
||||
className="absolute inset-y-0 rounded-full bg-primary"
|
||||
style={{ insetInlineStart: percent(segment.start), width: percent(segment.end - segment.start) }}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
<div className="flex gap-2" aria-hidden="true">
|
||||
<span className="w-10 shrink-0" />
|
||||
<div className="relative h-4 flex-1 text-[11px] text-dim tabular-nums">
|
||||
{AXIS_HOURS.map((hour) => (
|
||||
<span
|
||||
key={hour}
|
||||
className={cn(
|
||||
'absolute',
|
||||
hour === 0 ? 'start-0' : hour === 24 ? 'end-0' : '-translate-x-1/2 rtl:translate-x-1/2',
|
||||
)}
|
||||
style={hour === 0 || hour === 24 ? undefined : { insetInlineStart: percent(hour * MINUTES_PER_HOUR) }}
|
||||
>
|
||||
{formatNumber(hour)}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const DISPLAY_RULES: ScheduleRules = 'overnight';
|
||||
|
||||
export function WeeklyScheduleValue({ value, variant }: ValueProps) {
|
||||
const { t } = useTranslation();
|
||||
const order = localeWeekdayOrder();
|
||||
const entries = slotEntries(value).map(([key, item]): [string, Slot] => [key, parseSlot(item)]);
|
||||
const lines = entries.map(([, slot]) => formatSlot(t, slot, order, DISPLAY_RULES));
|
||||
if (variant === 'compact') return <span className="text-sm">{lines.join('; ')}</span>;
|
||||
return (
|
||||
<div className="space-y-3">
|
||||
<WeekChart entries={entries} rules={DISPLAY_RULES} order={order} label={lines.join('; ')} />
|
||||
<ul className="space-y-0.5 text-sm">
|
||||
{lines.map((line, i) => (
|
||||
<li key={entries[i][0]}>{line}</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -4,6 +4,7 @@
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
import type { ComponentType } from 'react';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { ValueRow } from '@/components/values/FieldValue';
|
||||
import { cn } from '@/lib/utils';
|
||||
@@ -11,12 +12,22 @@ import { resolveForm, resolveSchema, resolveVariantForm } from '@/lib/schemaReso
|
||||
import { isEmptyValue, variantLabel } from '@/lib/embeddedSchema';
|
||||
import type { Field, Fields, Form, FormField, Schema } from '@/types/schema';
|
||||
|
||||
export interface ViewRenderProps {
|
||||
schema: Schema;
|
||||
field: Field;
|
||||
formField: FormField;
|
||||
data: Record<string, unknown>;
|
||||
}
|
||||
|
||||
export type ViewRenderers = Readonly<Record<string, ComponentType<ViewRenderProps>>>;
|
||||
|
||||
export interface DynamicViewProps {
|
||||
schema: Schema;
|
||||
objectName: string;
|
||||
viewName: string;
|
||||
data: Record<string, unknown>;
|
||||
visibleFields?: Set<string>;
|
||||
renderers?: ViewRenderers;
|
||||
}
|
||||
|
||||
interface ViewSection {
|
||||
@@ -70,7 +81,7 @@ function buildViewSections(
|
||||
return items.length > 0 ? [{ key: 'section-0', items }] : [];
|
||||
}
|
||||
|
||||
export function DynamicView({ schema, objectName, viewName, data, visibleFields }: DynamicViewProps) {
|
||||
export function DynamicView({ schema, objectName, viewName, data, visibleFields, renderers }: DynamicViewProps) {
|
||||
const layout = resolveViewLayout(schema, objectName, viewName, data);
|
||||
if (!layout) return null;
|
||||
const sections = buildViewSections(layout, data, visibleFields);
|
||||
@@ -83,16 +94,21 @@ export function DynamicView({ schema, objectName, viewName, data, visibleFields
|
||||
<section key={section.key} className="tile @container px-5 pb-1.5 sm:px-6">
|
||||
{section.title && <h2 className="section-title pb-1 pt-5">{section.title}</h2>}
|
||||
<dl className={cn('divide-y divide-border', !section.title && 'pt-1')}>
|
||||
{section.items.map(({ formField, field }) => (
|
||||
<ValueRow
|
||||
key={formField.name}
|
||||
schema={schema}
|
||||
label={formField.label}
|
||||
description={field.description}
|
||||
type={field.type}
|
||||
value={data[formField.name]}
|
||||
/>
|
||||
))}
|
||||
{section.items.map(({ formField, field }) => {
|
||||
const Render = renderers && Object.hasOwn(renderers, formField.name) ? renderers[formField.name] : null;
|
||||
return Render ? (
|
||||
<Render key={formField.name} schema={schema} field={field} formField={formField} data={data} />
|
||||
) : (
|
||||
<ValueRow
|
||||
key={formField.name}
|
||||
schema={schema}
|
||||
label={formField.label}
|
||||
description={field.description}
|
||||
type={field.type}
|
||||
value={data[formField.name]}
|
||||
/>
|
||||
);
|
||||
})}
|
||||
</dl>
|
||||
</section>
|
||||
))}
|
||||
|
||||
@@ -13,19 +13,21 @@ import { resolveObject, resolveList, getDisplayProperty } from '@/lib/schemaReso
|
||||
import { coerceLabel } from '@/lib/objectOptions';
|
||||
import { errorMessage } from '@/lib/jmapErrors';
|
||||
import { useJmapObject } from '@/data/objects';
|
||||
import { DynamicView } from './DynamicView';
|
||||
import { DynamicView, type ViewRenderers } from './DynamicView';
|
||||
|
||||
interface DynamicViewPageProps {
|
||||
viewName: string;
|
||||
objectId: string;
|
||||
accountId?: string;
|
||||
renderers?: ViewRenderers;
|
||||
}
|
||||
|
||||
export function DynamicViewPage({ viewName, objectId }: DynamicViewPageProps) {
|
||||
export function DynamicViewPage({ viewName, objectId, accountId, renderers }: DynamicViewPageProps) {
|
||||
const { t } = useTranslation();
|
||||
const navigate = useNavigate();
|
||||
const schema = useSchemaStore((s) => s.schema);
|
||||
const resolvedObject = schema ? resolveObject(schema, viewName) : null;
|
||||
const query = useJmapObject(resolvedObject?.objectName, objectId);
|
||||
const query = useJmapObject(resolvedObject?.objectName, objectId, undefined, { accountId });
|
||||
const data = query.data ?? null;
|
||||
const loading = query.isPending && query.fetchStatus !== 'idle';
|
||||
const error = !schema
|
||||
@@ -87,7 +89,13 @@ export function DynamicViewPage({ viewName, objectId }: DynamicViewPageProps) {
|
||||
<h1 className="page-title min-w-0 flex-1 break-words pt-1.5">{title}</h1>
|
||||
</div>
|
||||
|
||||
<DynamicView schema={schema} objectName={resolved.objectName} viewName={viewName} data={data} />
|
||||
<DynamicView
|
||||
schema={schema}
|
||||
objectName={resolved.objectName}
|
||||
viewName={viewName}
|
||||
data={data}
|
||||
renderers={renderers}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
+2
-2
@@ -14,8 +14,8 @@ export const jmapKeys = {
|
||||
all: ['jmap'] as const,
|
||||
type: (objectName: string) => ['jmap', objectName] as const,
|
||||
objects: (objectName: string) => ['jmap', objectName, 'object'] as const,
|
||||
object: (objectName: string, id: string, properties?: readonly string[]) =>
|
||||
['jmap', objectName, 'object', id, properties ? [...properties].sort() : null] as const,
|
||||
object: (objectName: string, id: string, properties?: readonly string[], accountId?: string) =>
|
||||
['jmap', objectName, 'object', id, properties ? [...properties].sort() : null, accountId ?? null] as const,
|
||||
lists: (objectName: string) => ['jmap', objectName, 'list'] as const,
|
||||
list: (objectName: string, params: ListPageParams) => ['jmap', objectName, 'list', params] as const,
|
||||
allOptions: (objectName: string) => ['jmap', objectName, 'options'] as const,
|
||||
|
||||
+18
-7
@@ -21,11 +21,21 @@ import type { JmapSetResponse } from '@/types/jmap';
|
||||
|
||||
export interface SetVariables extends JmapSetOptions {
|
||||
blobs?: Record<string, BlobUpload>;
|
||||
accountId?: string;
|
||||
}
|
||||
|
||||
export type BulkTarget = { ids: string[] } | { query: JmapQueryOptions };
|
||||
|
||||
export type BulkVariables = BulkTarget & ({ action: 'destroy' } | { action: 'update'; patch: JmapObject });
|
||||
export type BulkVariables = (
|
||||
| (BulkTarget & ({ action: 'destroy' } | { action: 'update'; patch: JmapObject }))
|
||||
| { action: 'updateEach'; patches: Record<string, JmapObject> }
|
||||
) & { accountId?: string };
|
||||
|
||||
async function bulkIds(objectName: string, vars: BulkVariables, signal?: AbortSignal): Promise<string[]> {
|
||||
if (vars.action === 'updateEach') return Object.keys(vars.patches);
|
||||
if ('ids' in vars) return vars.ids;
|
||||
return jmapQueryAll(objectName, vars.query, { accountId: vars.accountId, signal });
|
||||
}
|
||||
|
||||
function isListOf(key: QueryKey, objectName: string): boolean {
|
||||
return key[1] === objectName && key[2] === 'list';
|
||||
@@ -45,9 +55,9 @@ export async function invalidateObjectType(client: QueryClient, objectName: stri
|
||||
export function useJmapSet(objectName: string | null | undefined) {
|
||||
const client = useQueryClient();
|
||||
return useMutation<JmapSetResponse, Error, SetVariables>({
|
||||
mutationFn: ({ blobs, ...set }) => {
|
||||
mutationFn: ({ blobs, accountId, ...set }) => {
|
||||
if (!objectName) throw new Error('No object type to update');
|
||||
return jmapSet(objectName, set, { blobs });
|
||||
return jmapSet(objectName, set, { blobs, accountId });
|
||||
},
|
||||
onSettled: () => {
|
||||
if (objectName) return invalidateObjectType(client, objectName);
|
||||
@@ -56,7 +66,8 @@ export function useJmapSet(objectName: string | null | undefined) {
|
||||
}
|
||||
|
||||
export async function runBulkSet(objectName: string, vars: BulkVariables, signal?: AbortSignal): Promise<SetOutcome> {
|
||||
const ids = 'ids' in vars ? vars.ids : await jmapQueryAll(objectName, vars.query, { signal });
|
||||
const ids = await bulkIds(objectName, vars, signal);
|
||||
const { accountId } = vars;
|
||||
const batchSize = Math.max(1, useAuthStore.getState().maxObjectsInSet);
|
||||
const outcome: SetOutcome = { succeeded: [], failed: {} };
|
||||
for (let offset = 0; offset < ids.length; offset += batchSize) {
|
||||
@@ -65,11 +76,11 @@ export async function runBulkSet(objectName: string, vars: BulkVariables, signal
|
||||
let partial: SetOutcome;
|
||||
try {
|
||||
if (vars.action === 'destroy') {
|
||||
partial = destroyedOutcome(await jmapSet(objectName, { destroy: batch }, { signal }));
|
||||
partial = destroyedOutcome(await jmapSet(objectName, { destroy: batch }, { accountId, signal }));
|
||||
} else {
|
||||
const update: Record<string, JmapObject> = {};
|
||||
for (const id of batch) update[id] = vars.patch;
|
||||
partial = updatedOutcome(await jmapSet(objectName, { update }, { signal }));
|
||||
for (const id of batch) update[id] = vars.action === 'updateEach' ? vars.patches[id] : vars.patch;
|
||||
partial = updatedOutcome(await jmapSet(objectName, { update }, { accountId, signal }));
|
||||
}
|
||||
} catch (err) {
|
||||
const aborted = isAbortError(err);
|
||||
|
||||
+5
-4
@@ -17,14 +17,15 @@ export interface ListPage {
|
||||
|
||||
interface QueryTuning {
|
||||
enabled?: boolean;
|
||||
accountId?: string;
|
||||
staleTime?: number;
|
||||
refetchOnMount?: boolean | 'always';
|
||||
}
|
||||
|
||||
export function jmapObjectQuery(objectName: string, id: string, properties?: string[]) {
|
||||
export function jmapObjectQuery(objectName: string, id: string, properties?: string[], accountId?: string) {
|
||||
return queryOptions({
|
||||
queryKey: jmapKeys.object(objectName, id, properties),
|
||||
queryFn: ({ signal }) => jmapGetOne(objectName, id, properties, { signal }),
|
||||
queryKey: jmapKeys.object(objectName, id, properties, accountId),
|
||||
queryFn: ({ signal }) => jmapGetOne(objectName, id, properties, { signal, accountId }),
|
||||
staleTime: 0,
|
||||
});
|
||||
}
|
||||
@@ -36,7 +37,7 @@ export function useJmapObject(
|
||||
tuning: QueryTuning = {},
|
||||
) {
|
||||
return useQuery({
|
||||
...jmapObjectQuery(objectName ?? '', id ?? '', properties),
|
||||
...jmapObjectQuery(objectName ?? '', id ?? '', properties, tuning.accountId),
|
||||
enabled: !!objectName && !!id && (tuning.enabled ?? true),
|
||||
staleTime: tuning.staleTime ?? 0,
|
||||
refetchOnMount: tuning.refetchOnMount ?? true,
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
*/
|
||||
|
||||
import { QueryClient, type QueryKey } from '@tanstack/react-query';
|
||||
import { resolveAccountId, type AccountSelection } from '@/services/jmap/client';
|
||||
import { isRetryableError } from '@/services/errors';
|
||||
import { useAuthStore } from '@/stores/authStore';
|
||||
import { jmapKeys } from '@/data/keys';
|
||||
@@ -16,8 +17,10 @@ export function shouldRetry(failureCount: number, error: unknown): boolean {
|
||||
return failureCount < MAX_QUERY_RETRIES && isRetryableError(error);
|
||||
}
|
||||
|
||||
function isManagementKey(key: QueryKey): boolean {
|
||||
return typeof key[1] === 'string' && key[1].startsWith('x:');
|
||||
function accountChanged(key: QueryKey, prev: AccountSelection, next: AccountSelection): boolean {
|
||||
const objectType = key[1];
|
||||
if (typeof objectType !== 'string') return true;
|
||||
return resolveAccountId(objectType, prev) !== resolveAccountId(objectType, next);
|
||||
}
|
||||
|
||||
export function createQueryClient(): QueryClient {
|
||||
@@ -45,7 +48,10 @@ export function bindQueryClientToAuth(client: QueryClient): () => void {
|
||||
return;
|
||||
}
|
||||
if (prev.activeAccountId !== null && state.activeAccountId !== prev.activeAccountId) {
|
||||
void client.resetQueries({ queryKey: jmapKeys.all, predicate: (query) => !isManagementKey(query.queryKey) });
|
||||
void client.resetQueries({
|
||||
queryKey: jmapKeys.all,
|
||||
predicate: (query) => accountChanged(query.queryKey, prev, state),
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
+14
-4
@@ -6,14 +6,20 @@
|
||||
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { sessionKeys } from '@/data/keys';
|
||||
import { fetchAccountInfo, fetchSchema, fetchSession, type JmapSession } from '@/services/jmap/client';
|
||||
import { useAuthStore } from '@/stores/authStore';
|
||||
import {
|
||||
fetchAccountInfo,
|
||||
fetchSchema,
|
||||
fetchSession,
|
||||
MANAGEMENT_CAPABILITY,
|
||||
type JmapSession,
|
||||
} from '@/services/jmap/client';
|
||||
import { useAuthStore, type AccountInfo } from '@/stores/authStore';
|
||||
import { useSchemaStore } from '@/stores/schemaStore';
|
||||
import { useAccountStore } from '@/stores/accountStore';
|
||||
import { setLocale } from '@/i18n';
|
||||
|
||||
export interface SessionInfo {
|
||||
accounts: Record<string, { name: string; isPersonal: boolean }>;
|
||||
accounts: Record<string, AccountInfo>;
|
||||
primaryAccountId: string;
|
||||
apiUrl: string;
|
||||
maxObjectsInGet?: number;
|
||||
@@ -23,7 +29,11 @@ export interface SessionInfo {
|
||||
export function parseSession(session: JmapSession): SessionInfo {
|
||||
const accounts: SessionInfo['accounts'] = {};
|
||||
for (const [accountId, info] of Object.entries(session.accounts ?? {})) {
|
||||
accounts[accountId] = { name: info.name, isPersonal: info.isPersonal };
|
||||
accounts[accountId] = {
|
||||
name: info.name,
|
||||
isPersonal: info.isPersonal,
|
||||
hasManagement: !!info.accountCapabilities && Object.hasOwn(info.accountCapabilities, MANAGEMENT_CAPABILITY),
|
||||
};
|
||||
}
|
||||
const primaryAccounts = session.primaryAccounts ?? {};
|
||||
const primaryAccountId =
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
/*
|
||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
import { lazy, type ComponentType } from 'react';
|
||||
import type { PageComponent, PageProps } from '@/extensions/types';
|
||||
|
||||
export function lazyPage<M>(load: () => Promise<M>, select: (module: M) => ComponentType<PageProps>): PageComponent {
|
||||
return lazy(() => load().then((module) => ({ default: select(module) })));
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
/*
|
||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
*
|
||||
* SPDX-License-Identifier: LicenseRef-SEL
|
||||
*/
|
||||
|
||||
import { lazyPage } from '@/extensions/lazyPage';
|
||||
import type { PageGate, PageOverride } from '@/extensions/types';
|
||||
|
||||
const DashboardPage = lazyPage(
|
||||
() => import('@/features/dashboard/components/DashboardPage'),
|
||||
(m) => m.DashboardPage,
|
||||
);
|
||||
|
||||
const METRICS_GATE: PageGate = { permission: 'liveMetrics', backingObject: 'x:Metric' };
|
||||
|
||||
export const SEL_PAGES: readonly PageOverride[] = [
|
||||
{ match: { customComponent: 'Dashboard' }, component: DashboardPage, gate: METRICS_GATE },
|
||||
{ match: { viewPrefix: 'Dashboard/' }, component: DashboardPage, gate: METRICS_GATE },
|
||||
{
|
||||
match: { customComponent: 'LiveTracing' },
|
||||
component: lazyPage(
|
||||
() => import('@/features/tracing/components/LiveTracingPage'),
|
||||
(m) => m.LiveTracingPage,
|
||||
),
|
||||
gate: { permission: 'liveTracing', enterprise: true },
|
||||
},
|
||||
{
|
||||
match: { object: 'x:Trace' },
|
||||
modes: ['edit', 'detail'],
|
||||
component: lazyPage(
|
||||
() => import('@/features/tracing/components/TraceDetailView'),
|
||||
(m) => m.TraceDetailView,
|
||||
),
|
||||
},
|
||||
];
|
||||
@@ -0,0 +1,170 @@
|
||||
/*
|
||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
import { lazyPage } from '@/extensions/lazyPage';
|
||||
// SPDX-SnippetBegin
|
||||
// SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
// SPDX-License-Identifier: LicenseRef-SEL
|
||||
import { SEL_PAGES } from '@/extensions/pages.sel';
|
||||
// SPDX-SnippetEnd
|
||||
import { resolveObject } from '@/lib/schemaResolver';
|
||||
import type { PermissionCheckers } from '@/lib/permissions';
|
||||
import type { ObjectMatch, PageComponent, PageGate, PageMode, PageOverride, RouteMatch } from '@/extensions/types';
|
||||
import type { Schema } from '@/types/schema';
|
||||
|
||||
export const CUSTOM_COMPONENT_PREFIX = 'CustomComponent/';
|
||||
|
||||
const ALL_MODES: readonly PageMode[] = ['list', 'create', 'edit', 'detail', 'singleton'];
|
||||
|
||||
export const PAGES: readonly PageOverride[] = [
|
||||
{
|
||||
match: { customComponent: 'LiveDelivery' },
|
||||
component: lazyPage(
|
||||
() => import('@/features/troubleshoot/DeliveryTracePage'),
|
||||
(m) => m.DeliveryTracePage,
|
||||
),
|
||||
gate: { permission: 'liveDeliveryTest' },
|
||||
},
|
||||
{
|
||||
match: { object: 'x:Action' },
|
||||
modes: ALL_MODES,
|
||||
component: lazyPage(
|
||||
() => import('@/features/actions/ActionPage'),
|
||||
(m) => m.ActionPage,
|
||||
),
|
||||
},
|
||||
{
|
||||
match: { object: 'x:MailRule' },
|
||||
modes: ['list'],
|
||||
component: lazyPage(
|
||||
() => import('@/features/mailRules/components/MailRulesPage'),
|
||||
(m) => m.MailRulesPage,
|
||||
),
|
||||
},
|
||||
{
|
||||
match: { object: 'x:MailRule' },
|
||||
modes: ['create', 'edit'],
|
||||
component: lazyPage(
|
||||
() => import('@/features/mailRules/components/MailRuleFormPage'),
|
||||
(m) => m.MailRuleFormPage,
|
||||
),
|
||||
},
|
||||
{
|
||||
match: { object: 'x:MailRule' },
|
||||
modes: ['detail'],
|
||||
component: lazyPage(
|
||||
() => import('@/features/mailRules/components/MailRuleFormPage'),
|
||||
(m) => m.MailRuleViewPage,
|
||||
),
|
||||
},
|
||||
{
|
||||
match: { object: 'x:BlockedSender' },
|
||||
modes: ['list', 'create', 'edit', 'detail'],
|
||||
component: lazyPage(
|
||||
() => import('@/features/mailRules/components/SenderListPage'),
|
||||
(m) => m.SenderListPage,
|
||||
),
|
||||
},
|
||||
{
|
||||
match: { object: 'x:SafeSender' },
|
||||
modes: ['list', 'create', 'edit', 'detail'],
|
||||
component: lazyPage(
|
||||
() => import('@/features/mailRules/components/SenderListPage'),
|
||||
(m) => m.SenderListPage,
|
||||
),
|
||||
},
|
||||
{
|
||||
match: { object: 'VacationResponse' },
|
||||
modes: ['singleton'],
|
||||
component: lazyPage(
|
||||
() => import('@/features/vacation/VacationResponsePage'),
|
||||
(m) => m.VacationResponsePage,
|
||||
),
|
||||
},
|
||||
// SPDX-SnippetBegin
|
||||
// SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
// SPDX-License-Identifier: LicenseRef-SEL
|
||||
...SEL_PAGES,
|
||||
// SPDX-SnippetEnd
|
||||
];
|
||||
|
||||
export interface RoutePage {
|
||||
component: PageComponent;
|
||||
gate?: PageGate;
|
||||
}
|
||||
|
||||
function routeMatches(match: RouteMatch, viewName: string): boolean {
|
||||
return 'customComponent' in match
|
||||
? viewName === `${CUSTOM_COMPONENT_PREFIX}${match.customComponent}`
|
||||
: viewName.startsWith(match.viewPrefix);
|
||||
}
|
||||
|
||||
export function matchRoutePage(viewName: string): RoutePage | null {
|
||||
for (const page of PAGES) {
|
||||
if (!('modes' in page) && routeMatches(page.match, viewName)) return page;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function findObjectPage(test: (match: ObjectMatch) => boolean, mode: PageMode): PageComponent | null {
|
||||
for (const page of PAGES) {
|
||||
if ('modes' in page && page.modes.includes(mode) && test(page.match)) return page.component;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
export type PageTarget = { mode: 'list' | 'create' | 'singleton' } | { mode: 'edit' | 'detail'; id: string };
|
||||
|
||||
export function pageObjectId(target: PageTarget): string | null {
|
||||
switch (target.mode) {
|
||||
case 'list':
|
||||
return null;
|
||||
case 'create':
|
||||
return 'new';
|
||||
case 'singleton':
|
||||
return 'singleton';
|
||||
default:
|
||||
return target.id;
|
||||
}
|
||||
}
|
||||
|
||||
export type ResolvedPage =
|
||||
| { kind: 'loading' }
|
||||
| { kind: 'unknownComponent'; name: string }
|
||||
| { kind: 'unknownView' }
|
||||
| { kind: 'route'; viewName: string; component: PageComponent }
|
||||
| { kind: 'object'; viewName: string; target: PageTarget; component: PageComponent | null };
|
||||
|
||||
export function resolvePage(
|
||||
schema: Schema | null,
|
||||
viewName: string | undefined,
|
||||
id: string | undefined,
|
||||
permissions: PermissionCheckers,
|
||||
): ResolvedPage {
|
||||
if (!viewName) return { kind: 'loading' };
|
||||
const route = matchRoutePage(viewName);
|
||||
if (route) return { kind: 'route', viewName, component: route.component };
|
||||
if (viewName.startsWith(CUSTOM_COMPONENT_PREFIX)) {
|
||||
return { kind: 'unknownComponent', name: viewName.slice(CUSTOM_COMPONENT_PREFIX.length) };
|
||||
}
|
||||
if (!schema) return { kind: 'loading' };
|
||||
|
||||
const resolved = resolveObject(schema, viewName);
|
||||
if (!resolved) return { kind: 'unknownView' };
|
||||
|
||||
const target: PageTarget =
|
||||
resolved.objectType.type === 'singleton'
|
||||
? { mode: 'singleton' }
|
||||
: id === 'new'
|
||||
? { mode: 'create' }
|
||||
: id
|
||||
? { mode: permissions.hasObjectPermission(resolved.permissionPrefix, 'Update') ? 'edit' : 'detail', id }
|
||||
: { mode: 'list' };
|
||||
const component =
|
||||
findObjectPage((match) => 'view' in match && match.view === viewName, target.mode) ??
|
||||
findObjectPage((match) => 'object' in match && match.object === resolved.objectName, target.mode);
|
||||
return { kind: 'object', viewName, target, component };
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
/*
|
||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
import type { ComponentType, LazyExoticComponent } from 'react';
|
||||
import type { WidgetProps } from '@/components/forms/widgets/types';
|
||||
import type { ValueVariant } from '@/components/values/ScalarValues';
|
||||
import type { FieldType, NumberFormat, ScalarType, Schema, StringFormat } from '@/types/schema';
|
||||
|
||||
export type PageMode = 'list' | 'create' | 'edit' | 'detail' | 'singleton';
|
||||
|
||||
export interface PageProps {
|
||||
viewName: string;
|
||||
objectId: string | null;
|
||||
section: string;
|
||||
}
|
||||
|
||||
export type PageComponent = LazyExoticComponent<ComponentType<PageProps>>;
|
||||
|
||||
export interface PageGate {
|
||||
permission: string;
|
||||
backingObject?: string;
|
||||
enterprise?: boolean;
|
||||
}
|
||||
|
||||
export type RouteMatch = { customComponent: string } | { viewPrefix: string };
|
||||
|
||||
export type ObjectMatch = { object: string } | { view: string };
|
||||
|
||||
export type PageOverride =
|
||||
| { match: RouteMatch; component: PageComponent; gate?: PageGate }
|
||||
| { match: ObjectMatch; modes: readonly PageMode[]; component: PageComponent };
|
||||
|
||||
export type LabelMode = 'control' | 'group' | 'none';
|
||||
|
||||
export type RowLayout = 'side' | 'block' | 'inline';
|
||||
|
||||
export interface WidgetTraits {
|
||||
labelMode: LabelMode;
|
||||
readOnlyAsValue: boolean;
|
||||
layout: RowLayout;
|
||||
createOnly?: true;
|
||||
}
|
||||
|
||||
export type WidgetKey =
|
||||
| 'string'
|
||||
| 'string:secret'
|
||||
| 'string:multiline'
|
||||
| 'string:sieve'
|
||||
| 'string:color'
|
||||
| 'string:localTime'
|
||||
| 'string:localDate'
|
||||
| 'number'
|
||||
| 'number:size'
|
||||
| 'number:duration'
|
||||
| 'utcDateTime'
|
||||
| 'boolean'
|
||||
| 'enum'
|
||||
| 'enum:TimeZone'
|
||||
| 'blobId'
|
||||
| 'objectId'
|
||||
| 'object'
|
||||
| 'object:x:Expression'
|
||||
| 'object:x:Rate'
|
||||
| 'object:x:OtpAuth'
|
||||
| 'object:x:PasskeyRegistration'
|
||||
| 'objectList'
|
||||
| 'objectList:x:WorkingHoursSlot'
|
||||
| 'set'
|
||||
| 'set:enum'
|
||||
| 'map'
|
||||
| 'unsupported';
|
||||
|
||||
export type WidgetMatch =
|
||||
| { objectName: string }
|
||||
| { listObjectName: string }
|
||||
| { enumName: string }
|
||||
| { stringFormat: readonly StringFormat[] }
|
||||
| { numberFormat: readonly NumberFormat[] }
|
||||
| { setOf: ScalarType['type'] }
|
||||
| { type: FieldType['type'] };
|
||||
|
||||
export interface ValueProps {
|
||||
schema: Schema;
|
||||
type: FieldType;
|
||||
value: unknown;
|
||||
variant: ValueVariant;
|
||||
}
|
||||
|
||||
export interface WidgetDefinition {
|
||||
key: WidgetKey;
|
||||
match: WidgetMatch;
|
||||
traits: WidgetTraits;
|
||||
Edit: ComponentType<WidgetProps>;
|
||||
View?: ComponentType<ValueProps>;
|
||||
RowAddon?: ComponentType<WidgetProps>;
|
||||
}
|
||||
|
||||
export type ResolvedWidget = Omit<WidgetDefinition, 'match'>;
|
||||
@@ -0,0 +1,253 @@
|
||||
/*
|
||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
import type { ComponentType } from 'react';
|
||||
import {
|
||||
ColorWidget,
|
||||
MultilineWidget,
|
||||
SecretWidget,
|
||||
SieveWidget,
|
||||
TextWidget,
|
||||
} from '@/components/forms/widgets/StringWidgets';
|
||||
import { DurationWidget, NumberWidget, SizeWidget } from '@/components/forms/widgets/NumberWidgets';
|
||||
import { DateTimeWidget } from '@/components/forms/widgets/DateTimeWidget';
|
||||
import {
|
||||
LocalDateValue,
|
||||
LocalDateWidget,
|
||||
LocalTimeValue,
|
||||
LocalTimeWidget,
|
||||
} from '@/components/forms/widgets/LocalDateTimeWidgets';
|
||||
import { BooleanWidget } from '@/components/forms/widgets/BooleanWidget';
|
||||
import { EnumWidget } from '@/components/forms/widgets/EnumWidgets';
|
||||
import { BlobWidget } from '@/components/forms/widgets/BlobWidget';
|
||||
import { ObjectIdWidget } from '@/components/forms/widgets/ObjectIdWidgets';
|
||||
import { SetWidget } from '@/components/forms/widgets/SetWidget';
|
||||
import { EmbeddedObjectWidget } from '@/components/forms/widgets/EmbeddedObjectWidget';
|
||||
import { ObjectListWidget } from '@/components/forms/widgets/ObjectListWidget';
|
||||
import { MapWidget } from '@/components/forms/widgets/MapWidget';
|
||||
import { RateWidget } from '@/components/forms/widgets/RateWidget';
|
||||
import { ExpressionWidget } from '@/components/forms/widgets/ExpressionWidget';
|
||||
import { OtpAuthWidget, PasskeyRegistrationWidget } from '@/components/forms/widgets/LazyWidgets';
|
||||
import { UnsupportedWidget } from '@/components/forms/widgets/UnsupportedWidget';
|
||||
import { TimeZoneWidget } from '@/components/forms/widgets/TimeZoneWidget';
|
||||
import { WeeklyScheduleWidget } from '@/components/forms/widgets/WeeklyScheduleWidget';
|
||||
import { TimeZoneValue } from '@/components/values/TimeZoneValue';
|
||||
import { WeeklyScheduleValue } from '@/components/values/WeeklyScheduleValue';
|
||||
import { SievepadRowAddon } from '@/components/forms/SievepadButton';
|
||||
import type { WidgetProps } from '@/components/forms/widgets/types';
|
||||
import type { ResolvedWidget, WidgetDefinition, WidgetKey, WidgetMatch, WidgetTraits } from '@/extensions/types';
|
||||
import type {
|
||||
FieldType,
|
||||
FieldTypeEnum,
|
||||
FieldTypeNumber,
|
||||
FieldTypeObject,
|
||||
FieldTypeObjectList,
|
||||
FieldTypeSet,
|
||||
FieldTypeString,
|
||||
NumberFormat,
|
||||
StringFormat,
|
||||
} from '@/types/schema';
|
||||
|
||||
type MatchedType<M extends WidgetMatch> = M extends { objectName: string }
|
||||
? FieldTypeObject
|
||||
: M extends { listObjectName: string }
|
||||
? FieldTypeObjectList
|
||||
: M extends { enumName: string }
|
||||
? FieldTypeEnum
|
||||
: M extends { stringFormat: readonly StringFormat[] }
|
||||
? FieldTypeString
|
||||
: M extends { numberFormat: readonly NumberFormat[] }
|
||||
? FieldTypeNumber
|
||||
: M extends { setOf: string }
|
||||
? FieldTypeSet
|
||||
: M extends { type: infer T }
|
||||
? Extract<FieldType, { type: T }>
|
||||
: never;
|
||||
|
||||
interface TypedDefinition<M extends WidgetMatch> extends Omit<WidgetDefinition, 'match' | 'Edit'> {
|
||||
match: M;
|
||||
Edit: ComponentType<WidgetProps<MatchedType<M>>>;
|
||||
}
|
||||
|
||||
function widget<M extends WidgetMatch>(definition: TypedDefinition<M>): WidgetDefinition {
|
||||
return definition as unknown as WidgetDefinition;
|
||||
}
|
||||
|
||||
const SIDE: WidgetTraits = { labelMode: 'control', readOnlyAsValue: true, layout: 'side' };
|
||||
const BLOCK_TEXT: WidgetTraits = { labelMode: 'control', readOnlyAsValue: true, layout: 'block' };
|
||||
const GROUP_BLOCK: WidgetTraits = { labelMode: 'group', readOnlyAsValue: false, layout: 'block' };
|
||||
const UNLABELLED: WidgetTraits = { labelMode: 'none', readOnlyAsValue: false, layout: 'block' };
|
||||
|
||||
export const WIDGETS: readonly WidgetDefinition[] = [
|
||||
widget({ key: 'string', match: { type: 'string' }, traits: SIDE, Edit: TextWidget }),
|
||||
widget({
|
||||
key: 'string:secret',
|
||||
match: { stringFormat: ['secret', 'secretText'] },
|
||||
traits: SIDE,
|
||||
Edit: SecretWidget,
|
||||
}),
|
||||
widget({
|
||||
key: 'string:multiline',
|
||||
match: { stringFormat: ['text', 'html'] },
|
||||
traits: BLOCK_TEXT,
|
||||
Edit: MultilineWidget,
|
||||
}),
|
||||
widget({
|
||||
key: 'string:sieve',
|
||||
match: { stringFormat: ['sieve'] },
|
||||
traits: BLOCK_TEXT,
|
||||
Edit: SieveWidget,
|
||||
RowAddon: SievepadRowAddon,
|
||||
}),
|
||||
widget({ key: 'string:color', match: { stringFormat: ['color'] }, traits: SIDE, Edit: ColorWidget }),
|
||||
widget({
|
||||
key: 'string:localTime',
|
||||
match: { stringFormat: ['localTime'] },
|
||||
traits: { labelMode: 'group', readOnlyAsValue: true, layout: 'side' },
|
||||
Edit: LocalTimeWidget,
|
||||
View: LocalTimeValue,
|
||||
}),
|
||||
widget({
|
||||
key: 'string:localDate',
|
||||
match: { stringFormat: ['localDate'] },
|
||||
traits: SIDE,
|
||||
Edit: LocalDateWidget,
|
||||
View: LocalDateValue,
|
||||
}),
|
||||
widget({ key: 'number', match: { type: 'number' }, traits: SIDE, Edit: NumberWidget }),
|
||||
widget({ key: 'number:size', match: { numberFormat: ['size'] }, traits: SIDE, Edit: SizeWidget }),
|
||||
widget({ key: 'number:duration', match: { numberFormat: ['duration'] }, traits: SIDE, Edit: DurationWidget }),
|
||||
widget({ key: 'utcDateTime', match: { type: 'utcDateTime' }, traits: SIDE, Edit: DateTimeWidget }),
|
||||
widget({
|
||||
key: 'boolean',
|
||||
match: { type: 'boolean' },
|
||||
traits: { labelMode: 'control', readOnlyAsValue: true, layout: 'inline' },
|
||||
Edit: BooleanWidget,
|
||||
}),
|
||||
widget({ key: 'enum', match: { type: 'enum' }, traits: SIDE, Edit: EnumWidget }),
|
||||
widget({
|
||||
key: 'enum:TimeZone',
|
||||
match: { enumName: 'TimeZone' },
|
||||
traits: SIDE,
|
||||
Edit: TimeZoneWidget,
|
||||
View: TimeZoneValue,
|
||||
}),
|
||||
widget({
|
||||
key: 'blobId',
|
||||
match: { type: 'blobId' },
|
||||
traits: { labelMode: 'control', readOnlyAsValue: false, layout: 'block' },
|
||||
Edit: BlobWidget,
|
||||
}),
|
||||
widget({ key: 'objectId', match: { type: 'objectId' }, traits: SIDE, Edit: ObjectIdWidget }),
|
||||
widget({ key: 'object', match: { type: 'object' }, traits: GROUP_BLOCK, Edit: EmbeddedObjectWidget }),
|
||||
widget({
|
||||
key: 'object:x:Expression',
|
||||
match: { objectName: 'x:Expression' },
|
||||
traits: GROUP_BLOCK,
|
||||
Edit: ExpressionWidget,
|
||||
}),
|
||||
widget({
|
||||
key: 'object:x:Rate',
|
||||
match: { objectName: 'x:Rate' },
|
||||
traits: { labelMode: 'control', readOnlyAsValue: false, layout: 'side' },
|
||||
Edit: RateWidget,
|
||||
}),
|
||||
widget({ key: 'object:x:OtpAuth', match: { objectName: 'x:OtpAuth' }, traits: UNLABELLED, Edit: OtpAuthWidget }),
|
||||
widget({
|
||||
key: 'object:x:PasskeyRegistration',
|
||||
match: { objectName: 'x:PasskeyRegistration' },
|
||||
traits: { ...UNLABELLED, createOnly: true },
|
||||
Edit: PasskeyRegistrationWidget,
|
||||
}),
|
||||
widget({ key: 'objectList', match: { type: 'objectList' }, traits: GROUP_BLOCK, Edit: ObjectListWidget }),
|
||||
widget({
|
||||
key: 'objectList:x:WorkingHoursSlot',
|
||||
match: { listObjectName: 'x:WorkingHoursSlot' },
|
||||
traits: { labelMode: 'group', readOnlyAsValue: true, layout: 'block' },
|
||||
Edit: WeeklyScheduleWidget,
|
||||
View: WeeklyScheduleValue,
|
||||
}),
|
||||
widget({ key: 'set', match: { type: 'set' }, traits: SIDE, Edit: SetWidget }),
|
||||
widget({
|
||||
key: 'set:enum',
|
||||
match: { setOf: 'enum' },
|
||||
traits: { labelMode: 'group', readOnlyAsValue: true, layout: 'side' },
|
||||
Edit: SetWidget,
|
||||
}),
|
||||
widget({ key: 'map', match: { type: 'map' }, traits: GROUP_BLOCK, Edit: MapWidget }),
|
||||
];
|
||||
|
||||
const UNSUPPORTED: ResolvedWidget = {
|
||||
key: 'unsupported',
|
||||
traits: UNLABELLED,
|
||||
Edit: UnsupportedWidget,
|
||||
};
|
||||
|
||||
interface WidgetIndex {
|
||||
objectName: Map<string, WidgetDefinition>;
|
||||
listObjectName: Map<string, WidgetDefinition>;
|
||||
enumName: Map<string, WidgetDefinition>;
|
||||
stringFormat: Map<string, WidgetDefinition>;
|
||||
numberFormat: Map<string, WidgetDefinition>;
|
||||
setOf: Map<string, WidgetDefinition>;
|
||||
type: Map<string, WidgetDefinition>;
|
||||
}
|
||||
|
||||
function buildIndex(definitions: readonly WidgetDefinition[]): WidgetIndex {
|
||||
const index: WidgetIndex = {
|
||||
objectName: new Map(),
|
||||
listObjectName: new Map(),
|
||||
enumName: new Map(),
|
||||
stringFormat: new Map(),
|
||||
numberFormat: new Map(),
|
||||
setOf: new Map(),
|
||||
type: new Map(),
|
||||
};
|
||||
for (const definition of definitions) {
|
||||
const { match } = definition;
|
||||
if ('objectName' in match) index.objectName.set(match.objectName, definition);
|
||||
else if ('listObjectName' in match) index.listObjectName.set(match.listObjectName, definition);
|
||||
else if ('enumName' in match) index.enumName.set(match.enumName, definition);
|
||||
else if ('stringFormat' in match) for (const f of match.stringFormat) index.stringFormat.set(f, definition);
|
||||
else if ('numberFormat' in match) for (const f of match.numberFormat) index.numberFormat.set(f, definition);
|
||||
else if ('setOf' in match) index.setOf.set(match.setOf, definition);
|
||||
else index.type.set(match.type, definition);
|
||||
}
|
||||
return index;
|
||||
}
|
||||
|
||||
const INDEX = buildIndex(WIDGETS);
|
||||
|
||||
function specific(table: Map<string, WidgetDefinition>, name: string, type: FieldType): ResolvedWidget {
|
||||
return table.get(name) ?? INDEX.type.get(type.type) ?? UNSUPPORTED;
|
||||
}
|
||||
|
||||
export function resolveWidget(type: FieldType): ResolvedWidget {
|
||||
switch (type.type) {
|
||||
case 'object':
|
||||
return specific(INDEX.objectName, type.objectName, type);
|
||||
case 'objectList':
|
||||
return specific(INDEX.listObjectName, type.objectName, type);
|
||||
case 'enum':
|
||||
return specific(INDEX.enumName, type.enumName, type);
|
||||
case 'string':
|
||||
return specific(INDEX.stringFormat, type.format, type);
|
||||
case 'number':
|
||||
return specific(INDEX.numberFormat, type.format, type);
|
||||
case 'set':
|
||||
return specific(INDEX.setOf, type.class.type, type);
|
||||
default:
|
||||
return INDEX.type.get(type.type) ?? UNSUPPORTED;
|
||||
}
|
||||
}
|
||||
|
||||
export function widgetKey(type: FieldType): WidgetKey {
|
||||
return resolveWidget(type).key;
|
||||
}
|
||||
|
||||
export function widgetTraits(type: FieldType): WidgetTraits {
|
||||
return resolveWidget(type).traits;
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
/*
|
||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
*
|
||||
* SPDX-License-Identifier: LicenseRef-SEL
|
||||
*/
|
||||
|
||||
import { useSchemaStore } from '@/stores/schemaStore';
|
||||
import { DashboardView } from '@/features/dashboard/components/DashboardView';
|
||||
import type { PageProps } from '@/extensions/types';
|
||||
|
||||
const DASHBOARD_PREFIX = 'Dashboard/';
|
||||
const DEFAULT_DASHBOARD = 'overview';
|
||||
|
||||
export function DashboardPage({ viewName, section }: PageProps) {
|
||||
const firstDashboard = useSchemaStore((s) => s.schema?.dashboards?.[0]?.id);
|
||||
const dashboardId = viewName.startsWith(DASHBOARD_PREFIX)
|
||||
? viewName.slice(DASHBOARD_PREFIX.length)
|
||||
: (firstDashboard ?? DEFAULT_DASHBOARD);
|
||||
return <DashboardView dashboardId={dashboardId} section={section} />;
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
/*
|
||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
import { useAuthStore } from '@/stores/authStore';
|
||||
import { resolveAccountId } from '@/services/jmap/client';
|
||||
import { MAIL_RULE_OBJECT } from './model';
|
||||
|
||||
export function useRuleAccountId(): string | null {
|
||||
return useAuthStore((s) => resolveAccountId(MAIL_RULE_OBJECT, s));
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
/*
|
||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
import { isRecord, isMultilineFormat } from '@/lib/embeddedSchema';
|
||||
import type { Field } from '@/types/schema';
|
||||
|
||||
export type ListItems = Record<string, Record<string, unknown>>;
|
||||
|
||||
export const MAILBOX_FIELD = 'mailboxId';
|
||||
export const MAILBOX_SCHEMA = 'x:MailRuleMailbox';
|
||||
|
||||
export function listEntries(value: unknown): [string, Record<string, unknown>][] {
|
||||
if (!isRecord(value)) return [];
|
||||
const entries: [string, Record<string, unknown>][] = [];
|
||||
for (const [key, item] of Object.entries(value)) {
|
||||
if (isRecord(item)) entries.push([key, item]);
|
||||
}
|
||||
return entries.sort(([a], [b]) => Number(a) - Number(b));
|
||||
}
|
||||
|
||||
export function appendItem(value: unknown, item: Record<string, unknown>): ListItems {
|
||||
const entries = listEntries(value);
|
||||
const next = entries.reduce((max, [key]) => Math.max(max, (Number(key) || 0) + 1), 0);
|
||||
return { ...Object.fromEntries(entries), [String(next)]: item };
|
||||
}
|
||||
|
||||
export function replaceItem(value: unknown, key: string, item: Record<string, unknown>): ListItems {
|
||||
return { ...Object.fromEntries(listEntries(value)), [key]: item };
|
||||
}
|
||||
|
||||
export function removeItem(value: unknown, key: string): ListItems {
|
||||
return Object.fromEntries(listEntries(value).filter(([k]) => k !== key));
|
||||
}
|
||||
|
||||
export function isInlineField(field: Field): boolean {
|
||||
const { type } = field;
|
||||
switch (type.type) {
|
||||
case 'enum':
|
||||
case 'number':
|
||||
case 'utcDateTime':
|
||||
return true;
|
||||
case 'string':
|
||||
return !isMultilineFormat(type.format) && type.format !== 'secret' && type.format !== 'secretText';
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,394 @@
|
||||
/*
|
||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
import { useState } from 'react';
|
||||
import { Link } from 'react-router-dom';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import {
|
||||
closestCenter,
|
||||
DndContext,
|
||||
KeyboardSensor,
|
||||
PointerSensor,
|
||||
useSensor,
|
||||
useSensors,
|
||||
type Announcements,
|
||||
type DragEndEvent,
|
||||
} from '@dnd-kit/core';
|
||||
import {
|
||||
SortableContext,
|
||||
sortableKeyboardCoordinates,
|
||||
useSortable,
|
||||
verticalListSortingStrategy,
|
||||
} from '@dnd-kit/sortable';
|
||||
import { CSS } from '@dnd-kit/utilities';
|
||||
import { AlertTriangle, GripVertical, MoreHorizontal } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Switch } from '@/components/ui/switch';
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuSeparator,
|
||||
DropdownMenuTrigger,
|
||||
} from '@/components/ui/dropdown-menu';
|
||||
import { ConfirmDialog } from '@/components/common/ConfirmDialog';
|
||||
import { ListMessage } from '@/components/lists/ListStates';
|
||||
import { useJmapBulkSet, useJmapSet } from '@/data/mutations';
|
||||
import { toast } from '@/hooks/use-toast';
|
||||
import { errorMessage, friendlySetError } from '@/lib/jmapErrors';
|
||||
import type { PermissionCheckers } from '@/lib/permissions';
|
||||
import { cn } from '@/lib/utils';
|
||||
import {
|
||||
MAIL_RULE_OBJECT,
|
||||
moveInOrder,
|
||||
pinnedRuleIds,
|
||||
positionPatches,
|
||||
reorderPositions,
|
||||
ruleIssues,
|
||||
type MailRule,
|
||||
} from '../model';
|
||||
import { ruleIssueMessage, ruleSentence, summarizeCustomRule, type SummaryContext } from '../summary';
|
||||
|
||||
export interface CustomRulePermissions {
|
||||
update: boolean;
|
||||
destroy: boolean;
|
||||
}
|
||||
|
||||
interface CustomRuleListProps {
|
||||
rules: MailRule[];
|
||||
accountId: string;
|
||||
editHref: (id: string) => string;
|
||||
allowed: CustomRulePermissions;
|
||||
checkers: Pick<PermissionCheckers, 'hasPermission'>;
|
||||
summary: SummaryContext;
|
||||
}
|
||||
|
||||
interface RowProps {
|
||||
rule: MailRule;
|
||||
index: number;
|
||||
count: number;
|
||||
href: string;
|
||||
sentence: string;
|
||||
issues: string[];
|
||||
sortable: boolean;
|
||||
allowed: CustomRulePermissions;
|
||||
busy: boolean;
|
||||
onMove: (from: number, to: number) => void;
|
||||
onToggle: (rule: MailRule, isEnabled: boolean) => void;
|
||||
onDelete: (rule: MailRule) => void;
|
||||
}
|
||||
|
||||
function ruleName(rule: MailRule): string {
|
||||
return rule.name || rule.id;
|
||||
}
|
||||
|
||||
function SortableRuleRow({
|
||||
rule,
|
||||
index,
|
||||
count,
|
||||
href,
|
||||
sentence,
|
||||
issues,
|
||||
sortable,
|
||||
allowed,
|
||||
busy,
|
||||
onMove,
|
||||
onToggle,
|
||||
onDelete,
|
||||
}: RowProps) {
|
||||
const { t } = useTranslation();
|
||||
const { attributes, listeners, setNodeRef, setActivatorNodeRef, transform, transition, isDragging } = useSortable({
|
||||
id: rule.id,
|
||||
disabled: !sortable || busy,
|
||||
attributes: { roleDescription: t('mailRules.dnd.roleDescription', 'sortable rule') },
|
||||
});
|
||||
const name = ruleName(rule);
|
||||
return (
|
||||
<li
|
||||
ref={setNodeRef}
|
||||
style={{ transform: CSS.Translate.toString(transform), transition }}
|
||||
className={cn(
|
||||
'flex items-start gap-2 border-t border-border bg-card px-3 py-3 first:border-t-0 sm:gap-3 sm:px-4',
|
||||
isDragging && 'relative z-10 rounded-xl shadow-lg',
|
||||
!rule.isEnabled && 'text-muted-foreground',
|
||||
)}
|
||||
data-testid="mail-rule-row"
|
||||
>
|
||||
{sortable && (
|
||||
<button
|
||||
type="button"
|
||||
ref={setActivatorNodeRef}
|
||||
{...attributes}
|
||||
{...listeners}
|
||||
aria-label={t('mailRules.dragRule', 'Reorder {{name}}', { name })}
|
||||
className="mt-0.5 grid size-7 shrink-0 cursor-grab touch-none place-items-center rounded-md text-dim hover:bg-muted hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring active:cursor-grabbing"
|
||||
>
|
||||
<GripVertical className="size-4" aria-hidden="true" />
|
||||
</button>
|
||||
)}
|
||||
<div className="min-w-0 flex-1 space-y-1">
|
||||
<Link
|
||||
to={href}
|
||||
className="block break-words text-sm font-semibold hover:underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
|
||||
>
|
||||
{name}
|
||||
</Link>
|
||||
<p className="break-words text-[13px] leading-relaxed text-muted-foreground">{sentence}</p>
|
||||
{issues.map((issue) => (
|
||||
<p key={issue} className="flex items-start gap-1.5 text-xs text-warning">
|
||||
<AlertTriangle className="mt-0.5 size-3.5 shrink-0" aria-hidden="true" />
|
||||
{issue}
|
||||
</p>
|
||||
))}
|
||||
</div>
|
||||
<Switch
|
||||
className="mt-0.5"
|
||||
checked={rule.isEnabled}
|
||||
disabled={!allowed.update || busy}
|
||||
onCheckedChange={(checked) => onToggle(rule, checked)}
|
||||
aria-label={t('mailRules.enableRule', 'Enable {{name}}', { name })}
|
||||
/>
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon-sm"
|
||||
aria-label={t('list.actionsFor', 'Actions for {{label}}', { label: name })}
|
||||
>
|
||||
<MoreHorizontal className="size-4" aria-hidden="true" />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end">
|
||||
<DropdownMenuItem asChild>
|
||||
<Link to={href}>{allowed.update ? t('mailRules.edit', 'Edit') : t('mailRules.view', 'View')}</Link>
|
||||
</DropdownMenuItem>
|
||||
{sortable && (
|
||||
<>
|
||||
<DropdownMenuItem disabled={busy || index === 0} onSelect={() => onMove(index, index - 1)}>
|
||||
{t('mailRules.moveUp', 'Move up')}
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem disabled={busy || index === count - 1} onSelect={() => onMove(index, index + 1)}>
|
||||
{t('mailRules.moveDown', 'Move down')}
|
||||
</DropdownMenuItem>
|
||||
</>
|
||||
)}
|
||||
{allowed.destroy && (
|
||||
<>
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuItem
|
||||
disabled={busy}
|
||||
className="text-destructive focus:bg-destructive-soft focus:text-destructive"
|
||||
onSelect={() => onDelete(rule)}
|
||||
>
|
||||
{t('list.delete', 'Delete')}
|
||||
</DropdownMenuItem>
|
||||
</>
|
||||
)}
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</li>
|
||||
);
|
||||
}
|
||||
|
||||
export function CustomRuleList({ rules, accountId, editHref, allowed, checkers, summary }: CustomRuleListProps) {
|
||||
const { t } = useTranslation();
|
||||
const bulk = useJmapBulkSet(MAIL_RULE_OBJECT);
|
||||
const single = useJmapSet(MAIL_RULE_OBJECT);
|
||||
const [pendingOrder, setPendingOrder] = useState<string[] | null>(null);
|
||||
const [deleting, setDeleting] = useState<MailRule | null>(null);
|
||||
const sensors = useSensors(
|
||||
useSensor(PointerSensor, { activationConstraint: { distance: 4 } }),
|
||||
useSensor(KeyboardSensor, { coordinateGetter: sortableKeyboardCoordinates }),
|
||||
);
|
||||
const busy = bulk.isPending || single.isPending;
|
||||
const sortable = allowed.update && rules.length > 1;
|
||||
|
||||
const byId = new Map(rules.map((rule) => [rule.id, rule]));
|
||||
const shown = pendingOrder
|
||||
? pendingOrder.map((id) => byId.get(id)).filter((rule): rule is MailRule => !!rule)
|
||||
: rules;
|
||||
const order = shown.map((rule) => rule.id);
|
||||
const nameOf = (id: string | number) => {
|
||||
const rule = byId.get(String(id));
|
||||
return rule ? ruleName(rule) : String(id);
|
||||
};
|
||||
const positionOf = (id: string | number) => order.indexOf(String(id)) + 1;
|
||||
|
||||
const announcements: Announcements = {
|
||||
onDragStart: ({ active }) =>
|
||||
t('mailRules.dnd.picked', 'Picked up {{name}}, position {{position}} of {{count}}.', {
|
||||
name: nameOf(active.id),
|
||||
position: positionOf(active.id),
|
||||
count: order.length,
|
||||
}),
|
||||
onDragOver: ({ active, over }) =>
|
||||
over
|
||||
? t('mailRules.dnd.over', '{{name}} moved to position {{position}} of {{count}}.', {
|
||||
name: nameOf(active.id),
|
||||
position: positionOf(over.id),
|
||||
count: order.length,
|
||||
})
|
||||
: undefined,
|
||||
onDragEnd: ({ active, over }) =>
|
||||
over
|
||||
? t('mailRules.dnd.dropped', '{{name}} dropped at position {{position}} of {{count}}.', {
|
||||
name: nameOf(active.id),
|
||||
position: positionOf(over.id),
|
||||
count: order.length,
|
||||
})
|
||||
: undefined,
|
||||
onDragCancel: ({ active }) =>
|
||||
t('mailRules.dnd.cancelled', 'Reordering cancelled, {{name}} returned to its position.', {
|
||||
name: nameOf(active.id),
|
||||
}),
|
||||
};
|
||||
|
||||
const reorder = async (next: string[]) => {
|
||||
const changes = reorderPositions(rules, next, pinnedRuleIds(rules, checkers));
|
||||
if (changes === null) {
|
||||
toast({
|
||||
title: t('mailRules.reorderFailed', 'Could not reorder the rules'),
|
||||
description: t(
|
||||
'mailRules.reorderPinned',
|
||||
'This order would move a forwarding rule, and your account is not allowed to change forwarding rules.',
|
||||
),
|
||||
variant: 'destructive',
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (changes.size === 0) return;
|
||||
setPendingOrder(next);
|
||||
try {
|
||||
const outcome = await bulk.mutateAsync({ action: 'updateEach', patches: positionPatches(changes), accountId });
|
||||
const [failed] = Object.values(outcome.failed);
|
||||
if (failed) {
|
||||
toast({
|
||||
title: t('mailRules.reorderFailed', 'Could not reorder the rules'),
|
||||
description: friendlySetError(failed),
|
||||
variant: 'destructive',
|
||||
});
|
||||
}
|
||||
} catch (err) {
|
||||
toast({
|
||||
title: t('mailRules.reorderFailed', 'Could not reorder the rules'),
|
||||
description: errorMessage(err),
|
||||
variant: 'destructive',
|
||||
});
|
||||
} finally {
|
||||
setPendingOrder(null);
|
||||
}
|
||||
};
|
||||
|
||||
const move = (from: number, to: number) => {
|
||||
const next = moveInOrder(order, from, to);
|
||||
if (next) void reorder(next);
|
||||
};
|
||||
|
||||
const onDragEnd = ({ active, over }: DragEndEvent) => {
|
||||
if (!over || busy) return;
|
||||
move(order.indexOf(String(active.id)), order.indexOf(String(over.id)));
|
||||
};
|
||||
|
||||
const toggle = async (rule: MailRule, isEnabled: boolean) => {
|
||||
try {
|
||||
const result = await single.mutateAsync({ update: { [rule.id]: { isEnabled } }, accountId });
|
||||
const notUpdated = result.notUpdated?.[rule.id];
|
||||
if (notUpdated) {
|
||||
toast({
|
||||
title: t('form.failedToSave', 'Failed to save.'),
|
||||
description: friendlySetError(notUpdated),
|
||||
variant: 'destructive',
|
||||
});
|
||||
}
|
||||
} catch (err) {
|
||||
toast({
|
||||
title: t('form.failedToSave', 'Failed to save.'),
|
||||
description: errorMessage(err),
|
||||
variant: 'destructive',
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
const destroy = async (rule: MailRule) => {
|
||||
const failed = (description: string) =>
|
||||
toast({ title: t('form.failedToDelete', 'Failed to delete.'), description, variant: 'destructive' });
|
||||
try {
|
||||
const result = await single.mutateAsync({ destroy: [rule.id], accountId });
|
||||
const notDestroyed = result.notDestroyed?.[rule.id];
|
||||
if (notDestroyed) failed(friendlySetError(notDestroyed));
|
||||
} catch (err) {
|
||||
failed(errorMessage(err));
|
||||
}
|
||||
};
|
||||
|
||||
if (rules.length === 0) {
|
||||
return (
|
||||
<ListMessage>{t('mailRules.noRules', 'No mail rules yet. Create one to sort, file or answer mail.')}</ListMessage>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<DndContext
|
||||
sensors={sensors}
|
||||
collisionDetection={closestCenter}
|
||||
onDragEnd={onDragEnd}
|
||||
accessibility={{
|
||||
announcements,
|
||||
screenReaderInstructions: {
|
||||
draggable: t(
|
||||
'mailRules.dnd.instructions',
|
||||
'To reorder a rule, press Space or Enter to pick it up, use the arrow keys to move it, then press Space or Enter again to drop it, or Escape to cancel.',
|
||||
),
|
||||
},
|
||||
}}
|
||||
>
|
||||
<SortableContext items={order} strategy={verticalListSortingStrategy}>
|
||||
<ol
|
||||
className={cn('tile overflow-hidden p-0', busy && 'opacity-70')}
|
||||
aria-label={t('mailRules.ruleList', 'Mail rules')}
|
||||
aria-busy={busy}
|
||||
>
|
||||
{shown.map((rule, index) => (
|
||||
<SortableRuleRow
|
||||
key={rule.id}
|
||||
rule={rule}
|
||||
index={index}
|
||||
count={shown.length}
|
||||
href={editHref(rule.id)}
|
||||
sentence={ruleSentence(summary, summarizeCustomRule(summary, rule.body))}
|
||||
issues={ruleIssues(rule, checkers).map((issue) => ruleIssueMessage(t, issue))}
|
||||
sortable={sortable}
|
||||
allowed={allowed}
|
||||
busy={busy}
|
||||
onMove={move}
|
||||
onToggle={(target, isEnabled) => void toggle(target, isEnabled)}
|
||||
onDelete={setDeleting}
|
||||
/>
|
||||
))}
|
||||
</ol>
|
||||
</SortableContext>
|
||||
</DndContext>
|
||||
<ConfirmDialog
|
||||
open={deleting !== null}
|
||||
onOpenChange={(open) => {
|
||||
if (!open) setDeleting(null);
|
||||
}}
|
||||
title={t('mailRules.deleteTitle', 'Delete this rule?')}
|
||||
description={t(
|
||||
'list.deleteItemDescription',
|
||||
'Are you sure you want to delete {{label}}? This action cannot be undone.',
|
||||
{
|
||||
label: deleting ? ruleName(deleting) : '',
|
||||
},
|
||||
)}
|
||||
confirmLabel={t('list.delete', 'Delete')}
|
||||
variant="destructive"
|
||||
onConfirm={() => (deleting ? destroy(deleting) : undefined)}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
/*
|
||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { DynamicForm } from '@/components/forms/DynamicForm';
|
||||
import { ListError, ListSpinner } from '@/components/lists/ListStates';
|
||||
import { DynamicViewPage } from '@/components/views/DynamicViewPage';
|
||||
import { errorMessage } from '@/lib/jmapErrors';
|
||||
import type { FieldOverrides } from '@/components/forms/useDynamicForm';
|
||||
import type { ViewRenderers } from '@/components/views/DynamicView';
|
||||
import type { PageProps } from '@/extensions/types';
|
||||
import { useRuleAccountId } from '../account';
|
||||
import { nextRulePosition } from '../model';
|
||||
import { useMailRules } from '../queries';
|
||||
import { RuleBuilderRow, RuleSummaryRow } from './RuleBuilder';
|
||||
|
||||
const RULE_ANCHOR = 'actions';
|
||||
const RULE_FIELDS = ['matchAll', 'conditions', 'exceptions', 'stopProcessing', 'timeZone'] as const;
|
||||
|
||||
function Omitted() {
|
||||
return null;
|
||||
}
|
||||
|
||||
const FIELD_OVERRIDES: FieldOverrides = {
|
||||
hidden: ['position'],
|
||||
render: {
|
||||
...Object.fromEntries(RULE_FIELDS.map((name) => [name, Omitted])),
|
||||
[RULE_ANCHOR]: RuleBuilderRow,
|
||||
},
|
||||
};
|
||||
|
||||
const VIEW_RENDERERS: ViewRenderers = {
|
||||
...Object.fromEntries(RULE_FIELDS.map((name) => [name, Omitted])),
|
||||
[RULE_ANCHOR]: RuleSummaryRow,
|
||||
};
|
||||
|
||||
function CreateRuleForm({ viewName, accountId }: { viewName: string; accountId: string }) {
|
||||
const { t } = useTranslation();
|
||||
const rules = useMailRules(accountId);
|
||||
if (rules.isError) {
|
||||
return (
|
||||
<ListError
|
||||
message={errorMessage(rules.error, t('mailRules.loadFailed', 'Failed to load the mail rules.'))}
|
||||
onRetry={() => void rules.refetch()}
|
||||
/>
|
||||
);
|
||||
}
|
||||
if (!rules.data) return <ListSpinner />;
|
||||
return (
|
||||
<DynamicForm
|
||||
viewName={viewName}
|
||||
objectId={null}
|
||||
accountId={accountId}
|
||||
fieldOverrides={FIELD_OVERRIDES}
|
||||
createValues={{ position: nextRulePosition(rules.data) }}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export function MailRuleFormPage({ viewName, objectId }: PageProps) {
|
||||
const accountId = useRuleAccountId();
|
||||
if (!accountId) return null;
|
||||
if (objectId === 'new') return <CreateRuleForm viewName={viewName} accountId={accountId} />;
|
||||
return <DynamicForm viewName={viewName} objectId={objectId} accountId={accountId} fieldOverrides={FIELD_OVERRIDES} />;
|
||||
}
|
||||
|
||||
export function MailRuleViewPage({ viewName, objectId }: PageProps) {
|
||||
const accountId = useRuleAccountId();
|
||||
if (!accountId || !objectId) return null;
|
||||
return <DynamicViewPage viewName={viewName} objectId={objectId} accountId={accountId} renderers={VIEW_RENDERERS} />;
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
/*
|
||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
import { Link } from 'react-router-dom';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Plus } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { ListError, ListSpinner } from '@/components/lists/ListStates';
|
||||
import { useHasObjectPermission, usePermissionCheckers } from '@/hooks/usePermissions';
|
||||
import { useResolvedView } from '@/hooks/useResolvedView';
|
||||
import { errorMessage } from '@/lib/jmapErrors';
|
||||
import { useSchemaStore } from '@/stores/schemaStore';
|
||||
import type { PageProps } from '@/extensions/types';
|
||||
import { useRuleAccountId } from '../account';
|
||||
import { mailboxNameResolver } from '../mailboxes';
|
||||
import { useMailboxOptions, useMailRules } from '../queries';
|
||||
import { CustomRuleList } from './CustomRuleList';
|
||||
|
||||
export function MailRulesPage({ viewName, section }: PageProps) {
|
||||
const { t } = useTranslation();
|
||||
const schema = useSchemaStore((s) => s.schema);
|
||||
const resolved = useResolvedView(viewName);
|
||||
const checkers = usePermissionCheckers();
|
||||
const accountId = useRuleAccountId();
|
||||
const prefix = resolved?.object.permissionPrefix;
|
||||
const allowed = {
|
||||
create: useHasObjectPermission(prefix, 'Create'),
|
||||
update: useHasObjectPermission(prefix, 'Update'),
|
||||
destroy: useHasObjectPermission(prefix, 'Destroy'),
|
||||
};
|
||||
const rules = useMailRules(accountId);
|
||||
const mailboxes = useMailboxOptions(accountId);
|
||||
const list = resolved?.list;
|
||||
|
||||
if (!schema || !resolved || !list) return null;
|
||||
|
||||
const basePath = `/${section}/${viewName}`;
|
||||
const summary = {
|
||||
t,
|
||||
schema,
|
||||
mailboxName: mailboxes.status === 'ready' ? mailboxNameResolver(mailboxes.options) : undefined,
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-3.5">
|
||||
<div className="flex flex-wrap items-end justify-between gap-4 px-1 pb-1 pt-3">
|
||||
<div className="min-w-0">
|
||||
<h1 className="page-title">{list.title}</h1>
|
||||
{list.subtitle && <p className="mt-1 text-sm text-muted-foreground">{list.subtitle}</p>}
|
||||
</div>
|
||||
{allowed.create && accountId && (
|
||||
<Button asChild>
|
||||
<Link to={`${basePath}/new`}>
|
||||
<Plus aria-hidden="true" />
|
||||
{t('mailRules.createRule', 'Create rule')}
|
||||
</Link>
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{rules.isError && (
|
||||
<ListError
|
||||
message={errorMessage(rules.error, t('mailRules.loadFailed', 'Failed to load the mail rules.'))}
|
||||
onRetry={() => void rules.refetch()}
|
||||
/>
|
||||
)}
|
||||
{rules.isPending && rules.fetchStatus !== 'idle' && <ListSpinner />}
|
||||
|
||||
{rules.data && accountId && (
|
||||
<CustomRuleList
|
||||
rules={rules.data}
|
||||
accountId={accountId}
|
||||
editHref={(id) => `${basePath}/${id}`}
|
||||
allowed={allowed}
|
||||
checkers={checkers}
|
||||
summary={summary}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
/*
|
||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
|
||||
import { BufferedInput } from '@/components/forms/widgets/BufferedInputs';
|
||||
import type { ControlProps } from '@/components/forms/widgets/types';
|
||||
import { useMailboxOptions } from '../queries';
|
||||
|
||||
const INDENT_REM = 0.75;
|
||||
|
||||
interface MailboxPickerProps {
|
||||
accountId: string | null;
|
||||
value: unknown;
|
||||
onChange: (value: string) => void;
|
||||
readOnly: boolean;
|
||||
control: ControlProps;
|
||||
}
|
||||
|
||||
export function MailboxPicker({ accountId, value, onChange, readOnly, control }: MailboxPickerProps) {
|
||||
const { t } = useTranslation();
|
||||
const mailboxes = useMailboxOptions(accountId);
|
||||
const current = typeof value === 'string' ? value : '';
|
||||
|
||||
if (mailboxes.status !== 'ready') {
|
||||
return (
|
||||
<BufferedInput
|
||||
{...control}
|
||||
value={current}
|
||||
onCommit={onChange}
|
||||
readOnly={readOnly}
|
||||
disabled={mailboxes.status === 'loading'}
|
||||
placeholder={t('mailRules.mailboxId', 'Mailbox id')}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
const { options } = mailboxes;
|
||||
const selected = options.find((option) => option.id === current);
|
||||
return (
|
||||
<Select value={current} onValueChange={onChange} disabled={readOnly}>
|
||||
<SelectTrigger {...control} className="w-full">
|
||||
<SelectValue placeholder={t('mailRules.chooseMailbox', 'Choose a mailbox')}>
|
||||
{selected ? selected.path.join(' / ') : undefined}
|
||||
</SelectValue>
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{current && !selected && (
|
||||
<SelectItem value={current}>
|
||||
{t('mailRules.unknownMailbox', 'Unknown mailbox ({{id}})', { id: current })}
|
||||
</SelectItem>
|
||||
)}
|
||||
{options.map((option) => (
|
||||
<SelectItem key={option.id} value={option.id} textValue={option.path.join(' / ')}>
|
||||
<span style={{ paddingInlineStart: `${option.depth * INDENT_REM}rem` }}>{option.name}</span>
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,315 @@
|
||||
/*
|
||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
import { useRef, useState, type KeyboardEvent, type ReactNode } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { AlertTriangle, ChevronRight } from 'lucide-react';
|
||||
import { FieldError, FieldRow } from '@/components/forms/FieldRow';
|
||||
import { ValueRow } from '@/components/values/FieldValue';
|
||||
import { fieldIds, useFormContext } from '@/components/forms/formContext';
|
||||
import { missingNestedFields } from '@/components/forms/formLogic';
|
||||
import type { FieldRenderProps } from '@/components/forms/useDynamicForm';
|
||||
import { usePermissionCheckers } from '@/hooks/usePermissions';
|
||||
import { embeddedEntries, resolveEmbedded } from '@/lib/embeddedSchema';
|
||||
import { cn } from '@/lib/utils';
|
||||
import type { ViewRenderProps } from '@/components/views/DynamicView';
|
||||
import type { Field, FieldTypeObjectList } from '@/types/schema';
|
||||
import { useRuleAccountId } from '../account';
|
||||
import { listEntries } from '../builder';
|
||||
import { mailboxNameResolver } from '../mailboxes';
|
||||
import {
|
||||
hasRejectAction,
|
||||
hasScheduleCondition,
|
||||
isRejectAllowed,
|
||||
MAIL_RULE_ACTION_OBJECT,
|
||||
MAIL_RULE_CONDITION_OBJECT,
|
||||
MAIL_RULE_OBJECT,
|
||||
parseCustomBody,
|
||||
REJECT_ACTION,
|
||||
ruleIssues,
|
||||
type RuleIssue,
|
||||
} from '../model';
|
||||
import { useMailboxOptions } from '../queries';
|
||||
import { ruleIssueMessage, ruleSentence, summarizeCustomRule } from '../summary';
|
||||
import { RuleItemList } from './RuleItemList';
|
||||
|
||||
const TRAILING_FIELDS = new Set(['stopProcessing', 'timeZone']);
|
||||
const RULE_ERROR_FIELDS = ['matchAll', 'conditions', 'exceptions'] as const;
|
||||
const STOP_PROCESSING = 'stopProcessing';
|
||||
const TOGGLE_KEYS = new Set(['ArrowLeft', 'ArrowRight', 'ArrowUp', 'ArrowDown']);
|
||||
|
||||
function listBounds(field: Field | undefined): { minItems?: number; maxItems?: number } {
|
||||
const type = field?.type as FieldTypeObjectList | undefined;
|
||||
return type?.type === 'objectList' ? { minItems: type.minItems, maxItems: type.maxItems } : {};
|
||||
}
|
||||
|
||||
function MatchModeToggle({
|
||||
matchAll,
|
||||
onChange,
|
||||
readOnly,
|
||||
}: {
|
||||
matchAll: boolean;
|
||||
onChange: (matchAll: boolean) => void;
|
||||
readOnly: boolean;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const options = [
|
||||
{ value: true, label: t('mailRules.builder.all', 'all') },
|
||||
{ value: false, label: t('mailRules.builder.any', 'any') },
|
||||
];
|
||||
const onKeyDown = (event: KeyboardEvent<HTMLSpanElement>) => {
|
||||
if (readOnly || !TOGGLE_KEYS.has(event.key)) return;
|
||||
event.preventDefault();
|
||||
onChange(!matchAll);
|
||||
event.currentTarget.querySelector<HTMLButtonElement>('[aria-checked="false"]')?.focus();
|
||||
};
|
||||
return (
|
||||
<span
|
||||
role="radiogroup"
|
||||
aria-label={t('mailRules.builder.matchMode', 'Conditions that must match')}
|
||||
className="inline-flex rounded-lg bg-muted p-0.5 align-middle"
|
||||
onKeyDown={onKeyDown}
|
||||
>
|
||||
{options.map((option) => (
|
||||
<button
|
||||
key={String(option.value)}
|
||||
type="button"
|
||||
role="radio"
|
||||
aria-checked={matchAll === option.value}
|
||||
tabIndex={matchAll === option.value ? 0 : -1}
|
||||
disabled={readOnly}
|
||||
onClick={() => onChange(option.value)}
|
||||
className={cn(
|
||||
'rounded-md px-2.5 py-0.5 text-sm font-semibold transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring',
|
||||
matchAll === option.value ? 'bg-primary text-primary-foreground' : 'text-muted-foreground',
|
||||
)}
|
||||
>
|
||||
{option.label}
|
||||
</button>
|
||||
))}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
function Step({ heading, title, children }: { heading: string; title?: ReactNode; children: ReactNode }) {
|
||||
return (
|
||||
<section className="space-y-2 py-3">
|
||||
<h3 className={title ? 'sr-only' : 'text-[13.5px] font-semibold'}>{heading}</h3>
|
||||
{title && <div className="text-[13.5px] font-semibold">{title}</div>}
|
||||
{children}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
function IssueList({ issues }: { issues: readonly RuleIssue[] }) {
|
||||
const { t } = useTranslation();
|
||||
if (issues.length === 0) return null;
|
||||
return (
|
||||
<ul className="space-y-1.5 py-3">
|
||||
{issues.map((issue) => (
|
||||
<li key={issue} className="flex items-start gap-1.5 rounded-lg bg-warning-soft px-3 py-2 text-xs text-warning">
|
||||
<AlertTriangle className="mt-0.5 size-3.5 shrink-0" aria-hidden="true" />
|
||||
{ruleIssueMessage(t, issue)}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
);
|
||||
}
|
||||
|
||||
export function RuleBuilderRow({ data: body, errors, readOnly, onFieldChange: set }: FieldRenderProps) {
|
||||
const { t } = useTranslation();
|
||||
const { schema, idPrefix } = useFormContext();
|
||||
const checkers = usePermissionCheckers();
|
||||
const exceptionsButton = useRef<HTMLButtonElement>(null);
|
||||
const custom = parseCustomBody(body);
|
||||
const resolved = resolveEmbedded(schema, MAIL_RULE_OBJECT, body);
|
||||
const entries = resolved ? embeddedEntries(resolved) : [];
|
||||
const fieldOf = (name: string) => entries.find((entry) => entry.formField.name === name);
|
||||
const [exceptionsExpanded, setExceptionsExpanded] = useState<boolean | null>(null);
|
||||
const missing = new Set(
|
||||
errors.conditions || errors.exceptions || errors.actions ? missingNestedFields(schema, MAIL_RULE_OBJECT, body) : [],
|
||||
);
|
||||
const errorOf = (name: string) => (missing.has(name) ? undefined : errors[name]);
|
||||
const issues = ruleIssues({ isEnabled: true, body }, checkers);
|
||||
const hasReject = hasRejectAction(custom);
|
||||
const rejectBlocked =
|
||||
custom.actions.length > 1
|
||||
? t('mailRules.builder.rejectNotAlone', 'Reject must be the only action.')
|
||||
: isRejectAllowed(custom)
|
||||
? undefined
|
||||
: t(
|
||||
'mailRules.builder.rejectNeedsAuthentication',
|
||||
'Reject needs all conditions to match, including an authenticated sender.',
|
||||
);
|
||||
const disabledActions = rejectBlocked ? new Map([[REJECT_ACTION, rejectBlocked]]) : undefined;
|
||||
const conditionLabel = (n: number) => t('mailRules.builder.conditionN', 'Condition {{n}}', { n });
|
||||
const exceptionLabel = (n: number) => t('mailRules.builder.exceptionN', 'Exception {{n}}', { n });
|
||||
const actionLabel = (n: number) => t('mailRules.builder.actionN', 'Action {{n}}', { n });
|
||||
const showExceptions = !!errors.exceptions || (exceptionsExpanded ?? custom.exceptions.length > 0);
|
||||
const exceptionsId = `${fieldIds(idPrefix, ['exceptions']).inputId}-list`;
|
||||
const actionsErrorId = fieldIds(idPrefix, ['actions']).errorId;
|
||||
const ruleErrorField = RULE_ERROR_FIELDS.find((name) => errorOf(name));
|
||||
const actionsError =
|
||||
errors.actions &&
|
||||
(custom.actions.length === 0
|
||||
? t('mailRules.builder.actionRequired', 'Add at least one action.')
|
||||
: errorOf('actions'));
|
||||
const changeExceptions = (next: unknown) => {
|
||||
if (custom.exceptions.length > 0 && listEntries(next).length === 0) exceptionsButton.current?.focus();
|
||||
set('exceptions', next);
|
||||
};
|
||||
const trailing = entries.filter(
|
||||
({ formField }) =>
|
||||
TRAILING_FIELDS.has(formField.name) && (formField.name !== 'timeZone' || hasScheduleCondition(custom)),
|
||||
);
|
||||
|
||||
return (
|
||||
<div className="divide-y divide-border" data-testid="mail-rule-builder">
|
||||
{ruleErrorField && (
|
||||
<div className="py-3">
|
||||
<FieldError id={fieldIds(idPrefix, [ruleErrorField]).errorId} error={errorOf(ruleErrorField)} />
|
||||
</div>
|
||||
)}
|
||||
<Step
|
||||
heading={
|
||||
custom.conditions.length >= 2
|
||||
? t('mailRules.builder.conditions', 'Conditions')
|
||||
: custom.conditions.length === 1
|
||||
? t('mailRules.builder.ifOne', 'If this condition matches')
|
||||
: t('mailRules.builder.ifNone', 'For every message')
|
||||
}
|
||||
title={
|
||||
custom.conditions.length >= 2 && (
|
||||
<span className="flex flex-wrap items-center gap-1.5">
|
||||
{t('mailRules.builder.ifPrefix', 'If')}
|
||||
<MatchModeToggle
|
||||
matchAll={custom.matchAll}
|
||||
onChange={(matchAll) => set('matchAll', matchAll)}
|
||||
readOnly={readOnly}
|
||||
/>
|
||||
{t('mailRules.builder.ifSuffix', 'of these conditions match')}
|
||||
</span>
|
||||
)
|
||||
}
|
||||
>
|
||||
{custom.conditions.length === 0 && (
|
||||
<p className="text-[12.5px] text-muted-foreground">
|
||||
{t('mailRules.builder.noConditions', 'Without conditions the rule applies to every message.')}
|
||||
</p>
|
||||
)}
|
||||
<RuleItemList
|
||||
name="conditions"
|
||||
objectName={MAIL_RULE_CONDITION_OBJECT}
|
||||
value={body.conditions}
|
||||
onChange={(next) => set('conditions', next)}
|
||||
readOnly={readOnly}
|
||||
invalid={!!errors.conditions}
|
||||
{...listBounds(fieldOf('conditions')?.field)}
|
||||
itemLabel={conditionLabel}
|
||||
addLabel={t('mailRules.builder.addCondition', 'Add condition')}
|
||||
/>
|
||||
</Step>
|
||||
|
||||
<section className="py-3">
|
||||
<button
|
||||
ref={exceptionsButton}
|
||||
type="button"
|
||||
aria-expanded={showExceptions}
|
||||
aria-controls={exceptionsId}
|
||||
onClick={() => setExceptionsExpanded(!showExceptions)}
|
||||
className="flex items-center gap-1.5 rounded-md text-[13.5px] font-semibold focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
|
||||
>
|
||||
<ChevronRight
|
||||
className={cn('size-4 text-dim transition-transform', showExceptions && 'rotate-90')}
|
||||
aria-hidden="true"
|
||||
/>
|
||||
{t('mailRules.builder.except', 'Except if any of these match')}
|
||||
{!showExceptions && custom.exceptions.length > 0 && (
|
||||
<span className="font-normal text-muted-foreground">({custom.exceptions.length})</span>
|
||||
)}
|
||||
</button>
|
||||
{showExceptions && (
|
||||
<div id={exceptionsId} className="mt-2">
|
||||
<RuleItemList
|
||||
name="exceptions"
|
||||
objectName={MAIL_RULE_CONDITION_OBJECT}
|
||||
value={body.exceptions}
|
||||
onChange={changeExceptions}
|
||||
readOnly={readOnly}
|
||||
invalid={!!errors.exceptions}
|
||||
{...listBounds(fieldOf('exceptions')?.field)}
|
||||
itemLabel={exceptionLabel}
|
||||
addLabel={t('mailRules.builder.addException', 'Add exception')}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</section>
|
||||
|
||||
<Step heading={t('mailRules.builder.then', 'Then')}>
|
||||
<RuleItemList
|
||||
name="actions"
|
||||
objectName={MAIL_RULE_ACTION_OBJECT}
|
||||
value={body.actions}
|
||||
onChange={(next) => set('actions', next)}
|
||||
readOnly={readOnly}
|
||||
invalid={!!errors.actions}
|
||||
{...listBounds(fieldOf('actions')?.field)}
|
||||
canAddMore={!hasReject}
|
||||
itemLabel={actionLabel}
|
||||
addLabel={t('mailRules.builder.addAction', 'Add action')}
|
||||
disabledVariants={disabledActions}
|
||||
/>
|
||||
<FieldError id={actionsErrorId} error={actionsError} />
|
||||
</Step>
|
||||
|
||||
{trailing.length > 0 && (
|
||||
<div className="@container">
|
||||
{trailing.map(({ formField, field }) =>
|
||||
hasReject && formField.name === STOP_PROCESSING ? (
|
||||
<div key={formField.name}>
|
||||
<FieldRow field={field} formField={formField} value={true} onChange={() => {}} readOnly />
|
||||
<p className="pb-3 text-[12.5px] text-muted-foreground">
|
||||
{t('mailRules.builder.rejectStops', 'A rule that rejects mail always stops processing more rules.')}
|
||||
</p>
|
||||
</div>
|
||||
) : (
|
||||
<FieldRow
|
||||
key={formField.name}
|
||||
field={field}
|
||||
formField={formField}
|
||||
value={body[formField.name]}
|
||||
onChange={(next) => set(formField.name, next)}
|
||||
error={errors[formField.name]}
|
||||
readOnly={readOnly}
|
||||
/>
|
||||
),
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<IssueList issues={issues} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function RuleSummaryRow({ schema, data }: ViewRenderProps) {
|
||||
const { t } = useTranslation();
|
||||
const accountId = useRuleAccountId();
|
||||
const mailboxes = useMailboxOptions(accountId);
|
||||
const ctx = {
|
||||
t,
|
||||
schema,
|
||||
mailboxName: mailboxes.status === 'ready' ? mailboxNameResolver(mailboxes.options) : undefined,
|
||||
};
|
||||
return (
|
||||
<ValueRow
|
||||
schema={schema}
|
||||
label={t('mailRules.summaryLabel', 'Summary')}
|
||||
type={undefined}
|
||||
value={ruleSentence(ctx, summarizeCustomRule(ctx, data))}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,272 @@
|
||||
/*
|
||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
import { useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Plus, Trash2 } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
|
||||
import { FieldError, FieldRow } from '@/components/forms/FieldRow';
|
||||
import { FieldScopeProvider } from '@/components/forms/FormProvider';
|
||||
import { missingNestedFields } from '@/components/forms/formLogic';
|
||||
import { EnclosingSchemaContext, fieldIds, useFieldScope, useFormContext } from '@/components/forms/formContext';
|
||||
import { FieldControl } from '@/components/forms/widgets/FieldControl';
|
||||
import { embeddedEntries, resolveEmbedded, switchVariantValues } from '@/lib/embeddedSchema';
|
||||
import { formatList } from '@/lib/format';
|
||||
import { buildEmbeddedDefaults, buildNewObjectValue } from '@/lib/schemaResolver';
|
||||
import { useRuleAccountId } from '../account';
|
||||
import {
|
||||
appendItem,
|
||||
isInlineField,
|
||||
listEntries,
|
||||
MAILBOX_FIELD,
|
||||
MAILBOX_SCHEMA,
|
||||
removeItem,
|
||||
replaceItem,
|
||||
} from '../builder';
|
||||
import { MailboxPicker } from './MailboxPicker';
|
||||
|
||||
const NO_MISSING: ReadonlySet<string> = new Set();
|
||||
|
||||
interface RuleItemListProps {
|
||||
name: string;
|
||||
objectName: string;
|
||||
value: unknown;
|
||||
onChange: (value: unknown) => void;
|
||||
readOnly: boolean;
|
||||
invalid: boolean;
|
||||
minItems?: number;
|
||||
maxItems?: number;
|
||||
canAddMore?: boolean;
|
||||
itemLabel: (n: number) => string;
|
||||
addLabel: string;
|
||||
disabledVariants?: ReadonlyMap<string, string>;
|
||||
}
|
||||
|
||||
interface RuleItemProps {
|
||||
objectName: string;
|
||||
itemKey: string;
|
||||
item: Record<string, unknown>;
|
||||
label: string;
|
||||
onChange: (item: Record<string, unknown>) => void;
|
||||
onRemove: (() => void) | null;
|
||||
readOnly: boolean;
|
||||
invalid: boolean;
|
||||
disabledVariants?: ReadonlyMap<string, string>;
|
||||
}
|
||||
|
||||
function RuleItem({
|
||||
objectName,
|
||||
itemKey,
|
||||
item,
|
||||
label,
|
||||
onChange,
|
||||
onRemove,
|
||||
readOnly,
|
||||
invalid,
|
||||
disabledVariants,
|
||||
}: RuleItemProps) {
|
||||
const { t } = useTranslation();
|
||||
const { schema, idPrefix, mode, baseline } = useFormContext();
|
||||
const scope = useFieldScope();
|
||||
const accountId = useRuleAccountId();
|
||||
const [initial, setInitial] = useState({ baseline, item });
|
||||
if (initial.baseline !== baseline) setInitial({ baseline, item });
|
||||
const resolved = resolveEmbedded(schema, objectName, item);
|
||||
if (!resolved) return null;
|
||||
const variant = resolved.variant?.name ?? '';
|
||||
const schemaName = resolved.variant?.schemaName;
|
||||
const entries = embeddedEntries(resolved).filter(({ field }) => field.update !== 'serverSet');
|
||||
const inline = entries.filter(({ field }) => isInlineField(field));
|
||||
const block = entries.filter(({ field }) => !isInlineField(field));
|
||||
const path = [...scope.path, itemKey];
|
||||
const missing = invalid ? new Set(missingNestedFields(schema, objectName, item)) : NO_MISSING;
|
||||
const missingInline = inline.filter(({ formField }) => missing.has(formField.name));
|
||||
const itemErrorId = fieldIds(idPrefix, path).errorId;
|
||||
const requiredMessage = t('form.required', 'This field is required.');
|
||||
|
||||
const changeVariant = (next: string) => {
|
||||
const defaults = buildEmbeddedDefaults(schema, objectName, {}, next);
|
||||
const target = resolveEmbedded(schema, objectName, defaults);
|
||||
const original = mode === 'edit' ? initial.item : undefined;
|
||||
onChange(switchVariantValues(resolved.fields, target?.fields, item, defaults, original));
|
||||
};
|
||||
|
||||
return (
|
||||
<li className="rounded-xl bg-card px-3 py-2.5 shadow-tile" data-testid="mail-rule-item">
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<Select value={variant} onValueChange={changeVariant} disabled={readOnly}>
|
||||
<SelectTrigger
|
||||
id={fieldIds(idPrefix, [...path, '@type']).inputId}
|
||||
aria-label={label}
|
||||
className="min-w-0 flex-1 gap-2 sm:min-w-56 sm:max-w-sm sm:flex-none"
|
||||
>
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{(resolved.variants ?? []).map((option) => {
|
||||
const reason = option.name !== variant ? disabledVariants?.get(option.name) : undefined;
|
||||
return (
|
||||
<SelectItem key={option.name} value={option.name} disabled={!!reason}>
|
||||
{reason ? (
|
||||
<span className="flex flex-col">
|
||||
<span>{option.label}</span>
|
||||
<span className="text-xs text-muted-foreground">{reason}</span>
|
||||
</span>
|
||||
) : (
|
||||
option.label
|
||||
)}
|
||||
</SelectItem>
|
||||
);
|
||||
})}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
{inline.map(({ formField, field }) => {
|
||||
const ids = fieldIds(idPrefix, [...path, formField.name]);
|
||||
const fieldValue = item[formField.name];
|
||||
const setValue = (next: unknown) => onChange({ ...item, [formField.name]: next });
|
||||
const isMissing = missing.has(formField.name);
|
||||
const control = {
|
||||
id: ids.inputId,
|
||||
'aria-label': `${label}: ${formField.label}`,
|
||||
'aria-invalid': isMissing || undefined,
|
||||
'aria-describedby': isMissing ? itemErrorId : undefined,
|
||||
};
|
||||
const isMailbox = schemaName === MAILBOX_SCHEMA && formField.name === MAILBOX_FIELD;
|
||||
return (
|
||||
<div
|
||||
key={formField.name}
|
||||
className="order-2 flex min-w-0 flex-1 basis-full items-center gap-2 sm:order-none sm:basis-40"
|
||||
>
|
||||
{!isMailbox && field.type.type !== 'enum' && (
|
||||
<label htmlFor={ids.inputId} className="shrink-0 text-[12.5px] text-muted-foreground">
|
||||
{formField.label}
|
||||
</label>
|
||||
)}
|
||||
<div className="min-w-0 flex-1">
|
||||
{isMailbox ? (
|
||||
<MailboxPicker
|
||||
accountId={accountId}
|
||||
value={fieldValue}
|
||||
onChange={setValue}
|
||||
readOnly={readOnly}
|
||||
control={control}
|
||||
/>
|
||||
) : (
|
||||
<FieldScopeProvider name={itemKey} readOnly={readOnly}>
|
||||
<FieldControl
|
||||
type={field.type}
|
||||
field={field}
|
||||
formField={formField}
|
||||
value={fieldValue}
|
||||
onChange={setValue}
|
||||
readOnly={readOnly}
|
||||
control={control}
|
||||
/>
|
||||
</FieldScopeProvider>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
{onRemove && (
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost-danger"
|
||||
size="icon-sm"
|
||||
className="order-1 ml-auto shrink-0 sm:order-none"
|
||||
onClick={onRemove}
|
||||
aria-label={t('mailRules.removeItem', 'Remove {{label}}', { label })}
|
||||
>
|
||||
<Trash2 className="size-4" aria-hidden="true" />
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
{missingInline.length > 0 && (
|
||||
<div className="mt-1.5">
|
||||
<FieldError
|
||||
id={itemErrorId}
|
||||
error={t('mailRules.builder.missingFields', 'Fill in {{fields}}.', {
|
||||
fields: formatList(missingInline.map(({ formField }) => formField.label)),
|
||||
})}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
{block.length > 0 && (
|
||||
<FieldScopeProvider name={itemKey} readOnly={readOnly}>
|
||||
<EnclosingSchemaContext value={resolved.schemaName}>
|
||||
<div className="@container mt-1 divide-y divide-border [&>[data-slot=field-row]]:py-3">
|
||||
{block.map(({ formField, field }) => (
|
||||
<FieldRow
|
||||
key={formField.name}
|
||||
field={field}
|
||||
formField={formField}
|
||||
value={item[formField.name]}
|
||||
onChange={(next) => onChange({ ...item, [formField.name]: next })}
|
||||
error={missing.has(formField.name) ? requiredMessage : undefined}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</EnclosingSchemaContext>
|
||||
</FieldScopeProvider>
|
||||
)}
|
||||
</li>
|
||||
);
|
||||
}
|
||||
|
||||
export function RuleItemList({
|
||||
name,
|
||||
objectName,
|
||||
value,
|
||||
onChange,
|
||||
readOnly,
|
||||
invalid,
|
||||
minItems,
|
||||
maxItems,
|
||||
canAddMore = true,
|
||||
itemLabel,
|
||||
addLabel,
|
||||
disabledVariants,
|
||||
}: RuleItemListProps) {
|
||||
const { schema } = useFormContext();
|
||||
const entries = listEntries(value);
|
||||
const canRemove = !readOnly && (minItems == null || entries.length > minItems);
|
||||
const canAdd = !readOnly && canAddMore && (maxItems == null || entries.length < maxItems);
|
||||
return (
|
||||
<FieldScopeProvider name={name} readOnly={readOnly}>
|
||||
{entries.length > 0 && (
|
||||
<ol className="space-y-2">
|
||||
{entries.map(([key, item], index) => (
|
||||
<RuleItem
|
||||
key={key}
|
||||
objectName={objectName}
|
||||
itemKey={key}
|
||||
item={item}
|
||||
label={itemLabel(index + 1)}
|
||||
onChange={(next) => onChange(replaceItem(value, key, next))}
|
||||
onRemove={canRemove ? () => onChange(removeItem(value, key)) : null}
|
||||
readOnly={readOnly}
|
||||
invalid={invalid}
|
||||
disabledVariants={disabledVariants}
|
||||
/>
|
||||
))}
|
||||
</ol>
|
||||
)}
|
||||
{canAdd && (
|
||||
<Button
|
||||
type="button"
|
||||
variant="secondary"
|
||||
size="sm"
|
||||
className="mt-2"
|
||||
onClick={() => onChange(appendItem(value, buildNewObjectValue(schema, objectName)))}
|
||||
>
|
||||
<Plus className="size-4" aria-hidden="true" />
|
||||
{addLabel}
|
||||
</Button>
|
||||
)}
|
||||
</FieldScopeProvider>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,371 @@
|
||||
/*
|
||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
import { useState, type FormEvent, type KeyboardEvent } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Loader2, Plus, X } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { SearchInput } from '@/components/common/SearchInput';
|
||||
import { Textarea } from '@/components/ui/textarea';
|
||||
import { Markdown } from '@/components/common/Markdown';
|
||||
import { ListError, ListMessage, ListSpinner } from '@/components/lists/ListStates';
|
||||
import { useJmapSet } from '@/data/mutations';
|
||||
import { toast } from '@/hooks/use-toast';
|
||||
import { useHasObjectPermission } from '@/hooks/usePermissions';
|
||||
import { useResolvedView } from '@/hooks/useResolvedView';
|
||||
import { formatList, formatNumber } from '@/lib/format';
|
||||
import { errorMessage, friendlySetError } from '@/lib/jmapErrors';
|
||||
import type { PageProps } from '@/extensions/types';
|
||||
import type { JmapSetError } from '@/types/jmap';
|
||||
import { useRuleAccountId } from '../account';
|
||||
import { useCreateSenderEntries, useSenderEntries } from '../queries';
|
||||
import {
|
||||
ADDRESS_PROPERTY,
|
||||
filterSenders,
|
||||
MAX_SENDER_ENTRIES,
|
||||
planSenders,
|
||||
type SenderEntry,
|
||||
type SenderPlan,
|
||||
} from '../senders';
|
||||
|
||||
interface AddReport {
|
||||
added: string[];
|
||||
duplicates: string[];
|
||||
invalid: string[];
|
||||
overLimit: string[];
|
||||
failed: { address: string; error: JmapSetError }[];
|
||||
}
|
||||
|
||||
const SEARCH_THRESHOLD = 8;
|
||||
|
||||
function emptyReport(plan: SenderPlan): AddReport {
|
||||
return { ...plan, added: [], failed: [] };
|
||||
}
|
||||
|
||||
function ReportLines({ report }: { report: AddReport }) {
|
||||
const { t } = useTranslation();
|
||||
const lines: { key: string; text: string; tone: 'success' | 'muted' | 'destructive' }[] = [];
|
||||
if (report.added.length > 0) {
|
||||
lines.push({
|
||||
key: 'added',
|
||||
tone: 'success',
|
||||
text: t('senderLists.added', 'Added {{count}} entries.', { count: report.added.length }),
|
||||
});
|
||||
}
|
||||
if (report.duplicates.length > 0) {
|
||||
lines.push({
|
||||
key: 'duplicates',
|
||||
tone: 'muted',
|
||||
text: t('senderLists.duplicates', 'Already in the list: {{list}}.', { list: formatList(report.duplicates) }),
|
||||
});
|
||||
}
|
||||
if (report.invalid.length > 0) {
|
||||
lines.push({
|
||||
key: 'invalid',
|
||||
tone: 'destructive',
|
||||
text: t('senderLists.invalid', 'Not an email address or a domain: {{list}}.', {
|
||||
list: formatList(report.invalid),
|
||||
}),
|
||||
});
|
||||
}
|
||||
if (report.overLimit.length > 0) {
|
||||
lines.push({
|
||||
key: 'overLimit',
|
||||
tone: 'destructive',
|
||||
text: t('senderLists.overLimit', 'The list holds at most {{max}} entries; not added: {{list}}.', {
|
||||
max: formatNumber(MAX_SENDER_ENTRIES),
|
||||
list: formatList(report.overLimit),
|
||||
}),
|
||||
});
|
||||
}
|
||||
for (const { address, error } of report.failed) {
|
||||
lines.push({
|
||||
key: `failed:${address}`,
|
||||
tone: 'destructive',
|
||||
text: t('senderLists.failed', 'Could not add {{address}}: {{reason}}', {
|
||||
address,
|
||||
reason: friendlySetError(error),
|
||||
}),
|
||||
});
|
||||
}
|
||||
if (lines.length === 0) return null;
|
||||
return (
|
||||
<ul className="space-y-1 text-[13px]" role="status" data-testid="sender-list-report">
|
||||
{lines.map((line) => (
|
||||
<li
|
||||
key={line.key}
|
||||
className={
|
||||
line.tone === 'success'
|
||||
? 'text-success'
|
||||
: line.tone === 'destructive'
|
||||
? 'text-destructive'
|
||||
: 'text-muted-foreground'
|
||||
}
|
||||
>
|
||||
{line.text}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
);
|
||||
}
|
||||
|
||||
function AddEntries({
|
||||
objectName,
|
||||
accountId,
|
||||
existing,
|
||||
label,
|
||||
description,
|
||||
}: {
|
||||
objectName: string;
|
||||
accountId: string;
|
||||
existing: readonly string[];
|
||||
label: string;
|
||||
description: string | undefined;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const create = useCreateSenderEntries(objectName);
|
||||
const [draft, setDraft] = useState('');
|
||||
const [report, setReport] = useState<AddReport | null>(null);
|
||||
const inputId = `sender-add-${objectName}`;
|
||||
const descriptionId = `${inputId}-description`;
|
||||
|
||||
const submit = async () => {
|
||||
const plan = planSenders(existing, draft);
|
||||
if (plan.added.length === 0) {
|
||||
setReport(emptyReport(plan));
|
||||
setDraft(plan.invalid.join('\n'));
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const outcome = await create.mutateAsync({ addresses: plan.added, accountId });
|
||||
const failed = outcome.failed.map((entry) => entry.address);
|
||||
setReport({
|
||||
added: outcome.created,
|
||||
duplicates: [...plan.duplicates, ...outcome.duplicates],
|
||||
invalid: plan.invalid,
|
||||
overLimit: plan.overLimit,
|
||||
failed: outcome.failed,
|
||||
});
|
||||
setDraft([...plan.invalid, ...failed].join('\n'));
|
||||
} catch (err) {
|
||||
toast({
|
||||
title: t('senderLists.addFailed', 'Could not add the entries'),
|
||||
description: errorMessage(err),
|
||||
variant: 'destructive',
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
const onSubmit = (event: FormEvent) => {
|
||||
event.preventDefault();
|
||||
void submit();
|
||||
};
|
||||
|
||||
const onKeyDown = (event: KeyboardEvent<HTMLTextAreaElement>) => {
|
||||
if (event.key === 'Enter' && !event.shiftKey && !event.nativeEvent.isComposing) {
|
||||
event.preventDefault();
|
||||
void submit();
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<form className="tile space-y-3 px-5 py-4" onSubmit={onSubmit} aria-busy={create.isPending}>
|
||||
<div className="space-y-1">
|
||||
<label htmlFor={inputId} className="text-[13.5px] font-semibold">
|
||||
{label}
|
||||
</label>
|
||||
<div id={descriptionId} className="space-y-1">
|
||||
{description && (
|
||||
<Markdown source={description} className="text-[12.5px] leading-relaxed text-muted-foreground" />
|
||||
)}
|
||||
<p className="text-[12.5px] leading-relaxed text-muted-foreground">
|
||||
{t(
|
||||
'senderLists.addHint',
|
||||
'Enter one or more entries, or paste a list separated by commas, spaces or new lines. Press Enter to add them.',
|
||||
)}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex flex-col gap-2 sm:flex-row sm:items-start">
|
||||
<Textarea
|
||||
id={inputId}
|
||||
aria-describedby={descriptionId}
|
||||
value={draft}
|
||||
rows={2}
|
||||
placeholder={t('senderLists.placeholder', 'name@example.org or @example.org')}
|
||||
onChange={(event) => setDraft(event.target.value)}
|
||||
onKeyDown={onKeyDown}
|
||||
disabled={create.isPending}
|
||||
className="min-h-[44px] flex-1 resize-y"
|
||||
/>
|
||||
<Button type="submit" disabled={create.isPending || draft.trim() === ''} className="shrink-0">
|
||||
{create.isPending ? <Loader2 className="animate-spin" aria-hidden="true" /> : <Plus aria-hidden="true" />}
|
||||
{t('senderLists.add', 'Add')}
|
||||
</Button>
|
||||
</div>
|
||||
{report && <ReportLines report={report} />}
|
||||
</form>
|
||||
);
|
||||
}
|
||||
|
||||
function EntryRow({
|
||||
entry,
|
||||
canRemove,
|
||||
removing,
|
||||
onRemove,
|
||||
}: {
|
||||
entry: SenderEntry;
|
||||
canRemove: boolean;
|
||||
removing: boolean;
|
||||
onRemove: (entry: SenderEntry) => void;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const isDomain = entry.address.startsWith('@');
|
||||
return (
|
||||
<li
|
||||
className="flex items-center gap-3 border-t border-border px-4 py-2.5 first:border-t-0 sm:px-5"
|
||||
data-testid="sender-entry"
|
||||
>
|
||||
<span className="min-w-0 flex-1 break-all text-sm">{entry.address}</span>
|
||||
{isDomain && (
|
||||
<span className="shrink-0 rounded-full bg-muted px-2 py-0.5 text-[11.5px] text-muted-foreground">
|
||||
{t('senderLists.domain', 'Domain')}
|
||||
</span>
|
||||
)}
|
||||
{canRemove && (
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost-danger"
|
||||
size="icon-sm"
|
||||
disabled={removing}
|
||||
onClick={() => onRemove(entry)}
|
||||
aria-label={t('senderLists.remove', 'Remove {{address}}', { address: entry.address })}
|
||||
>
|
||||
{removing ? <Loader2 className="animate-spin" aria-hidden="true" /> : <X aria-hidden="true" />}
|
||||
</Button>
|
||||
)}
|
||||
</li>
|
||||
);
|
||||
}
|
||||
|
||||
export function SenderListPage({ viewName }: PageProps) {
|
||||
const { t } = useTranslation();
|
||||
const resolved = useResolvedView(viewName);
|
||||
const accountId = useRuleAccountId();
|
||||
const objectName = resolved?.object.objectName ?? '';
|
||||
const prefix = resolved?.object.permissionPrefix;
|
||||
const canCreate = useHasObjectPermission(prefix, 'Create');
|
||||
const canDestroy = useHasObjectPermission(prefix, 'Destroy');
|
||||
const entries = useSenderEntries(objectName, accountId);
|
||||
const remove = useJmapSet(objectName);
|
||||
const [removing, setRemoving] = useState<ReadonlySet<string>>(new Set());
|
||||
const [search, setSearch] = useState('');
|
||||
const list = resolved?.list;
|
||||
|
||||
if (!resolved || !list || !accountId) return null;
|
||||
|
||||
const fields = resolved.resolvedSchema.type === 'single' ? resolved.resolvedSchema.fields : null;
|
||||
const label = list.columns.find((column) => column.name === ADDRESS_PROPERTY)?.label ?? ADDRESS_PROPERTY;
|
||||
const description = fields?.properties[ADDRESS_PROPERTY]?.description;
|
||||
const all = entries.data ?? [];
|
||||
const shown = filterSenders(all, search);
|
||||
|
||||
const onRemove = async (entry: SenderEntry) => {
|
||||
setRemoving((prev) => new Set(prev).add(entry.id));
|
||||
try {
|
||||
const result = await remove.mutateAsync({ destroy: [entry.id], accountId });
|
||||
const error = result.notDestroyed?.[entry.id];
|
||||
if (error) {
|
||||
toast({
|
||||
title: t('senderLists.removeFailed', 'Could not remove {{address}}', { address: entry.address }),
|
||||
description: friendlySetError(error),
|
||||
variant: 'destructive',
|
||||
});
|
||||
}
|
||||
} catch (err) {
|
||||
toast({
|
||||
title: t('senderLists.removeFailed', 'Could not remove {{address}}', { address: entry.address }),
|
||||
description: errorMessage(err),
|
||||
variant: 'destructive',
|
||||
});
|
||||
} finally {
|
||||
setRemoving((prev) => {
|
||||
const next = new Set(prev);
|
||||
next.delete(entry.id);
|
||||
return next;
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-3.5">
|
||||
<div className="px-1 pb-1 pt-3">
|
||||
<h1 className="page-title">{list.title}</h1>
|
||||
{list.subtitle && <p className="mt-1 text-sm text-muted-foreground">{list.subtitle}</p>}
|
||||
</div>
|
||||
|
||||
{canCreate && entries.data && (
|
||||
<AddEntries
|
||||
key={`${objectName}:${accountId}`}
|
||||
objectName={objectName}
|
||||
accountId={accountId}
|
||||
existing={all.map((entry) => entry.address)}
|
||||
label={label}
|
||||
description={description}
|
||||
/>
|
||||
)}
|
||||
|
||||
{entries.isError && (
|
||||
<ListError
|
||||
message={errorMessage(entries.error, t('senderLists.loadFailed', 'Failed to load the list.'))}
|
||||
onRetry={() => void entries.refetch()}
|
||||
/>
|
||||
)}
|
||||
{entries.isPending && entries.fetchStatus !== 'idle' && <ListSpinner />}
|
||||
|
||||
{entries.data &&
|
||||
(all.length === 0 ? (
|
||||
<ListMessage>{t('senderLists.empty', 'No entries yet. Add an email address or a domain.')}</ListMessage>
|
||||
) : (
|
||||
<section className="tile overflow-hidden p-0" aria-labelledby={`${objectName}-entries`}>
|
||||
<div className="flex flex-wrap items-center justify-between gap-3 border-b border-border px-4 py-3 sm:px-5">
|
||||
<h2 id={`${objectName}-entries`} className="text-[13.5px] font-semibold">
|
||||
{t('senderLists.count', '{{count}} entries', { count: all.length })}
|
||||
</h2>
|
||||
{all.length > SEARCH_THRESHOLD && (
|
||||
<div className="w-full sm:w-64">
|
||||
<SearchInput
|
||||
icon
|
||||
value={search}
|
||||
onValueChange={setSearch}
|
||||
placeholder={t('senderLists.search', 'Search')}
|
||||
aria-label={t('senderLists.searchLabel', 'Search {{label}}', { label: list.title })}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
{shown.length === 0 ? (
|
||||
<p className="px-5 py-6 text-center text-sm text-muted-foreground">
|
||||
{t('senderLists.noMatch', 'No entries match “{{search}}”.', { search: search.trim() })}
|
||||
</p>
|
||||
) : (
|
||||
<ul aria-label={list.title}>
|
||||
{shown.map((entry) => (
|
||||
<EntryRow
|
||||
key={entry.id}
|
||||
entry={entry}
|
||||
canRemove={canDestroy}
|
||||
removing={removing.has(entry.id)}
|
||||
onRemove={(target) => void onRemove(target)}
|
||||
/>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</section>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
/*
|
||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
import type { JmapObject } from '@/services/jmap/client';
|
||||
|
||||
export const MAILBOX_PROPERTIES = ['id', 'name', 'parentId', 'role', 'sortOrder'];
|
||||
|
||||
export interface MailboxOption {
|
||||
id: string;
|
||||
name: string;
|
||||
role: string | null;
|
||||
depth: number;
|
||||
path: string[];
|
||||
}
|
||||
|
||||
interface MailboxNode {
|
||||
id: string;
|
||||
name: string;
|
||||
role: string | null;
|
||||
sortOrder: number;
|
||||
parentId: string | null;
|
||||
}
|
||||
|
||||
function parseMailbox(raw: JmapObject): MailboxNode | null {
|
||||
if (typeof raw.id !== 'string') return null;
|
||||
return {
|
||||
id: raw.id,
|
||||
name: typeof raw.name === 'string' ? raw.name : raw.id,
|
||||
role: typeof raw.role === 'string' && raw.role !== '' ? raw.role : null,
|
||||
sortOrder: typeof raw.sortOrder === 'number' ? raw.sortOrder : 0,
|
||||
parentId: typeof raw.parentId === 'string' && raw.parentId !== '' ? raw.parentId : null,
|
||||
};
|
||||
}
|
||||
|
||||
function compareNodes(a: MailboxNode, b: MailboxNode): number {
|
||||
return a.sortOrder - b.sortOrder || a.name.localeCompare(b.name);
|
||||
}
|
||||
|
||||
export function buildMailboxOptions(list: readonly JmapObject[]): MailboxOption[] {
|
||||
const nodes = new Map<string, MailboxNode>();
|
||||
for (const raw of list) {
|
||||
const node = parseMailbox(raw);
|
||||
if (node) nodes.set(node.id, node);
|
||||
}
|
||||
const children = new Map<string | null, MailboxNode[]>();
|
||||
for (const node of nodes.values()) {
|
||||
const parent = node.parentId !== null && nodes.has(node.parentId) ? node.parentId : null;
|
||||
const siblings = children.get(parent);
|
||||
if (siblings) siblings.push(node);
|
||||
else children.set(parent, [node]);
|
||||
}
|
||||
for (const siblings of children.values()) siblings.sort(compareNodes);
|
||||
|
||||
const options: MailboxOption[] = [];
|
||||
const visited = new Set<string>();
|
||||
const visit = (node: MailboxNode, path: string[]) => {
|
||||
if (visited.has(node.id)) return;
|
||||
visited.add(node.id);
|
||||
const nodePath = [...path, node.name];
|
||||
options.push({ id: node.id, name: node.name, role: node.role, depth: path.length, path: nodePath });
|
||||
for (const child of children.get(node.id) ?? []) visit(child, nodePath);
|
||||
};
|
||||
for (const root of children.get(null) ?? []) visit(root, []);
|
||||
const orphans = [...nodes.values()].filter((node) => !visited.has(node.id)).sort(compareNodes);
|
||||
for (const node of orphans) visit(node, []);
|
||||
return options;
|
||||
}
|
||||
|
||||
export function mailboxNameResolver(options: readonly MailboxOption[]): (id: string) => string | undefined {
|
||||
const byId = new Map(options.map((option) => [option.id, option.path.join(' / ')]));
|
||||
return (id) => byId.get(id);
|
||||
}
|
||||
@@ -0,0 +1,250 @@
|
||||
/*
|
||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
import { isRecord } from '@/lib/embeddedSchema';
|
||||
import { jmapMapToArray } from '@/lib/jmapUtils';
|
||||
import type { PermissionCheckers } from '@/lib/permissions';
|
||||
import type { JmapObject } from '@/services/jmap/client';
|
||||
|
||||
export const MAIL_RULE_OBJECT = 'x:MailRule';
|
||||
export const MAIL_RULE_CONDITION_OBJECT = 'x:MailRuleCondition';
|
||||
export const MAIL_RULE_ACTION_OBJECT = 'x:MailRuleAction';
|
||||
|
||||
const FORWARD_PERMISSIONS = ['jmapSieveScriptCreate', 'jmapSieveScriptUpdate', 'sievePutScript'] as const;
|
||||
|
||||
export interface MailRule {
|
||||
id: string;
|
||||
name: string;
|
||||
isEnabled: boolean;
|
||||
position: number;
|
||||
body: Record<string, unknown>;
|
||||
}
|
||||
|
||||
export interface CustomRuleBody {
|
||||
matchAll: boolean;
|
||||
conditions: Record<string, unknown>[];
|
||||
exceptions: Record<string, unknown>[];
|
||||
actions: Record<string, unknown>[];
|
||||
stopProcessing: boolean;
|
||||
timeZone: string | null;
|
||||
}
|
||||
|
||||
export type RuleIssue =
|
||||
'rejectNotAlone' | 'rejectNeedsAuthentication' | 'forwardingNotAllowed' | 'scheduleTooManySlots';
|
||||
|
||||
export const MAX_SCHEDULE_SLOTS = 14;
|
||||
const SCHEDULE_CONDITION = 'Schedule';
|
||||
export const REJECT_ACTION = 'Reject';
|
||||
|
||||
export function variantType(value: unknown): string | null {
|
||||
if (!isRecord(value)) return null;
|
||||
const type = value['@type'];
|
||||
return typeof type === 'string' ? type : null;
|
||||
}
|
||||
|
||||
export function setValues(value: unknown): string[] {
|
||||
if (Array.isArray(value)) return value.filter((item): item is string => typeof item === 'string');
|
||||
if (!isRecord(value)) return [];
|
||||
return Object.keys(value).filter((key) => value[key] === true);
|
||||
}
|
||||
|
||||
export function parseMailRule(raw: JmapObject): MailRule | null {
|
||||
const { id } = raw;
|
||||
if (typeof id !== 'string') return null;
|
||||
const position = raw.position;
|
||||
return {
|
||||
id,
|
||||
name: typeof raw.name === 'string' ? raw.name : '',
|
||||
isEnabled: raw.isEnabled !== false,
|
||||
position: typeof position === 'number' && Number.isFinite(position) && position >= 0 ? position : 0,
|
||||
body: raw,
|
||||
};
|
||||
}
|
||||
|
||||
export function orderMailRules(rules: readonly MailRule[]): MailRule[] {
|
||||
return [...rules].sort((a, b) => a.position - b.position);
|
||||
}
|
||||
|
||||
export function parseMailRules(list: readonly JmapObject[]): MailRule[] {
|
||||
const parsed: MailRule[] = [];
|
||||
for (const raw of list) {
|
||||
const rule = parseMailRule(raw);
|
||||
if (rule) parsed.push(rule);
|
||||
}
|
||||
return orderMailRules(parsed);
|
||||
}
|
||||
|
||||
interface Placed {
|
||||
position: number;
|
||||
index: number;
|
||||
}
|
||||
|
||||
export function reorderPositions(
|
||||
current: readonly Pick<MailRule, 'id' | 'position'>[],
|
||||
nextOrder: readonly string[],
|
||||
pinned: ReadonlySet<string> = new Set(),
|
||||
): Map<string, number> | null {
|
||||
const changes = new Map<string, number>();
|
||||
if (current.length !== nextOrder.length) return changes;
|
||||
const before = new Map<string, Placed>();
|
||||
current.forEach((rule, index) => before.set(rule.id, { position: rule.position, index }));
|
||||
const sequence: Placed[] = [];
|
||||
for (const id of nextOrder) {
|
||||
const placed = before.get(id);
|
||||
if (!placed) return changes;
|
||||
before.delete(id);
|
||||
sequence.push(placed);
|
||||
}
|
||||
if (sequence.length === 0) return changes;
|
||||
|
||||
const canFollow = (i: number, j: number): boolean => {
|
||||
const a = sequence[i];
|
||||
const b = sequence[j];
|
||||
const gap = j - i;
|
||||
if (b.position - a.position >= gap) return true;
|
||||
return gap === 1 && b.position === a.position && a.index < b.index;
|
||||
};
|
||||
|
||||
let lastPinned = -1;
|
||||
const pinnedBefore = nextOrder.map((id, index) => {
|
||||
const previousPinned = lastPinned;
|
||||
if (pinned.has(id)) lastPinned = index;
|
||||
return previousPinned;
|
||||
});
|
||||
|
||||
const kept = sequence.map((placed, j): number => (placed.position >= j && pinnedBefore[j] < 0 ? 1 : 0));
|
||||
const previous = sequence.map(() => -1);
|
||||
let last = -1;
|
||||
kept.forEach((_, j) => {
|
||||
for (let i = Math.max(0, pinnedBefore[j]); i < j; i++) {
|
||||
if (kept[i] > 0 && kept[i] + 1 > kept[j] && canFollow(i, j)) {
|
||||
kept[j] = kept[i] + 1;
|
||||
previous[j] = i;
|
||||
}
|
||||
}
|
||||
if (kept[j] > 0 && j >= lastPinned && (last < 0 || kept[j] >= kept[last])) last = j;
|
||||
});
|
||||
if (last < 0) return null;
|
||||
|
||||
const anchors: number[] = [];
|
||||
for (let k = last; k >= 0; k = previous[k]) anchors.push(k);
|
||||
anchors.reverse();
|
||||
|
||||
const positions = sequence.map((placed) => placed.position);
|
||||
const [first] = anchors;
|
||||
for (let i = 0; i < first; i++) positions[i] = sequence[first].position - (first - i);
|
||||
anchors.forEach((anchor, n) => {
|
||||
const end = n + 1 < anchors.length ? anchors[n + 1] : sequence.length;
|
||||
for (let i = anchor + 1; i < end; i++) positions[i] = sequence[anchor].position + (i - anchor);
|
||||
});
|
||||
|
||||
nextOrder.forEach((id, i) => {
|
||||
if (positions[i] !== sequence[i].position) changes.set(id, positions[i]);
|
||||
});
|
||||
return changes;
|
||||
}
|
||||
|
||||
export function parseCustomBody(body: Record<string, unknown>): CustomRuleBody {
|
||||
const list = (value: unknown) => jmapMapToArray<unknown>(value).filter(isRecord);
|
||||
const conditions = list(body.conditions);
|
||||
return {
|
||||
matchAll: conditions.length < 2 || body.matchAll !== false,
|
||||
conditions,
|
||||
exceptions: list(body.exceptions),
|
||||
actions: list(body.actions),
|
||||
stopProcessing: body.stopProcessing === true,
|
||||
timeZone: typeof body.timeZone === 'string' && body.timeZone !== '' ? body.timeZone : null,
|
||||
};
|
||||
}
|
||||
|
||||
function hasVariant(items: readonly Record<string, unknown>[], type: string): boolean {
|
||||
return items.some((item) => variantType(item) === type);
|
||||
}
|
||||
|
||||
export function hasScheduleCondition(custom: CustomRuleBody): boolean {
|
||||
return hasVariant(custom.conditions, SCHEDULE_CONDITION) || hasVariant(custom.exceptions, SCHEDULE_CONDITION);
|
||||
}
|
||||
|
||||
export function mergedScheduleOverflow(items: readonly Record<string, unknown>[]): boolean {
|
||||
let run = 0;
|
||||
for (const item of items) {
|
||||
if (variantType(item) !== SCHEDULE_CONDITION) {
|
||||
run = 0;
|
||||
continue;
|
||||
}
|
||||
run += jmapMapToArray<unknown>(item.slots).length;
|
||||
if (run > MAX_SCHEDULE_SLOTS) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
export function hasRejectAction(custom: CustomRuleBody): boolean {
|
||||
return hasVariant(custom.actions, REJECT_ACTION);
|
||||
}
|
||||
|
||||
export function isRejectAllowed(custom: CustomRuleBody): boolean {
|
||||
return custom.matchAll && hasVariant(custom.conditions, 'SenderAuthenticated');
|
||||
}
|
||||
|
||||
function redirectTargets(custom: CustomRuleBody): number {
|
||||
return custom.actions.reduce(
|
||||
(total, action) => total + (variantType(action) === 'Redirect' ? setValues(action.addresses).length : 0),
|
||||
0,
|
||||
);
|
||||
}
|
||||
|
||||
export function forwardingTargets(body: Record<string, unknown>): number {
|
||||
return redirectTargets(parseCustomBody(body));
|
||||
}
|
||||
|
||||
export function canForward(checkers: Pick<PermissionCheckers, 'hasPermission'>): boolean {
|
||||
return FORWARD_PERMISSIONS.some((permission) => checkers.hasPermission(permission));
|
||||
}
|
||||
|
||||
export function ruleIssues(
|
||||
rule: Pick<MailRule, 'isEnabled' | 'body'>,
|
||||
checkers: Pick<PermissionCheckers, 'hasPermission'>,
|
||||
): RuleIssue[] {
|
||||
const issues: RuleIssue[] = [];
|
||||
const custom = parseCustomBody(rule.body);
|
||||
if (hasRejectAction(custom)) {
|
||||
if (custom.actions.length > 1) issues.push('rejectNotAlone');
|
||||
if (!isRejectAllowed(custom)) issues.push('rejectNeedsAuthentication');
|
||||
}
|
||||
if (mergedScheduleOverflow(custom.exceptions) || (!custom.matchAll && mergedScheduleOverflow(custom.conditions))) {
|
||||
issues.push('scheduleTooManySlots');
|
||||
}
|
||||
if (rule.isEnabled && redirectTargets(custom) > 0 && !canForward(checkers)) {
|
||||
issues.push('forwardingNotAllowed');
|
||||
}
|
||||
return issues;
|
||||
}
|
||||
|
||||
export function pinnedRuleIds(
|
||||
rules: readonly Pick<MailRule, 'id' | 'isEnabled' | 'body'>[],
|
||||
checkers: Pick<PermissionCheckers, 'hasPermission'>,
|
||||
): Set<string> {
|
||||
if (canForward(checkers)) return new Set();
|
||||
return new Set(rules.filter((rule) => rule.isEnabled && forwardingTargets(rule.body) > 0).map((rule) => rule.id));
|
||||
}
|
||||
|
||||
export function positionPatches(changes: ReadonlyMap<string, number>): Record<string, JmapObject> {
|
||||
const patches: Record<string, JmapObject> = {};
|
||||
for (const [id, position] of changes) patches[id] = { position };
|
||||
return patches;
|
||||
}
|
||||
|
||||
export function nextRulePosition(rules: readonly Pick<MailRule, 'position'>[]): number {
|
||||
return rules.reduce((next, rule) => Math.max(next, rule.position + 1), 0);
|
||||
}
|
||||
|
||||
export function moveInOrder(order: readonly string[], from: number, to: number): string[] | null {
|
||||
if (from === to || from < 0 || to < 0 || from >= order.length || to >= order.length) return null;
|
||||
const next = [...order];
|
||||
const [moved] = next.splice(from, 1);
|
||||
next.splice(to, 0, moved);
|
||||
return next;
|
||||
}
|
||||
@@ -0,0 +1,128 @@
|
||||
/*
|
||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
|
||||
import { jmapKeys } from '@/data/keys';
|
||||
import { invalidateObjectType } from '@/data/mutations';
|
||||
import { errorMessage } from '@/lib/jmapErrors';
|
||||
import { jmapGet, jmapSet } from '@/services/jmap/client';
|
||||
import { useAuthStore } from '@/stores/authStore';
|
||||
import { buildMailboxOptions, MAILBOX_PROPERTIES, type MailboxOption } from './mailboxes';
|
||||
import { MAIL_RULE_OBJECT, parseMailRules } from './model';
|
||||
import {
|
||||
ADDRESS_PROPERTY,
|
||||
mergeCreateOutcomes,
|
||||
parseSenderEntries,
|
||||
senderCreateOutcome,
|
||||
senderCreates,
|
||||
type SenderCreateOutcome,
|
||||
} from './senders';
|
||||
|
||||
const MAILBOX_OBJECT = 'Mailbox';
|
||||
const MAILBOX_STALE_MS = 60_000;
|
||||
|
||||
export function mailRulesKey(accountId: string) {
|
||||
return [...jmapKeys.type(MAIL_RULE_OBJECT), 'rules', accountId] as const;
|
||||
}
|
||||
|
||||
export function mailboxOptionsKey(accountId: string) {
|
||||
return [...jmapKeys.type(MAILBOX_OBJECT), 'mailRuleOptions', accountId] as const;
|
||||
}
|
||||
|
||||
export async function fetchMailRules(accountId: string, signal?: AbortSignal) {
|
||||
const result = await jmapGet(MAIL_RULE_OBJECT, null, undefined, { accountId, signal });
|
||||
return parseMailRules(result.list ?? []);
|
||||
}
|
||||
|
||||
export function useMailRules(accountId: string | null | undefined) {
|
||||
return useQuery({
|
||||
queryKey: mailRulesKey(accountId ?? ''),
|
||||
queryFn: ({ signal }) => fetchMailRules(accountId!, signal),
|
||||
enabled: !!accountId,
|
||||
staleTime: 0,
|
||||
});
|
||||
}
|
||||
|
||||
export function canReadMailboxes(
|
||||
accountId: string | null | undefined,
|
||||
sessionAccounts: Readonly<Record<string, unknown>>,
|
||||
): accountId is string {
|
||||
return !!accountId && Object.hasOwn(sessionAccounts, accountId);
|
||||
}
|
||||
|
||||
export async function fetchMailboxOptions(accountId: string, signal?: AbortSignal): Promise<MailboxOption[]> {
|
||||
const result = await jmapGet(MAILBOX_OBJECT, null, MAILBOX_PROPERTIES, { accountId, signal });
|
||||
return buildMailboxOptions(result.list ?? []);
|
||||
}
|
||||
|
||||
export type MailboxOptionsState =
|
||||
{ status: 'loading' } | { status: 'ready'; options: MailboxOption[] } | { status: 'unavailable' };
|
||||
|
||||
export function useMailboxOptions(accountId: string | null | undefined): MailboxOptionsState {
|
||||
const sessionAccounts = useAuthStore((s) => s.accounts);
|
||||
const readable = canReadMailboxes(accountId, sessionAccounts);
|
||||
const query = useQuery({
|
||||
queryKey: mailboxOptionsKey(accountId ?? ''),
|
||||
queryFn: ({ signal }) => fetchMailboxOptions(accountId!, signal),
|
||||
enabled: readable,
|
||||
staleTime: MAILBOX_STALE_MS,
|
||||
});
|
||||
if (readable && query.data) return { status: 'ready', options: query.data };
|
||||
if (!readable || query.isError) return { status: 'unavailable' };
|
||||
return { status: 'loading' };
|
||||
}
|
||||
|
||||
export function senderEntriesKey(objectName: string, accountId: string) {
|
||||
return [...jmapKeys.type(objectName), 'entries', accountId] as const;
|
||||
}
|
||||
|
||||
export async function fetchSenderEntries(objectName: string, accountId: string, signal?: AbortSignal) {
|
||||
const result = await jmapGet(objectName, null, [ADDRESS_PROPERTY], { accountId, signal });
|
||||
return parseSenderEntries(result.list ?? []);
|
||||
}
|
||||
|
||||
export function useSenderEntries(objectName: string, accountId: string | null | undefined) {
|
||||
return useQuery({
|
||||
queryKey: senderEntriesKey(objectName, accountId ?? ''),
|
||||
queryFn: ({ signal }) => fetchSenderEntries(objectName, accountId!, signal),
|
||||
enabled: !!accountId,
|
||||
staleTime: 0,
|
||||
});
|
||||
}
|
||||
|
||||
export async function createSenderEntries(
|
||||
objectName: string,
|
||||
addresses: readonly string[],
|
||||
accountId: string,
|
||||
): Promise<SenderCreateOutcome> {
|
||||
const batchSize = Math.max(1, useAuthStore.getState().maxObjectsInSet);
|
||||
const outcomes: SenderCreateOutcome[] = [];
|
||||
for (let offset = 0; offset < addresses.length; offset += batchSize) {
|
||||
const batch = addresses.slice(offset, offset + batchSize);
|
||||
try {
|
||||
const response = await jmapSet(objectName, { create: senderCreates(batch) }, { accountId });
|
||||
outcomes.push(senderCreateOutcome(batch, response));
|
||||
} catch (err) {
|
||||
if (outcomes.length === 0) throw err;
|
||||
const error = { type: 'serverFail', description: errorMessage(err) };
|
||||
outcomes.push({
|
||||
created: [],
|
||||
duplicates: [],
|
||||
failed: addresses.slice(offset).map((address) => ({ address, error })),
|
||||
});
|
||||
break;
|
||||
}
|
||||
}
|
||||
return mergeCreateOutcomes(outcomes);
|
||||
}
|
||||
|
||||
export function useCreateSenderEntries(objectName: string) {
|
||||
const client = useQueryClient();
|
||||
return useMutation<SenderCreateOutcome, Error, { addresses: readonly string[]; accountId: string }>({
|
||||
mutationFn: ({ addresses, accountId }) => createSenderEntries(objectName, addresses, accountId),
|
||||
onSettled: () => invalidateObjectType(client, objectName),
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
/*
|
||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
import type { JmapObject } from '@/services/jmap/client';
|
||||
import type { JmapSetError, JmapSetResponse } from '@/types/jmap';
|
||||
|
||||
export const BLOCKED_SENDER_OBJECT = 'x:BlockedSender';
|
||||
export const SAFE_SENDER_OBJECT = 'x:SafeSender';
|
||||
export const ADDRESS_PROPERTY = 'address';
|
||||
export const MAX_SENDER_ENTRIES = 1024;
|
||||
export const MAX_ENTRY_LENGTH = 255;
|
||||
|
||||
const SEPARATORS = /[\s,;]+/;
|
||||
const WRAPPERS = /^[<("']+|[>)"'.]+$/g;
|
||||
const MAILTO = /^mailto:/i;
|
||||
const LABEL = /^[\p{L}\p{N}](?:[\p{L}\p{N}-]*[\p{L}\p{N}])?$/u;
|
||||
const LOCAL_PART = /^[^\s\p{Cc}@<>()[\]\\,;:"]+$/u;
|
||||
|
||||
export interface SenderEntry {
|
||||
id: string;
|
||||
address: string;
|
||||
}
|
||||
|
||||
export interface SenderPlan {
|
||||
added: string[];
|
||||
duplicates: string[];
|
||||
invalid: string[];
|
||||
overLimit: string[];
|
||||
}
|
||||
|
||||
export interface SenderCreateOutcome {
|
||||
created: string[];
|
||||
duplicates: string[];
|
||||
failed: { address: string; error: JmapSetError }[];
|
||||
}
|
||||
|
||||
function isDomain(value: string): boolean {
|
||||
const labels = value.split('.');
|
||||
return labels.length >= 2 && labels.every((label) => LABEL.test(label));
|
||||
}
|
||||
|
||||
export function normalizeSender(raw: string): string | null {
|
||||
const value = raw.trim().replace(MAILTO, '').replace(WRAPPERS, '').toLowerCase();
|
||||
if (value === '' || value.length > MAX_ENTRY_LENGTH) return null;
|
||||
const at = value.lastIndexOf('@');
|
||||
if (at < 0) return isDomain(value) ? `@${value}` : null;
|
||||
const local = value.slice(0, at);
|
||||
const domain = value.slice(at + 1);
|
||||
if (!isDomain(domain)) return null;
|
||||
if (local === '') return value;
|
||||
return LOCAL_PART.test(local) ? value : null;
|
||||
}
|
||||
|
||||
export function splitSenders(text: string): string[] {
|
||||
return text.split(SEPARATORS).filter((part) => part !== '');
|
||||
}
|
||||
|
||||
export function planSenders(existing: readonly string[], text: string, limit = MAX_SENDER_ENTRIES): SenderPlan {
|
||||
const plan: SenderPlan = { added: [], duplicates: [], invalid: [], overLimit: [] };
|
||||
const seen = new Set(existing);
|
||||
for (const raw of splitSenders(text)) {
|
||||
const value = normalizeSender(raw);
|
||||
if (value === null) plan.invalid.push(raw);
|
||||
else if (seen.has(value)) plan.duplicates.push(value);
|
||||
else if (existing.length + plan.added.length >= limit) plan.overLimit.push(value);
|
||||
else {
|
||||
seen.add(value);
|
||||
plan.added.push(value);
|
||||
}
|
||||
}
|
||||
return plan;
|
||||
}
|
||||
|
||||
export function parseSenderEntries(list: readonly JmapObject[]): SenderEntry[] {
|
||||
const entries: SenderEntry[] = [];
|
||||
for (const raw of list) {
|
||||
const address = raw[ADDRESS_PROPERTY];
|
||||
if (typeof raw.id === 'string' && typeof address === 'string') entries.push({ id: raw.id, address });
|
||||
}
|
||||
return entries.sort((a, b) => a.address.localeCompare(b.address));
|
||||
}
|
||||
|
||||
export function filterSenders(entries: readonly SenderEntry[], search: string): readonly SenderEntry[] {
|
||||
const needle = search.trim().toLowerCase();
|
||||
return needle === '' ? entries : entries.filter((entry) => entry.address.includes(needle));
|
||||
}
|
||||
|
||||
export function senderCreates(addresses: readonly string[]): Record<string, JmapObject> {
|
||||
const create: Record<string, JmapObject> = {};
|
||||
addresses.forEach((address, index) => {
|
||||
create[`s${index}`] = { [ADDRESS_PROPERTY]: address };
|
||||
});
|
||||
return create;
|
||||
}
|
||||
|
||||
export function senderCreateOutcome(addresses: readonly string[], response: JmapSetResponse): SenderCreateOutcome {
|
||||
const outcome: SenderCreateOutcome = { created: [], duplicates: [], failed: [] };
|
||||
addresses.forEach((address, index) => {
|
||||
const key = `s${index}`;
|
||||
const error = response.notCreated?.[key];
|
||||
if (response.created?.[key]) outcome.created.push(address);
|
||||
else if (error?.type === 'alreadyExists') outcome.duplicates.push(address);
|
||||
else outcome.failed.push({ address, error: error ?? { type: 'serverFail' } });
|
||||
});
|
||||
return outcome;
|
||||
}
|
||||
|
||||
export function mergeCreateOutcomes(outcomes: readonly SenderCreateOutcome[]): SenderCreateOutcome {
|
||||
const merged: SenderCreateOutcome = { created: [], duplicates: [], failed: [] };
|
||||
for (const outcome of outcomes) {
|
||||
merged.created.push(...outcome.created);
|
||||
merged.duplicates.push(...outcome.duplicates);
|
||||
merged.failed.push(...outcome.failed);
|
||||
}
|
||||
return merged;
|
||||
}
|
||||
@@ -0,0 +1,240 @@
|
||||
/*
|
||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
import type { TFunction } from 'i18next';
|
||||
import { isRecord, variantLabel } from '@/lib/embeddedSchema';
|
||||
import {
|
||||
formatDateTime,
|
||||
formatIntervalEnd,
|
||||
formatList,
|
||||
formatLocalTime,
|
||||
formatPercent,
|
||||
formatSize,
|
||||
} from '@/lib/format';
|
||||
import { MINUTES_PER_DAY, localTimeFromMinutes, parseLocalTime } from '@/lib/localDateTime';
|
||||
import { jmapMapToArray } from '@/lib/jmapUtils';
|
||||
import { getEnumVariant } from '@/lib/schemaResolver';
|
||||
import type { Schema } from '@/types/schema';
|
||||
import {
|
||||
MAIL_RULE_ACTION_OBJECT,
|
||||
MAIL_RULE_CONDITION_OBJECT,
|
||||
MAX_SCHEDULE_SLOTS,
|
||||
parseCustomBody,
|
||||
setValues,
|
||||
variantType,
|
||||
type RuleIssue,
|
||||
} from './model';
|
||||
|
||||
const KILOBYTE = 1024;
|
||||
|
||||
export interface SummaryContext {
|
||||
t: TFunction;
|
||||
schema: Schema;
|
||||
mailboxName?: (id: string) => string | undefined;
|
||||
}
|
||||
|
||||
export interface RuleSummary {
|
||||
conditions: string[];
|
||||
matchAll: boolean;
|
||||
exceptions: string[];
|
||||
actions: string[];
|
||||
stopProcessing: boolean;
|
||||
}
|
||||
|
||||
function enumLabel(schema: Schema, enumName: string, value: unknown): string {
|
||||
if (typeof value !== 'string') return '';
|
||||
return getEnumVariant(schema, enumName, value)?.label ?? value;
|
||||
}
|
||||
|
||||
function quoted(ctx: SummaryContext, value: string): string {
|
||||
return ctx.t('mailRules.summary.quoted', '“{{value}}”', { value });
|
||||
}
|
||||
|
||||
function quotedValues(ctx: SummaryContext, value: unknown): string {
|
||||
return formatList(
|
||||
setValues(value).map((item) => quoted(ctx, item)),
|
||||
'disjunction',
|
||||
);
|
||||
}
|
||||
|
||||
function detailed(ctx: SummaryContext, label: string, detail: string): string {
|
||||
if (detail === '') return label;
|
||||
return ctx.t('mailRules.summary.detail', '{{label}}: {{detail}}', { label, detail });
|
||||
}
|
||||
|
||||
function operatorTest(ctx: SummaryContext, enumName: string, item: Record<string, unknown>): string {
|
||||
return ctx.t('mailRules.summary.test', '{{operator}} {{values}}', {
|
||||
operator: enumLabel(ctx.schema, enumName, item.operator),
|
||||
values: quotedValues(ctx, item.values),
|
||||
});
|
||||
}
|
||||
|
||||
function slotStart(value: unknown): string {
|
||||
return typeof value === 'string' ? formatLocalTime(value) : '';
|
||||
}
|
||||
|
||||
function slotEnd(value: unknown): string {
|
||||
if (typeof value !== 'string') return '';
|
||||
return formatIntervalEnd(parseLocalTime(value) === 0 ? localTimeFromMinutes(MINUTES_PER_DAY) : value);
|
||||
}
|
||||
|
||||
function scheduleSlots(ctx: SummaryContext, value: unknown): string {
|
||||
const slots = jmapMapToArray<unknown>(value)
|
||||
.filter(isRecord)
|
||||
.map((slot) =>
|
||||
ctx.t('mailRules.summary.slot', '{{days}} {{start}}–{{end}}', {
|
||||
days: formatList(setValues(slot.days).map((day) => enumLabel(ctx.schema, 'Weekday', day))),
|
||||
start: slotStart(slot.start),
|
||||
end: slotEnd(slot.end),
|
||||
}),
|
||||
);
|
||||
return slots.join('; ');
|
||||
}
|
||||
|
||||
export function conditionPhrase(ctx: SummaryContext, condition: Record<string, unknown>): string {
|
||||
const type = variantType(condition) ?? '';
|
||||
const label = variantLabel(ctx.schema, MAIL_RULE_CONDITION_OBJECT, type) ?? type;
|
||||
switch (type) {
|
||||
case 'From':
|
||||
case 'To':
|
||||
case 'Cc':
|
||||
case 'ToOrCc':
|
||||
case 'RecipientAddress':
|
||||
return detailed(ctx, label, operatorTest(ctx, 'MailRuleAddressOperator', condition));
|
||||
case 'Subject':
|
||||
case 'Body':
|
||||
case 'AttachmentName':
|
||||
case 'AttachmentType':
|
||||
case 'RecipientDetail':
|
||||
case 'SubjectOrBody':
|
||||
return detailed(ctx, label, operatorTest(ctx, 'MailRuleTextOperator', condition));
|
||||
case 'Header':
|
||||
return detailed(
|
||||
ctx,
|
||||
typeof condition.header === 'string' ? condition.header : label,
|
||||
operatorTest(ctx, 'MailRuleTextOperator', condition),
|
||||
);
|
||||
case 'HeaderExists':
|
||||
return detailed(ctx, label, typeof condition.header === 'string' ? condition.header : '');
|
||||
case 'SentToMe':
|
||||
return detailed(ctx, label, enumLabel(ctx.schema, 'MailRuleSentToMePlacement', condition.placement));
|
||||
case 'SizeOver':
|
||||
case 'SizeUnder':
|
||||
return detailed(
|
||||
ctx,
|
||||
label,
|
||||
typeof condition.kilobytes === 'number' ? formatSize(condition.kilobytes * KILOBYTE) : '',
|
||||
);
|
||||
case 'Importance':
|
||||
return detailed(ctx, label, enumLabel(ctx.schema, 'MailRuleImportanceLevel', condition.level));
|
||||
case 'Sensitivity':
|
||||
return detailed(ctx, label, enumLabel(ctx.schema, 'MailRuleSensitivityLevel', condition.level));
|
||||
case 'MessageType':
|
||||
return detailed(ctx, label, enumLabel(ctx.schema, 'MailRuleMessageKind', condition.kind));
|
||||
case 'SpamScore':
|
||||
return detailed(ctx, label, typeof condition.percent === 'number' ? formatPercent(condition.percent, 0) : '');
|
||||
case 'ReceivedAfter':
|
||||
case 'ReceivedBefore':
|
||||
return detailed(ctx, label, typeof condition.date === 'string' ? formatDateTime(condition.date) : '');
|
||||
case 'Schedule':
|
||||
return detailed(ctx, label, scheduleSlots(ctx, condition.slots));
|
||||
default:
|
||||
return label;
|
||||
}
|
||||
}
|
||||
|
||||
function mailboxPhrase(ctx: SummaryContext, value: unknown): string {
|
||||
if (typeof value !== 'string' || value === '') return '';
|
||||
return quoted(ctx, ctx.mailboxName?.(value) ?? value);
|
||||
}
|
||||
|
||||
export function actionPhrase(ctx: SummaryContext, action: Record<string, unknown>): string {
|
||||
const type = variantType(action) ?? '';
|
||||
const label = variantLabel(ctx.schema, MAIL_RULE_ACTION_OBJECT, type) ?? type;
|
||||
switch (type) {
|
||||
case 'MoveTo':
|
||||
case 'CopyTo':
|
||||
return detailed(ctx, label, mailboxPhrase(ctx, action.mailboxId));
|
||||
case 'AddKeywords':
|
||||
return detailed(ctx, label, quotedValues(ctx, action.keywords));
|
||||
case 'Redirect': {
|
||||
const addresses = formatList(setValues(action.addresses));
|
||||
const detail =
|
||||
action.keepCopy === false
|
||||
? ctx.t('mailRules.summary.withoutCopy', '{{addresses}} without keeping a copy', { addresses })
|
||||
: addresses;
|
||||
return detailed(ctx, label, detail);
|
||||
}
|
||||
case 'SetImportance':
|
||||
return detailed(ctx, label, enumLabel(ctx.schema, 'MailRuleImportanceLevel', action.level));
|
||||
case 'Reply':
|
||||
return detailed(
|
||||
ctx,
|
||||
label,
|
||||
typeof action.subject === 'string' && action.subject ? quoted(ctx, action.subject) : '',
|
||||
);
|
||||
case 'Reject':
|
||||
return detailed(ctx, label, typeof action.reason === 'string' && action.reason ? quoted(ctx, action.reason) : '');
|
||||
default:
|
||||
return label;
|
||||
}
|
||||
}
|
||||
|
||||
export function summarizeCustomRule(ctx: SummaryContext, body: Record<string, unknown>): RuleSummary {
|
||||
const custom = parseCustomBody(body);
|
||||
return {
|
||||
conditions: custom.conditions.map((condition) => conditionPhrase(ctx, condition)),
|
||||
matchAll: custom.matchAll,
|
||||
exceptions: custom.exceptions.map((condition) => conditionPhrase(ctx, condition)),
|
||||
actions: custom.actions.map((action) => actionPhrase(ctx, action)),
|
||||
stopProcessing: custom.stopProcessing,
|
||||
};
|
||||
}
|
||||
|
||||
export function ruleSentence(ctx: SummaryContext, summary: RuleSummary): string {
|
||||
const { t } = ctx;
|
||||
let when =
|
||||
summary.conditions.length === 0
|
||||
? t('mailRules.summary.always', 'For every message')
|
||||
: t('mailRules.summary.if', 'If {{conditions}}', {
|
||||
conditions: formatList(summary.conditions, summary.matchAll ? 'conjunction' : 'disjunction'),
|
||||
});
|
||||
if (summary.exceptions.length > 0) {
|
||||
when = t('mailRules.summary.except', '{{when}}, except if {{exceptions}}', {
|
||||
when,
|
||||
exceptions: formatList(summary.exceptions, 'disjunction'),
|
||||
});
|
||||
}
|
||||
const actions =
|
||||
summary.actions.length === 0 ? t('mailRules.summary.noActions', 'do nothing') : formatList(summary.actions);
|
||||
const then = summary.stopProcessing
|
||||
? t('mailRules.summary.thenStop', 'then {{actions}} and stop processing more rules', { actions })
|
||||
: t('mailRules.summary.then', 'then {{actions}}', { actions });
|
||||
return t('mailRules.summary.sentence', '{{when}}, {{then}}.', { when, then });
|
||||
}
|
||||
|
||||
export function ruleIssueMessage(t: TFunction, issue: RuleIssue): string {
|
||||
switch (issue) {
|
||||
case 'rejectNotAlone':
|
||||
return t('mailRules.issue.rejectNotAlone', 'A rule that rejects mail cannot have other actions.');
|
||||
case 'rejectNeedsAuthentication':
|
||||
return t(
|
||||
'mailRules.issue.rejectNeedsAuthentication',
|
||||
'A rule that rejects mail must match all conditions and require an authenticated sender.',
|
||||
);
|
||||
case 'forwardingNotAllowed':
|
||||
return t(
|
||||
'mailRules.issue.forwardingNotAllowed',
|
||||
'Your account is not allowed to forward mail, so this rule cannot be saved while it is enabled.',
|
||||
);
|
||||
case 'scheduleTooManySlots':
|
||||
return t(
|
||||
'mailRules.issue.scheduleTooManySlots',
|
||||
'Adjacent schedule conditions are combined into one, which can have at most {{max}} time slots.',
|
||||
{ max: MAX_SCHEDULE_SLOTS },
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -12,17 +12,13 @@ import { Button } from '@/components/ui/button';
|
||||
import { Card, CardContent } from '@/components/ui/card';
|
||||
import { useResolvedView } from '@/hooks/useResolvedView';
|
||||
import { useJmapObject } from '@/data/objects';
|
||||
import type { PageProps } from '@/extensions/types';
|
||||
import { errorMessage } from '@/lib/jmapErrors';
|
||||
import { normalizeTraceEvents } from '../normalize';
|
||||
import { TraceTimeline } from './TraceTimeline';
|
||||
import { TraceSummaryCards } from './TraceSummaryCards';
|
||||
|
||||
interface TraceDetailViewProps {
|
||||
viewName: string;
|
||||
objectId: string;
|
||||
}
|
||||
|
||||
export function TraceDetailView({ viewName, objectId }: TraceDetailViewProps) {
|
||||
export function TraceDetailView({ viewName, objectId }: PageProps) {
|
||||
const { t } = useTranslation();
|
||||
const navigate = useNavigate();
|
||||
const resolved = useResolvedView(viewName);
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
/*
|
||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { DynamicForm } from '@/components/forms/DynamicForm';
|
||||
import type { FieldOverrides } from '@/components/forms/useDynamicForm';
|
||||
import type { PageProps } from '@/extensions/types';
|
||||
import { formatNumber } from '@/lib/format';
|
||||
import { validateVacation } from './model';
|
||||
import { PeriodRow } from './components/PeriodRow';
|
||||
import { VacationPreview } from './components/VacationPreview';
|
||||
|
||||
export function VacationResponsePage({ viewName, objectId }: PageProps) {
|
||||
const { t } = useTranslation();
|
||||
const fieldOverrides: FieldOverrides = {
|
||||
hidden: ['toDate'],
|
||||
render: { fromDate: PeriodRow },
|
||||
validate: (data) =>
|
||||
validateVacation(data, {
|
||||
tooLong: (limit) =>
|
||||
t('vacation.tooLong', 'Too long: the server accepts up to {{limit}} bytes.', {
|
||||
limit: formatNumber(limit),
|
||||
}),
|
||||
endBeforeStart: t('vacation.endBeforeStart', 'The end must be after the start.'),
|
||||
}),
|
||||
};
|
||||
return (
|
||||
<DynamicForm
|
||||
viewName={viewName}
|
||||
objectId={objectId}
|
||||
fieldOverrides={fieldOverrides}
|
||||
afterSections={VacationPreview}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,206 @@
|
||||
/*
|
||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
import { Suspense, useId, useState, useSyncExternalStore } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { ArrowRight, CalendarRange, X } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
|
||||
import { Calendar, CalendarFallback } from '@/components/forms/widgets/DateTimeWidget';
|
||||
import { LocalTimeInput } from '@/components/forms/widgets/LocalTimeInput';
|
||||
import { formatDateTime } from '@/lib/format';
|
||||
import { localTimeFromMinutes, parseLocalTime } from '@/lib/localDateTime';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { atLocalTime, localMinutes, pickRangeDay, type DateRange, type RangeEdge } from '../model';
|
||||
import type { ControlProps } from '@/components/forms/widgets/types';
|
||||
|
||||
const TWO_MONTHS_QUERY = '(min-width: 48rem)';
|
||||
|
||||
function subscribeTwoMonths(onChange: () => void): () => void {
|
||||
const query = window.matchMedia(TWO_MONTHS_QUERY);
|
||||
query.addEventListener('change', onChange);
|
||||
return () => query.removeEventListener('change', onChange);
|
||||
}
|
||||
|
||||
function showsTwoMonths(): boolean {
|
||||
return window.matchMedia(TWO_MONTHS_QUERY).matches;
|
||||
}
|
||||
|
||||
function hasMoreBelow(scroller: HTMLElement): boolean {
|
||||
return scroller.scrollTop + scroller.clientHeight < scroller.scrollHeight - 1;
|
||||
}
|
||||
|
||||
interface DateRangePickerProps {
|
||||
value: DateRange;
|
||||
onChange: (value: DateRange) => void;
|
||||
readOnly?: boolean;
|
||||
control?: ControlProps;
|
||||
}
|
||||
|
||||
export function DateRangePicker({ value, onChange, readOnly = false, control }: DateRangePickerProps) {
|
||||
const { t } = useTranslation();
|
||||
const [open, setOpen] = useState(false);
|
||||
const [edge, setEdge] = useState<RangeEdge>('start');
|
||||
const [moreBelow, setMoreBelow] = useState(false);
|
||||
const twoMonths = useSyncExternalStore(subscribeTwoMonths, showsTwoMonths, () => false);
|
||||
const idPrefix = useId();
|
||||
const { from, to } = value;
|
||||
|
||||
const startText = from ? formatDateTime(from) : t('vacation.startsNow', 'Starts immediately');
|
||||
const endText = to ? formatDateTime(to) : t('vacation.noEnd', 'No end date');
|
||||
const edges: readonly { edge: RangeEdge; label: string; text: string; date: Date | null; clearLabel: string }[] = [
|
||||
{
|
||||
edge: 'start',
|
||||
label: t('vacation.start', 'Start'),
|
||||
text: startText,
|
||||
date: from,
|
||||
clearLabel: t('vacation.startNow', 'Start immediately'),
|
||||
},
|
||||
{
|
||||
edge: 'end',
|
||||
label: t('vacation.end', 'End'),
|
||||
text: endText,
|
||||
date: to,
|
||||
clearLabel: t('vacation.removeEnd', 'No end date'),
|
||||
},
|
||||
];
|
||||
|
||||
const setEdgeDate = (target: RangeEdge, date: Date | null) =>
|
||||
onChange(target === 'start' ? { from: date, to } : { from, to: date });
|
||||
|
||||
const trackOverflow = (scroller: HTMLDivElement | null) => {
|
||||
const content = scroller?.firstElementChild;
|
||||
if (!scroller || !content) return;
|
||||
const observer = new ResizeObserver(() => setMoreBelow(hasMoreBelow(scroller)));
|
||||
observer.observe(scroller);
|
||||
observer.observe(content);
|
||||
return () => observer.disconnect();
|
||||
};
|
||||
|
||||
const openWith = (next: boolean) => {
|
||||
if (next) setEdge(from || !to ? 'start' : 'end');
|
||||
setOpen(next);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="flex items-center gap-2">
|
||||
<Popover open={open} onOpenChange={openWith}>
|
||||
<PopoverTrigger asChild>
|
||||
<Button
|
||||
{...control}
|
||||
type="button"
|
||||
variant="field"
|
||||
disabled={readOnly}
|
||||
className="h-auto min-h-9 flex-1 flex-wrap justify-start gap-x-2 gap-y-0.5 px-3 py-1.5 text-left"
|
||||
>
|
||||
<CalendarRange className="text-dim" aria-hidden="true" />
|
||||
<span className={cn(!from && 'text-dim')}>{startText}</span>
|
||||
<ArrowRight className="size-3.5 text-dim" aria-hidden="true" />
|
||||
<span className="sr-only">{` ${t('vacation.until', 'until')} `}</span>
|
||||
<span className={cn(!to && 'text-dim')}>{endText}</span>
|
||||
</Button>
|
||||
</PopoverTrigger>
|
||||
<PopoverContent
|
||||
ref={trackOverflow}
|
||||
onScroll={(event) => setMoreBelow(hasMoreBelow(event.currentTarget))}
|
||||
className="max-h-(--radix-popover-content-available-height) w-auto max-w-[calc(100vw-2rem)] overflow-y-auto p-0"
|
||||
align="start"
|
||||
collisionPadding={16}
|
||||
>
|
||||
<div>
|
||||
<div
|
||||
role="group"
|
||||
aria-label={t('vacation.editingEdge', 'Date to set')}
|
||||
className="grid grid-cols-2 gap-1 border-b border-border bg-muted/60 p-2"
|
||||
>
|
||||
{edges.map((item) => (
|
||||
<button
|
||||
key={item.edge}
|
||||
type="button"
|
||||
aria-pressed={edge === item.edge}
|
||||
onClick={() => setEdge(item.edge)}
|
||||
className={cn(
|
||||
'min-w-0 rounded-[10px] px-3 py-1.5 text-left transition-colors hover:bg-card',
|
||||
edge === item.edge && 'bg-card ring-1 ring-border',
|
||||
)}
|
||||
>
|
||||
<span className="eyebrow block">{item.label}</span>
|
||||
<span className={cn('block truncate text-[13px] font-medium', !item.date && 'text-dim')}>
|
||||
{item.text}
|
||||
</span>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
<Suspense fallback={<CalendarFallback />}>
|
||||
<Calendar
|
||||
className="mx-auto"
|
||||
mode="range"
|
||||
numberOfMonths={twoMonths ? 2 : 1}
|
||||
selected={{ from: from ?? undefined, to: to ?? undefined }}
|
||||
defaultMonth={(edge === 'start' ? from : to) ?? from ?? to ?? undefined}
|
||||
autoFocus
|
||||
onSelect={(_range, day) => {
|
||||
onChange(pickRangeDay(value, day, edge));
|
||||
if (edge === 'start') setEdge('end');
|
||||
}}
|
||||
/>
|
||||
</Suspense>
|
||||
<div className="grid gap-3 border-t border-border bg-muted/60 p-3 sm:grid-cols-2">
|
||||
{edges.map((item) => {
|
||||
const labelId = `${idPrefix}-${item.edge}-time`;
|
||||
return (
|
||||
<div key={item.edge} className="space-y-1.5">
|
||||
<span id={labelId} className="eyebrow block">
|
||||
{item.edge === 'start'
|
||||
? t('vacation.startTime', 'Start time')
|
||||
: t('vacation.endTime', 'End time')}
|
||||
</span>
|
||||
<div className="flex items-center gap-1.5">
|
||||
<LocalTimeInput
|
||||
aria-labelledby={labelId}
|
||||
value={item.date ? localTimeFromMinutes(localMinutes(item.date)) : null}
|
||||
disabled={!item.date}
|
||||
onChange={(time) => {
|
||||
const minutes = parseLocalTime(time);
|
||||
if (item.date && minutes !== null) {
|
||||
setEdgeDate(item.edge, atLocalTime(item.date, minutes, item.edge));
|
||||
}
|
||||
}}
|
||||
/>
|
||||
{item.date && (
|
||||
<Button type="button" variant="ghost" size="sm" onClick={() => setEdgeDate(item.edge, null)}>
|
||||
{item.clearLabel}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
{moreBelow && (
|
||||
<div
|
||||
aria-hidden="true"
|
||||
className="pointer-events-none sticky bottom-0 -mt-10 h-10 bg-gradient-to-t from-popover to-transparent"
|
||||
/>
|
||||
)}
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
{(from || to) && !readOnly && (
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="h-9 w-9 shrink-0"
|
||||
onClick={() => onChange({ from: null, to: null })}
|
||||
aria-label={t('vacation.clearPeriod', 'Clear period')}
|
||||
>
|
||||
<X aria-hidden="true" />
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
/*
|
||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { FieldError, FieldLabel } from '@/components/forms/FieldRow';
|
||||
import { fieldIds, useFormContext } from '@/components/forms/formContext';
|
||||
import type { FieldRenderProps } from '@/components/forms/useDynamicForm';
|
||||
import { rangeOf, utcDateValue } from '../model';
|
||||
import { DateRangePicker } from './DateRangePicker';
|
||||
import { VacationStatusLine } from './VacationStatusLine';
|
||||
|
||||
export function PeriodRow({ formField, data, errors, readOnly, onFieldChange }: FieldRenderProps) {
|
||||
const { t } = useTranslation();
|
||||
const ctx = useFormContext();
|
||||
const ids = fieldIds(ctx.idPrefix, [formField.name]);
|
||||
const error = errors.fromDate ?? errors.toDate;
|
||||
const describedBy = [ids.descriptionId, error ? ids.errorId : null].filter(Boolean).join(' ');
|
||||
|
||||
return (
|
||||
<div data-slot="field-row" className="field-grid py-4">
|
||||
<div className="min-w-0 space-y-1 @xl:pt-2">
|
||||
<FieldLabel
|
||||
id={ids.labelId}
|
||||
htmlFor={ids.inputId}
|
||||
label={t('vacation.period', 'Period')}
|
||||
marker={null}
|
||||
locked={false}
|
||||
/>
|
||||
<p id={ids.descriptionId} className="text-[12.5px] leading-relaxed text-muted-foreground">
|
||||
{t(
|
||||
'vacation.periodHelp',
|
||||
'Replies are sent only within this period. Leave the start open to begin now, or the end open to continue until you turn replies off.',
|
||||
)}
|
||||
</p>
|
||||
</div>
|
||||
<div className="min-w-0 space-y-2">
|
||||
<DateRangePicker
|
||||
value={rangeOf(data)}
|
||||
readOnly={readOnly}
|
||||
onChange={({ from, to }) => {
|
||||
onFieldChange('fromDate', utcDateValue(from));
|
||||
onFieldChange('toDate', utcDateValue(to));
|
||||
}}
|
||||
control={{
|
||||
id: ids.inputId,
|
||||
'aria-labelledby': `${ids.labelId} ${ids.inputId}`,
|
||||
'aria-describedby': describedBy,
|
||||
'aria-invalid': error ? true : undefined,
|
||||
}}
|
||||
/>
|
||||
<FieldError id={ids.errorId} error={error} />
|
||||
<VacationStatusLine data={data} />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
/*
|
||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
|
||||
import { FormSectionCard } from '@/components/forms/FormSections';
|
||||
import { htmlToText, previewDocument, vacationPreview } from '../model';
|
||||
import type { FieldValues } from '@/components/forms/formLogic';
|
||||
|
||||
function TextBody({ text, note }: { text: string; note?: string }) {
|
||||
return (
|
||||
<div className="space-y-2">
|
||||
{note && <p className="text-xs text-muted-foreground">{note}</p>}
|
||||
<p className="whitespace-pre-wrap break-words text-sm leading-relaxed">{text}</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function VacationPreview({ data }: { data: FieldValues }) {
|
||||
const { t } = useTranslation();
|
||||
const preview = vacationPreview(data);
|
||||
const derivedNote = t(
|
||||
'vacation.textFromHtml',
|
||||
'Generated by the server from the HTML body; line breaks may differ slightly.',
|
||||
);
|
||||
|
||||
return (
|
||||
<FormSectionCard title={t('vacation.preview', 'Preview')}>
|
||||
<div className="space-y-4 py-4">
|
||||
<div className="space-y-1">
|
||||
<span className="eyebrow block">{t('vacation.subject', 'Subject')}</span>
|
||||
{preview.subject ? (
|
||||
<p className="break-words text-sm font-semibold">{preview.subject}</p>
|
||||
) : (
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{t('vacation.defaultSubject', 'Chosen by the server, usually "Auto:" followed by the original subject.')}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
<div className="space-y-1.5">
|
||||
<span className="eyebrow block">{t('vacation.message', 'Message')}</span>
|
||||
{preview.html === null ? (
|
||||
<TextBody
|
||||
text={preview.text ?? ''}
|
||||
note={
|
||||
data.textBody ? undefined : t('vacation.defaultText', 'No message set: the server sends this text.')
|
||||
}
|
||||
/>
|
||||
) : (
|
||||
<Tabs defaultValue="html">
|
||||
<TabsList>
|
||||
<TabsTrigger value="html">{t('vacation.htmlTab', 'HTML')}</TabsTrigger>
|
||||
<TabsTrigger value="text">{t('vacation.textTab', 'Plain text')}</TabsTrigger>
|
||||
</TabsList>
|
||||
<TabsContent value="html" className="pt-2">
|
||||
<iframe
|
||||
title={t('vacation.htmlPreview', 'HTML reply preview')}
|
||||
sandbox=""
|
||||
srcDoc={previewDocument(preview.html)}
|
||||
className="h-64 w-full rounded-xl border-0 bg-white"
|
||||
/>
|
||||
</TabsContent>
|
||||
<TabsContent value="text" className="pt-2">
|
||||
{preview.textFromHtml ? (
|
||||
<TextBody text={htmlToText(preview.html)} note={derivedNote} />
|
||||
) : (
|
||||
<TextBody text={preview.text ?? ''} />
|
||||
)}
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
)}
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{t('vacation.spamNote', 'Replies are never sent to messages classified as spam.')}
|
||||
</p>
|
||||
</div>
|
||||
</FormSectionCard>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
/*
|
||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { useFormContext } from '@/components/forms/formContext';
|
||||
import { formatDateTime } from '@/lib/format';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { hasUnsavedStatus, nextStatusChange, vacationStatus, type VacationStatus } from '../model';
|
||||
import type { FieldValues } from '@/components/forms/formLogic';
|
||||
|
||||
const MAX_TIMER_DELAY_MS = 2 ** 31 - 1;
|
||||
|
||||
type Tone = 'muted' | 'success' | 'info' | 'warning';
|
||||
|
||||
const TONE_CLASSES: Record<Tone, string> = {
|
||||
muted: 'bg-muted text-muted-foreground',
|
||||
success: 'bg-success-soft text-success',
|
||||
info: 'bg-info-soft text-info',
|
||||
warning: 'bg-warning-soft text-warning',
|
||||
};
|
||||
|
||||
const DOT_CLASSES: Record<Tone, string> = {
|
||||
muted: 'bg-dim',
|
||||
success: 'bg-success',
|
||||
info: 'bg-info',
|
||||
warning: 'bg-warning',
|
||||
};
|
||||
|
||||
function useStatusText(status: VacationStatus): { tone: Tone; text: string } {
|
||||
const { t } = useTranslation();
|
||||
switch (status.kind) {
|
||||
case 'off':
|
||||
return { tone: 'muted', text: t('vacation.statusOff', 'Off: no automatic replies are sent.') };
|
||||
case 'invalidRange':
|
||||
return { tone: 'warning', text: t('vacation.statusInvalid', 'The period ends before it starts.') };
|
||||
case 'ended':
|
||||
return {
|
||||
tone: 'warning',
|
||||
text: t('vacation.statusEnded', 'The period ended on {{date}}: no replies are sent.', {
|
||||
date: formatDateTime(status.at),
|
||||
}),
|
||||
};
|
||||
case 'scheduled':
|
||||
return {
|
||||
tone: 'info',
|
||||
text: status.until
|
||||
? t('vacation.statusScheduledUntil', 'Scheduled: replies from {{from}} until {{until}}.', {
|
||||
from: formatDateTime(status.from),
|
||||
until: formatDateTime(status.until),
|
||||
})
|
||||
: t('vacation.statusScheduled', 'Scheduled: replies from {{from}}, with no end date.', {
|
||||
from: formatDateTime(status.from),
|
||||
}),
|
||||
};
|
||||
case 'active':
|
||||
return {
|
||||
tone: 'success',
|
||||
text: status.until
|
||||
? t('vacation.statusActiveUntil', 'Replying now, until {{until}}.', {
|
||||
until: formatDateTime(status.until),
|
||||
})
|
||||
: t('vacation.statusActive', 'Replying now, until you turn it off.'),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
export function VacationStatusLine({ data }: { data: FieldValues }) {
|
||||
const { t } = useTranslation();
|
||||
const { baseline } = useFormContext();
|
||||
const [now, setNow] = useState(() => new Date());
|
||||
const status = vacationStatus(data, now);
|
||||
const changeAt = nextStatusChange(status)?.getTime() ?? null;
|
||||
useEffect(() => {
|
||||
if (changeAt === null) return;
|
||||
const delay = Math.min(Math.max(changeAt - Date.now(), 0), MAX_TIMER_DELAY_MS);
|
||||
const timer = setTimeout(() => setNow(new Date()), delay);
|
||||
return () => clearTimeout(timer);
|
||||
}, [changeAt, now]);
|
||||
const { tone, text } = useStatusText(status);
|
||||
return (
|
||||
<p
|
||||
role="status"
|
||||
data-status-tone={tone}
|
||||
className={cn('flex items-center gap-2 rounded-xl px-3 py-2 text-[13px] font-medium', TONE_CLASSES[tone])}
|
||||
>
|
||||
<span className={cn('size-2 shrink-0 rounded-full', DOT_CLASSES[tone])} aria-hidden="true" />
|
||||
{hasUnsavedStatus(data, baseline) ? `${text} ${t('vacation.statusUnsaved', 'Takes effect once saved.')}` : text}
|
||||
</p>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,186 @@
|
||||
/*
|
||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
import { MINUTES_PER_HOUR } from '@/lib/localDateTime';
|
||||
import type { FieldErrors, FieldValues } from '@/components/forms/formLogic';
|
||||
|
||||
export const SUBJECT_MAX_BYTES = 511;
|
||||
export const BODY_MAX_BYTES = 2047;
|
||||
export const DEFAULT_VACATION_TEXT = 'I am away.';
|
||||
|
||||
const START_OF_DAY_MINUTES = 0;
|
||||
const END_OF_DAY_MINUTES = 23 * MINUTES_PER_HOUR + 59;
|
||||
const LAST_SECOND = 59;
|
||||
const MS_PER_SECOND = 1000;
|
||||
|
||||
export type RangeEdge = 'start' | 'end';
|
||||
|
||||
export interface DateRange {
|
||||
from: Date | null;
|
||||
to: Date | null;
|
||||
}
|
||||
|
||||
export type VacationStatus =
|
||||
| { kind: 'off' }
|
||||
| { kind: 'invalidRange' }
|
||||
| { kind: 'active'; until: Date | null }
|
||||
| { kind: 'scheduled'; from: Date; until: Date | null }
|
||||
| { kind: 'ended'; at: Date };
|
||||
|
||||
export interface VacationPreview {
|
||||
subject: string | null;
|
||||
text: string | null;
|
||||
html: string | null;
|
||||
textFromHtml: boolean;
|
||||
}
|
||||
|
||||
export interface VacationMessages {
|
||||
tooLong: (limit: number) => string;
|
||||
endBeforeStart: string;
|
||||
}
|
||||
|
||||
const utf8 = new TextEncoder();
|
||||
|
||||
export function utf8Length(text: string): number {
|
||||
return utf8.encode(text).length;
|
||||
}
|
||||
|
||||
export function parseUtcDate(value: unknown): Date | null {
|
||||
if (typeof value !== 'string' || !value) return null;
|
||||
const date = new Date(value);
|
||||
return Number.isNaN(date.getTime()) ? null : date;
|
||||
}
|
||||
|
||||
export function utcDateValue(date: Date | null): string | null {
|
||||
return date ? date.toISOString().replace(/\.\d{3}Z$/, 'Z') : null;
|
||||
}
|
||||
|
||||
export function rangeOf(data: FieldValues): DateRange {
|
||||
return { from: parseUtcDate(data.fromDate), to: parseUtcDate(data.toDate) };
|
||||
}
|
||||
|
||||
export function localMinutes(date: Date): number {
|
||||
return date.getHours() * MINUTES_PER_HOUR + date.getMinutes();
|
||||
}
|
||||
|
||||
export function atLocalTime(day: Date, minutes: number, edge: RangeEdge): Date {
|
||||
const next = new Date(day);
|
||||
next.setHours(
|
||||
Math.floor(minutes / MINUTES_PER_HOUR),
|
||||
minutes % MINUTES_PER_HOUR,
|
||||
edge === 'end' ? LAST_SECOND : 0,
|
||||
0,
|
||||
);
|
||||
return next;
|
||||
}
|
||||
|
||||
function defaultMinutes(edge: RangeEdge): number {
|
||||
return edge === 'start' ? START_OF_DAY_MINUTES : END_OF_DAY_MINUTES;
|
||||
}
|
||||
|
||||
function onDay(day: Date, current: Date | null, edge: RangeEdge): Date {
|
||||
return atLocalTime(day, current ? localMinutes(current) : defaultMinutes(edge), edge);
|
||||
}
|
||||
|
||||
export function pickRangeDay(range: DateRange, day: Date, edge: RangeEdge): DateRange {
|
||||
if (edge === 'start') {
|
||||
const from = onDay(day, range.from, 'start');
|
||||
if (!range.to || range.to >= from) return { from, to: range.to };
|
||||
const to = onDay(day, range.to, 'end');
|
||||
return { from, to: to >= from ? to : atLocalTime(day, END_OF_DAY_MINUTES, 'end') };
|
||||
}
|
||||
const to = onDay(day, range.to, 'end');
|
||||
if (!range.from || range.from <= to) return { from: range.from, to };
|
||||
const from = onDay(day, range.from, 'start');
|
||||
return { from: from <= to ? from : atLocalTime(day, START_OF_DAY_MINUTES, 'start'), to };
|
||||
}
|
||||
|
||||
export function isRangeInverted({ from, to }: DateRange): boolean {
|
||||
return from !== null && to !== null && from > to;
|
||||
}
|
||||
|
||||
export function vacationStatus(data: FieldValues, now: Date): VacationStatus {
|
||||
if (data.isEnabled !== true) return { kind: 'off' };
|
||||
const range = rangeOf(data);
|
||||
if (isRangeInverted(range)) return { kind: 'invalidRange' };
|
||||
if (range.to && now > range.to) return { kind: 'ended', at: range.to };
|
||||
if (range.from && now < range.from) return { kind: 'scheduled', from: range.from, until: range.to };
|
||||
return { kind: 'active', until: range.to };
|
||||
}
|
||||
|
||||
const STATUS_FIELDS = ['isEnabled', 'fromDate', 'toDate'] as const;
|
||||
|
||||
export function hasUnsavedStatus(data: FieldValues, baseline: unknown): boolean {
|
||||
if (typeof baseline !== 'object' || baseline === null) return false;
|
||||
const saved = baseline as FieldValues;
|
||||
return STATUS_FIELDS.some((name) => (data[name] ?? null) !== (saved[name] ?? null));
|
||||
}
|
||||
|
||||
export function nextStatusChange(status: VacationStatus): Date | null {
|
||||
switch (status.kind) {
|
||||
case 'scheduled':
|
||||
return status.from;
|
||||
case 'active':
|
||||
return status.until ? new Date(status.until.getTime() + MS_PER_SECOND) : null;
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function nonEmpty(value: unknown): string | null {
|
||||
return typeof value === 'string' && value !== '' ? value : null;
|
||||
}
|
||||
|
||||
const BYTE_LIMITS: readonly (readonly [string, number])[] = [
|
||||
['subject', SUBJECT_MAX_BYTES],
|
||||
['textBody', BODY_MAX_BYTES],
|
||||
['htmlBody', BODY_MAX_BYTES],
|
||||
];
|
||||
|
||||
export function validateVacation(data: FieldValues, messages: VacationMessages): FieldErrors {
|
||||
const errors: FieldErrors = {};
|
||||
for (const [name, limit] of BYTE_LIMITS) {
|
||||
const value = data[name];
|
||||
if (typeof value === 'string' && utf8Length(value) > limit) errors[name] = messages.tooLong(limit);
|
||||
}
|
||||
if (isRangeInverted(rangeOf(data))) errors.fromDate = messages.endBeforeStart;
|
||||
return errors;
|
||||
}
|
||||
|
||||
const BLOCK_ELEMENTS = 'p, div, li, h1, h2, h3, h4, h5, h6, tr, blockquote, pre, table, ul, ol';
|
||||
const HIDDEN_ELEMENTS = 'style, script, template, noscript, title';
|
||||
|
||||
export function htmlToText(html: string): string {
|
||||
const { body } = new DOMParser().parseFromString(html, 'text/html');
|
||||
for (const hidden of body.querySelectorAll(HIDDEN_ELEMENTS)) hidden.remove();
|
||||
for (const br of body.querySelectorAll('br')) br.replaceWith('\n');
|
||||
for (const block of body.querySelectorAll(BLOCK_ELEMENTS)) block.append('\n\n');
|
||||
return (body.textContent ?? '')
|
||||
.replace(/[ \t]*\n[ \t]*/g, '\n')
|
||||
.replace(/\n{3,}/g, '\n\n')
|
||||
.trim();
|
||||
}
|
||||
|
||||
const PREVIEW_CSP =
|
||||
'<meta http-equiv="Content-Security-Policy" content="default-src \'none\'; img-src data: cid:; style-src \'unsafe-inline\'; font-src data:">';
|
||||
const LEADING_DOCTYPE = /^\s*<!doctype[^>]*>/i;
|
||||
|
||||
export function previewDocument(html: string): string {
|
||||
return LEADING_DOCTYPE.test(html)
|
||||
? html.replace(LEADING_DOCTYPE, (doctype) => doctype + PREVIEW_CSP)
|
||||
: PREVIEW_CSP + html;
|
||||
}
|
||||
|
||||
export function vacationPreview(data: FieldValues): VacationPreview {
|
||||
const text = nonEmpty(data.textBody);
|
||||
const html = nonEmpty(data.htmlBody);
|
||||
return {
|
||||
subject: nonEmpty(data.subject)?.replace(/[\r\n]/g, '') ?? null,
|
||||
text: text ?? (html ? null : DEFAULT_VACATION_TEXT),
|
||||
html,
|
||||
textFromHtml: text === null && html !== null,
|
||||
};
|
||||
}
|
||||
@@ -6,15 +6,25 @@
|
||||
|
||||
import { useAccountStore, selectIsCommunity } from '@/stores/accountStore';
|
||||
import { useSchemaStore } from '@/stores/schemaStore';
|
||||
import { canAccessView, createPermissionCheckers, type ObjectAction, type PermissionCheckers } from '@/lib/permissions';
|
||||
import { selectActiveAccountIsPersonal, useAuthStore } from '@/stores/authStore';
|
||||
import {
|
||||
canAccessView,
|
||||
createPermissionCheckers,
|
||||
personalOnlyPermissions,
|
||||
type ObjectAction,
|
||||
type PermissionCheckers,
|
||||
} from '@/lib/permissions';
|
||||
|
||||
export function usePermissionCheckers(): PermissionCheckers {
|
||||
const permissions = useAccountStore((s) => s.permissions);
|
||||
return createPermissionCheckers(permissions);
|
||||
const schema = useSchemaStore((s) => s.schema);
|
||||
const personal = useAuthStore(selectActiveAccountIsPersonal);
|
||||
return createPermissionCheckers(permissions, personal || !schema ? undefined : personalOnlyPermissions(schema));
|
||||
}
|
||||
|
||||
export function useHasObjectPermission(permissionPrefix: string | null | undefined, action: ObjectAction): boolean {
|
||||
return useAccountStore((s) => !!permissionPrefix && s.permissions.includes(`${permissionPrefix}${action}`));
|
||||
const { hasObjectPermission } = usePermissionCheckers();
|
||||
return !!permissionPrefix && hasObjectPermission(permissionPrefix, action);
|
||||
}
|
||||
|
||||
export function useCanAccess(viewName: string | null | undefined, action: ObjectAction = 'Get'): boolean {
|
||||
|
||||
+183
-2
@@ -35,6 +35,7 @@
|
||||
"back": "Back",
|
||||
"cancel": "Cancel",
|
||||
"clear": "Clear",
|
||||
"clearSearch": "Clear search",
|
||||
"clipboardBlocked": "Your browser blocked clipboard access. Select the value and copy it manually.",
|
||||
"close": "Close",
|
||||
"confirm": "Confirm",
|
||||
@@ -227,7 +228,23 @@
|
||||
"removeItemN": "Remove item {{n}}",
|
||||
"showValue": "Show value",
|
||||
"unit": "Unit",
|
||||
"unsupportedType": "Unsupported field type: {{type}}"
|
||||
"unsupportedType": "Unsupported field type: {{type}}",
|
||||
"chooseTime": "Choose a time",
|
||||
"dayPeriod": "AM/PM",
|
||||
"endOfDay": "End of day",
|
||||
"endOfDayOption": "End of day (24:00)",
|
||||
"hours": "Hours",
|
||||
"minutes": "Minutes",
|
||||
"segmentOf": "{{field}}, {{segment}}",
|
||||
"entriesAdded_one": "Added {{count}} value.",
|
||||
"entriesAdded_other": "Added {{count}} values.",
|
||||
"entriesDuplicate_one": "Skipped {{count}} duplicate: {{list}}",
|
||||
"entriesDuplicate_other": "Skipped {{count}} duplicates: {{list}}",
|
||||
"entriesInvalid": "Not added, invalid: {{list}}",
|
||||
"entriesOverLimit": "Not added, the limit is {{max}}: {{list}}",
|
||||
"entriesSample_one": "{{list}} and {{count}} more",
|
||||
"entriesSample_other": "{{list}} and {{count}} more",
|
||||
"midnight": "midnight"
|
||||
},
|
||||
"filters": {
|
||||
"after": "After",
|
||||
@@ -248,6 +265,8 @@
|
||||
"failedToDelete": "Failed to delete.",
|
||||
"failedToLoadData": "Failed to load data.",
|
||||
"failedToSave": "Failed to save.",
|
||||
"invalidLocalDate": "Enter a valid date as YYYY-MM-DD.",
|
||||
"invalidLocalTime": "Enter a valid time.",
|
||||
"invalidValue": "Invalid value.",
|
||||
"item": "item",
|
||||
"leave": "Leave",
|
||||
@@ -257,6 +276,8 @@
|
||||
"maxValueIs": "Maximum value is {{max}}.",
|
||||
"minLengthIs": "Minimum length is {{min}}.",
|
||||
"minValueIs": "Minimum value is {{min}}.",
|
||||
"minItems_one": "Add at least one entry.",
|
||||
"minItems_other": "Add at least {{count}} entries.",
|
||||
"noChangesToSave": "No changes to save",
|
||||
"objectNotFound": "Object not found.",
|
||||
"otpCodeRequired": "Enter your current authenticator code to authorise this change.",
|
||||
@@ -269,7 +290,8 @@
|
||||
"unsavedChanges": "You have unsaved changes. Are you sure you want to leave?",
|
||||
"unsavedChangesLabel": "Unsaved changes",
|
||||
"unsavedChangesTitle": "Unsaved changes",
|
||||
"notConfirmed": "The server did not confirm the change."
|
||||
"notConfirmed": "The server did not confirm the change.",
|
||||
"invalidWeeklySchedule": "Correct the intervals in this schedule."
|
||||
},
|
||||
"globalSearch": {
|
||||
"create": "Create",
|
||||
@@ -488,5 +510,164 @@
|
||||
"couldNotResolve": "Could not resolve object",
|
||||
"failedToLoad": "Failed to load",
|
||||
"objectNotFound": "Object not found"
|
||||
},
|
||||
"mailRules": {
|
||||
"summary": {
|
||||
"quoted": "“{{value}}”",
|
||||
"detail": "{{label}}: {{detail}}",
|
||||
"test": "{{operator}} {{values}}",
|
||||
"slot": "{{days}} {{start}}–{{end}}",
|
||||
"withoutCopy": "{{addresses}} without keeping a copy",
|
||||
"always": "For every message",
|
||||
"if": "If {{conditions}}",
|
||||
"except": "{{when}}, except if {{exceptions}}",
|
||||
"noActions": "do nothing",
|
||||
"then": "then {{actions}}",
|
||||
"thenStop": "then {{actions}} and stop processing more rules",
|
||||
"sentence": "{{when}}, {{then}}."
|
||||
},
|
||||
"issue": {
|
||||
"rejectNotAlone": "A rule that rejects mail cannot have other actions.",
|
||||
"rejectNeedsAuthentication": "A rule that rejects mail must match all conditions and require an authenticated sender.",
|
||||
"forwardingNotAllowed": "Your account is not allowed to forward mail, so this rule cannot be saved while it is enabled.",
|
||||
"scheduleTooManySlots": "Adjacent schedule conditions are combined into one, which can have at most {{max}} time slots."
|
||||
},
|
||||
"loadFailed": "Failed to load the mail rules.",
|
||||
"enableRule": "Enable {{name}}",
|
||||
"createRule": "Create rule",
|
||||
"ruleList": "Mail rules",
|
||||
"dragRule": "Reorder {{name}}",
|
||||
"edit": "Edit",
|
||||
"view": "View",
|
||||
"summaryLabel": "Summary",
|
||||
"moveUp": "Move up",
|
||||
"moveDown": "Move down",
|
||||
"dnd": {
|
||||
"picked": "Picked up {{name}}, position {{position}} of {{count}}.",
|
||||
"over": "{{name}} moved to position {{position}} of {{count}}.",
|
||||
"dropped": "{{name}} dropped at position {{position}} of {{count}}.",
|
||||
"cancelled": "Reordering cancelled, {{name}} returned to its position.",
|
||||
"instructions": "To reorder a rule, press Space or Enter to pick it up, use the arrow keys to move it, then press Space or Enter again to drop it, or Escape to cancel.",
|
||||
"roleDescription": "sortable rule"
|
||||
},
|
||||
"reorderFailed": "Could not reorder the rules",
|
||||
"reorderPinned": "This order would move a forwarding rule, and your account is not allowed to change forwarding rules.",
|
||||
"noRules": "No mail rules yet. Create one to sort, file or answer mail.",
|
||||
"deleteTitle": "Delete this rule?",
|
||||
"mailboxId": "Mailbox id",
|
||||
"chooseMailbox": "Choose a mailbox",
|
||||
"unknownMailbox": "Unknown mailbox ({{id}})",
|
||||
"builder": {
|
||||
"all": "all",
|
||||
"any": "any",
|
||||
"matchMode": "Conditions that must match",
|
||||
"rejectNeedsAuthentication": "Reject needs all conditions to match, including an authenticated sender.",
|
||||
"conditionN": "Condition {{n}}",
|
||||
"exceptionN": "Exception {{n}}",
|
||||
"actionN": "Action {{n}}",
|
||||
"ifPrefix": "If",
|
||||
"ifSuffix": "of these conditions match",
|
||||
"ifOne": "If this condition matches",
|
||||
"ifNone": "For every message",
|
||||
"noConditions": "Without conditions the rule applies to every message.",
|
||||
"addCondition": "Add condition",
|
||||
"except": "Except if any of these match",
|
||||
"addException": "Add exception",
|
||||
"then": "Then",
|
||||
"addAction": "Add action",
|
||||
"conditions": "Conditions",
|
||||
"rejectNotAlone": "Reject must be the only action.",
|
||||
"rejectStops": "A rule that rejects mail always stops processing more rules.",
|
||||
"actionRequired": "Add at least one action.",
|
||||
"missingFields": "Fill in {{fields}}."
|
||||
},
|
||||
"removeItem": "Remove {{label}}"
|
||||
},
|
||||
"schedule": {
|
||||
"add": "Add interval",
|
||||
"dayRange": "{{first}}–{{last}}",
|
||||
"days": "Days",
|
||||
"empty": "No intervals yet.",
|
||||
"end": "{{slot}} end",
|
||||
"everyDay": "Every day",
|
||||
"interval": "Interval {{n}}",
|
||||
"issueEmpty": "Add at least one interval.",
|
||||
"issueEndNotAfterStart": "The end must be later than the start. Split hours that cross midnight into two intervals.",
|
||||
"issueMissingTime": "Enter a start and an end time.",
|
||||
"issueNoDays": "Choose at least one day.",
|
||||
"issueSameStartEnd": "The start and the end cannot be the same time.",
|
||||
"issueStartAtEndOfDay": "The start must be before 24:00.",
|
||||
"nextDay": "next day",
|
||||
"noDays": "No days",
|
||||
"presetOutsideWorkdays": "Evenings, nights and weekends",
|
||||
"remove": "Remove {{slot}}",
|
||||
"slot": "{{days}}, {{start}} to {{end}}",
|
||||
"slotAllDay": "{{days}}, all day",
|
||||
"slotOvernight": "{{days}}, {{start}} to {{end}} the next day",
|
||||
"start": "{{slot}} start",
|
||||
"startFrom": "Start from:",
|
||||
"to": "to"
|
||||
},
|
||||
"timeZone": {
|
||||
"currentOffset": "Currently {{offset}}",
|
||||
"search": "Search by city, region or offset...",
|
||||
"useMine": "Use my time zone ({{zone}})"
|
||||
},
|
||||
"vacation": {
|
||||
"tooLong": "Too long: the server accepts up to {{limit}} bytes.",
|
||||
"endBeforeStart": "The end must be after the start.",
|
||||
"startsNow": "Starts immediately",
|
||||
"noEnd": "No end date",
|
||||
"start": "Start",
|
||||
"startNow": "Start immediately",
|
||||
"end": "End",
|
||||
"removeEnd": "No end date",
|
||||
"until": "until",
|
||||
"editingEdge": "Date to set",
|
||||
"startTime": "Start time",
|
||||
"endTime": "End time",
|
||||
"clearPeriod": "Clear period",
|
||||
"period": "Period",
|
||||
"periodHelp": "Replies are sent only within this period. Leave the start open to begin now, or the end open to continue until you turn replies off.",
|
||||
"statusUnsaved": "Takes effect once saved.",
|
||||
"textFromHtml": "Generated by the server from the HTML body; line breaks may differ slightly.",
|
||||
"preview": "Preview",
|
||||
"subject": "Subject",
|
||||
"defaultSubject": "Chosen by the server, usually \"Auto:\" followed by the original subject.",
|
||||
"message": "Message",
|
||||
"defaultText": "No message set: the server sends this text.",
|
||||
"htmlTab": "HTML",
|
||||
"textTab": "Plain text",
|
||||
"htmlPreview": "HTML reply preview",
|
||||
"spamNote": "Replies are never sent to messages classified as spam.",
|
||||
"statusOff": "Off: no automatic replies are sent.",
|
||||
"statusInvalid": "The period ends before it starts.",
|
||||
"statusEnded": "The period ended on {{date}}: no replies are sent.",
|
||||
"statusScheduledUntil": "Scheduled: replies from {{from}} until {{until}}.",
|
||||
"statusScheduled": "Scheduled: replies from {{from}}, with no end date.",
|
||||
"statusActiveUntil": "Replying now, until {{until}}.",
|
||||
"statusActive": "Replying now, until you turn it off."
|
||||
},
|
||||
"senderLists": {
|
||||
"added_one": "Added {{count}} entry.",
|
||||
"added_other": "Added {{count}} entries.",
|
||||
"duplicates": "Already in the list: {{list}}.",
|
||||
"invalid": "Not an email address or a domain: {{list}}.",
|
||||
"overLimit": "The list holds at most {{max}} entries; not added: {{list}}.",
|
||||
"failed": "Could not add {{address}}: {{reason}}",
|
||||
"addFailed": "Could not add the entries",
|
||||
"addHint": "Enter one or more entries, or paste a list separated by commas, spaces or new lines. Press Enter to add them.",
|
||||
"placeholder": "name@example.org or @example.org",
|
||||
"add": "Add",
|
||||
"domain": "Domain",
|
||||
"remove": "Remove {{address}}",
|
||||
"removeFailed": "Could not remove {{address}}",
|
||||
"loadFailed": "Failed to load the list.",
|
||||
"empty": "No entries yet. Add an email address or a domain.",
|
||||
"count_one": "{{count}} entry",
|
||||
"count_other": "{{count}} entries",
|
||||
"search": "Search",
|
||||
"searchLabel": "Search {{label}}",
|
||||
"noMatch": "No entries match “{{search}}”."
|
||||
}
|
||||
}
|
||||
@@ -15,6 +15,7 @@ export interface EmbeddedVariant {
|
||||
|
||||
export interface ResolvedEmbedded {
|
||||
objectName: string;
|
||||
schemaName: string | null;
|
||||
variants: EmbeddedVariant[] | null;
|
||||
variant: EmbeddedVariant | null;
|
||||
fields: Fields | null;
|
||||
@@ -36,6 +37,7 @@ export function resolveEmbedded(schema: Schema, objectName: string, value: unkno
|
||||
if (entry.type === 'single') {
|
||||
return {
|
||||
objectName,
|
||||
schemaName: entry.schemaName,
|
||||
variants: null,
|
||||
variant: null,
|
||||
fields: schema.fields[entry.schemaName] ?? null,
|
||||
@@ -47,6 +49,7 @@ export function resolveEmbedded(schema: Schema, objectName: string, value: unkno
|
||||
const schemaName = variant?.schemaName;
|
||||
return {
|
||||
objectName,
|
||||
schemaName: schemaName ?? null,
|
||||
variants: entry.variants,
|
||||
variant,
|
||||
fields: schemaName ? (schema.fields[schemaName] ?? null) : null,
|
||||
|
||||
@@ -4,7 +4,16 @@
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
import i18n from '@/i18n';
|
||||
import { SIZE_UNITS } from '@/lib/durationFormat';
|
||||
import {
|
||||
MINUTES_PER_DAY,
|
||||
MINUTES_PER_HOUR,
|
||||
localDateToUtcDate,
|
||||
parseLocalDate,
|
||||
parseLocalTime,
|
||||
} from '@/lib/localDateTime';
|
||||
import { WEEKDAYS, type Weekday } from '@/lib/weeklySchedule';
|
||||
import { DEFAULT_LOCALE, useAccountStore } from '@/stores/accountStore';
|
||||
|
||||
export type DateInput = string | number | Date;
|
||||
@@ -155,3 +164,84 @@ export function formatTime(value: DateInput, options: { seconds?: boolean; milli
|
||||
if (options.milliseconds) opts.fractionalSecondDigits = 3;
|
||||
return dateFormat(opts).format(d);
|
||||
}
|
||||
|
||||
export function formatLocalTime(value: unknown): string {
|
||||
const minutes = parseLocalTime(value);
|
||||
if (minutes === null) return String(value);
|
||||
if (minutes === MINUTES_PER_DAY) return i18n.t('field.endOfDay', 'End of day');
|
||||
const utc = Date.UTC(1970, 0, 1, Math.floor(minutes / MINUTES_PER_HOUR), minutes % MINUTES_PER_HOUR);
|
||||
return dateFormat({ timeStyle: 'short', timeZone: 'UTC' }).format(utc);
|
||||
}
|
||||
|
||||
export function formatIntervalEnd(value: unknown): string {
|
||||
return parseLocalTime(value) === MINUTES_PER_DAY ? i18n.t('field.midnight', 'midnight') : formatLocalTime(value);
|
||||
}
|
||||
|
||||
export function formatLocalDate(value: unknown, options: Intl.DateTimeFormatOptions = { dateStyle: 'medium' }): string {
|
||||
const date = parseLocalDate(value);
|
||||
if (!date) return String(value);
|
||||
return dateFormat({ ...options, timeZone: 'UTC' }).format(localDateToUtcDate(date));
|
||||
}
|
||||
|
||||
const FIRST_MONDAY_OF_EPOCH = 5;
|
||||
const ZERO_OFFSET = /^GMT([+-]00:?00)?$/;
|
||||
|
||||
export function formatWeekday(day: Weekday, weekday: 'narrow' | 'short' | 'long' = 'long'): string {
|
||||
const offset = WEEKDAYS.indexOf(day);
|
||||
return dateFormat({ weekday, timeZone: 'UTC' }).format(Date.UTC(1970, 0, FIRST_MONDAY_OF_EPOCH + offset));
|
||||
}
|
||||
|
||||
const offsetFormats = new Map<string, Intl.DateTimeFormat>();
|
||||
|
||||
export function formatUtcOffset(timeZone: string, at: Date): string | null {
|
||||
try {
|
||||
let fmt = offsetFormats.get(timeZone);
|
||||
if (!fmt) {
|
||||
fmt = new Intl.DateTimeFormat('en-US', { timeZone, timeZoneName: 'longOffset' });
|
||||
offsetFormats.set(timeZone, fmt);
|
||||
}
|
||||
const name = fmt.formatToParts(at).find((part) => part.type === 'timeZoneName')?.value;
|
||||
if (!name) return null;
|
||||
return ZERO_OFFSET.test(name) ? 'UTC' : name.replace(/^GMT/, 'UTC');
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export interface LocaleClock {
|
||||
hour12: boolean;
|
||||
am: string;
|
||||
pm: string;
|
||||
meridiemFirst: boolean;
|
||||
}
|
||||
|
||||
function dayPeriod(parts: Intl.DateTimeFormatPart[]): string | undefined {
|
||||
return parts.find((part) => part.type === 'dayPeriod')?.value;
|
||||
}
|
||||
|
||||
export function localeClock(): LocaleClock {
|
||||
const fmt = dateFormat({ hour: 'numeric', minute: '2-digit', timeZone: 'UTC' });
|
||||
const { hourCycle } = fmt.resolvedOptions();
|
||||
const morning = fmt.formatToParts(Date.UTC(1970, 0, 1, 1));
|
||||
const evening = fmt.formatToParts(Date.UTC(1970, 0, 1, 13));
|
||||
const periodIndex = morning.findIndex((part) => part.type === 'dayPeriod');
|
||||
return {
|
||||
hour12: hourCycle === 'h11' || hourCycle === 'h12',
|
||||
am: dayPeriod(morning) ?? 'AM',
|
||||
pm: dayPeriod(evening) ?? 'PM',
|
||||
meridiemFirst: periodIndex >= 0 && periodIndex < morning.findIndex((part) => part.type === 'hour'),
|
||||
};
|
||||
}
|
||||
|
||||
const listFormats = new Map<string, Intl.ListFormat>();
|
||||
|
||||
export function formatList(items: readonly string[], type: 'conjunction' | 'disjunction' = 'conjunction'): string {
|
||||
const locale = getFormatLocale();
|
||||
const key = `${locale}|${type}`;
|
||||
let fmt = listFormats.get(key);
|
||||
if (!fmt) {
|
||||
fmt = new Intl.ListFormat(locale, { style: 'long', type });
|
||||
listFormats.set(key, fmt);
|
||||
}
|
||||
return fmt.format(items);
|
||||
}
|
||||
+4
-29
@@ -7,6 +7,7 @@
|
||||
import type { Layout, LayoutSubItem, Schema } from '@/types/schema';
|
||||
import { resolveObject } from '@/lib/schemaResolver';
|
||||
import { isCommunityEdition, isCreateOnly } from '@/lib/permissions';
|
||||
import { CUSTOM_COMPONENT_PREFIX, matchRoutePage } from '@/extensions/pages';
|
||||
|
||||
export type CanGet = (permissionPrefix: string) => boolean;
|
||||
export type HasPermission = (permission: string) => boolean;
|
||||
@@ -16,41 +17,15 @@ interface SpecialLinkInfo {
|
||||
enterprise: boolean;
|
||||
}
|
||||
|
||||
interface CustomComponentRule {
|
||||
permission: string;
|
||||
backingObject?: string;
|
||||
enterprise?: boolean;
|
||||
}
|
||||
|
||||
const CUSTOM_COMPONENTS: Record<string, CustomComponentRule> = {
|
||||
LiveDelivery: { permission: 'liveDeliveryTest' },
|
||||
// SPDX-SnippetBegin
|
||||
// SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
// SPDX-License-Identifier: LicenseRef-SEL
|
||||
Dashboard: { permission: 'liveMetrics', backingObject: 'x:Metric' },
|
||||
LiveTracing: { permission: 'liveTracing', enterprise: true },
|
||||
// SPDX-SnippetEnd
|
||||
};
|
||||
|
||||
function customComponentName(viewName: string): string | null {
|
||||
// SPDX-SnippetBegin
|
||||
// SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
// SPDX-License-Identifier: LicenseRef-SEL
|
||||
if (viewName.startsWith('Dashboard/')) return 'Dashboard';
|
||||
// SPDX-SnippetEnd
|
||||
if (viewName.startsWith('CustomComponent/')) return viewName.slice('CustomComponent/'.length);
|
||||
return null;
|
||||
}
|
||||
|
||||
function checkSpecialLink(
|
||||
schema: Schema,
|
||||
viewName: string,
|
||||
hasPerm?: HasPermission,
|
||||
canGet?: CanGet,
|
||||
): SpecialLinkInfo | null {
|
||||
const component = customComponentName(viewName);
|
||||
if (component === null) return null;
|
||||
const rule = CUSTOM_COMPONENTS[component];
|
||||
const page = matchRoutePage(viewName);
|
||||
if (!page && !viewName.startsWith(CUSTOM_COMPONENT_PREFIX)) return null;
|
||||
const rule = page?.gate;
|
||||
if (!rule) return { visible: true, enterprise: false };
|
||||
|
||||
const backing = rule.backingObject ? resolveObject(schema, rule.backingObject) : null;
|
||||
|
||||
@@ -0,0 +1,89 @@
|
||||
/*
|
||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
export const MINUTES_PER_HOUR = 60;
|
||||
export const MINUTES_PER_DAY = 24 * MINUTES_PER_HOUR;
|
||||
|
||||
const LOCAL_TIME = /^(\d{2}):(\d{2})$/;
|
||||
const LOCAL_DATE = /^(\d{4})-(\d{2})-(\d{2})$/;
|
||||
const MIN_YEAR = 1;
|
||||
const MAX_YEAR = 9999;
|
||||
|
||||
export interface LocalDate {
|
||||
year: number;
|
||||
month: number;
|
||||
day: number;
|
||||
}
|
||||
|
||||
export function parseLocalTime(value: unknown): number | null {
|
||||
if (typeof value !== 'string') return null;
|
||||
const match = LOCAL_TIME.exec(value);
|
||||
if (!match) return null;
|
||||
const hours = Number(match[1]);
|
||||
const minutes = Number(match[2]);
|
||||
if (hours < 24 && minutes < MINUTES_PER_HOUR) return hours * MINUTES_PER_HOUR + minutes;
|
||||
return hours === 24 && minutes === 0 ? MINUTES_PER_DAY : null;
|
||||
}
|
||||
|
||||
function pad(value: number, width: number): string {
|
||||
return String(value).padStart(width, '0');
|
||||
}
|
||||
|
||||
export function localTimeFromMinutes(minutes: number): string {
|
||||
return `${pad(Math.floor(minutes / MINUTES_PER_HOUR), 2)}:${pad(minutes % MINUTES_PER_HOUR, 2)}`;
|
||||
}
|
||||
|
||||
export type Meridiem = 'am' | 'pm';
|
||||
|
||||
export const HOURS_PER_HALF_DAY = 12;
|
||||
|
||||
export function hour12Of(hours: number): number {
|
||||
return hours % HOURS_PER_HALF_DAY || HOURS_PER_HALF_DAY;
|
||||
}
|
||||
|
||||
export function meridiemOf(hours: number): Meridiem {
|
||||
return hours >= HOURS_PER_HALF_DAY ? 'pm' : 'am';
|
||||
}
|
||||
|
||||
export function hours24From(hour12: number, meridiem: Meridiem): number {
|
||||
return (hour12 % HOURS_PER_HALF_DAY) + (meridiem === 'pm' ? HOURS_PER_HALF_DAY : 0);
|
||||
}
|
||||
|
||||
export function daysInMonth(year: number, month: number): number {
|
||||
if (month === 2) return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0) ? 29 : 28;
|
||||
return month === 4 || month === 6 || month === 9 || month === 11 ? 30 : 31;
|
||||
}
|
||||
|
||||
export function parseLocalDate(value: unknown): LocalDate | null {
|
||||
if (typeof value !== 'string') return null;
|
||||
const match = LOCAL_DATE.exec(value);
|
||||
if (!match) return null;
|
||||
const year = Number(match[1]);
|
||||
const month = Number(match[2]);
|
||||
const day = Number(match[3]);
|
||||
if (year < MIN_YEAR || year > MAX_YEAR || month < 1 || month > 12) return null;
|
||||
return day >= 1 && day <= daysInMonth(year, month) ? { year, month, day } : null;
|
||||
}
|
||||
|
||||
export function formatLocalDateValue({ year, month, day }: LocalDate): string {
|
||||
return `${pad(year, 4)}-${pad(month, 2)}-${pad(day, 2)}`;
|
||||
}
|
||||
|
||||
export function localDateToCalendarDate({ year, month, day }: LocalDate): Date {
|
||||
const date = new Date(2000, month - 1, day);
|
||||
date.setFullYear(year);
|
||||
return date;
|
||||
}
|
||||
|
||||
export function localDateFromCalendarDate(date: Date): LocalDate {
|
||||
return { year: date.getFullYear(), month: date.getMonth() + 1, day: date.getDate() };
|
||||
}
|
||||
|
||||
export function localDateToUtcDate({ year, month, day }: LocalDate): Date {
|
||||
const date = new Date(Date.UTC(2000, month - 1, day));
|
||||
date.setUTCFullYear(year);
|
||||
return date;
|
||||
}
|
||||
+41
-4
@@ -9,27 +9,64 @@ import { resolveObject } from '@/lib/schemaResolver';
|
||||
|
||||
export type ObjectAction = 'Get' | 'Query' | 'Create' | 'Update' | 'Destroy';
|
||||
|
||||
const OBJECT_ACTIONS: readonly ObjectAction[] = ['Get', 'Query', 'Create', 'Update', 'Destroy'];
|
||||
|
||||
export const PERSONAL_ONLY_OBJECTS: readonly string[] = [
|
||||
'x:AccountPassword',
|
||||
'x:AccountSettings',
|
||||
'x:ApiKey',
|
||||
'x:AppPassword',
|
||||
'x:OAuthGrant',
|
||||
'x:Passkey',
|
||||
];
|
||||
|
||||
export interface PermissionCheckers {
|
||||
hasPermission: (permission: string) => boolean;
|
||||
hasObjectPermission: (permissionPrefix: string, action: ObjectAction) => boolean;
|
||||
canGet: (permissionPrefix: string) => boolean;
|
||||
}
|
||||
|
||||
const checkersCache = new WeakMap<readonly string[], PermissionCheckers>();
|
||||
const NO_DENIED_PERMISSIONS: ReadonlySet<string> = new Set();
|
||||
const checkersCache = new WeakMap<readonly string[], WeakMap<ReadonlySet<string>, PermissionCheckers>>();
|
||||
|
||||
export function createPermissionCheckers(permissions: readonly string[]): PermissionCheckers {
|
||||
const cached = checkersCache.get(permissions);
|
||||
export function createPermissionCheckers(
|
||||
permissions: readonly string[],
|
||||
denied: ReadonlySet<string> = NO_DENIED_PERMISSIONS,
|
||||
): PermissionCheckers {
|
||||
let byDenied = checkersCache.get(permissions);
|
||||
if (!byDenied) {
|
||||
byDenied = new WeakMap();
|
||||
checkersCache.set(permissions, byDenied);
|
||||
}
|
||||
const cached = byDenied.get(denied);
|
||||
if (cached) return cached;
|
||||
const granted = new Set(permissions);
|
||||
for (const permission of denied) granted.delete(permission);
|
||||
const checkers: PermissionCheckers = {
|
||||
hasPermission: (permission) => granted.has(permission),
|
||||
hasObjectPermission: (permissionPrefix, action) => granted.has(`${permissionPrefix}${action}`),
|
||||
canGet: (permissionPrefix) => granted.has(`${permissionPrefix}Get`),
|
||||
};
|
||||
checkersCache.set(permissions, checkers);
|
||||
byDenied.set(denied, checkers);
|
||||
return checkers;
|
||||
}
|
||||
|
||||
const personalOnlyCache = new WeakMap<Schema, ReadonlySet<string>>();
|
||||
|
||||
export function personalOnlyPermissions(schema: Schema): ReadonlySet<string> {
|
||||
let denied = personalOnlyCache.get(schema);
|
||||
if (!denied) {
|
||||
const set = new Set<string>();
|
||||
for (const objectName of PERSONAL_ONLY_OBJECTS) {
|
||||
const prefix = resolveObject(schema, objectName)?.permissionPrefix;
|
||||
if (prefix) for (const action of OBJECT_ACTIONS) set.add(`${prefix}${action}`);
|
||||
}
|
||||
denied = set;
|
||||
personalOnlyCache.set(schema, denied);
|
||||
}
|
||||
return denied;
|
||||
}
|
||||
|
||||
const definedPermissionsCache = new WeakMap<Schema, ReadonlySet<string>>();
|
||||
|
||||
function definedPermissions(schema: Schema): ReadonlySet<string> {
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
/*
|
||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
import type { TFunction } from 'i18next';
|
||||
import { formatIntervalEnd, formatList, formatLocalTime, formatWeekday, getFormatLocale } from '@/lib/format';
|
||||
import { MINUTES_PER_DAY, localTimeFromMinutes } from '@/lib/localDateTime';
|
||||
import {
|
||||
WEEKDAYS,
|
||||
dayRuns,
|
||||
firstWeekdayOf,
|
||||
isOvernight,
|
||||
weekdayOrder,
|
||||
type ScheduleRules,
|
||||
type Slot,
|
||||
type Weekday,
|
||||
} from '@/lib/weeklySchedule';
|
||||
|
||||
const RANGE_MIN_DAYS = 3;
|
||||
const MISSING_TIME = '--:--';
|
||||
|
||||
export function localeWeekdayOrder(): Weekday[] {
|
||||
return weekdayOrder(firstWeekdayOf(getFormatLocale()));
|
||||
}
|
||||
|
||||
export function formatDays(t: TFunction, days: readonly Weekday[], order: readonly Weekday[]): string {
|
||||
if (days.length === 0) return t('schedule.noDays', 'No days');
|
||||
if (days.length === WEEKDAYS.length) return t('schedule.everyDay', 'Every day');
|
||||
const parts = dayRuns(days, order).flatMap((run) =>
|
||||
run.length >= RANGE_MIN_DAYS
|
||||
? [
|
||||
t('schedule.dayRange', '{{first}}–{{last}}', {
|
||||
first: formatWeekday(run[0], 'short'),
|
||||
last: formatWeekday(run[run.length - 1], 'short'),
|
||||
}),
|
||||
]
|
||||
: run.map((day) => formatWeekday(day, 'short')),
|
||||
);
|
||||
return formatList(parts);
|
||||
}
|
||||
|
||||
function formatClock(minutes: number | null, end: boolean): string {
|
||||
if (minutes === null) return MISSING_TIME;
|
||||
const time = localTimeFromMinutes(minutes);
|
||||
return end ? formatIntervalEnd(time) : formatLocalTime(time);
|
||||
}
|
||||
|
||||
export function formatSlot(t: TFunction, slot: Slot, order: readonly Weekday[], rules: ScheduleRules): string {
|
||||
const days = formatDays(t, slot.days, order);
|
||||
const end = slot.end !== null && rules === 'overnight' && slot.end === 0 ? MINUTES_PER_DAY : slot.end;
|
||||
if (slot.start === 0 && end === MINUTES_PER_DAY) return t('schedule.slotAllDay', '{{days}}, all day', { days });
|
||||
const times = { days, start: formatClock(slot.start, false), end: formatClock(end, true) };
|
||||
return isOvernight(slot, rules)
|
||||
? t('schedule.slotOvernight', '{{days}}, {{start}} to {{end}} the next day', times)
|
||||
: t('schedule.slot', '{{days}}, {{start}} to {{end}}', times);
|
||||
}
|
||||
@@ -4,7 +4,17 @@
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
import type { Schema, ObjectTypeObject, ObjectTypeSingleton, Fields, Form, List, EnumVariant } from '@/types/schema';
|
||||
import type {
|
||||
Schema,
|
||||
ObjectTypeObject,
|
||||
ObjectTypeSingleton,
|
||||
Fields,
|
||||
Form,
|
||||
List,
|
||||
EnumVariant,
|
||||
MapValueType,
|
||||
ScalarType,
|
||||
} from '@/types/schema';
|
||||
|
||||
export interface ResolvedObject {
|
||||
viewName: string;
|
||||
@@ -347,6 +357,17 @@ export function getEnumVariant(
|
||||
return schema?.enums[enumName]?.find((v) => v.name === name);
|
||||
}
|
||||
|
||||
export function mapEntryValueType(
|
||||
schema: Schema | null | undefined,
|
||||
keyClass: ScalarType,
|
||||
valueClass: MapValueType,
|
||||
key: string,
|
||||
): MapValueType {
|
||||
if (keyClass.type !== 'enum' || valueClass.type !== 'number') return valueClass;
|
||||
const format = getEnumVariant(schema, keyClass.enumName, key)?.valueFormat;
|
||||
return format ? { ...valueClass, format } : valueClass;
|
||||
}
|
||||
|
||||
export interface ResolvedView {
|
||||
object: ResolvedObject;
|
||||
resolvedSchema: ResolvedSchema;
|
||||
|
||||
@@ -0,0 +1,160 @@
|
||||
/*
|
||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
import { parseLocalDate, parseLocalTime } from '@/lib/localDateTime';
|
||||
import type { ScalarTypeString, StringFormat } from '@/types/schema';
|
||||
|
||||
const LINE_SEPARATORS = /[\r\n]+/;
|
||||
const LIST_SEPARATORS = /[\r\n,;]+/;
|
||||
const LIST_FORMATS: ReadonlySet<StringFormat> = new Set([
|
||||
'emailAddress',
|
||||
'ipAddress',
|
||||
'ipNetwork',
|
||||
'socketAddress',
|
||||
'localTime',
|
||||
'localDate',
|
||||
]);
|
||||
|
||||
const IPV4_OCTET = /^(?:0|[1-9]\d{0,2})$/;
|
||||
const IPV6_GROUP = /^[0-9a-fA-F]{1,4}$/;
|
||||
const IPV6_GROUPS = 8;
|
||||
const IPV4_MAX_PREFIX = 32;
|
||||
const IPV6_MAX_PREFIX = 128;
|
||||
const MIN_PREFIX = 8;
|
||||
const PREFIX = /^\+?\d+$/;
|
||||
const EMAIL = /^[^\s@]+@[^\s@]+$/;
|
||||
|
||||
export interface SetEntriesResult {
|
||||
added: string[];
|
||||
duplicates: string[];
|
||||
invalid: string[];
|
||||
overLimit: string[];
|
||||
}
|
||||
|
||||
export function splitEntries(text: string, format: StringFormat): string[] {
|
||||
const entries: string[] = [];
|
||||
for (const part of text.split(LIST_FORMATS.has(format) ? LIST_SEPARATORS : LINE_SEPARATORS)) {
|
||||
const entry = part.trim();
|
||||
if (entry) entries.push(entry);
|
||||
}
|
||||
return entries;
|
||||
}
|
||||
|
||||
function canonicalIpv4(value: string): string | null {
|
||||
const octets = value.split('.');
|
||||
return octets.length === 4 && octets.every((octet) => IPV4_OCTET.test(octet) && Number(octet) <= 255) ? value : null;
|
||||
}
|
||||
|
||||
function ipv6Groups(part: string): string[] {
|
||||
return part === '' ? [] : part.split(':');
|
||||
}
|
||||
|
||||
function hexGroups(groups: readonly string[], ipv4: string | null): number[] | null {
|
||||
if (!groups.every((group) => IPV6_GROUP.test(group))) return null;
|
||||
const values = groups.map((group) => parseInt(group, 16));
|
||||
if (ipv4) {
|
||||
const [a, b, c, d] = ipv4.split('.').map(Number);
|
||||
values.push(a * 256 + b, c * 256 + d);
|
||||
}
|
||||
return values;
|
||||
}
|
||||
|
||||
function canonicalIpv6(value: string): string | null {
|
||||
const halves = value.split('::');
|
||||
if (halves.length > 2) return null;
|
||||
const compressed = halves.length === 2;
|
||||
const head = ipv6Groups(halves[0]);
|
||||
const tail = compressed ? ipv6Groups(halves[1]) : [];
|
||||
const trailing = compressed ? tail : head;
|
||||
let ipv4: string | null = null;
|
||||
if (trailing.at(-1)?.includes('.')) {
|
||||
ipv4 = canonicalIpv4(trailing.pop() ?? '');
|
||||
if (!ipv4) return null;
|
||||
}
|
||||
const headValues = hexGroups(head, compressed ? null : ipv4);
|
||||
const tailValues = hexGroups(tail, compressed ? ipv4 : null);
|
||||
if (!headValues || !tailValues) return null;
|
||||
const count = headValues.length + tailValues.length;
|
||||
if (compressed ? count >= IPV6_GROUPS : count !== IPV6_GROUPS) return null;
|
||||
const zeros = new Array<number>(IPV6_GROUPS - count).fill(0);
|
||||
return [...headValues, ...zeros, ...tailValues].map((group) => group.toString(16)).join(':');
|
||||
}
|
||||
|
||||
function canonicalIp(value: string): string | null {
|
||||
return canonicalIpv4(value) ?? canonicalIpv6(value);
|
||||
}
|
||||
|
||||
function canonicalIpNetwork(value: string): string | null {
|
||||
const slash = value.lastIndexOf('/');
|
||||
if (slash < 0) return canonicalIp(value);
|
||||
const prefix = value.slice(slash + 1).trim();
|
||||
if (!PREFIX.test(prefix)) return null;
|
||||
const address = value.slice(0, slash).trim();
|
||||
const bits = Number(prefix);
|
||||
const v4 = canonicalIpv4(address);
|
||||
const canonical = v4 ?? canonicalIpv6(address);
|
||||
const maxPrefix = v4 ? IPV4_MAX_PREFIX : IPV6_MAX_PREFIX;
|
||||
if (!canonical || bits < MIN_PREFIX || bits > maxPrefix) return null;
|
||||
return bits === maxPrefix ? canonical : `${canonical}/${bits}`;
|
||||
}
|
||||
|
||||
export function isValidStringValue(type: ScalarTypeString, value: string): boolean {
|
||||
if (type.minLength != null && value.length < type.minLength) return false;
|
||||
if (type.maxLength != null && value.length > type.maxLength) return false;
|
||||
switch (type.format) {
|
||||
case 'emailAddress':
|
||||
return EMAIL.test(value);
|
||||
case 'ipAddress':
|
||||
return canonicalIp(value) !== null;
|
||||
case 'ipNetwork':
|
||||
return canonicalIpNetwork(value) !== null;
|
||||
case 'localTime':
|
||||
return parseLocalTime(value) !== null;
|
||||
case 'localDate':
|
||||
return parseLocalDate(value) !== null;
|
||||
default:
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
function dedupeKey(format: StringFormat, value: string): string {
|
||||
switch (format) {
|
||||
case 'emailAddress':
|
||||
return value.toLowerCase();
|
||||
case 'ipAddress':
|
||||
return canonicalIp(value) ?? value;
|
||||
case 'ipNetwork':
|
||||
return canonicalIpNetwork(value) ?? value;
|
||||
default:
|
||||
return value;
|
||||
}
|
||||
}
|
||||
|
||||
export function joinEntries(entries: readonly string[], format: StringFormat): string | null {
|
||||
if (entries.length <= 1) return entries[0] ?? '';
|
||||
return LIST_FORMATS.has(format) ? entries.join(', ') : null;
|
||||
}
|
||||
|
||||
export function addSetEntries(
|
||||
existing: readonly string[],
|
||||
entries: readonly string[],
|
||||
type: ScalarTypeString,
|
||||
maxItems?: number,
|
||||
): SetEntriesResult {
|
||||
const result: SetEntriesResult = { added: [], duplicates: [], invalid: [], overLimit: [] };
|
||||
const seen = new Set(existing.map((item) => dedupeKey(type.format, item)));
|
||||
for (const entry of entries) {
|
||||
const key = dedupeKey(type.format, entry);
|
||||
if (seen.has(key)) result.duplicates.push(entry);
|
||||
else if (!isValidStringValue(type, entry)) result.invalid.push(entry);
|
||||
else if (maxItems != null && existing.length + result.added.length >= maxItems) result.overLimit.push(entry);
|
||||
else {
|
||||
seen.add(key);
|
||||
result.added.push(entry);
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
@@ -0,0 +1,173 @@
|
||||
/*
|
||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
import { MINUTES_PER_DAY, parseLocalTime } from '@/lib/localDateTime';
|
||||
import { isRecord } from '@/lib/embeddedSchema';
|
||||
|
||||
export const WORKING_HOURS_SLOT = 'x:WorkingHoursSlot';
|
||||
|
||||
export const WEEKDAYS = ['monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday'] as const;
|
||||
|
||||
export type Weekday = (typeof WEEKDAYS)[number];
|
||||
|
||||
export type ScheduleRules = 'sameDay' | 'overnight';
|
||||
|
||||
const OVERNIGHT_CONTAINERS: ReadonlySet<string> = new Set(['x:MailRuleSchedule']);
|
||||
|
||||
export function scheduleRules(container: string | null | undefined): ScheduleRules {
|
||||
return container != null && OVERNIGHT_CONTAINERS.has(container) ? 'overnight' : 'sameDay';
|
||||
}
|
||||
|
||||
export interface Slot {
|
||||
days: Weekday[];
|
||||
start: number | null;
|
||||
end: number | null;
|
||||
}
|
||||
|
||||
export type SlotIssue = 'noDays' | 'missingTime' | 'endNotAfterStart' | 'startAtEndOfDay' | 'sameStartEnd';
|
||||
|
||||
const WEEKDAY_INDEX: ReadonlyMap<string, number> = new Map(WEEKDAYS.map((day, index) => [day, index]));
|
||||
|
||||
export function weekdayIndex(day: string): number | undefined {
|
||||
return WEEKDAY_INDEX.get(day);
|
||||
}
|
||||
|
||||
export function parseSlot(value: unknown): Slot {
|
||||
const record = isRecord(value) ? value : {};
|
||||
const set = isRecord(record.days) ? record.days : {};
|
||||
return {
|
||||
days: WEEKDAYS.filter((day) => Object.hasOwn(set, day) && set[day] === true),
|
||||
start: parseLocalTime(record.start),
|
||||
end: parseLocalTime(record.end),
|
||||
};
|
||||
}
|
||||
|
||||
export function slotEntries(value: unknown): [string, unknown][] {
|
||||
return isRecord(value) ? Object.entries(value).sort(([a], [b]) => Number(a) - Number(b)) : [];
|
||||
}
|
||||
|
||||
export function nextSlotKey(entries: readonly [string, unknown][]): string {
|
||||
let max = -1;
|
||||
for (const [key] of entries) max = Math.max(max, Number(key) || 0);
|
||||
return String(max + 1);
|
||||
}
|
||||
|
||||
function effectiveEnd(end: number, rules: ScheduleRules): number {
|
||||
return rules === 'overnight' && end === 0 ? MINUTES_PER_DAY : end;
|
||||
}
|
||||
|
||||
export function slotIssue(slot: Slot, rules: ScheduleRules): SlotIssue | null {
|
||||
if (slot.days.length === 0) return 'noDays';
|
||||
if (slot.start === null || slot.end === null) return 'missingTime';
|
||||
if (rules === 'sameDay') return slot.start < slot.end ? null : 'endNotAfterStart';
|
||||
if (slot.start >= MINUTES_PER_DAY) return 'startAtEndOfDay';
|
||||
return slot.start === effectiveEnd(slot.end, rules) ? 'sameStartEnd' : null;
|
||||
}
|
||||
|
||||
export function isOvernight(slot: Slot, rules: ScheduleRules): boolean {
|
||||
return (
|
||||
rules === 'overnight' && slot.start !== null && slot.end !== null && effectiveEnd(slot.end, rules) < slot.start
|
||||
);
|
||||
}
|
||||
|
||||
export function isScheduleInvalid(value: unknown, rules: ScheduleRules, minItems = 0): boolean {
|
||||
const entries = slotEntries(value);
|
||||
return entries.length < minItems || entries.some(([, item]) => slotIssue(parseSlot(item), rules) !== null);
|
||||
}
|
||||
|
||||
export interface DaySegment {
|
||||
key: string;
|
||||
start: number;
|
||||
end: number;
|
||||
}
|
||||
|
||||
export function daySegments(entries: readonly [string, Slot][], rules: ScheduleRules): DaySegment[][] {
|
||||
const days: DaySegment[][] = WEEKDAYS.map(() => []);
|
||||
for (const [key, slot] of entries) {
|
||||
if (slot.start === null || slot.end === null) continue;
|
||||
const start = slot.start;
|
||||
const end = effectiveEnd(slot.end, rules);
|
||||
const wraps = rules === 'overnight' && end < start;
|
||||
if (!wraps && start >= end) continue;
|
||||
for (const day of slot.days) {
|
||||
const index = WEEKDAY_INDEX.get(day) ?? 0;
|
||||
if (wraps) {
|
||||
days[index].push({ key, start, end: MINUTES_PER_DAY });
|
||||
if (end > 0) days[(index + 1) % WEEKDAYS.length].push({ key, start: 0, end });
|
||||
} else {
|
||||
days[index].push({ key, start, end });
|
||||
}
|
||||
}
|
||||
}
|
||||
return days;
|
||||
}
|
||||
|
||||
export function firstWeekdayOf(locale: string): Weekday {
|
||||
try {
|
||||
const info = new Intl.Locale(locale) as Intl.Locale & {
|
||||
getWeekInfo?: () => { firstDay: number };
|
||||
weekInfo?: { firstDay: number };
|
||||
};
|
||||
const firstDay = info.getWeekInfo?.().firstDay ?? info.weekInfo?.firstDay;
|
||||
return (firstDay !== undefined ? WEEKDAYS[firstDay - 1] : undefined) ?? 'monday';
|
||||
} catch {
|
||||
return 'monday';
|
||||
}
|
||||
}
|
||||
|
||||
export function weekdayOrder(first: Weekday): Weekday[] {
|
||||
const offset = WEEKDAY_INDEX.get(first) ?? 0;
|
||||
return WEEKDAYS.map((_, i) => WEEKDAYS[(i + offset) % WEEKDAYS.length]);
|
||||
}
|
||||
|
||||
export function dayRuns(days: readonly Weekday[], order: readonly Weekday[]): Weekday[][] {
|
||||
const selected = new Set(days);
|
||||
const runs: Weekday[][] = [];
|
||||
let current: Weekday[] = [];
|
||||
for (const day of order) {
|
||||
if (selected.has(day)) {
|
||||
current.push(day);
|
||||
} else if (current.length > 0) {
|
||||
runs.push(current);
|
||||
current = [];
|
||||
}
|
||||
}
|
||||
if (current.length > 0) runs.push(current);
|
||||
return runs;
|
||||
}
|
||||
|
||||
export interface SlotTemplate {
|
||||
days: readonly Weekday[];
|
||||
start: string;
|
||||
end: string;
|
||||
}
|
||||
|
||||
export type PresetName = 'workdays' | 'everyDay' | 'outsideWorkdays';
|
||||
|
||||
const WORKDAYS: readonly Weekday[] = ['monday', 'tuesday', 'wednesday', 'thursday', 'friday'];
|
||||
|
||||
export const PRESETS: Readonly<Record<PresetName, readonly SlotTemplate[]>> = {
|
||||
workdays: [{ days: WORKDAYS, start: '09:00', end: '17:00' }],
|
||||
everyDay: [{ days: WEEKDAYS, start: '09:00', end: '17:00' }],
|
||||
outsideWorkdays: [
|
||||
{ days: WORKDAYS, start: '17:00', end: '09:00' },
|
||||
{ days: ['saturday', 'sunday'], start: '00:00', end: '24:00' },
|
||||
],
|
||||
};
|
||||
|
||||
export function presetsFor(rules: ScheduleRules): PresetName[] {
|
||||
return rules === 'overnight' ? ['workdays', 'everyDay', 'outsideWorkdays'] : ['workdays', 'everyDay'];
|
||||
}
|
||||
|
||||
export function daysValue(days: readonly Weekday[]): Record<string, true> {
|
||||
return Object.fromEntries(days.map((day) => [day, true]));
|
||||
}
|
||||
|
||||
export function slotsValue(templates: readonly SlotTemplate[]): Record<string, Record<string, unknown>> {
|
||||
return Object.fromEntries(
|
||||
templates.map((slot, index) => [String(index), { days: daysValue(slot.days), start: slot.start, end: slot.end }]),
|
||||
);
|
||||
}
|
||||
+19
-10
@@ -4,7 +4,7 @@
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
import { useAuthStore } from '@/stores/authStore';
|
||||
import { useAuthStore, type AuthState } from '@/stores/authStore';
|
||||
import type { Edition } from '@/stores/accountStore';
|
||||
import { apiFetchJson } from '@/services/api';
|
||||
import { JmapMethodError, JmapProtocolError } from '@/services/errors';
|
||||
@@ -19,9 +19,11 @@ import type {
|
||||
} from '@/types/jmap';
|
||||
import type { Schema } from '@/types/schema';
|
||||
|
||||
export const MANAGEMENT_CAPABILITY = 'urn:stalwart:jmap';
|
||||
|
||||
const JMAP_USING = [
|
||||
'urn:ietf:params:jmap:core',
|
||||
'urn:stalwart:jmap',
|
||||
MANAGEMENT_CAPABILITY,
|
||||
'urn:ietf:params:jmap:blob',
|
||||
'urn:ietf:params:jmap:mail',
|
||||
'urn:ietf:params:jmap:calendars',
|
||||
@@ -61,14 +63,21 @@ export interface BlobUpload {
|
||||
type?: string;
|
||||
}
|
||||
|
||||
export function getAccountId(objectType: string): string {
|
||||
const { primaryAccountId, activeAccountId } = useAuthStore.getState();
|
||||
if (objectType.startsWith('x:')) {
|
||||
if (!primaryAccountId) throw new Error('No primary account ID available');
|
||||
return primaryAccountId;
|
||||
export type AccountSelection = Pick<AuthState, 'accounts' | 'primaryAccountId' | 'activeAccountId'>;
|
||||
|
||||
export function resolveAccountId(objectType: string, selection: AccountSelection): string | null {
|
||||
const { accounts, primaryAccountId, activeAccountId } = selection;
|
||||
if (!objectType.startsWith('x:')) return activeAccountId;
|
||||
if (activeAccountId && Object.hasOwn(accounts, activeAccountId) && accounts[activeAccountId].hasManagement) {
|
||||
return activeAccountId;
|
||||
}
|
||||
if (!activeAccountId) throw new Error('No active account ID available');
|
||||
return activeAccountId;
|
||||
return primaryAccountId;
|
||||
}
|
||||
|
||||
export function getAccountId(objectType: string): string {
|
||||
const accountId = resolveAccountId(objectType, useAuthStore.getState());
|
||||
if (!accountId) throw new Error(`No account ID available for ${objectType}`);
|
||||
return accountId;
|
||||
}
|
||||
|
||||
export function jmapApiPath(apiUrl: string | null): string {
|
||||
@@ -300,7 +309,7 @@ export async function fetchBlobText(blobId: string, options: JmapCallOptions = {
|
||||
}
|
||||
|
||||
export interface JmapSession {
|
||||
accounts: Record<string, { name: string; isPersonal: boolean }>;
|
||||
accounts: Record<string, { name: string; isPersonal: boolean; accountCapabilities?: Record<string, unknown> }>;
|
||||
primaryAccounts: Record<string, string>;
|
||||
apiUrl?: string;
|
||||
capabilities?: Record<string, Record<string, unknown>>;
|
||||
|
||||
@@ -7,12 +7,13 @@
|
||||
import { create } from 'zustand';
|
||||
import { persist } from 'zustand/middleware';
|
||||
|
||||
interface AccountInfo {
|
||||
export interface AccountInfo {
|
||||
name: string;
|
||||
isPersonal: boolean;
|
||||
hasManagement: boolean;
|
||||
}
|
||||
|
||||
interface AuthState {
|
||||
export interface AuthState {
|
||||
accessToken: string | null;
|
||||
refreshToken: string | null;
|
||||
tokenExpiresAt: number | null;
|
||||
@@ -175,6 +176,12 @@ export const useAuthStore = create<AuthState>()(
|
||||
),
|
||||
);
|
||||
|
||||
export function selectActiveAccountIsPersonal(state: AuthState): boolean {
|
||||
const { accounts, activeAccountId } = state;
|
||||
if (!activeAccountId || !Object.hasOwn(accounts, activeAccountId)) return true;
|
||||
return accounts[activeAccountId].isPersonal;
|
||||
}
|
||||
|
||||
export function applyAccessTokenOverride(): void {
|
||||
const token = import.meta.env.VITE_ACCESS_TOKEN as string | undefined;
|
||||
if (!token) return;
|
||||
|
||||
+4
-1
@@ -220,7 +220,9 @@ export type StringFormat =
|
||||
| 'color'
|
||||
| 'text'
|
||||
| 'html'
|
||||
| 'sieve';
|
||||
| 'sieve'
|
||||
| 'localTime'
|
||||
| 'localDate';
|
||||
|
||||
export type NumberFormat = 'integer' | 'unsignedInteger' | 'float' | 'size' | 'duration';
|
||||
|
||||
@@ -229,6 +231,7 @@ export interface EnumVariant {
|
||||
label: string;
|
||||
explanation?: string;
|
||||
color?: string;
|
||||
valueFormat?: NumberFormat;
|
||||
}
|
||||
|
||||
export interface List {
|
||||
|
||||
Reference in new issue
Block a user