mirror of
https://github.com/stalwartlabs/webui.git
synced 2026-12-06 16:04:38 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
51f47f0f81 | ||
|
|
64bebee21a | ||
|
|
337437bf31 | ||
|
|
a692e8a270 | ||
|
|
2ca40e9559 | ||
|
|
1a595c2121 | ||
|
|
6b8ad61b57 | ||
|
|
0e31addbbb | ||
|
|
e777b81fb8 | ||
|
|
44b3f914c6 | ||
|
|
03954f8052 |
No files matched your search
@@ -2,6 +2,68 @@
|
||||
|
||||
All notable changes to this project will be documented in this file. This project adheres to [Semantic Versioning](http://semver.org/).
|
||||
|
||||
## [2.1.2] - 2026-11-29
|
||||
|
||||
### Fixed
|
||||
- Sign-in no longer sends `prompt=login`, so an existing single sign-on session at an external OpenID Connect provider is reused instead of asking for the login again.
|
||||
- Calendars, address books and mailboxes that still hold events, contacts or messages can be deleted. The delete confirmation says that their contents are deleted with them.
|
||||
- Dashboard:
|
||||
- Counter charts drop to zero in empty intervals instead of repeating the last value, so a short burst (for example the morning DMARC and TLS reports) no longer shows as hours of steady activity.
|
||||
- Pass, ham and other good series are drawn in teal and fail or spam in red, instead of the reverse.
|
||||
- Mail Rules editor: alternatives and exceptions keep their place. Adding an exception no longer moves the "Add alternative" button below it, and the add buttons are evenly spaced.
|
||||
|
||||
## [2.1.1] - 2026-11-23
|
||||
|
||||
### Added
|
||||
- Mail Rules editor: rules that apply only while the vacation response is in effect, stop-only rules, and replies sent to every message.
|
||||
|
||||
### Changed
|
||||
- Mail Rules editor follows the new rule format: conditions that must all match, alternatives of which at least one must match, and exceptions, each explained in plain words.
|
||||
- Rule page with a summary of what the rule does, a Conditions step and an Actions step. Each action appears at most once, as a card added from grouped buttons.
|
||||
- Trash and Junk are ordinary move and copy targets, and read, flagged and not spam are shown by name instead of as keywords.
|
||||
- The rule summary is fully translatable: whole-sentence templates, plural forms and lists joined for the user's locale.
|
||||
|
||||
## [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
|
||||
- OIDC sign-in keeps a query already present in the provider's `authorization_endpoint` (for example Casdoor's `?organization=`) and appends its own parameters with `&`.
|
||||
- Clicking or hovering a list row in Safari now targets that row instead of the last row of the table.
|
||||
|
||||
## [2.0.5] - 2026-11-05
|
||||
|
||||
### Added
|
||||
- Passkey registration under Account > Credentials.
|
||||
|
||||
### Changed
|
||||
|
||||
### Fixed
|
||||
- Dates and numbers are formatted with the account locale, or the browser's preferred language when the account uses the default, instead of always en-US.
|
||||
- The last setup screen no longer tells users to sign in with credentials that were never created when an external directory is used.
|
||||
|
||||
## [2.0.4] - 2026-11-02
|
||||
|
||||
### Added
|
||||
|
||||
Generated
+58
-2
@@ -1,14 +1,17 @@
|
||||
{
|
||||
"name": "stalwart-webui",
|
||||
"version": "2.0.4",
|
||||
"version": "2.1.2",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "stalwart-webui",
|
||||
"version": "2.0.4",
|
||||
"version": "2.1.2",
|
||||
"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",
|
||||
|
||||
+4
-1
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "stalwart-webui",
|
||||
"private": true,
|
||||
"version": "2.0.4",
|
||||
"version": "2.1.2",
|
||||
"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",
|
||||
|
||||
@@ -104,10 +104,15 @@ export function SuccessScreen({
|
||||
<div className="rounded-xl bg-info-soft p-4 text-info">
|
||||
<p className="text-sm">
|
||||
<span className="font-medium">{t('bootstrap.nextStepLabel', 'Next step:')}</span>{' '}
|
||||
{t(
|
||||
'bootstrap.nextStepBody',
|
||||
'restart Stalwart for the new configuration to take effect. Once restarted, sign in with the credentials above to continue administering your server.',
|
||||
)}
|
||||
{hasCredentials
|
||||
? t(
|
||||
'bootstrap.nextStepBody',
|
||||
'restart Stalwart for the new configuration to take effect. Once restarted, sign in with the credentials above to continue administering your server.',
|
||||
)
|
||||
: t(
|
||||
'bootstrap.nextStepBodyNoCredentials',
|
||||
'restart Stalwart for the new configuration to take effect. No administrator account was created because accounts come from the external directory. Once restarted, sign in with the recovery administrator set in STALWART_RECOVERY_ADMIN and assign an administrator role to a directory account.',
|
||||
)}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -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,22 @@ 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 { withDestroyContentsNotice } from '@/lib/destroyContents';
|
||||
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 +139,20 @@ function Loading({ label }: { label: string }) {
|
||||
);
|
||||
}
|
||||
|
||||
export function DynamicForm({ viewName, objectId }: DynamicFormProps) {
|
||||
export function DynamicForm({
|
||||
viewName,
|
||||
objectId,
|
||||
accountId,
|
||||
fieldOverrides,
|
||||
createValues,
|
||||
showCreatedValues,
|
||||
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, showCreatedValues });
|
||||
const { schema, resolved, mode, isSingleton, state, isDirty, saving, loading, loadError } = model;
|
||||
const [deleteConfirmOpen, setDeleteConfirmOpen] = useState(false);
|
||||
const title = useFormTitle(model);
|
||||
@@ -223,12 +238,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>
|
||||
@@ -283,10 +300,11 @@ export function DynamicForm({ viewName, objectId }: DynamicFormProps) {
|
||||
onOpenChange={setDeleteConfirmOpen}
|
||||
variant="destructive"
|
||||
title={t('form.deleteTitle', 'Delete {{name}}?', { name: capitalize(deleteLabel) })}
|
||||
description={t(
|
||||
'form.deleteDescription',
|
||||
'This action cannot be undone. This will permanently delete this {{name}}.',
|
||||
{ name: deleteLabel },
|
||||
description={withDestroyContentsNotice(
|
||||
t('form.deleteDescription', 'This action cannot be undone. This will permanently delete this {{name}}.', {
|
||||
name: deleteLabel,
|
||||
}),
|
||||
resolved.object.objectName,
|
||||
)}
|
||||
confirmLabel={t('common.delete', 'Delete')}
|
||||
onConfirm={model.remove}
|
||||
|
||||
@@ -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,9 +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 { 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>;
|
||||
@@ -67,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;
|
||||
}
|
||||
@@ -152,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);
|
||||
}
|
||||
@@ -201,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;
|
||||
@@ -227,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) {
|
||||
@@ -296,12 +461,20 @@ export interface RenderableSection {
|
||||
fields: RenderableField[];
|
||||
}
|
||||
|
||||
export function buildSections(form: Form | null, fields: Fields | null, mode: FormMode): RenderableSection[] {
|
||||
const visible = (field: Field) => !(mode === 'create' && field.update === 'serverSet');
|
||||
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 }] : [];
|
||||
}
|
||||
@@ -313,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 });
|
||||
}
|
||||
@@ -321,6 +495,18 @@ export function buildSections(form: Form | null, fields: Fields | null, mode: Fo
|
||||
return sections;
|
||||
}
|
||||
|
||||
export function withoutSectionTitles(
|
||||
sections: RenderableSection[],
|
||||
fieldNames: readonly string[] | undefined,
|
||||
): RenderableSection[] {
|
||||
if (!fieldNames || fieldNames.length === 0) return sections;
|
||||
return sections.map((section) =>
|
||||
section.title && section.fields.some(({ formField }) => fieldNames.includes(formField.name))
|
||||
? { ...section, title: undefined }
|
||||
: section,
|
||||
);
|
||||
}
|
||||
|
||||
export function collectFetchProperties(schema: Schema, view: ResolvedView, viewName: string): string[] {
|
||||
const { object, resolvedSchema } = view;
|
||||
const names = new Set<string>(['id']);
|
||||
|
||||
@@ -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,32 @@ import {
|
||||
formFieldNames,
|
||||
isOtpAuthValid,
|
||||
mapSetError,
|
||||
mergeFieldErrors,
|
||||
validateFormat,
|
||||
validateRequired,
|
||||
validatedFieldNames,
|
||||
VARIANT_FIELD,
|
||||
withoutSectionTitles,
|
||||
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 +75,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 +92,34 @@ 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[];
|
||||
untitled?: readonly string[];
|
||||
render?: Readonly<Record<string, ComponentType<FieldRenderProps>>>;
|
||||
validate?: (data: FieldValues) => FieldErrors;
|
||||
}
|
||||
|
||||
export interface DynamicFormOptions {
|
||||
accountId?: string;
|
||||
fieldOverrides?: FieldOverrides;
|
||||
createValues?: FieldValues;
|
||||
showCreatedValues?: boolean;
|
||||
}
|
||||
|
||||
export function useDynamicForm(
|
||||
viewName: string,
|
||||
objectId: string | null,
|
||||
{ accountId, fieldOverrides, createValues, showCreatedValues = true }: DynamicFormOptions = {},
|
||||
) {
|
||||
const { t } = useTranslation();
|
||||
const navigate = useNavigate();
|
||||
const schema = useSchemaStore((s) => s.schema);
|
||||
@@ -86,14 +130,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 +147,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 +184,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 = withoutSectionTitles(buildSections(form, fields, mode, hidden), fieldOverrides?.untitled);
|
||||
|
||||
const loading = mode === 'edit' && objectQuery.fetchStatus !== 'idle' && !objectQuery.isFetchedAfterMount;
|
||||
const loadError =
|
||||
@@ -165,7 +210,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 +230,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 +245,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,14 +300,14 @@ 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 = {};
|
||||
for (const [key, value] of Object.entries(created)) {
|
||||
if (!NOISY_CREATED_KEYS.has(key)) extras[key] = value;
|
||||
}
|
||||
if (Object.keys(extras).length > 0) {
|
||||
if (showCreatedValues && Object.keys(extras).length > 0) {
|
||||
dispatch({ type: 'created', result: { id: String(created.id), values: extras } });
|
||||
} else {
|
||||
toast({ title: t('form.createdSuccess', 'Created successfully'), variant: 'success' });
|
||||
@@ -263,7 +329,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 +348,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,92 +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 })),
|
||||
);
|
||||
|
||||
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 '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';
|
||||
|
||||
@@ -0,0 +1,251 @@
|
||||
/*
|
||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
import { useEffect, useId, useState, type KeyboardEvent } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { FingerprintPattern, Loader2, ShieldCheck } from 'lucide-react';
|
||||
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { useFormContext } from '@/components/forms/formContext';
|
||||
import { getAccountId, jmapCall, jmapGetOne } from '@/services/jmap/client';
|
||||
import { JmapMethodError } from '@/services/errors';
|
||||
import type { WidgetProps } from '@/components/forms/widgets/types';
|
||||
import type { FieldTypeObject } from '@/types/schema';
|
||||
|
||||
interface PasskeyRegistrationValue {
|
||||
clientDataJson?: string;
|
||||
attestationObject?: string;
|
||||
}
|
||||
|
||||
interface CredentialDescriptorJson {
|
||||
type: 'public-key';
|
||||
id: string;
|
||||
}
|
||||
|
||||
interface CreationOptionsJson {
|
||||
rp: { id: string; name: string };
|
||||
user: { id: string; name: string; displayName: string };
|
||||
challenge: string;
|
||||
pubKeyCredParams: { type: 'public-key'; alg: number }[];
|
||||
timeout: number;
|
||||
excludeCredentials: CredentialDescriptorJson[];
|
||||
authenticatorSelection: AuthenticatorSelectionCriteria;
|
||||
attestation: AttestationConveyancePreference;
|
||||
}
|
||||
|
||||
interface RegistrationOptionsResponse {
|
||||
accountId: string;
|
||||
publicKey: CreationOptionsJson;
|
||||
}
|
||||
|
||||
type PublicKeyCredentialStatic = {
|
||||
parseCreationOptionsFromJSON?: (options: CreationOptionsJson) => PublicKeyCredentialCreationOptions;
|
||||
};
|
||||
|
||||
function toBase64Url(buffer: ArrayBuffer): string {
|
||||
const bytes = new Uint8Array(buffer);
|
||||
let binary = '';
|
||||
for (const byte of bytes) binary += String.fromCharCode(byte);
|
||||
return btoa(binary).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
|
||||
}
|
||||
|
||||
function fromBase64Url(value: string): Uint8Array<ArrayBuffer> {
|
||||
let base64 = value.replace(/-/g, '+').replace(/_/g, '/');
|
||||
while (base64.length % 4) base64 += '=';
|
||||
const binary = atob(base64);
|
||||
const bytes = new Uint8Array(binary.length);
|
||||
for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
|
||||
return bytes;
|
||||
}
|
||||
|
||||
function parseCreationOptions(options: CreationOptionsJson): PublicKeyCredentialCreationOptions {
|
||||
const parse = (window.PublicKeyCredential as unknown as PublicKeyCredentialStatic).parseCreationOptionsFromJSON;
|
||||
if (typeof parse === 'function') return parse(options);
|
||||
return {
|
||||
rp: options.rp,
|
||||
user: { ...options.user, id: fromBase64Url(options.user.id) },
|
||||
challenge: fromBase64Url(options.challenge),
|
||||
pubKeyCredParams: options.pubKeyCredParams,
|
||||
timeout: options.timeout,
|
||||
excludeCredentials: options.excludeCredentials.map((credential) => ({
|
||||
type: credential.type,
|
||||
id: fromBase64Url(credential.id),
|
||||
})),
|
||||
authenticatorSelection: options.authenticatorSelection,
|
||||
attestation: options.attestation,
|
||||
};
|
||||
}
|
||||
|
||||
function isPasskeySupported(): boolean {
|
||||
return typeof window !== 'undefined' && !!window.PublicKeyCredential && !!navigator.credentials?.create;
|
||||
}
|
||||
|
||||
function isRegistered(value: unknown): boolean {
|
||||
const registration = value as PasskeyRegistrationValue | null | undefined;
|
||||
return !!registration?.clientDataJson && !!registration.attestationObject;
|
||||
}
|
||||
|
||||
export function PasskeyRegistrationField({ value, onChange, readOnly }: WidgetProps<FieldTypeObject>) {
|
||||
const { t } = useTranslation();
|
||||
const { mode } = useFormContext();
|
||||
const secretId = useId();
|
||||
const otpId = useId();
|
||||
const [currentSecret, setCurrentSecret] = useState('');
|
||||
const [otpCode, setOtpCode] = useState('');
|
||||
const [otpRequired, setOtpRequired] = useState(false);
|
||||
const [waiting, setWaiting] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const isActive = mode === 'create' && !readOnly;
|
||||
|
||||
useEffect(() => {
|
||||
if (!isActive) return;
|
||||
const controller = new AbortController();
|
||||
jmapGetOne('x:AccountPassword', 'singleton', undefined, { signal: controller.signal })
|
||||
.then((password) => {
|
||||
const otpAuth = password?.otpAuth as { otpUrl?: string | null } | undefined;
|
||||
setOtpRequired(!!otpAuth?.otpUrl);
|
||||
})
|
||||
.catch(() => {
|
||||
if (!controller.signal.aborted) setOtpRequired(true);
|
||||
});
|
||||
return () => controller.abort();
|
||||
}, [isActive]);
|
||||
|
||||
if (!isActive) return null;
|
||||
|
||||
if (!isPasskeySupported()) {
|
||||
return (
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{t('passkey.unsupported', 'This browser does not support passkeys.')}
|
||||
</p>
|
||||
);
|
||||
}
|
||||
|
||||
if (isRegistered(value)) {
|
||||
return (
|
||||
<div className="flex items-center gap-2 rounded-xl bg-muted p-4 text-sm">
|
||||
<ShieldCheck className="h-4 w-4 shrink-0" aria-hidden="true" />
|
||||
<span className="flex-1">{t('passkey.ready', 'Passkey created. Save to add it to your account.')}</span>
|
||||
<Button type="button" variant="ghost" size="sm" onClick={() => onChange(null)}>
|
||||
{t('passkey.createAgain', 'Create again')}
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const createPasskey = async () => {
|
||||
setError(null);
|
||||
if (!currentSecret) {
|
||||
setError(t('passkey.secretRequired', 'Enter your current password to create a passkey.'));
|
||||
return;
|
||||
}
|
||||
const code = otpCode.trim();
|
||||
if (otpRequired && !code) {
|
||||
setError(t('passkey.otpRequired', 'Enter your current authenticator code to create a passkey.'));
|
||||
return;
|
||||
}
|
||||
|
||||
setWaiting(true);
|
||||
try {
|
||||
const options = await jmapCall<RegistrationOptionsResponse>('x:Passkey/registrationOptions', {
|
||||
accountId: getAccountId('x:Passkey'),
|
||||
currentSecret,
|
||||
...(code ? { otpCode: code } : {}),
|
||||
});
|
||||
const credential = await navigator.credentials.create({ publicKey: parseCreationOptions(options.publicKey) });
|
||||
if (!(credential instanceof PublicKeyCredential)) throw new Error('No passkey was returned');
|
||||
const response = credential.response as AuthenticatorAttestationResponse;
|
||||
setCurrentSecret('');
|
||||
setOtpCode('');
|
||||
onChange({
|
||||
clientDataJson: toBase64Url(response.clientDataJSON),
|
||||
attestationObject: toBase64Url(response.attestationObject),
|
||||
});
|
||||
} catch (err) {
|
||||
if (err instanceof DOMException && (err.name === 'NotAllowedError' || err.name === 'AbortError')) return;
|
||||
if (err instanceof DOMException && err.name === 'InvalidStateError') {
|
||||
setError(t('passkey.alreadyRegistered', 'This device already holds a passkey for your account.'));
|
||||
} else if (err instanceof JmapMethodError && err.description) {
|
||||
setError(err.description);
|
||||
} else {
|
||||
console.error('Passkey registration failed', err);
|
||||
setError(t('passkey.createFailed', 'The passkey could not be created. Please try again.'));
|
||||
}
|
||||
} finally {
|
||||
setWaiting(false);
|
||||
}
|
||||
};
|
||||
|
||||
const submitOnEnter = (e: KeyboardEvent<HTMLInputElement>) => {
|
||||
if (e.key === 'Enter') {
|
||||
e.preventDefault();
|
||||
if (!waiting) void createPasskey();
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-4 rounded-xl bg-muted p-4">
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{t(
|
||||
'passkey.createPrompt',
|
||||
'Confirm your password, then follow the prompt from your browser to create a passkey on this device or a security key.',
|
||||
)}
|
||||
</p>
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor={secretId} className="text-sm font-medium">
|
||||
{t('passkey.currentSecretLabel', 'Current password')}
|
||||
</Label>
|
||||
<Input
|
||||
id={secretId}
|
||||
type="password"
|
||||
autoComplete="current-password"
|
||||
value={currentSecret}
|
||||
onChange={(e) => setCurrentSecret(e.target.value)}
|
||||
onKeyDown={submitOnEnter}
|
||||
disabled={waiting}
|
||||
className="max-w-sm"
|
||||
/>
|
||||
</div>
|
||||
{otpRequired && (
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor={otpId} className="text-sm font-medium">
|
||||
{t('otp.currentCodeLabel', 'Current code')}
|
||||
</Label>
|
||||
<Input
|
||||
id={otpId}
|
||||
type="text"
|
||||
inputMode="numeric"
|
||||
autoComplete="one-time-code"
|
||||
placeholder="123456"
|
||||
value={otpCode}
|
||||
onChange={(e) => setOtpCode(e.target.value.replace(/\s+/g, ''))}
|
||||
onKeyDown={submitOnEnter}
|
||||
disabled={waiting}
|
||||
maxLength={10}
|
||||
className="font-mono tracking-widest text-center max-w-[12rem]"
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
{error && (
|
||||
<p className="text-sm text-destructive" role="alert">
|
||||
{error}
|
||||
</p>
|
||||
)}
|
||||
<div className="flex items-center justify-end">
|
||||
<Button type="button" size="sm" onClick={() => void createPasskey()} disabled={waiting}>
|
||||
{waiting ? (
|
||||
<Loader2 className="animate-spin" aria-hidden="true" />
|
||||
) : (
|
||||
<FingerprintPattern aria-hidden="true" />
|
||||
)}
|
||||
{waiting ? t('passkey.waiting', 'Waiting for your passkey') : t('passkey.create', 'Create passkey')}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -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,112 +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;
|
||||
}
|
||||
|
||||
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'
|
||||
| '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';
|
||||
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' },
|
||||
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} />;
|
||||
}
|
||||
@@ -14,6 +14,7 @@ import { ConfirmDialog } from '@/components/common/ConfirmDialog';
|
||||
import { EnterpriseUpsell } from '@/components/common/EnterpriseUpsell';
|
||||
import { useIsCommunity, usePermissionCheckers } from '@/hooks/usePermissions';
|
||||
import { useResolvedView } from '@/hooks/useResolvedView';
|
||||
import { withDestroyContentsNotice } from '@/lib/destroyContents';
|
||||
import { layoutViewFor } from '@/lib/layout';
|
||||
import { canAccessView } from '@/lib/permissions';
|
||||
import { getDisplayProperty } from '@/lib/schemaResolver';
|
||||
@@ -128,20 +129,23 @@ function DynamicListView({ viewName, schema, resolved, list }: DynamicListViewPr
|
||||
title: allMatching
|
||||
? t('list.deleteAllMatchingTitle', 'Delete all matching {{name}}', { name: list.pluralName })
|
||||
: t('list.deleteManyTitle', 'Delete {{count}} {{name}}', { count, name }),
|
||||
description: allMatching
|
||||
? t(
|
||||
'list.deleteAllMatchingDescription',
|
||||
'Are you sure you want to delete ALL {{name}} matching the current filters? This action cannot be undone.',
|
||||
{ name: list.pluralName },
|
||||
)
|
||||
: t(
|
||||
'list.deleteManyDescription',
|
||||
'Are you sure you want to delete {{count}} {{name}}? This action cannot be undone.',
|
||||
{
|
||||
count,
|
||||
name,
|
||||
},
|
||||
),
|
||||
description: withDestroyContentsNotice(
|
||||
allMatching
|
||||
? t(
|
||||
'list.deleteAllMatchingDescription',
|
||||
'Are you sure you want to delete ALL {{name}} matching the current filters? This action cannot be undone.',
|
||||
{ name: list.pluralName },
|
||||
)
|
||||
: t(
|
||||
'list.deleteManyDescription',
|
||||
'Are you sure you want to delete {{count}} {{name}}? This action cannot be undone.',
|
||||
{
|
||||
count,
|
||||
name,
|
||||
},
|
||||
),
|
||||
objectName,
|
||||
),
|
||||
confirmLabel: t('list.deleteAll', 'Delete all'),
|
||||
destructive: true,
|
||||
onConfirm: run,
|
||||
@@ -170,10 +174,11 @@ function DynamicListView({ viewName, schema, resolved, list }: DynamicListViewPr
|
||||
if (action.type === 'delete') {
|
||||
setConfirm({
|
||||
title: t('list.deleteItemTitle', 'Delete {{name}}?', { name: list.singularName }),
|
||||
description: t(
|
||||
'list.deleteItemDescription',
|
||||
'Are you sure you want to delete {{label}}? This action cannot be undone.',
|
||||
{ label },
|
||||
description: withDestroyContentsNotice(
|
||||
t('list.deleteItemDescription', 'Are you sure you want to delete {{label}}? This action cannot be undone.', {
|
||||
label,
|
||||
}),
|
||||
objectName,
|
||||
),
|
||||
confirmLabel: t('list.delete', 'Delete'),
|
||||
destructive: true,
|
||||
|
||||
@@ -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>
|
||||
);
|
||||
|
||||
@@ -4,8 +4,8 @@
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
import type { ReactNode } from 'react';
|
||||
import { Link } from 'react-router-dom';
|
||||
import type { MouseEvent, ReactNode } from 'react';
|
||||
import { Link, useNavigate } from 'react-router-dom';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
import { Checkbox } from '@/components/ui/checkbox';
|
||||
@@ -39,8 +39,26 @@ interface ListTableProps {
|
||||
|
||||
const BODY_CELL = 'px-3.5 py-2.5 first:pl-5 last:pr-5 align-middle';
|
||||
|
||||
const STRETCHED_LINK =
|
||||
"font-semibold text-foreground hover:underline focus-visible:outline-none after:absolute after:inset-0 after:content-[''] focus-visible:after:ring-2 focus-visible:after:ring-inset focus-visible:after:ring-ring";
|
||||
const ROW_LINK =
|
||||
'rounded-sm font-semibold text-foreground hover:underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring';
|
||||
|
||||
const INTERACTIVE = 'a, button, input, label, select, textarea, [role="checkbox"], [data-row-controls]';
|
||||
|
||||
function isRowClick(event: MouseEvent<HTMLTableRowElement>): boolean {
|
||||
const target = event.target;
|
||||
return (
|
||||
event.button === 0 &&
|
||||
!event.defaultPrevented &&
|
||||
!event.metaKey &&
|
||||
!event.ctrlKey &&
|
||||
!event.shiftKey &&
|
||||
!event.altKey &&
|
||||
target instanceof Element &&
|
||||
event.currentTarget.contains(target) &&
|
||||
target.closest(INTERACTIVE) === null &&
|
||||
window.getSelection()?.isCollapsed !== false
|
||||
);
|
||||
}
|
||||
|
||||
export function ListTable({
|
||||
caption,
|
||||
@@ -60,6 +78,7 @@ export function ListTable({
|
||||
busy,
|
||||
}: ListTableProps) {
|
||||
const { t } = useTranslation();
|
||||
const navigate = useNavigate();
|
||||
const colSpan = columns.length + (selection ? 1 : 0) + (renderRowActions ? 1 : 0);
|
||||
const rows = items.flatMap((item) => {
|
||||
const id = itemId(item);
|
||||
@@ -111,12 +130,20 @@ export function ListTable({
|
||||
<tr
|
||||
key={id}
|
||||
className={cn(
|
||||
'relative border-t border-border transition-colors duration-150',
|
||||
'border-t border-border transition-colors duration-150',
|
||||
href && 'cursor-pointer',
|
||||
selection?.isSelected(id) ? 'bg-highlight/70' : 'hover:bg-muted/55',
|
||||
)}
|
||||
onClick={
|
||||
href
|
||||
? (event) => {
|
||||
if (isRowClick(event)) void navigate(href);
|
||||
}
|
||||
: undefined
|
||||
}
|
||||
>
|
||||
{selection && (
|
||||
<td className="relative z-10 w-10 py-2.5 pl-5 pr-2 align-middle">
|
||||
<td data-row-controls className="w-10 py-2.5 pl-5 pr-2 align-middle">
|
||||
<Checkbox
|
||||
checked={selection.isSelected(id)}
|
||||
onCheckedChange={() => selection.toggle(id)}
|
||||
@@ -139,11 +166,7 @@ export function ListTable({
|
||||
return (
|
||||
<th key={col.name} scope="row" className={cn(BODY_CELL, 'text-left font-normal')}>
|
||||
{href ? (
|
||||
<Link
|
||||
to={href}
|
||||
className={STRETCHED_LINK}
|
||||
aria-label={isEmptyValue(value) ? label : undefined}
|
||||
>
|
||||
<Link to={href} className={ROW_LINK} aria-label={isEmptyValue(value) ? label : undefined}>
|
||||
{content}
|
||||
</Link>
|
||||
) : (
|
||||
@@ -159,7 +182,7 @@ export function ListTable({
|
||||
);
|
||||
})}
|
||||
{renderRowActions && (
|
||||
<td className="relative z-10 py-1.5 pl-2 pr-3 text-right align-middle">
|
||||
<td data-row-controls className="py-1.5 pl-2 pr-3 text-right align-middle">
|
||||
{renderRowActions(item, id, label)}
|
||||
</td>
|
||||
)}
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
@@ -13,7 +13,7 @@ import { HelpTooltip } from '@/components/common/HelpTooltip';
|
||||
import { ChartTooltipContent, getChartColor } from '@/components/ui/chart';
|
||||
import type { Chart as ChartSchema, Placement } from '../types/schema';
|
||||
import type { Metric, Period } from '../types/metrics';
|
||||
import { bucketTimestamps, bucketValues, getBucketCount, formatTimeTick, formatValue } from '../helpers';
|
||||
import { bucketTimestamps, chartBucketValues, getBucketCount, formatTimeTick, formatValue } from '../helpers';
|
||||
import { ChartSizedContainer } from './ChartSizedContainer';
|
||||
import { toneClasses } from './tone';
|
||||
import { cn } from '@/lib/utils';
|
||||
@@ -33,10 +33,12 @@ export function DashboardChart({ chart, historySamples, historyWindow, period, c
|
||||
const valueFormat = chart.valueFormat ?? 'number';
|
||||
|
||||
const data = useMemo(() => {
|
||||
const seriesValues = chart.series.map((series) => bucketValues(series, historySamples, from, to, bucketCount));
|
||||
const seriesValues = chart.series.map((series) =>
|
||||
chartBucketValues(series, historySamples, from, to, bucketCount, chart.stacked ?? false),
|
||||
);
|
||||
const timestamps = bucketTimestamps(from, to, bucketCount);
|
||||
|
||||
const points = timestamps.map((ts, i) => {
|
||||
return timestamps.map((ts, i) => {
|
||||
const point: Record<string, unknown> = {
|
||||
time: ts.getTime(),
|
||||
timeLabel: formatTimeTick(ts, period),
|
||||
@@ -46,22 +48,6 @@ export function DashboardChart({ chart, historySamples, historyWindow, period, c
|
||||
});
|
||||
return point;
|
||||
});
|
||||
|
||||
if (chart.stacked) {
|
||||
const lastSeen: Record<string, number> = {};
|
||||
for (const point of points) {
|
||||
for (const series of chart.series) {
|
||||
const v = point[series.label];
|
||||
if (typeof v === 'number') {
|
||||
lastSeen[series.label] = v;
|
||||
} else {
|
||||
point[series.label] = lastSeen[series.label] ?? 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return points;
|
||||
}, [historySamples, from, to, bucketCount, chart.series, chart.stacked, period]);
|
||||
|
||||
const tickFormatter = (value: number) => formatValue(value, valueFormat);
|
||||
|
||||
@@ -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} />;
|
||||
}
|
||||
@@ -249,6 +249,29 @@ export function bucketValues(
|
||||
});
|
||||
}
|
||||
|
||||
export function chartBucketValues(
|
||||
target: MetricTarget,
|
||||
samples: Metric[],
|
||||
from: Date,
|
||||
to: Date,
|
||||
bucketCount: number,
|
||||
stacked: boolean,
|
||||
): (number | null)[] {
|
||||
const values = bucketValues(target, samples, from, to, bucketCount);
|
||||
const index = indexSamples(samples);
|
||||
const kind = target.metrics.map((id) => index.get(id)?.[0]).find((m) => m !== undefined)?.['@type'];
|
||||
if (kind === 'Gauge') {
|
||||
if (!stacked) return values;
|
||||
let lastSeen = 0;
|
||||
return values.map((v) => {
|
||||
if (v !== null) lastSeen = v;
|
||||
return lastSeen;
|
||||
});
|
||||
}
|
||||
if (kind === 'Histogram' && !stacked) return values;
|
||||
return values.map((v) => v ?? 0);
|
||||
}
|
||||
|
||||
export function cardValue(card: Card, samples: Metric[]): number {
|
||||
return reduceSamples(card, selectSamples(card, samples)) ?? 0;
|
||||
}
|
||||
|
||||
@@ -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,118 @@
|
||||
/*
|
||||
* 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';
|
||||
import { FLAG_ACTIONS, setValues, type FlagAction, type KeywordSet } from './model';
|
||||
|
||||
export type ListItems = Record<string, Record<string, unknown>>;
|
||||
|
||||
export const KEYWORDS_FIELD = 'keywords';
|
||||
export const KEYWORD_TEST_SCHEMA = 'x:MailRuleKeywordTest';
|
||||
|
||||
const TIME_ZONE_ENUM = 'TimeZone';
|
||||
|
||||
export function toSet(keys: readonly string[]): Record<string, true> {
|
||||
return Object.fromEntries(keys.map((key) => [key, true]));
|
||||
}
|
||||
|
||||
const IMAP_FLAG_PREFIX = '\\';
|
||||
const JMAP_KEYWORD_PREFIX = '$';
|
||||
|
||||
const SYSTEM_KEYWORD_NAMES: ReadonlySet<string> = new Set([
|
||||
'seen',
|
||||
'draft',
|
||||
'flagged',
|
||||
'answered',
|
||||
'recent',
|
||||
'important',
|
||||
'phishing',
|
||||
'junk',
|
||||
'notjunk',
|
||||
'deleted',
|
||||
'forwarded',
|
||||
'mdnsent',
|
||||
'autosent',
|
||||
'canunsubscribe',
|
||||
'followed',
|
||||
'hasattachment',
|
||||
'hasmemo',
|
||||
'hasnoattachment',
|
||||
'imported',
|
||||
'istrusted',
|
||||
'mailflagbit0',
|
||||
'mailflagbit1',
|
||||
'mailflagbit2',
|
||||
'maskedemail',
|
||||
'memo',
|
||||
'muted',
|
||||
'new',
|
||||
'notify',
|
||||
'unsubscribed',
|
||||
]);
|
||||
|
||||
export function canonicalKeyword(typed: string): string {
|
||||
const keyword = typed.toLowerCase();
|
||||
if (!keyword.startsWith(IMAP_FLAG_PREFIX)) return keyword;
|
||||
const name = keyword.slice(IMAP_FLAG_PREFIX.length);
|
||||
return SYSTEM_KEYWORD_NAMES.has(name) ? `${JMAP_KEYWORD_PREFIX}${name}` : keyword;
|
||||
}
|
||||
|
||||
export function editKeywords(value: unknown, shown: readonly string[], next: readonly string[]): Record<string, true> {
|
||||
const before = new Set(shown);
|
||||
const after = new Set(next);
|
||||
const kept = setValues(value).filter((keyword) => !before.has(keyword) || after.has(keyword));
|
||||
const added = next.filter((keyword) => !before.has(keyword)).map(canonicalKeyword);
|
||||
return toSet([...kept, ...added]);
|
||||
}
|
||||
|
||||
export function setFlag(actions: Record<string, unknown>, flag: FlagAction, on: boolean): Record<string, unknown> {
|
||||
const { set, keyword } = FLAG_ACTIONS[flag];
|
||||
const opposite: KeywordSet = set === 'addKeywords' ? 'removeKeywords' : 'addKeywords';
|
||||
const others = setValues(actions[set]).filter((key) => key !== keyword);
|
||||
const next = { ...actions, [set]: toSet(on ? [...others, keyword] : others) };
|
||||
const conflicting = setValues(actions[opposite]);
|
||||
if (!on || !conflicting.includes(keyword)) return next;
|
||||
return { ...next, [opposite]: toSet(conflicting.filter((key) => key !== keyword)) };
|
||||
}
|
||||
|
||||
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':
|
||||
return type.enumName !== TIME_ZONE_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,535 @@
|
||||
/*
|
||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
import { useId, useState, type ComponentType, type ReactNode } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import type { TFunction } from 'i18next';
|
||||
import { Plus, Trash2 } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Switch } from '@/components/ui/switch';
|
||||
import { FieldRow, type FieldRowProps } from '@/components/forms/FieldRow';
|
||||
import { FieldScopeProvider } from '@/components/forms/FormProvider';
|
||||
import { useFormContext } from '@/components/forms/formContext';
|
||||
import { missingNestedFields } from '@/components/forms/formLogic';
|
||||
import { embeddedEntries, isRecord, resolveEmbedded } from '@/lib/embeddedSchema';
|
||||
import { buildNewObjectValue } from '@/lib/schemaResolver';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { FieldControl } from '@/components/forms/widgets/FieldControl';
|
||||
import type { WidgetProps } from '@/components/forms/widgets/types';
|
||||
import type { FieldType } from '@/types/schema';
|
||||
import { editKeywords, setFlag, toSet } from '../builder';
|
||||
import {
|
||||
FLAG_ACTIONS,
|
||||
hasFlag,
|
||||
hasOtherAction,
|
||||
isEveryMessageReply,
|
||||
MAIL_RULE_ACTIONS_OBJECT,
|
||||
otherKeywords,
|
||||
parseActions,
|
||||
setValues,
|
||||
type FlagAction,
|
||||
type KeywordSet,
|
||||
type RuleActions,
|
||||
} from '../model';
|
||||
import { actionLabel } from '../summary';
|
||||
import { KeywordInput } from './KeywordInput';
|
||||
import { MailboxPicker } from './MailboxPicker';
|
||||
import { RuleFieldRow } from './RuleFieldRow';
|
||||
|
||||
type ObjectAction = 'redirect' | 'reply' | 'reject';
|
||||
type FilledAction = 'moveTo' | 'copyTo' | 'setImportance' | KeywordSet;
|
||||
type RuleAction = FilledAction | FlagAction | ObjectAction | 'clearKeywords' | 'discard';
|
||||
type ActionGroup = 'file' | 'mark' | 'answer' | 'remove';
|
||||
|
||||
const ACTION_GROUPS: readonly { group: ActionGroup; actions: readonly RuleAction[] }[] = [
|
||||
{ group: 'file', actions: ['moveTo', 'copyTo'] },
|
||||
{
|
||||
group: 'mark',
|
||||
actions: [
|
||||
'markRead',
|
||||
'flag',
|
||||
'clearFlag',
|
||||
'markNotJunk',
|
||||
'setImportance',
|
||||
'addKeywords',
|
||||
'removeKeywords',
|
||||
'clearKeywords',
|
||||
],
|
||||
},
|
||||
{ group: 'answer', actions: ['reply', 'redirect'] },
|
||||
{ group: 'remove', actions: ['discard', 'reject'] },
|
||||
];
|
||||
|
||||
interface Focus {
|
||||
action: RuleAction;
|
||||
target: 'card' | 'chip';
|
||||
}
|
||||
|
||||
const FILLED_ACTIONS: readonly FilledAction[] = ['moveTo', 'copyTo', 'setImportance', 'addKeywords', 'removeKeywords'];
|
||||
|
||||
const FIRST_CONTROL = 'input:not([type="hidden"]), textarea, button, [role="combobox"]';
|
||||
|
||||
function focusFirstControl(card: HTMLElement | null) {
|
||||
card?.querySelector<HTMLElement>(FIRST_CONTROL)?.focus();
|
||||
}
|
||||
|
||||
function isFilled(actions: RuleActions, action: FilledAction): boolean {
|
||||
switch (action) {
|
||||
case 'moveTo':
|
||||
case 'copyTo':
|
||||
return actions[action].length > 0;
|
||||
case 'addKeywords':
|
||||
case 'removeKeywords':
|
||||
return otherKeywords(actions, action).length > 0;
|
||||
case 'setImportance':
|
||||
return actions.setImportance !== null;
|
||||
}
|
||||
}
|
||||
|
||||
function filledActions(value: unknown): ReadonlySet<RuleAction> {
|
||||
const actions = parseActions(isRecord(value) ? value : {});
|
||||
return new Set(FILLED_ACTIONS.filter((action) => isFilled(actions, action)));
|
||||
}
|
||||
|
||||
function isFlag(action: RuleAction): action is FlagAction {
|
||||
return Object.hasOwn(FLAG_ACTIONS, action);
|
||||
}
|
||||
|
||||
function LockedSwitch({ value, control }: WidgetProps) {
|
||||
return <Switch {...control} checked={value === true} disabled />;
|
||||
}
|
||||
|
||||
interface ActionRowProps extends Pick<FieldRowProps, 'value' | 'onChange'> {
|
||||
name: string;
|
||||
label: string;
|
||||
type: FieldType | undefined;
|
||||
description?: string;
|
||||
Edit?: ComponentType<WidgetProps>;
|
||||
}
|
||||
|
||||
function ActionRow({ name, label, type, description = '', Edit, ...props }: ActionRowProps) {
|
||||
if (!type) return null;
|
||||
const row = { field: { type, description, update: 'mutable' as const }, formField: { name, label }, ...props };
|
||||
return Edit ? <RuleFieldRow {...row} Edit={Edit} /> : <FieldRow {...row} />;
|
||||
}
|
||||
|
||||
interface ActionDetailsProps {
|
||||
name: string;
|
||||
objectName: string;
|
||||
value: Record<string, unknown>;
|
||||
onChange: (value: Record<string, unknown>) => void;
|
||||
readOnly: boolean;
|
||||
invalid: boolean;
|
||||
}
|
||||
|
||||
function ActionDetails({ name, objectName, value, onChange, readOnly, invalid }: ActionDetailsProps) {
|
||||
const { t } = useTranslation();
|
||||
const { schema } = useFormContext();
|
||||
const resolved = resolveEmbedded(schema, objectName, value);
|
||||
if (!resolved) return null;
|
||||
const missing = new Set(invalid ? missingNestedFields(schema, objectName, value) : []);
|
||||
return (
|
||||
<FieldScopeProvider name={name} readOnly={readOnly}>
|
||||
<div className="divide-y divide-border">
|
||||
{embeddedEntries(resolved).map(({ formField, field }) => (
|
||||
<FieldRow
|
||||
key={formField.name}
|
||||
field={field}
|
||||
formField={formField}
|
||||
value={value[formField.name]}
|
||||
onChange={(next) => onChange({ ...value, [formField.name]: next })}
|
||||
error={missing.has(formField.name) ? t('form.required', 'This field is required.') : undefined}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</FieldScopeProvider>
|
||||
);
|
||||
}
|
||||
|
||||
interface ActionCardProps {
|
||||
label: string;
|
||||
onRemove: (() => void) | null;
|
||||
focused: boolean;
|
||||
title?: ReactNode;
|
||||
children?: ReactNode;
|
||||
}
|
||||
|
||||
function ActionCard({ label, onRemove, focused, title, children }: ActionCardProps) {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<li
|
||||
ref={focused ? focusFirstControl : undefined}
|
||||
className="rounded-xl bg-card px-3 shadow-tile"
|
||||
data-testid="mail-rule-action"
|
||||
>
|
||||
<div className="flex items-start gap-2">
|
||||
<div className="min-w-0 flex-1">
|
||||
{title && <div className="py-3">{title}</div>}
|
||||
{children}
|
||||
</div>
|
||||
{onRemove && (
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost-danger"
|
||||
size="icon-sm"
|
||||
className="mt-2.5 shrink-0"
|
||||
onClick={onRemove}
|
||||
aria-label={t('mailRules.removeItem', 'Remove {{label}}', { label })}
|
||||
>
|
||||
<Trash2 className="size-4" aria-hidden="true" />
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</li>
|
||||
);
|
||||
}
|
||||
|
||||
function CardTitle({ label, description }: { label: string; description?: string }) {
|
||||
return (
|
||||
<>
|
||||
<p className="text-[13.5px] font-semibold">{label}</p>
|
||||
{description && <p className="mt-1 text-[12.5px] leading-relaxed text-muted-foreground">{description}</p>}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
interface ActionFormProps {
|
||||
value: unknown;
|
||||
onChange: (value: Record<string, unknown>) => void;
|
||||
readOnly: boolean;
|
||||
invalid: boolean;
|
||||
}
|
||||
|
||||
export function ActionForm({ value, onChange, readOnly, invalid }: ActionFormProps) {
|
||||
const { t } = useTranslation();
|
||||
const { schema, mode, baseline } = useFormContext();
|
||||
const [opened, setOpened] = useState(() => filledActions(value));
|
||||
const rejectHintId = useId();
|
||||
const [focus, setFocus] = useState<Focus | null>(null);
|
||||
const raw = isRecord(value) ? value : {};
|
||||
const actions = parseActions(raw);
|
||||
const properties = resolveEmbedded(schema, MAIL_RULE_ACTIONS_OBJECT, raw)?.fields?.properties ?? {};
|
||||
const saved = mode === 'edit' && isRecord(baseline) && isRecord(baseline.actions) ? baseline.actions : {};
|
||||
const hasOther = hasOtherAction(actions);
|
||||
const rejects = actions.reject !== null;
|
||||
const rejectBlocked = hasOther && !rejects;
|
||||
const set = (name: keyof RuleActions, next: unknown) => onChange({ ...raw, [name]: next });
|
||||
const open = (action: RuleAction, on: boolean) =>
|
||||
setOpened((current) => {
|
||||
const next = new Set(current);
|
||||
if (on) next.add(action);
|
||||
else next.delete(action);
|
||||
return next;
|
||||
});
|
||||
|
||||
const isActive = (action: RuleAction): boolean => {
|
||||
if (isFlag(action)) return hasFlag(actions, action);
|
||||
switch (action) {
|
||||
case 'moveTo':
|
||||
case 'copyTo':
|
||||
case 'addKeywords':
|
||||
case 'removeKeywords':
|
||||
case 'setImportance':
|
||||
return isFilled(actions, action) || opened.has(action);
|
||||
case 'clearKeywords':
|
||||
case 'discard':
|
||||
return actions[action];
|
||||
case 'redirect':
|
||||
case 'reply':
|
||||
case 'reject':
|
||||
return actions[action] !== null;
|
||||
}
|
||||
};
|
||||
|
||||
const objectType = (name: ObjectAction) => {
|
||||
const type = properties[name]?.type;
|
||||
return type?.type === 'object' ? type : null;
|
||||
};
|
||||
|
||||
const add = (action: RuleAction) => {
|
||||
setFocus({ action, target: 'card' });
|
||||
if (isFlag(action)) return onChange(setFlag(raw, action, true));
|
||||
switch (action) {
|
||||
case 'clearKeywords':
|
||||
case 'discard':
|
||||
return set(action, true);
|
||||
case 'redirect':
|
||||
case 'reply':
|
||||
case 'reject': {
|
||||
const type = objectType(action);
|
||||
if (!type) return;
|
||||
return set(action, isRecord(saved[action]) ? saved[action] : buildNewObjectValue(schema, type.objectName));
|
||||
}
|
||||
default:
|
||||
return open(action, true);
|
||||
}
|
||||
};
|
||||
|
||||
const remove = (action: RuleAction) => {
|
||||
setFocus({ action, target: 'chip' });
|
||||
if (isFlag(action)) return onChange(setFlag(raw, action, false));
|
||||
switch (action) {
|
||||
case 'moveTo':
|
||||
case 'copyTo':
|
||||
open(action, false);
|
||||
return set(action, {});
|
||||
case 'addKeywords':
|
||||
case 'removeKeywords':
|
||||
open(action, false);
|
||||
return set(action, editKeywords(raw[action], otherKeywords(actions, action), []));
|
||||
case 'setImportance':
|
||||
open(action, false);
|
||||
return set(action, null);
|
||||
case 'clearKeywords':
|
||||
case 'discard':
|
||||
return set(action, false);
|
||||
case 'redirect':
|
||||
case 'reply':
|
||||
case 'reject':
|
||||
return set(action, null);
|
||||
}
|
||||
};
|
||||
|
||||
const keywordRow = (name: KeywordSet, label: string) => {
|
||||
const shown = otherKeywords(actions, name);
|
||||
return (
|
||||
<ActionRow
|
||||
name={name}
|
||||
label={label}
|
||||
type={properties[name]?.type}
|
||||
value={toSet(shown)}
|
||||
onChange={(next) => set(name, editKeywords(raw[name], shown, setValues(next)))}
|
||||
Edit={KeywordInput}
|
||||
/>
|
||||
);
|
||||
};
|
||||
|
||||
const objectDetails = (name: ObjectAction) => {
|
||||
const type = objectType(name);
|
||||
const current = actions[name];
|
||||
if (!type || !current) return null;
|
||||
return (
|
||||
<ActionDetails
|
||||
name={name}
|
||||
objectName={type.objectName}
|
||||
value={current}
|
||||
onChange={(next) => set(name, next)}
|
||||
readOnly={readOnly}
|
||||
invalid={invalid}
|
||||
/>
|
||||
);
|
||||
};
|
||||
|
||||
const cardContent = (action: RuleAction): { title?: ReactNode; body?: ReactNode } => {
|
||||
const label = actionLabel(t, action);
|
||||
switch (action) {
|
||||
case 'moveTo':
|
||||
return {
|
||||
body: (
|
||||
<ActionRow
|
||||
name="moveTo"
|
||||
label={label}
|
||||
description={t('mailRules.builder.moveToHint', 'Moving to Junk also marks the message as spam.')}
|
||||
type={properties.moveTo?.type}
|
||||
value={raw.moveTo}
|
||||
onChange={(next) => set('moveTo', next)}
|
||||
Edit={MailboxPicker}
|
||||
/>
|
||||
),
|
||||
};
|
||||
case 'copyTo':
|
||||
return {
|
||||
body: (
|
||||
<ActionRow
|
||||
name="copyTo"
|
||||
label={label}
|
||||
type={properties.copyTo?.type}
|
||||
value={raw.copyTo}
|
||||
onChange={(next) => set('copyTo', next)}
|
||||
Edit={MailboxPicker}
|
||||
/>
|
||||
),
|
||||
};
|
||||
case 'addKeywords':
|
||||
return { body: keywordRow('addKeywords', t('mailRules.builder.keywordsToAdd', 'Keywords to add')) };
|
||||
case 'removeKeywords':
|
||||
return { body: keywordRow('removeKeywords', t('mailRules.builder.keywordsToRemove', 'Keywords to remove')) };
|
||||
case 'setImportance':
|
||||
return {
|
||||
body: (
|
||||
<ActionRow
|
||||
name="setImportance"
|
||||
label={label}
|
||||
type={properties.setImportance?.type}
|
||||
value={actions.setImportance}
|
||||
onChange={(next) => set('setImportance', next)}
|
||||
Edit={FieldControl}
|
||||
/>
|
||||
),
|
||||
};
|
||||
case 'markNotJunk':
|
||||
return {
|
||||
title: (
|
||||
<CardTitle
|
||||
label={label}
|
||||
description={t('mailRules.builder.markNotJunkHint', 'Keeps the message out of Junk.')}
|
||||
/>
|
||||
),
|
||||
};
|
||||
case 'discard':
|
||||
return {
|
||||
title: (
|
||||
<CardTitle
|
||||
label={label}
|
||||
description={t('mailRules.builder.discardHint', 'The message does not go to Trash.')}
|
||||
/>
|
||||
),
|
||||
};
|
||||
case 'reply':
|
||||
return {
|
||||
title: <CardTitle label={label} />,
|
||||
body: (
|
||||
<>
|
||||
{objectDetails('reply')}
|
||||
{isEveryMessageReply(actions.reply) && (
|
||||
<p className="pb-3 text-[12.5px] text-muted-foreground">
|
||||
{t('mailRules.builder.replyEveryMessage', 'With 0 days between replies, every message gets a reply.')}
|
||||
</p>
|
||||
)}
|
||||
</>
|
||||
),
|
||||
};
|
||||
case 'redirect':
|
||||
return { title: <CardTitle label={label} />, body: objectDetails('redirect') };
|
||||
case 'reject':
|
||||
return {
|
||||
title: (
|
||||
<CardTitle
|
||||
label={label}
|
||||
description={t(
|
||||
'mailRules.builder.rejectHint',
|
||||
'Reject must be the only action. The sender is told only when their address can be verified; otherwise the message is deleted without notice.',
|
||||
)}
|
||||
/>
|
||||
),
|
||||
body: objectDetails('reject'),
|
||||
};
|
||||
default:
|
||||
return { title: <CardTitle label={label} /> };
|
||||
}
|
||||
};
|
||||
|
||||
const ordered = ACTION_GROUPS.flatMap(({ actions: group }) => group);
|
||||
const active = ordered.filter(isActive);
|
||||
const showChips = !readOnly && !rejects;
|
||||
|
||||
return (
|
||||
<FieldScopeProvider name="actions" readOnly={readOnly}>
|
||||
<div className="@container space-y-4">
|
||||
{active.length === 0 ? (
|
||||
<p className="text-[12.5px] text-muted-foreground">
|
||||
{readOnly
|
||||
? t('mailRules.builder.noActionsReadOnly', 'No actions.')
|
||||
: t('mailRules.builder.noActions', 'No actions yet. Choose at least one below.')}
|
||||
</p>
|
||||
) : (
|
||||
<ul className="space-y-2 [&_[data-slot=field-row]]:py-3">
|
||||
{active.map((action) => {
|
||||
const { title, body } = cardContent(action);
|
||||
return (
|
||||
<ActionCard
|
||||
key={action}
|
||||
label={actionLabel(t, action)}
|
||||
onRemove={readOnly ? null : () => remove(action)}
|
||||
focused={focus?.action === action && focus.target === 'card'}
|
||||
title={title}
|
||||
>
|
||||
{body}
|
||||
</ActionCard>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
)}
|
||||
|
||||
{showChips && active.length < ordered.length && (
|
||||
<div className="space-y-2">
|
||||
<p className="text-[13px] font-semibold">
|
||||
{active.length === 0
|
||||
? t('mailRules.builder.addAction', 'Add an action')
|
||||
: t('mailRules.builder.addAnotherAction', 'Add another action')}
|
||||
</p>
|
||||
<dl className="space-y-2">
|
||||
{ACTION_GROUPS.map(({ group, actions: members }) => {
|
||||
const available = members.filter((action) => !isActive(action));
|
||||
if (available.length === 0) return null;
|
||||
return (
|
||||
<div key={group} className="grid gap-x-3 gap-y-1.5 sm:grid-cols-[5.5rem_minmax(0,1fr)]">
|
||||
<dt className="pt-1.5 text-[12.5px] text-muted-foreground">{groupLabel(t, group)}</dt>
|
||||
<dd className="flex flex-wrap gap-1.5">
|
||||
{available.map((action) => {
|
||||
const blocked = action === 'reject' && rejectBlocked;
|
||||
return (
|
||||
<Button
|
||||
key={action}
|
||||
type="button"
|
||||
variant="secondary"
|
||||
size="sm"
|
||||
className={cn(blocked && 'cursor-not-allowed opacity-50')}
|
||||
aria-disabled={blocked || undefined}
|
||||
aria-describedby={blocked ? rejectHintId : undefined}
|
||||
autoFocus={focus?.action === action && focus.target === 'chip'}
|
||||
onClick={blocked ? undefined : () => add(action)}
|
||||
>
|
||||
<Plus className="size-4" aria-hidden="true" />
|
||||
{actionLabel(t, action)}
|
||||
</Button>
|
||||
);
|
||||
})}
|
||||
</dd>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</dl>
|
||||
{rejectBlocked && (
|
||||
<p id={rejectHintId} className="text-[12.5px] text-muted-foreground">
|
||||
{t('mailRules.builder.rejectNotAlone', 'Reject must be the only action.')}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="border-t border-border [&_[data-slot=field-row]]:py-3">
|
||||
<ActionRow
|
||||
name="stopProcessing"
|
||||
label={actionLabel(t, 'stopProcessing')}
|
||||
description={
|
||||
rejects
|
||||
? t('mailRules.builder.rejectStops', 'A rule that rejects mail always stops processing more rules.')
|
||||
: t('mailRules.builder.stopHint', 'Rules below this one in the list are skipped for matching messages.')
|
||||
}
|
||||
type={properties.stopProcessing?.type}
|
||||
value={rejects || actions.stopProcessing}
|
||||
onChange={(next) => set('stopProcessing', next)}
|
||||
Edit={rejects ? LockedSwitch : undefined}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</FieldScopeProvider>
|
||||
);
|
||||
}
|
||||
|
||||
function groupLabel(t: TFunction, group: ActionGroup): string {
|
||||
switch (group) {
|
||||
case 'file':
|
||||
return t('mailRules.builder.group.file', 'File');
|
||||
case 'mark':
|
||||
return t('mailRules.builder.group.mark', 'Mark');
|
||||
case 'answer':
|
||||
return t('mailRules.builder.group.answer', 'Answer');
|
||||
case 'remove':
|
||||
return t('mailRules.builder.group.remove', 'Delete');
|
||||
}
|
||||
}
|
||||
@@ -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,48 @@
|
||||
/*
|
||||
* 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 { RemovablePill } from '@/components/forms/widgets/RemovablePill';
|
||||
import { SetWidget } from '@/components/forms/widgets/SetWidget';
|
||||
import type { WidgetProps } from '@/components/forms/widgets/types';
|
||||
import { editKeywords, toSet } from '../builder';
|
||||
import { setValues } from '../model';
|
||||
import { keywordName } from '../summary';
|
||||
|
||||
export function KeywordInput(props: WidgetProps) {
|
||||
const { t } = useTranslation();
|
||||
const { type, value, onChange, readOnly } = props;
|
||||
if (type.type !== 'set') return null;
|
||||
const keywords = setValues(value);
|
||||
const named: { keyword: string; name: string }[] = [];
|
||||
const typed: string[] = [];
|
||||
for (const keyword of keywords) {
|
||||
const name = keywordName(t, keyword);
|
||||
if (name) named.push({ keyword, name });
|
||||
else typed.push(keyword);
|
||||
}
|
||||
return (
|
||||
<div className="space-y-2">
|
||||
{named.length > 0 && (
|
||||
<div className="flex flex-wrap gap-1.5">
|
||||
{named.map(({ keyword, name }) => (
|
||||
<RemovablePill
|
||||
key={keyword}
|
||||
label={name}
|
||||
onRemove={readOnly ? undefined : () => onChange(toSet(keywords.filter((key) => key !== keyword)))}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
<SetWidget
|
||||
{...props}
|
||||
type={{ ...type, minItems: undefined, maxItems: type.maxItems && type.maxItems - named.length }}
|
||||
value={toSet(typed)}
|
||||
onChange={(next) => onChange(editKeywords(value, typed, setValues(next)))}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
/*
|
||||
* 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 { FieldErrors } from '@/components/forms/formLogic';
|
||||
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 { needsAction, newRuleValues, nextRulePosition, parseActions } from '../model';
|
||||
import { useMailRules } from '../queries';
|
||||
import { actionRequiredMessage } from '../summary';
|
||||
import { RuleBuilderRow, RuleSummaryRow } from './RuleBuilder';
|
||||
|
||||
const RULE_ANCHOR = 'actions';
|
||||
const ABSORBED_FIELD = 'conditions';
|
||||
|
||||
function Omitted() {
|
||||
return null;
|
||||
}
|
||||
|
||||
const FIELD_OVERRIDES: FieldOverrides = {
|
||||
hidden: ['position'],
|
||||
untitled: [RULE_ANCHOR],
|
||||
render: {
|
||||
[ABSORBED_FIELD]: Omitted,
|
||||
[RULE_ANCHOR]: RuleBuilderRow,
|
||||
},
|
||||
};
|
||||
|
||||
function useFieldOverrides(): FieldOverrides {
|
||||
const { t } = useTranslation();
|
||||
return {
|
||||
...FIELD_OVERRIDES,
|
||||
validate: (data): FieldErrors =>
|
||||
needsAction(parseActions(data.actions)) ? { [RULE_ANCHOR]: actionRequiredMessage(t) } : {},
|
||||
};
|
||||
}
|
||||
|
||||
const VIEW_RENDERERS: ViewRenderers = {
|
||||
[ABSORBED_FIELD]: Omitted,
|
||||
[RULE_ANCHOR]: RuleSummaryRow,
|
||||
};
|
||||
|
||||
function CreateRuleForm({
|
||||
viewName,
|
||||
accountId,
|
||||
fieldOverrides,
|
||||
}: {
|
||||
viewName: string;
|
||||
accountId: string;
|
||||
fieldOverrides: FieldOverrides;
|
||||
}) {
|
||||
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={fieldOverrides}
|
||||
createValues={newRuleValues(nextRulePosition(rules.data))}
|
||||
showCreatedValues={false}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export function MailRuleFormPage({ viewName, objectId }: PageProps) {
|
||||
const accountId = useRuleAccountId();
|
||||
const fieldOverrides = useFieldOverrides();
|
||||
if (!accountId) return null;
|
||||
if (objectId === 'new')
|
||||
return <CreateRuleForm viewName={viewName} accountId={accountId} fieldOverrides={fieldOverrides} />;
|
||||
return <DynamicForm viewName={viewName} objectId={objectId} accountId={accountId} fieldOverrides={fieldOverrides} />;
|
||||
}
|
||||
|
||||
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 { mailboxNamer } 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: mailboxNamer(t, mailboxes.status === 'ready' ? 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,80 @@
|
||||
/*
|
||||
* 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 { RemovablePill } from '@/components/forms/widgets/RemovablePill';
|
||||
import type { WidgetProps } from '@/components/forms/widgets/types';
|
||||
import { useRuleAccountId } from '../account';
|
||||
import { toSet } from '../builder';
|
||||
import { mailboxNamer } from '../mailboxes';
|
||||
import { setValues } from '../model';
|
||||
import { useMailboxOptions } from '../queries';
|
||||
|
||||
const INDENT_REM = 0.75;
|
||||
|
||||
export function MailboxPicker({ type, value, onChange, readOnly, control }: WidgetProps) {
|
||||
const { t } = useTranslation();
|
||||
const mailboxes = useMailboxOptions(useRuleAccountId());
|
||||
const ids = setValues(value);
|
||||
const isFull = type.type === 'set' && type.maxItems != null && ids.length >= type.maxItems;
|
||||
const nameOf = mailboxNamer(t, mailboxes.status === 'ready' ? mailboxes.options : undefined);
|
||||
const add = (entered: string) => {
|
||||
const id = entered.trim();
|
||||
if (id && !ids.includes(id)) onChange(toSet([...ids, id]));
|
||||
};
|
||||
const placeholder =
|
||||
ids.length > 0
|
||||
? t('mailRules.addMailbox', 'Add another mailbox')
|
||||
: t('mailRules.chooseMailbox', 'Choose a mailbox');
|
||||
|
||||
return (
|
||||
<div className="space-y-2">
|
||||
{ids.length > 0 && (
|
||||
<div className="flex flex-wrap gap-1.5">
|
||||
{ids.map((id) => (
|
||||
<RemovablePill
|
||||
key={id}
|
||||
label={nameOf(id)}
|
||||
onRemove={readOnly ? undefined : () => onChange(toSet(ids.filter((key) => key !== id)))}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
{!readOnly &&
|
||||
!isFull &&
|
||||
(mailboxes.status === 'ready' ? (
|
||||
<Select value="" onValueChange={add}>
|
||||
<SelectTrigger {...control} className="w-full">
|
||||
<SelectValue placeholder={placeholder} />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{mailboxes.options.map((option) => (
|
||||
<SelectItem
|
||||
key={option.id}
|
||||
value={option.id}
|
||||
textValue={option.path.join(' / ')}
|
||||
disabled={ids.includes(option.id)}
|
||||
>
|
||||
<span style={{ paddingInlineStart: `${option.depth * INDENT_REM}rem` }}>{option.name}</span>
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
) : (
|
||||
<BufferedInput
|
||||
key={ids.length}
|
||||
{...control}
|
||||
value=""
|
||||
onCommit={add}
|
||||
disabled={mailboxes.status === 'loading'}
|
||||
placeholder={t('mailRules.mailboxId', 'Mailbox id')}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,294 @@
|
||||
/*
|
||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
import { useState, type ReactNode } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { AlertTriangle, Plus } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { FieldError } from '@/components/forms/FieldRow';
|
||||
import { FieldScopeProvider } from '@/components/forms/FormProvider';
|
||||
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 { isRecord, resolveEmbedded } from '@/lib/embeddedSchema';
|
||||
import { buildNewObjectValue } from '@/lib/schemaResolver';
|
||||
import type { ViewRenderProps } from '@/components/views/DynamicView';
|
||||
import { useRuleAccountId } from '../account';
|
||||
import { appendItem, listEntries, type ListItems } from '../builder';
|
||||
import { mailboxNamer } from '../mailboxes';
|
||||
import {
|
||||
hasOtherAction,
|
||||
MAIL_RULE_ACTIONS_OBJECT,
|
||||
needsAction,
|
||||
MAIL_RULE_CONDITION_OBJECT,
|
||||
MAIL_RULE_CONDITIONS_OBJECT,
|
||||
parseCustomBody,
|
||||
ruleIssues,
|
||||
type ConditionGroup,
|
||||
type RuleIssue,
|
||||
} from '../model';
|
||||
import { useMailboxOptions } from '../queries';
|
||||
import { ruleIssueMessage, ruleSentence, summarizeCustomRule } from '../summary';
|
||||
import { ActionForm } from './ActionForm';
|
||||
import { RuleItemList, type RuleItemListProps } from './RuleItemList';
|
||||
|
||||
function Step({ number, heading, children }: { number: number; heading: string; children: ReactNode }) {
|
||||
return (
|
||||
<section className="space-y-3 py-4">
|
||||
<h2 className="flex items-center gap-2.5 text-[14px] font-semibold">
|
||||
<span
|
||||
className="flex size-6 shrink-0 items-center justify-center rounded-full bg-ink text-[12px] text-ink-foreground"
|
||||
aria-hidden="true"
|
||||
>
|
||||
{number}
|
||||
</span>
|
||||
{heading}
|
||||
</h2>
|
||||
<div className="space-y-3 sm:pl-[34px]">{children}</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
function Hint({ children }: { children: ReactNode }) {
|
||||
return <p className="text-[12.5px] leading-relaxed text-muted-foreground">{children}</p>;
|
||||
}
|
||||
|
||||
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>
|
||||
);
|
||||
}
|
||||
|
||||
function RulePreview({ body, incomplete }: { body: Record<string, unknown>; incomplete: boolean }) {
|
||||
const { t } = useTranslation();
|
||||
const { schema, idPrefix } = useFormContext();
|
||||
const accountId = useRuleAccountId();
|
||||
const mailboxes = useMailboxOptions(accountId);
|
||||
const ctx = {
|
||||
t,
|
||||
schema,
|
||||
mailboxName: mailboxNamer(t, mailboxes.status === 'ready' ? mailboxes.options : undefined),
|
||||
};
|
||||
return (
|
||||
<section
|
||||
className="space-y-1.5 rounded-xl bg-muted px-4 py-3"
|
||||
aria-labelledby={`${idPrefix}-preview`}
|
||||
data-testid="mail-rule-preview"
|
||||
>
|
||||
<h2
|
||||
id={`${idPrefix}-preview`}
|
||||
className="text-[12px] font-semibold uppercase tracking-wide text-muted-foreground"
|
||||
>
|
||||
{t('mailRules.builder.preview', 'Summary')}
|
||||
</h2>
|
||||
<p className="text-[14px] leading-relaxed">
|
||||
{incomplete
|
||||
? t('mailRules.builder.previewIncomplete', 'Nothing yet: choose what to do with matching messages.')
|
||||
: ruleSentence(ctx, summarizeCustomRule(ctx, body))}
|
||||
</p>
|
||||
<Hint>
|
||||
{t(
|
||||
'mailRules.builder.whenItRuns',
|
||||
'Rules run on new mail as it arrives. Saving does not change messages already in your mailboxes.',
|
||||
)}
|
||||
</Hint>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
const OPTIONAL_GROUPS = ['matchAny', 'matchNone'] as const;
|
||||
|
||||
type OptionalGroup = (typeof OPTIONAL_GROUPS)[number];
|
||||
|
||||
export function RuleBuilderRow({ data: body, errors, readOnly, onFieldChange }: FieldRenderProps) {
|
||||
const { t } = useTranslation();
|
||||
const { schema, idPrefix } = useFormContext();
|
||||
const checkers = usePermissionCheckers();
|
||||
const [focusGroup, setFocusGroup] = useState<OptionalGroup | null>(null);
|
||||
const { conditions, actions } = parseCustomBody(body);
|
||||
const groups = isRecord(body.conditions) ? body.conditions : {};
|
||||
const groupFields = resolveEmbedded(schema, MAIL_RULE_CONDITIONS_OBJECT, groups)?.fields?.properties ?? {};
|
||||
const issues = ruleIssues({ isEnabled: true, body }, checkers);
|
||||
const conditionsMarked =
|
||||
!!errors.conditions && missingNestedFields(schema, MAIL_RULE_CONDITIONS_OBJECT, groups).length > 0;
|
||||
const actionsMarked =
|
||||
!!errors.actions && missingNestedFields(schema, MAIL_RULE_ACTIONS_OBJECT, body.actions).length > 0;
|
||||
const hasAll = conditions.matchAll.length > 0;
|
||||
|
||||
const groupText = (group: ConditionGroup) => {
|
||||
switch (group) {
|
||||
case 'matchAll':
|
||||
return {
|
||||
title: '',
|
||||
hint: hasAll
|
||||
? t('mailRules.builder.conditionsHint', 'A message must match every condition.')
|
||||
: t('mailRules.builder.noConditions', 'No conditions: the rule applies to every message.'),
|
||||
joiner: t('mailRules.builder.and', 'and'),
|
||||
item: (n: number) => t('mailRules.builder.conditionN', 'Condition {{n}}', { n }),
|
||||
add: t('mailRules.builder.addCondition', 'Add condition'),
|
||||
addHint: '',
|
||||
};
|
||||
case 'matchAny':
|
||||
return {
|
||||
title: t('mailRules.builder.alternatives', 'Alternatives'),
|
||||
hint: hasAll
|
||||
? t('mailRules.builder.alternativesHintAnd', 'A message must also match at least one alternative.')
|
||||
: t('mailRules.builder.alternativesHint', 'A message must match at least one alternative.'),
|
||||
joiner: t('mailRules.builder.or', 'or'),
|
||||
item: (n: number) => t('mailRules.builder.alternativeN', 'Alternative {{n}}', { n }),
|
||||
add: t('mailRules.builder.addAlternative', 'Add alternative'),
|
||||
addHint: t('mailRules.builder.addAlternativeHint', 'Match one of several conditions, such as two senders.'),
|
||||
};
|
||||
case 'matchNone':
|
||||
return {
|
||||
title: t('mailRules.builder.exceptions', 'Exceptions'),
|
||||
hint: t('mailRules.builder.exceptionsHint', 'The rule skips a message that matches any exception.'),
|
||||
joiner: t('mailRules.builder.or', 'or'),
|
||||
item: (n: number) => t('mailRules.builder.exceptionN', 'Exception {{n}}', { n }),
|
||||
add: t('mailRules.builder.addException', 'Add exception'),
|
||||
addHint: t('mailRules.builder.addExceptionHint', 'Skip messages that would otherwise match.'),
|
||||
};
|
||||
}
|
||||
};
|
||||
|
||||
const change = (group: ConditionGroup, next: ListItems) => {
|
||||
if (group !== 'matchAll' && listEntries(next).length === 0) setFocusGroup(group);
|
||||
onFieldChange('conditions', { ...groups, [group]: next });
|
||||
};
|
||||
|
||||
const listProps = (group: ConditionGroup): RuleItemListProps => {
|
||||
const type = groupFields[group]?.type;
|
||||
const text = groupText(group);
|
||||
return {
|
||||
name: group,
|
||||
objectName: MAIL_RULE_CONDITION_OBJECT,
|
||||
value: groups[group],
|
||||
onChange: (next) => change(group, next),
|
||||
readOnly,
|
||||
invalid: !!errors.conditions,
|
||||
maxItems: type?.type === 'objectList' ? type.maxItems : undefined,
|
||||
itemLabel: text.item,
|
||||
addLabel: text.add,
|
||||
joiner: text.joiner,
|
||||
};
|
||||
};
|
||||
|
||||
const group = (name: ConditionGroup) => {
|
||||
const text = groupText(name);
|
||||
if (!text.title) {
|
||||
return (
|
||||
<div key={name} className="space-y-2">
|
||||
<Hint>{text.hint}</Hint>
|
||||
<RuleItemList {...listProps(name)} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<div key={name} className="space-y-2" role="group" aria-labelledby={`${idPrefix}-${name}-title`}>
|
||||
<div>
|
||||
<h3 id={`${idPrefix}-${name}-title`} className="text-[13px] font-semibold">
|
||||
{text.title}
|
||||
</h3>
|
||||
<Hint>{text.hint}</Hint>
|
||||
</div>
|
||||
<RuleItemList {...listProps(name)} />
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-1" data-testid="mail-rule-builder">
|
||||
<RulePreview body={body} incomplete={needsAction(actions)} />
|
||||
|
||||
<div className="divide-y divide-border">
|
||||
<Step number={1} heading={t('mailRules.builder.which', 'Conditions')}>
|
||||
<FieldError
|
||||
id={fieldIds(idPrefix, ['conditions']).errorId}
|
||||
error={conditionsMarked ? undefined : errors.conditions}
|
||||
/>
|
||||
<FieldScopeProvider name="conditions" readOnly={readOnly}>
|
||||
<div className="space-y-5">
|
||||
{group('matchAll')}
|
||||
{OPTIONAL_GROUPS.map((name) => {
|
||||
if (conditions[name].length > 0) return group(name);
|
||||
if (readOnly) return null;
|
||||
const text = groupText(name);
|
||||
return (
|
||||
<div key={name} className="flex flex-wrap items-center gap-x-3 gap-y-1">
|
||||
<Button
|
||||
type="button"
|
||||
variant="secondary"
|
||||
size="sm"
|
||||
autoFocus={focusGroup === name}
|
||||
onClick={() => {
|
||||
setFocusGroup(null);
|
||||
change(name, appendItem(groups[name], buildNewObjectValue(schema, MAIL_RULE_CONDITION_OBJECT)));
|
||||
}}
|
||||
>
|
||||
<Plus className="size-4" aria-hidden="true" />
|
||||
{text.add}
|
||||
</Button>
|
||||
<span className="text-[12.5px] text-muted-foreground">{text.addHint}</span>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</FieldScopeProvider>
|
||||
</Step>
|
||||
|
||||
<Step number={2} heading={t('mailRules.builder.what', 'Actions')}>
|
||||
<FieldError id={fieldIds(idPrefix, ['actions']).errorId} error={actionsMarked ? undefined : errors.actions} />
|
||||
<ActionForm
|
||||
value={body.actions}
|
||||
onChange={(next) => onFieldChange('actions', next)}
|
||||
readOnly={readOnly}
|
||||
invalid={!!errors.actions}
|
||||
/>
|
||||
{actions.stopProcessing && !actions.reject && !hasOtherAction(actions) && (
|
||||
<Hint>
|
||||
{t(
|
||||
'mailRules.builder.onlyStop',
|
||||
'Without other actions, a matching message only stops later rules from running.',
|
||||
)}
|
||||
</Hint>
|
||||
)}
|
||||
</Step>
|
||||
|
||||
<IssueList issues={issues} />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function RuleSummaryRow({ schema, data }: ViewRenderProps) {
|
||||
const { t } = useTranslation();
|
||||
const accountId = useRuleAccountId();
|
||||
const mailboxes = useMailboxOptions(accountId);
|
||||
const ctx = {
|
||||
t,
|
||||
schema,
|
||||
mailboxName: mailboxNamer(t, mailboxes.status === 'ready' ? mailboxes.options : undefined),
|
||||
};
|
||||
return (
|
||||
<ValueRow
|
||||
schema={schema}
|
||||
label={t('mailRules.summaryLabel', 'Summary')}
|
||||
type={undefined}
|
||||
value={ruleSentence(ctx, summarizeCustomRule(ctx, data))}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
/*
|
||||
* 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 { Markdown } from '@/components/common/Markdown';
|
||||
import { FieldError, FieldLabel, type FieldRowProps } from '@/components/forms/FieldRow';
|
||||
import { fieldIds, useFieldScope, useFormContext } from '@/components/forms/formContext';
|
||||
import { widgetTraits } from '@/extensions/widgets';
|
||||
import { cn } from '@/lib/utils';
|
||||
import type { WidgetProps } from '@/components/forms/widgets/types';
|
||||
|
||||
interface RuleFieldRowProps extends Omit<FieldRowProps, 'readOnly'> {
|
||||
Edit: ComponentType<WidgetProps>;
|
||||
}
|
||||
|
||||
export function RuleFieldRow({ field, formField, value, onChange, error, Edit }: RuleFieldRowProps) {
|
||||
const { idPrefix } = useFormContext();
|
||||
const { path, readOnly } = useFieldScope();
|
||||
const ids = fieldIds(idPrefix, [...path, formField.name]);
|
||||
const inline = widgetTraits(field.type).layout === 'inline';
|
||||
const describedBy =
|
||||
[field.description ? ids.descriptionId : null, error ? ids.errorId : null].filter(Boolean).join(' ') || undefined;
|
||||
return (
|
||||
<div
|
||||
data-slot="field-row"
|
||||
className={cn('py-4', inline ? 'grid grid-cols-[minmax(0,1fr)_auto] gap-x-8 gap-y-2' : 'field-grid')}
|
||||
>
|
||||
<div className={cn('min-w-0 space-y-1', !inline && '@xl:pt-2')}>
|
||||
<FieldLabel id={ids.labelId} htmlFor={ids.inputId} label={formField.label} marker={null} locked={false} />
|
||||
{field.description && (
|
||||
<div id={ids.descriptionId}>
|
||||
<Markdown source={field.description} className="text-[12.5px] leading-relaxed text-muted-foreground" />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<div className={cn('min-w-0 space-y-1.5', inline && 'pt-0.5')}>
|
||||
<Edit
|
||||
type={field.type}
|
||||
field={field}
|
||||
formField={formField}
|
||||
value={value}
|
||||
onChange={onChange}
|
||||
readOnly={readOnly}
|
||||
control={{ id: ids.inputId, 'aria-invalid': error ? true : undefined, 'aria-describedby': describedBy }}
|
||||
/>
|
||||
<FieldError id={ids.errorId} error={error} />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,250 @@
|
||||
/*
|
||||
* 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 {
|
||||
appendItem,
|
||||
isInlineField,
|
||||
KEYWORD_TEST_SCHEMA,
|
||||
KEYWORDS_FIELD,
|
||||
listEntries,
|
||||
removeItem,
|
||||
replaceItem,
|
||||
type ListItems,
|
||||
} from '../builder';
|
||||
import { KeywordInput } from './KeywordInput';
|
||||
import { RuleFieldRow } from './RuleFieldRow';
|
||||
|
||||
const NO_MISSING: ReadonlySet<string> = new Set();
|
||||
|
||||
export interface RuleItemListProps {
|
||||
name: string;
|
||||
objectName: string;
|
||||
value: unknown;
|
||||
onChange: (value: ListItems) => void;
|
||||
readOnly: boolean;
|
||||
invalid: boolean;
|
||||
maxItems?: number;
|
||||
itemLabel: (n: number) => string;
|
||||
addLabel: string;
|
||||
joiner?: 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;
|
||||
joiner?: string;
|
||||
}
|
||||
|
||||
function RuleItem({ objectName, itemKey, item, label, onChange, onRemove, readOnly, invalid, joiner }: RuleItemProps) {
|
||||
const { t } = useTranslation();
|
||||
const { schema, idPrefix, mode, baseline } = useFormContext();
|
||||
const scope = useFieldScope();
|
||||
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 data-testid="mail-rule-item">
|
||||
{joiner && (
|
||||
<p className="py-0.5 pl-3 text-[11.5px] font-semibold uppercase tracking-wide text-muted-foreground">
|
||||
{joiner}
|
||||
</p>
|
||||
)}
|
||||
<div className="rounded-xl bg-card px-3 py-2.5 shadow-tile">
|
||||
<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) => (
|
||||
<SelectItem key={option.name} value={option.name}>
|
||||
{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': t('mailRules.builder.itemField', '{{item}}: {{field}}', {
|
||||
item: label,
|
||||
field: formField.label,
|
||||
}),
|
||||
'aria-invalid': isMissing || undefined,
|
||||
'aria-describedby': isMissing ? itemErrorId : undefined,
|
||||
};
|
||||
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"
|
||||
>
|
||||
{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">
|
||||
<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 }) => {
|
||||
const row = {
|
||||
field,
|
||||
formField,
|
||||
value: item[formField.name],
|
||||
onChange: (next: unknown) => onChange({ ...item, [formField.name]: next }),
|
||||
error: missing.has(formField.name) ? requiredMessage : undefined,
|
||||
};
|
||||
return schemaName === KEYWORD_TEST_SCHEMA && formField.name === KEYWORDS_FIELD ? (
|
||||
<RuleFieldRow key={formField.name} {...row} Edit={KeywordInput} />
|
||||
) : (
|
||||
<FieldRow key={formField.name} {...row} />
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</EnclosingSchemaContext>
|
||||
</FieldScopeProvider>
|
||||
)}
|
||||
</div>
|
||||
</li>
|
||||
);
|
||||
}
|
||||
|
||||
export function RuleItemList({
|
||||
name,
|
||||
objectName,
|
||||
value,
|
||||
onChange,
|
||||
readOnly,
|
||||
invalid,
|
||||
maxItems,
|
||||
itemLabel,
|
||||
addLabel,
|
||||
joiner,
|
||||
}: RuleItemListProps) {
|
||||
const { schema } = useFormContext();
|
||||
const entries = listEntries(value);
|
||||
const canAdd = !readOnly && (maxItems == null || entries.length < maxItems);
|
||||
return (
|
||||
<FieldScopeProvider name={name} readOnly={readOnly}>
|
||||
{entries.length > 0 && (
|
||||
<ol className="space-y-1">
|
||||
{entries.map(([key, item], index) => (
|
||||
<RuleItem
|
||||
key={key}
|
||||
joiner={index > 0 ? joiner : undefined}
|
||||
objectName={objectName}
|
||||
itemKey={key}
|
||||
item={item}
|
||||
label={itemLabel(index + 1)}
|
||||
onChange={(next) => onChange(replaceItem(value, key, next))}
|
||||
onRemove={readOnly ? null : () => onChange(removeItem(value, key))}
|
||||
readOnly={readOnly}
|
||||
invalid={invalid}
|
||||
/>
|
||||
))}
|
||||
</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,91 @@
|
||||
/*
|
||||
* 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 type { JmapObject } from '@/services/jmap/client';
|
||||
|
||||
export const MAILBOX_PROPERTIES = ['id', 'name', 'parentId', 'role', 'sortOrder'];
|
||||
|
||||
const TRASH_MAILBOX_ID = 'b';
|
||||
const JUNK_MAILBOX_ID = 'c';
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
export function fallbackMailboxName(t: TFunction, id: string): string {
|
||||
if (id === TRASH_MAILBOX_ID) return t('mailRules.trashMailbox', 'Trash');
|
||||
if (id === JUNK_MAILBOX_ID) return t('mailRules.junkMailbox', 'Junk');
|
||||
return id;
|
||||
}
|
||||
|
||||
export function mailboxNamer(t: TFunction, options: readonly MailboxOption[] | undefined): (id: string) => string {
|
||||
if (!options) return (id) => fallbackMailboxName(t, id);
|
||||
const known = mailboxNameResolver(options);
|
||||
return (id) => known(id) ?? t('mailRules.unknownMailbox', 'Unknown mailbox ({{id}})', { id });
|
||||
}
|
||||
@@ -0,0 +1,322 @@
|
||||
/*
|
||||
* 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_CONDITIONS_OBJECT = 'x:MailRuleConditions';
|
||||
export const MAIL_RULE_ACTIONS_OBJECT = 'x:MailRuleActions';
|
||||
|
||||
const FORWARD_PERMISSIONS = ['jmapSieveScriptCreate', 'jmapSieveScriptUpdate', 'sievePutScript'] as const;
|
||||
|
||||
export interface MailRule {
|
||||
id: string;
|
||||
name: string;
|
||||
isEnabled: boolean;
|
||||
position: number;
|
||||
body: Record<string, unknown>;
|
||||
}
|
||||
|
||||
export type ConditionGroup = 'matchAll' | 'matchAny' | 'matchNone';
|
||||
|
||||
export type RuleConditions = Record<ConditionGroup, Record<string, unknown>[]>;
|
||||
|
||||
export interface RuleActions {
|
||||
addKeywords: string[];
|
||||
removeKeywords: string[];
|
||||
clearKeywords: boolean;
|
||||
setImportance: string | null;
|
||||
redirect: Record<string, unknown> | null;
|
||||
reply: Record<string, unknown> | null;
|
||||
copyTo: string[];
|
||||
moveTo: string[];
|
||||
discard: boolean;
|
||||
reject: Record<string, unknown> | null;
|
||||
stopProcessing: boolean;
|
||||
}
|
||||
|
||||
export interface CustomRuleBody {
|
||||
conditions: RuleConditions;
|
||||
actions: RuleActions;
|
||||
}
|
||||
|
||||
export type KeywordSet = 'addKeywords' | 'removeKeywords';
|
||||
|
||||
export const FLAG_ACTIONS = {
|
||||
markRead: { set: 'addKeywords', keyword: '$seen' },
|
||||
flag: { set: 'addKeywords', keyword: '$flagged' },
|
||||
clearFlag: { set: 'removeKeywords', keyword: '$flagged' },
|
||||
markNotJunk: { set: 'addKeywords', keyword: '$notjunk' },
|
||||
} as const satisfies Record<string, { set: KeywordSet; keyword: string }>;
|
||||
|
||||
export type FlagAction = keyof typeof FLAG_ACTIONS;
|
||||
|
||||
export type RuleIssue = 'rejectNotAlone' | 'keywordConflict' | 'forwardingNotAllowed' | 'sizeInvalid';
|
||||
|
||||
export const MAX_SIZE_KB = 2 ** 32;
|
||||
|
||||
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 newRuleValues(position: number): JmapObject {
|
||||
return {
|
||||
position,
|
||||
conditions: { matchAll: {}, matchAny: {}, matchNone: {} },
|
||||
actions: {
|
||||
addKeywords: {},
|
||||
removeKeywords: {},
|
||||
clearKeywords: false,
|
||||
setImportance: null,
|
||||
redirect: null,
|
||||
reply: null,
|
||||
copyTo: {},
|
||||
moveTo: {},
|
||||
discard: false,
|
||||
reject: null,
|
||||
stopProcessing: false,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function parseConditions(value: unknown): RuleConditions {
|
||||
const groups = isRecord(value) ? value : {};
|
||||
const list = (group: ConditionGroup) => jmapMapToArray<unknown>(groups[group]).filter(isRecord);
|
||||
return { matchAll: list('matchAll'), matchAny: list('matchAny'), matchNone: list('matchNone') };
|
||||
}
|
||||
|
||||
export function parseActions(value: unknown): RuleActions {
|
||||
const actions = isRecord(value) ? value : {};
|
||||
const { setImportance, redirect, reply, reject } = actions;
|
||||
return {
|
||||
addKeywords: setValues(actions.addKeywords),
|
||||
removeKeywords: setValues(actions.removeKeywords),
|
||||
clearKeywords: actions.clearKeywords === true,
|
||||
setImportance: typeof setImportance === 'string' && setImportance !== '' ? setImportance : null,
|
||||
redirect: isRecord(redirect) ? redirect : null,
|
||||
reply: isRecord(reply) ? reply : null,
|
||||
copyTo: setValues(actions.copyTo),
|
||||
moveTo: setValues(actions.moveTo),
|
||||
discard: actions.discard === true,
|
||||
reject: isRecord(reject) ? reject : null,
|
||||
stopProcessing: actions.stopProcessing === true,
|
||||
};
|
||||
}
|
||||
|
||||
export function parseCustomBody(body: Record<string, unknown>): CustomRuleBody {
|
||||
return { conditions: parseConditions(body.conditions), actions: parseActions(body.actions) };
|
||||
}
|
||||
|
||||
export function hasFlag(actions: RuleActions, flag: FlagAction): boolean {
|
||||
const { set, keyword } = FLAG_ACTIONS[flag];
|
||||
return actions[set].includes(keyword);
|
||||
}
|
||||
|
||||
export function otherKeywords(actions: RuleActions, set: KeywordSet): string[] {
|
||||
const flags = new Set<string>();
|
||||
for (const action of Object.values(FLAG_ACTIONS)) {
|
||||
if (action.set === set) flags.add(action.keyword);
|
||||
}
|
||||
return actions[set].filter((keyword) => !flags.has(keyword));
|
||||
}
|
||||
|
||||
export function hasOtherAction(actions: RuleActions): boolean {
|
||||
return (
|
||||
actions.addKeywords.length > 0 ||
|
||||
actions.removeKeywords.length > 0 ||
|
||||
actions.clearKeywords ||
|
||||
actions.setImportance !== null ||
|
||||
actions.redirect !== null ||
|
||||
actions.reply !== null ||
|
||||
actions.copyTo.length > 0 ||
|
||||
actions.moveTo.length > 0 ||
|
||||
actions.discard
|
||||
);
|
||||
}
|
||||
|
||||
export function needsAction(actions: RuleActions): boolean {
|
||||
return !actions.stopProcessing && actions.reject === null && !hasOtherAction(actions);
|
||||
}
|
||||
|
||||
export function isEveryMessageReply(reply: Record<string, unknown> | null): boolean {
|
||||
return reply?.days === 0;
|
||||
}
|
||||
|
||||
function hasKeywordConflict(actions: RuleActions): boolean {
|
||||
const removed = new Set(actions.removeKeywords);
|
||||
return actions.addKeywords.some((keyword) => removed.has(keyword));
|
||||
}
|
||||
|
||||
export function sizeIssue(condition: Record<string, unknown>): RuleIssue | null {
|
||||
const type = variantType(condition);
|
||||
if (type !== 'SizeOver' && type !== 'SizeUnder') return null;
|
||||
const { kilobytes } = condition;
|
||||
if (typeof kilobytes !== 'number' || !Number.isFinite(kilobytes)) return null;
|
||||
return kilobytes < 1 || kilobytes > MAX_SIZE_KB ? 'sizeInvalid' : null;
|
||||
}
|
||||
|
||||
function redirectTargets(actions: RuleActions): number {
|
||||
return setValues(actions.redirect?.addresses).length;
|
||||
}
|
||||
|
||||
export function forwardingTargets(body: Record<string, unknown>): number {
|
||||
return redirectTargets(parseActions(body.actions));
|
||||
}
|
||||
|
||||
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 { conditions, actions } = parseCustomBody(rule.body);
|
||||
if (actions.reject && hasOtherAction(actions)) issues.push('rejectNotAlone');
|
||||
if (hasKeywordConflict(actions)) issues.push('keywordConflict');
|
||||
if (Object.values(conditions).some((items) => items.some((condition) => sizeIssue(condition) !== null))) {
|
||||
issues.push('sizeInvalid');
|
||||
}
|
||||
if (rule.isEnabled && redirectTargets(actions) > 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,505 @@
|
||||
/*
|
||||
* 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 { fallbackMailboxName } from './mailboxes';
|
||||
import {
|
||||
hasFlag,
|
||||
isEveryMessageReply,
|
||||
MAIL_RULE_CONDITION_OBJECT,
|
||||
MAX_SIZE_KB,
|
||||
otherKeywords,
|
||||
parseCustomBody,
|
||||
setValues,
|
||||
variantType,
|
||||
type FlagAction,
|
||||
type RuleActions,
|
||||
type RuleIssue,
|
||||
} from './model';
|
||||
|
||||
const KILOBYTE = 1024;
|
||||
|
||||
export interface SummaryContext {
|
||||
t: TFunction;
|
||||
schema: Schema;
|
||||
mailboxName?: (id: string) => string | undefined;
|
||||
}
|
||||
|
||||
export interface RuleSummary {
|
||||
matchAll: string[];
|
||||
matchAny: string[];
|
||||
matchNone: string[];
|
||||
actions: string[];
|
||||
stopProcessing: boolean;
|
||||
}
|
||||
|
||||
export function actionLabel(t: TFunction, action: FlagAction | keyof RuleActions): string {
|
||||
switch (action) {
|
||||
case 'markRead':
|
||||
return t('mailRules.action.markRead', 'Mark as read');
|
||||
case 'flag':
|
||||
return t('mailRules.action.flag', 'Flag');
|
||||
case 'clearFlag':
|
||||
return t('mailRules.action.clearFlag', 'Clear the flag');
|
||||
case 'markNotJunk':
|
||||
return t('mailRules.action.markNotJunk', 'Mark as not spam');
|
||||
case 'addKeywords':
|
||||
return t('mailRules.action.addKeywords', 'Add keywords');
|
||||
case 'removeKeywords':
|
||||
return t('mailRules.action.removeKeywords', 'Remove keywords');
|
||||
case 'clearKeywords':
|
||||
return t('mailRules.action.clearKeywords', 'Remove all keywords added by earlier rules');
|
||||
case 'setImportance':
|
||||
return t('mailRules.action.setImportance', 'Set the importance');
|
||||
case 'redirect':
|
||||
return t('mailRules.action.redirect', 'Redirect to other addresses');
|
||||
case 'reply':
|
||||
return t('mailRules.action.reply', 'Reply with a template');
|
||||
case 'copyTo':
|
||||
return t('mailRules.action.copyTo', 'Copy to');
|
||||
case 'moveTo':
|
||||
return t('mailRules.action.moveTo', 'Move to');
|
||||
case 'discard':
|
||||
return t('mailRules.action.discard', 'Delete permanently');
|
||||
case 'reject':
|
||||
return t('mailRules.action.reject', 'Reject with a message');
|
||||
case 'stopProcessing':
|
||||
return t('mailRules.action.stopProcessing', 'Stop processing more rules');
|
||||
}
|
||||
}
|
||||
|
||||
export function keywordName(t: TFunction, keyword: string): string | undefined {
|
||||
switch (keyword) {
|
||||
case '$seen':
|
||||
return t('mailRules.keyword.seen', 'Read');
|
||||
case '$flagged':
|
||||
return t('mailRules.keyword.flagged', 'Flagged');
|
||||
case '$answered':
|
||||
return t('mailRules.keyword.answered', 'Replied');
|
||||
case '$forwarded':
|
||||
return t('mailRules.keyword.forwarded', 'Forwarded');
|
||||
case '$draft':
|
||||
return t('mailRules.keyword.draft', 'Draft');
|
||||
case '$deleted':
|
||||
return t('mailRules.keyword.deleted', 'Marked for deletion');
|
||||
case '$important':
|
||||
return t('mailRules.keyword.important', 'Important');
|
||||
case '$junk':
|
||||
return t('mailRules.keyword.junk', 'Spam');
|
||||
case '$notjunk':
|
||||
return t('mailRules.keyword.notJunk', 'Not spam');
|
||||
case '$phishing':
|
||||
return t('mailRules.keyword.phishing', 'Phishing');
|
||||
default:
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
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,
|
||||
values: readonly string[],
|
||||
type: 'conjunction' | 'disjunction' = 'disjunction',
|
||||
): string {
|
||||
return formatList(
|
||||
values.map((value) => quoted(ctx, value)),
|
||||
type,
|
||||
);
|
||||
}
|
||||
|
||||
function quotedKeywords(
|
||||
ctx: SummaryContext,
|
||||
keywords: readonly string[],
|
||||
type: 'conjunction' | 'disjunction' = 'disjunction',
|
||||
): string {
|
||||
return quotedValues(
|
||||
ctx,
|
||||
keywords.map((keyword) => keywordName(ctx.t, keyword) ?? keyword),
|
||||
type,
|
||||
);
|
||||
}
|
||||
|
||||
function sizeOf(value: unknown): string | null {
|
||||
return typeof value === 'number' ? formatSize(value * KILOBYTE) : null;
|
||||
}
|
||||
|
||||
function replyPhrase(ctx: SummaryContext, reply: Record<string, unknown>): string {
|
||||
const { t } = ctx;
|
||||
const subject = typeof reply.subject === 'string' && reply.subject ? quoted(ctx, reply.subject) : '';
|
||||
if (isEveryMessageReply(reply)) {
|
||||
return subject
|
||||
? t('mailRules.summary.action.replySubjectEveryMessage', 'reply with {{subject}} to every message', { subject })
|
||||
: t('mailRules.summary.action.replyEveryMessage', 'reply to every message');
|
||||
}
|
||||
if (typeof reply.days !== 'number') {
|
||||
return subject
|
||||
? t('mailRules.summary.action.replySubject', 'reply with {{subject}}', { subject })
|
||||
: t('mailRules.summary.action.reply', 'reply with a template');
|
||||
}
|
||||
const count = reply.days;
|
||||
return subject
|
||||
? t('mailRules.summary.action.replySubjectDays', {
|
||||
subject,
|
||||
count,
|
||||
defaultValue_one: 'reply with {{subject}} at most once a day per sender',
|
||||
defaultValue_other: 'reply with {{subject}} at most once every {{count}} days per sender',
|
||||
})
|
||||
: t('mailRules.summary.action.replyDays', {
|
||||
count,
|
||||
defaultValue_one: 'reply at most once a day per sender',
|
||||
defaultValue_other: 'reply at most once every {{count}} days per sender',
|
||||
});
|
||||
}
|
||||
|
||||
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, setValues(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 formatList(slots, 'unit');
|
||||
}
|
||||
|
||||
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, sizeOf(condition.kilobytes) ?? '');
|
||||
case 'Keyword':
|
||||
return detailed(ctx, label, quotedKeywords(ctx, setValues(condition.keywords)));
|
||||
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 mailboxNames(ctx: SummaryContext, ids: readonly string[]): string {
|
||||
return quotedValues(
|
||||
ctx,
|
||||
ids.map((id) => ctx.mailboxName?.(id) ?? fallbackMailboxName(ctx.t, id)),
|
||||
'conjunction',
|
||||
);
|
||||
}
|
||||
|
||||
export function actionPhrases(ctx: SummaryContext, actions: RuleActions): string[] {
|
||||
const { t } = ctx;
|
||||
const phrases: string[] = [];
|
||||
const keywords = (list: readonly string[]) => ({
|
||||
count: list.length,
|
||||
keywords: quotedKeywords(ctx, list, 'conjunction'),
|
||||
});
|
||||
|
||||
if (actions.clearKeywords) {
|
||||
phrases.push(t('mailRules.summary.action.clearKeywords', 'remove all keywords added by earlier rules'));
|
||||
}
|
||||
if (hasFlag(actions, 'clearFlag')) phrases.push(t('mailRules.summary.action.clearFlag', 'clear the flag'));
|
||||
const removed = otherKeywords(actions, 'removeKeywords');
|
||||
if (removed.length > 0) {
|
||||
phrases.push(
|
||||
t('mailRules.summary.action.removeKeywords', {
|
||||
...keywords(removed),
|
||||
defaultValue_one: 'remove the keyword {{keywords}}',
|
||||
defaultValue_other: 'remove the keywords {{keywords}}',
|
||||
}),
|
||||
);
|
||||
}
|
||||
if (hasFlag(actions, 'markRead')) phrases.push(t('mailRules.summary.action.markRead', 'mark it as read'));
|
||||
if (hasFlag(actions, 'flag')) phrases.push(t('mailRules.summary.action.flag', 'flag it'));
|
||||
if (hasFlag(actions, 'markNotJunk')) phrases.push(t('mailRules.summary.action.markNotJunk', 'mark it as not spam'));
|
||||
const added = otherKeywords(actions, 'addKeywords');
|
||||
if (added.length > 0) {
|
||||
phrases.push(
|
||||
t('mailRules.summary.action.addKeywords', {
|
||||
...keywords(added),
|
||||
defaultValue_one: 'add the keyword {{keywords}}',
|
||||
defaultValue_other: 'add the keywords {{keywords}}',
|
||||
}),
|
||||
);
|
||||
}
|
||||
if (actions.setImportance !== null) {
|
||||
phrases.push(
|
||||
t('mailRules.summary.action.setImportance', 'set the importance to {{level}}', {
|
||||
level: enumLabel(ctx.schema, 'MailRuleImportanceLevel', actions.setImportance),
|
||||
}),
|
||||
);
|
||||
}
|
||||
if (actions.redirect) {
|
||||
const addresses = formatList(setValues(actions.redirect.addresses));
|
||||
phrases.push(
|
||||
actions.redirect.keepCopy === false
|
||||
? t('mailRules.summary.action.redirectWithoutCopy', 'redirect to {{addresses}} without keeping a copy', {
|
||||
addresses,
|
||||
})
|
||||
: t('mailRules.summary.action.redirect', 'redirect to {{addresses}}', { addresses }),
|
||||
);
|
||||
}
|
||||
if (actions.reply) phrases.push(replyPhrase(ctx, actions.reply));
|
||||
if (actions.copyTo.length > 0) {
|
||||
phrases.push(
|
||||
t('mailRules.summary.action.copyTo', 'copy it to {{mailboxes}}', {
|
||||
mailboxes: mailboxNames(ctx, actions.copyTo),
|
||||
}),
|
||||
);
|
||||
}
|
||||
if (actions.moveTo.length > 0) {
|
||||
phrases.push(
|
||||
t('mailRules.summary.action.moveTo', 'move it to {{mailboxes}}', {
|
||||
mailboxes: mailboxNames(ctx, actions.moveTo),
|
||||
}),
|
||||
);
|
||||
}
|
||||
if (actions.discard) phrases.push(t('mailRules.summary.action.discard', 'delete it permanently'));
|
||||
if (actions.reject) {
|
||||
const { reason } = actions.reject;
|
||||
phrases.push(
|
||||
typeof reason === 'string' && reason
|
||||
? t('mailRules.summary.action.rejectReason', 'reject it with {{reason}}', { reason: quoted(ctx, reason) })
|
||||
: t('mailRules.summary.action.reject', 'reject it'),
|
||||
);
|
||||
}
|
||||
return phrases;
|
||||
}
|
||||
|
||||
export function summarizeCustomRule(ctx: SummaryContext, body: Record<string, unknown>): RuleSummary {
|
||||
const { conditions, actions } = parseCustomBody(body);
|
||||
const phrase = (condition: Record<string, unknown>) => conditionPhrase(ctx, condition);
|
||||
return {
|
||||
matchAll: conditions.matchAll.map(phrase),
|
||||
matchAny: conditions.matchAny.map(phrase),
|
||||
matchNone: conditions.matchNone.map(phrase),
|
||||
actions: actionPhrases(ctx, actions),
|
||||
stopProcessing: actions.stopProcessing || actions.reject !== null,
|
||||
};
|
||||
}
|
||||
|
||||
type SentenceOpening = 'always' | 'if';
|
||||
type SentenceEnding = 'then' | 'thenStop' | 'onlyStop' | 'nothing';
|
||||
|
||||
type SentenceValues = {
|
||||
conditions: string;
|
||||
exceptions: string;
|
||||
actions: string;
|
||||
};
|
||||
|
||||
function conditionsClause(t: TFunction, { matchAll, matchAny }: RuleSummary): string {
|
||||
if (matchAll.length > 0 && matchAny.length > 1) {
|
||||
return t('mailRules.summary.allAndAny', '{{all}}, and either {{any}}', {
|
||||
all: formatList(matchAll),
|
||||
any: formatList(matchAny, 'disjunction'),
|
||||
});
|
||||
}
|
||||
return matchAll.length > 0 ? formatList([...matchAll, ...matchAny]) : formatList(matchAny, 'disjunction');
|
||||
}
|
||||
|
||||
function sentence(
|
||||
t: TFunction,
|
||||
opening: SentenceOpening,
|
||||
except: boolean,
|
||||
ending: SentenceEnding,
|
||||
values: SentenceValues,
|
||||
): string {
|
||||
switch (`${opening}${except ? 'Except' : ''}_${ending}` as const) {
|
||||
case 'always_then':
|
||||
return t('mailRules.summary.rule.always_then', 'For every message, then {{actions}}.', values);
|
||||
case 'always_thenStop':
|
||||
return t(
|
||||
'mailRules.summary.rule.always_thenStop',
|
||||
'For every message, then {{actions}}, and stop processing more rules.',
|
||||
values,
|
||||
);
|
||||
case 'always_onlyStop':
|
||||
return t('mailRules.summary.rule.always_onlyStop', 'For every message, then stop processing more rules.', values);
|
||||
case 'always_nothing':
|
||||
return t('mailRules.summary.rule.always_nothing', 'For every message, then do nothing.', values);
|
||||
case 'alwaysExcept_then':
|
||||
return t(
|
||||
'mailRules.summary.rule.alwaysExcept_then',
|
||||
'For every message, except if {{exceptions}}, then {{actions}}.',
|
||||
values,
|
||||
);
|
||||
case 'alwaysExcept_thenStop':
|
||||
return t(
|
||||
'mailRules.summary.rule.alwaysExcept_thenStop',
|
||||
'For every message, except if {{exceptions}}, then {{actions}}, and stop processing more rules.',
|
||||
values,
|
||||
);
|
||||
case 'alwaysExcept_onlyStop':
|
||||
return t(
|
||||
'mailRules.summary.rule.alwaysExcept_onlyStop',
|
||||
'For every message, except if {{exceptions}}, then stop processing more rules.',
|
||||
values,
|
||||
);
|
||||
case 'alwaysExcept_nothing':
|
||||
return t(
|
||||
'mailRules.summary.rule.alwaysExcept_nothing',
|
||||
'For every message, except if {{exceptions}}, then do nothing.',
|
||||
values,
|
||||
);
|
||||
case 'if_then':
|
||||
return t('mailRules.summary.rule.if_then', 'If {{conditions}}, then {{actions}}.', values);
|
||||
case 'if_thenStop':
|
||||
return t(
|
||||
'mailRules.summary.rule.if_thenStop',
|
||||
'If {{conditions}}, then {{actions}}, and stop processing more rules.',
|
||||
values,
|
||||
);
|
||||
case 'if_onlyStop':
|
||||
return t('mailRules.summary.rule.if_onlyStop', 'If {{conditions}}, then stop processing more rules.', values);
|
||||
case 'if_nothing':
|
||||
return t('mailRules.summary.rule.if_nothing', 'If {{conditions}}, then do nothing.', values);
|
||||
case 'ifExcept_then':
|
||||
return t(
|
||||
'mailRules.summary.rule.ifExcept_then',
|
||||
'If {{conditions}}, except if {{exceptions}}, then {{actions}}.',
|
||||
values,
|
||||
);
|
||||
case 'ifExcept_thenStop':
|
||||
return t(
|
||||
'mailRules.summary.rule.ifExcept_thenStop',
|
||||
'If {{conditions}}, except if {{exceptions}}, then {{actions}}, and stop processing more rules.',
|
||||
values,
|
||||
);
|
||||
case 'ifExcept_onlyStop':
|
||||
return t(
|
||||
'mailRules.summary.rule.ifExcept_onlyStop',
|
||||
'If {{conditions}}, except if {{exceptions}}, then stop processing more rules.',
|
||||
values,
|
||||
);
|
||||
case 'ifExcept_nothing':
|
||||
return t(
|
||||
'mailRules.summary.rule.ifExcept_nothing',
|
||||
'If {{conditions}}, except if {{exceptions}}, then do nothing.',
|
||||
values,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export function ruleSentence(ctx: SummaryContext, summary: RuleSummary): string {
|
||||
const hasActions = summary.actions.length > 0;
|
||||
const ending: SentenceEnding = summary.stopProcessing
|
||||
? hasActions
|
||||
? 'thenStop'
|
||||
: 'onlyStop'
|
||||
: hasActions
|
||||
? 'then'
|
||||
: 'nothing';
|
||||
return sentence(
|
||||
ctx.t,
|
||||
summary.matchAll.length > 0 || summary.matchAny.length > 0 ? 'if' : 'always',
|
||||
summary.matchNone.length > 0,
|
||||
ending,
|
||||
{
|
||||
conditions: conditionsClause(ctx.t, summary),
|
||||
exceptions: formatList(summary.matchNone, 'disjunction'),
|
||||
actions: formatList(summary.actions),
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
export function actionRequiredMessage(t: TFunction): string {
|
||||
return t('mailRules.builder.actionRequired', 'Add at least one action, or stop processing more rules.');
|
||||
}
|
||||
|
||||
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 'keywordConflict':
|
||||
return t('mailRules.issue.keywordConflict', 'A rule cannot both add and remove the same keyword.');
|
||||
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 'sizeInvalid':
|
||||
return t('mailRules.issue.sizeInvalid', 'A size must be at least 1 KB and at most {{max}}.', {
|
||||
max: formatSize(MAX_SIZE_KB * KILOBYTE),
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -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 {
|
||||
|
||||
+296
-2
@@ -23,6 +23,7 @@
|
||||
"finishSetup": "Finish setup",
|
||||
"loadingSetup": "Loading setup...",
|
||||
"nextStepBody": "restart Stalwart for the new configuration to take effect. Once restarted, sign in with the credentials above to continue administering your server.",
|
||||
"nextStepBodyNoCredentials": "restart Stalwart for the new configuration to take effect. No administrator account was created because accounts come from the external directory. Once restarted, sign in with the recovery administrator set in STALWART_RECOVERY_ADMIN and assign an administrator role to a directory account.",
|
||||
"nextStepLabel": "Next step:",
|
||||
"noConfirm": "The server did not confirm the update.",
|
||||
"stepOf": "Step {{current}} of {{total}}",
|
||||
@@ -34,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",
|
||||
@@ -149,6 +151,11 @@
|
||||
"viewDetails": "View details",
|
||||
"waiting": "Waiting for more events"
|
||||
},
|
||||
"destroyContents": {
|
||||
"AddressBook": "Every contact in it is deleted too.",
|
||||
"Calendar": "Every event in it is deleted too.",
|
||||
"Mailbox": "Every message in it is deleted too."
|
||||
},
|
||||
"duration": {
|
||||
"days": "Days",
|
||||
"hours": "Hours",
|
||||
@@ -226,7 +233,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",
|
||||
@@ -247,6 +270,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",
|
||||
@@ -256,6 +281,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.",
|
||||
@@ -268,7 +295,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",
|
||||
@@ -408,6 +436,19 @@
|
||||
"statusDisabled": "Two-factor authentication is not enabled.",
|
||||
"statusEnabled": "Two-factor authentication is enabled."
|
||||
},
|
||||
"passkey": {
|
||||
"alreadyRegistered": "This device already holds a passkey for your account.",
|
||||
"create": "Create passkey",
|
||||
"createAgain": "Create again",
|
||||
"createFailed": "The passkey could not be created. Please try again.",
|
||||
"createPrompt": "Confirm your password, then follow the prompt from your browser to create a passkey on this device or a security key.",
|
||||
"currentSecretLabel": "Current password",
|
||||
"otpRequired": "Enter your current authenticator code to create a passkey.",
|
||||
"ready": "Passkey created. Save to add it to your account.",
|
||||
"secretRequired": "Enter your current password to create a passkey.",
|
||||
"unsupported": "This browser does not support passkeys.",
|
||||
"waiting": "Waiting for your passkey"
|
||||
},
|
||||
"rate": {
|
||||
"count": "Count",
|
||||
"per": "per",
|
||||
@@ -474,5 +515,258 @@
|
||||
"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}}",
|
||||
"allAndAny": "{{all}}, and either {{any}}",
|
||||
"rule": {
|
||||
"always_then": "For every message, then {{actions}}.",
|
||||
"always_thenStop": "For every message, then {{actions}}, and stop processing more rules.",
|
||||
"always_onlyStop": "For every message, then stop processing more rules.",
|
||||
"always_nothing": "For every message, then do nothing.",
|
||||
"alwaysExcept_then": "For every message, except if {{exceptions}}, then {{actions}}.",
|
||||
"alwaysExcept_thenStop": "For every message, except if {{exceptions}}, then {{actions}}, and stop processing more rules.",
|
||||
"alwaysExcept_onlyStop": "For every message, except if {{exceptions}}, then stop processing more rules.",
|
||||
"alwaysExcept_nothing": "For every message, except if {{exceptions}}, then do nothing.",
|
||||
"if_then": "If {{conditions}}, then {{actions}}.",
|
||||
"if_thenStop": "If {{conditions}}, then {{actions}}, and stop processing more rules.",
|
||||
"if_onlyStop": "If {{conditions}}, then stop processing more rules.",
|
||||
"if_nothing": "If {{conditions}}, then do nothing.",
|
||||
"ifExcept_then": "If {{conditions}}, except if {{exceptions}}, then {{actions}}.",
|
||||
"ifExcept_thenStop": "If {{conditions}}, except if {{exceptions}}, then {{actions}}, and stop processing more rules.",
|
||||
"ifExcept_onlyStop": "If {{conditions}}, except if {{exceptions}}, then stop processing more rules.",
|
||||
"ifExcept_nothing": "If {{conditions}}, except if {{exceptions}}, then do nothing."
|
||||
},
|
||||
"action": {
|
||||
"clearKeywords": "remove all keywords added by earlier rules",
|
||||
"clearFlag": "clear the flag",
|
||||
"removeKeywords_one": "remove the keyword {{keywords}}",
|
||||
"removeKeywords_other": "remove the keywords {{keywords}}",
|
||||
"markRead": "mark it as read",
|
||||
"flag": "flag it",
|
||||
"markNotJunk": "mark it as not spam",
|
||||
"addKeywords_one": "add the keyword {{keywords}}",
|
||||
"addKeywords_other": "add the keywords {{keywords}}",
|
||||
"setImportance": "set the importance to {{level}}",
|
||||
"redirect": "redirect to {{addresses}}",
|
||||
"redirectWithoutCopy": "redirect to {{addresses}} without keeping a copy",
|
||||
"reply": "reply with a template",
|
||||
"replySubject": "reply with {{subject}}",
|
||||
"replyEveryMessage": "reply to every message",
|
||||
"replySubjectEveryMessage": "reply with {{subject}} to every message",
|
||||
"replyDays_one": "reply at most once a day per sender",
|
||||
"replyDays_other": "reply at most once every {{count}} days per sender",
|
||||
"replySubjectDays_one": "reply with {{subject}} at most once a day per sender",
|
||||
"replySubjectDays_other": "reply with {{subject}} at most once every {{count}} days per sender",
|
||||
"copyTo": "copy it to {{mailboxes}}",
|
||||
"moveTo": "move it to {{mailboxes}}",
|
||||
"discard": "delete it permanently",
|
||||
"reject": "reject it",
|
||||
"rejectReason": "reject it with {{reason}}"
|
||||
}
|
||||
},
|
||||
"issue": {
|
||||
"rejectNotAlone": "A rule that rejects mail cannot have other actions.",
|
||||
"forwardingNotAllowed": "Your account is not allowed to forward mail, so this rule cannot be saved while it is enabled.",
|
||||
"sizeInvalid": "A size must be at least 1 KB and at most {{max}}.",
|
||||
"keywordConflict": "A rule cannot both add and remove the same keyword."
|
||||
},
|
||||
"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": {
|
||||
"conditionN": "Condition {{n}}",
|
||||
"exceptionN": "Exception {{n}}",
|
||||
"noConditions": "No conditions: the rule applies to every message.",
|
||||
"addCondition": "Add condition",
|
||||
"addException": "Add exception",
|
||||
"rejectNotAlone": "Reject must be the only action.",
|
||||
"rejectStops": "A rule that rejects mail always stops processing more rules.",
|
||||
"actionRequired": "Add at least one action, or stop processing more rules.",
|
||||
"missingFields": "Fill in {{fields}}.",
|
||||
"replyEveryMessage": "With 0 days between replies, every message gets a reply.",
|
||||
"onlyStop": "Without other actions, a matching message only stops later rules from running.",
|
||||
"moveToHint": "Moving to Junk also marks the message as spam.",
|
||||
"markNotJunkHint": "Keeps the message out of Junk.",
|
||||
"keywordsToAdd": "Keywords to add",
|
||||
"keywordsToRemove": "Keywords to remove",
|
||||
"discardHint": "The message does not go to Trash.",
|
||||
"rejectHint": "Reject must be the only action. The sender is told only when their address can be verified; otherwise the message is deleted without notice.",
|
||||
"alternativeN": "Alternative {{n}}",
|
||||
"addAlternative": "Add alternative",
|
||||
"which": "Conditions",
|
||||
"what": "Actions",
|
||||
"conditionsHint": "A message must match every condition.",
|
||||
"alternatives": "Alternatives",
|
||||
"alternativesHint": "A message must match at least one alternative.",
|
||||
"alternativesHintAnd": "A message must also match at least one alternative.",
|
||||
"addAlternativeHint": "Match one of several conditions, such as two senders.",
|
||||
"exceptions": "Exceptions",
|
||||
"exceptionsHint": "The rule skips a message that matches any exception.",
|
||||
"addExceptionHint": "Skip messages that would otherwise match.",
|
||||
"and": "and",
|
||||
"or": "or",
|
||||
"preview": "Summary",
|
||||
"previewIncomplete": "Nothing yet: choose what to do with matching messages.",
|
||||
"whenItRuns": "Rules run on new mail as it arrives. Saving does not change messages already in your mailboxes.",
|
||||
"noActions": "No actions yet. Choose at least one below.",
|
||||
"noActionsReadOnly": "No actions.",
|
||||
"addAction": "Add an action",
|
||||
"addAnotherAction": "Add another action",
|
||||
"stopHint": "Rules below this one in the list are skipped for matching messages.",
|
||||
"group": {
|
||||
"file": "File",
|
||||
"mark": "Mark",
|
||||
"answer": "Answer",
|
||||
"remove": "Delete"
|
||||
},
|
||||
"itemField": "{{item}}: {{field}}"
|
||||
},
|
||||
"removeItem": "Remove {{label}}",
|
||||
"action": {
|
||||
"markRead": "Mark as read",
|
||||
"flag": "Flag",
|
||||
"clearFlag": "Clear the flag",
|
||||
"markNotJunk": "Mark as not spam",
|
||||
"addKeywords": "Add keywords",
|
||||
"removeKeywords": "Remove keywords",
|
||||
"clearKeywords": "Remove all keywords added by earlier rules",
|
||||
"setImportance": "Set the importance",
|
||||
"redirect": "Redirect to other addresses",
|
||||
"reply": "Reply with a template",
|
||||
"copyTo": "Copy to",
|
||||
"moveTo": "Move to",
|
||||
"discard": "Delete permanently",
|
||||
"reject": "Reject with a message",
|
||||
"stopProcessing": "Stop processing more rules"
|
||||
},
|
||||
"keyword": {
|
||||
"seen": "Read",
|
||||
"flagged": "Flagged",
|
||||
"answered": "Replied",
|
||||
"forwarded": "Forwarded",
|
||||
"draft": "Draft",
|
||||
"deleted": "Marked for deletion",
|
||||
"important": "Important",
|
||||
"junk": "Spam",
|
||||
"notJunk": "Not spam",
|
||||
"phishing": "Phishing"
|
||||
},
|
||||
"trashMailbox": "Trash",
|
||||
"junkMailbox": "Junk",
|
||||
"addMailbox": "Add another mailbox"
|
||||
},
|
||||
"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}}”."
|
||||
}
|
||||
}
|
||||
+4
-4
@@ -80,8 +80,8 @@
|
||||
--shadow-c2: rgb(62 44 26 / 0.05);
|
||||
--hi: rgb(255 255 255 / 0);
|
||||
|
||||
--chart-1: #db2d54;
|
||||
--chart-2: #2a9d8f;
|
||||
--chart-1: #2a9d8f;
|
||||
--chart-2: #db2d54;
|
||||
--chart-3: #d9822b;
|
||||
--chart-4: #4a3f8f;
|
||||
--chart-5: #8b7e6e;
|
||||
@@ -153,8 +153,8 @@
|
||||
--shadow-c2: rgb(0 0 0 / 0.3);
|
||||
--hi: rgb(255 255 255 / 0.045);
|
||||
|
||||
--chart-1: #ff5c7f;
|
||||
--chart-2: #4cc3b3;
|
||||
--chart-1: #4cc3b3;
|
||||
--chart-2: #ff5c7f;
|
||||
--chart-3: #f0a35a;
|
||||
--chart-4: #a99bf0;
|
||||
--chart-5: #9e9ea4;
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
/*
|
||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||
*
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
import i18n from '@/i18n';
|
||||
|
||||
export function destroyContentsNotice(objectName: string): string | null {
|
||||
switch (objectName) {
|
||||
case 'Mailbox':
|
||||
return i18n.t('destroyContents.Mailbox', 'Every message in it is deleted too.');
|
||||
case 'Calendar':
|
||||
return i18n.t('destroyContents.Calendar', 'Every event in it is deleted too.');
|
||||
case 'AddressBook':
|
||||
return i18n.t('destroyContents.AddressBook', 'Every contact in it is deleted too.');
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export function withDestroyContentsNotice(description: string, objectName: string): string {
|
||||
const notice = destroyContentsNotice(objectName);
|
||||
return notice ? `${description} ${notice}` : description;
|
||||
}
|
||||
@@ -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,
|
||||
|
||||
+97
-9
@@ -4,21 +4,25 @@
|
||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||
*/
|
||||
|
||||
import i18next from 'i18next';
|
||||
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;
|
||||
|
||||
function baseLanguage(tag: string): string {
|
||||
return tag.toLowerCase().split(/[-_]/)[0];
|
||||
}
|
||||
|
||||
export function getFormatLocale(): string {
|
||||
const { locale } = useAccountStore.getState();
|
||||
if (locale && locale !== DEFAULT_LOCALE) return locale;
|
||||
const nav = typeof navigator !== 'undefined' ? (navigator.languages ?? [navigator.language]) : [];
|
||||
const lang = i18next.resolvedLanguage || i18next.language;
|
||||
if (!lang || lang === 'cimode') return nav[0] || 'en';
|
||||
const wanted = baseLanguage(lang);
|
||||
return nav.find((tag) => tag && baseLanguage(tag) === wanted) ?? lang;
|
||||
return nav[0] || DEFAULT_LOCALE;
|
||||
}
|
||||
|
||||
const numberFormats = new Map<string, Intl.NumberFormat>();
|
||||
@@ -160,3 +164,87 @@ 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' | 'unit' = '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 }]),
|
||||
);
|
||||
}
|
||||
@@ -224,7 +224,6 @@ export async function startAuthFlow(username: string, returnUrl?: string | null)
|
||||
code_challenge_method: codeChallengeMethod,
|
||||
state,
|
||||
login_hint: username,
|
||||
prompt: 'login',
|
||||
});
|
||||
|
||||
const scope = selectScopes(discovery);
|
||||
@@ -235,7 +234,7 @@ export async function startAuthFlow(username: string, returnUrl?: string | null)
|
||||
params.set('resource', resource);
|
||||
}
|
||||
|
||||
window.location.href = `${authorization_endpoint}?${params.toString()}`;
|
||||
window.location.href = appendQuery(authorization_endpoint, params);
|
||||
}
|
||||
|
||||
export function getStoredOAuthData() {
|
||||
@@ -276,6 +275,10 @@ export function buildEndSessionUrl(endSessionEndpoint: string, postLogoutRedirec
|
||||
client_id: clientId,
|
||||
post_logout_redirect_uri: postLogoutRedirectUri,
|
||||
});
|
||||
const sep = endSessionEndpoint.includes('?') ? '&' : '?';
|
||||
return `${endSessionEndpoint}${sep}${params.toString()}`;
|
||||
return appendQuery(endSessionEndpoint, params);
|
||||
}
|
||||
|
||||
function appendQuery(endpoint: string, params: URLSearchParams): string {
|
||||
const sep = endpoint.includes('?') ? '&' : '?';
|
||||
return `${endpoint}${sep}${params.toString()}`;
|
||||
}
|
||||
+30
-11
@@ -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 {
|
||||
@@ -159,11 +168,21 @@ export function jmapQuery(
|
||||
return jmapCall<JmapQueryResponse>(`${objectType}/query`, args, options.signal);
|
||||
}
|
||||
|
||||
const DESTROY_CONTENTS_ARGS: ReadonlyMap<string, string> = new Map([
|
||||
['Mailbox', 'onDestroyRemoveEmails'],
|
||||
['Calendar', 'onDestroyRemoveEvents'],
|
||||
['AddressBook', 'onDestroyRemoveContents'],
|
||||
]);
|
||||
|
||||
export function jmapSetArgs(objectType: string, set: JmapSetOptions, accountId?: string): Record<string, unknown> {
|
||||
const args: Record<string, unknown> = { accountId: accountId ?? getAccountId(objectType) };
|
||||
if (set.create && Object.keys(set.create).length > 0) args.create = set.create;
|
||||
if (set.update && Object.keys(set.update).length > 0) args.update = set.update;
|
||||
if (set.destroy && set.destroy.length > 0) args.destroy = set.destroy;
|
||||
if (set.destroy && set.destroy.length > 0) {
|
||||
args.destroy = set.destroy;
|
||||
const destroyContents = DESTROY_CONTENTS_ARGS.get(objectType);
|
||||
if (destroyContents) args[destroyContents] = true;
|
||||
}
|
||||
return args;
|
||||
}
|
||||
|
||||
@@ -300,7 +319,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,6 +7,8 @@
|
||||
import { create } from 'zustand';
|
||||
import { isCommunityEdition } from '@/lib/permissions';
|
||||
|
||||
export const DEFAULT_LOCALE = 'en-US';
|
||||
|
||||
export type Edition = 'enterprise' | 'community' | (string & {});
|
||||
|
||||
export interface AccountState {
|
||||
@@ -22,7 +24,7 @@ export interface AccountState {
|
||||
export const useAccountStore = create<AccountState>()((set, get) => ({
|
||||
permissions: [],
|
||||
edition: 'community',
|
||||
locale: 'en',
|
||||
locale: DEFAULT_LOCALE,
|
||||
|
||||
setAccountInfo: (permissions, edition, locale) => {
|
||||
set({ permissions, edition, locale });
|
||||
|
||||
@@ -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