8 Commits
28 changed files with 1918 additions and 654 deletions

No files matched your search

+27
View File
@@ -2,6 +2,33 @@
All notable changes to this project will be documented in this file. This project adheres to [Semantic Versioning](http://semver.org/).
## [2.1.3] - 2026-12-03
### Fixed
- Browser auto-translation (Chrome, Edge, Safari) is turned off for the web interface, which crashed with a `removeChild` error when the translator rewrote the page.
- Forms: Save is enabled as soon as a field is edited, without leaving the field first, and the Delete, Cancel and Save buttons no longer move when the "Unsaved changes" label appears.
## [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
+2 -1
View File
@@ -1,8 +1,9 @@
<!doctype html>
<html lang="en">
<html lang="en" translate="no">
<head>
<meta charset="UTF-8" />
<meta name="google" content="notranslate" />
<base href="/" />
<meta name="oauth-client-id" content="" />
<meta name="oauth-scopes" content="" />
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "stalwart-webui",
"version": "2.1.0",
"version": "2.1.3",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "stalwart-webui",
"version": "2.1.0",
"version": "2.1.3",
"dependencies": {
"@daypicker/react": "^10.0.2",
"@dnd-kit/core": "^6.3.1",
+1 -1
View File
@@ -1,7 +1,7 @@
{
"name": "stalwart-webui",
"private": true,
"version": "2.1.0",
"version": "2.1.3",
"stalwart": {
"minServerVersion": "1.0.0"
},
+27 -9
View File
@@ -21,6 +21,7 @@ import { UnsavedChangesDialog } from '@/components/forms/UnsavedChangesDialog';
import { formFieldLabels } 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;
@@ -144,15 +145,17 @@ export function DynamicForm({
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, { accountId, fieldOverrides, createValues });
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 [pendingInput, setPendingInput] = useState(false);
const title = useFormTitle(model);
const sectionPrefix = useId();
const wide = useSyncExternalStore(subscribeWide, isWide, () => false);
@@ -163,6 +166,7 @@ export function DynamicForm({
const isCreate = mode === 'create';
const readOnly = !isCreate && !canUpdate;
const canDelete = !isCreate && !isSingleton && canDestroy;
const hasChanges = isDirty || pendingInput;
const subtitle = (model.parentForm ?? model.variantForm)?.subtitle;
const errorText = state.generalError ?? loadError;
const header = (
@@ -220,7 +224,15 @@ export function DynamicForm({
<div className={cn(showIndex && 'xl:grid xl:grid-cols-[11rem_minmax(0,1fr)] xl:items-start xl:gap-6')}>
{showIndex && wide && <SectionIndex sections={model.sections} sectionId={sectionId} />}
<div className="space-y-3.5">
<div
className="space-y-3.5"
onInput={(e) => {
if (!pendingInput && e.target instanceof Node && e.currentTarget.contains(e.target)) setPendingInput(true);
}}
onBlur={() => {
if (pendingInput) setPendingInput(false);
}}
>
<FormProvider
schema={schema}
mode={mode}
@@ -264,8 +276,13 @@ export function DynamicForm({
<FloatingActionDivider />
</>
)}
{isDirty && (
<span className="flex items-center gap-2 px-2 text-[13px] text-ink-muted max-sm:hidden">
{!readOnly && (
<span
className={cn(
'flex items-center gap-2 px-2 text-[13px] text-ink-muted max-sm:hidden',
!hasChanges && 'invisible',
)}
>
<FloatingActionDot />
{t('form.unsavedChangesLabel', 'Unsaved changes')}
</span>
@@ -279,7 +296,7 @@ export function DynamicForm({
size="sm"
className="shadow-none"
onClick={() => void model.save()}
disabled={saving || (!isCreate && !isDirty)}
disabled={saving || (!isCreate && !hasChanges)}
>
{saving ? (
<Loader2 className="h-4 w-4 animate-spin" aria-hidden="true" />
@@ -298,10 +315,11 @@ export function DynamicForm({
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}
+12
View File
@@ -495,6 +495,18 @@ export function buildSections(
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']);
+6 -3
View File
@@ -43,6 +43,7 @@ import {
validateRequired,
validatedFieldNames,
VARIANT_FIELD,
withoutSectionTitles,
type FieldErrors,
type FieldValues,
} from '@/components/forms/formLogic';
@@ -102,6 +103,7 @@ export interface FieldRenderProps {
export interface FieldOverrides {
hidden?: readonly string[];
untitled?: readonly string[];
render?: Readonly<Record<string, ComponentType<FieldRenderProps>>>;
validate?: (data: FieldValues) => FieldErrors;
}
@@ -110,12 +112,13 @@ export interface DynamicFormOptions {
accountId?: string;
fieldOverrides?: FieldOverrides;
createValues?: FieldValues;
showCreatedValues?: boolean;
}
export function useDynamicForm(
viewName: string,
objectId: string | null,
{ accountId, fieldOverrides, createValues }: DynamicFormOptions = {},
{ accountId, fieldOverrides, createValues, showCreatedValues = true }: DynamicFormOptions = {},
) {
const { t } = useTranslation();
const navigate = useNavigate();
@@ -182,7 +185,7 @@ export function useDynamicForm(
}
const form = sch?.type === 'multiple' ? combineForms(parentForm, variantForm) : variantForm;
const hidden = new Set(fieldOverrides?.hidden);
const sections = buildSections(form, fields, mode, hidden);
const sections = withoutSectionTitles(buildSections(form, fields, mode, hidden), fieldOverrides?.untitled);
const loading = mode === 'edit' && objectQuery.fetchStatus !== 'idle' && !objectQuery.isFetchedAfterMount;
const loadError =
@@ -304,7 +307,7 @@ export function useDynamicForm(
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' });
+23 -18
View File
@@ -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,
@@ -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);
+23
View File
@@ -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;
}
+70 -2
View File
@@ -6,11 +6,78 @@
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 MAILBOX_FIELD = 'mailboxId';
export const MAILBOX_SCHEMA = 'x:MailRuleMailbox';
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 [];
@@ -39,6 +106,7 @@ 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;
@@ -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,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>
);
}
@@ -9,16 +9,18 @@ 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 { nextRulePosition } from '../model';
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 RULE_FIELDS = ['matchAll', 'conditions', 'exceptions', 'stopProcessing', 'timeZone'] as const;
const ABSORBED_FIELD = 'conditions';
function Omitted() {
return null;
@@ -26,18 +28,36 @@ function Omitted() {
const FIELD_OVERRIDES: FieldOverrides = {
hidden: ['position'],
untitled: [RULE_ANCHOR],
render: {
...Object.fromEntries(RULE_FIELDS.map((name) => [name, Omitted])),
[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 = {
...Object.fromEntries(RULE_FIELDS.map((name) => [name, Omitted])),
[ABSORBED_FIELD]: Omitted,
[RULE_ANCHOR]: RuleSummaryRow,
};
function CreateRuleForm({ viewName, accountId }: { viewName: string; accountId: string }) {
function CreateRuleForm({
viewName,
accountId,
fieldOverrides,
}: {
viewName: string;
accountId: string;
fieldOverrides: FieldOverrides;
}) {
const { t } = useTranslation();
const rules = useMailRules(accountId);
if (rules.isError) {
@@ -54,17 +74,20 @@ function CreateRuleForm({ viewName, accountId }: { viewName: string; accountId:
viewName={viewName}
objectId={null}
accountId={accountId}
fieldOverrides={FIELD_OVERRIDES}
createValues={{ position: nextRulePosition(rules.data) }}
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} />;
return <DynamicForm viewName={viewName} objectId={objectId} accountId={accountId} fieldOverrides={FIELD_OVERRIDES} />;
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) {
@@ -15,7 +15,7 @@ import { errorMessage } from '@/lib/jmapErrors';
import { useSchemaStore } from '@/stores/schemaStore';
import type { PageProps } from '@/extensions/types';
import { useRuleAccountId } from '../account';
import { mailboxNameResolver } from '../mailboxes';
import { mailboxNamer } from '../mailboxes';
import { useMailboxOptions, useMailRules } from '../queries';
import { CustomRuleList } from './CustomRuleList';
@@ -41,7 +41,7 @@ export function MailRulesPage({ viewName, section }: PageProps) {
const summary = {
t,
schema,
mailboxName: mailboxes.status === 'ready' ? mailboxNameResolver(mailboxes.options) : undefined,
mailboxName: mailboxNamer(t, mailboxes.status === 'ready' ? mailboxes.options : undefined),
};
return (
@@ -7,58 +7,74 @@
import { useTranslation } from 'react-i18next';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { BufferedInput } from '@/components/forms/widgets/BufferedInputs';
import type { ControlProps } from '@/components/forms/widgets/types';
import { 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;
interface MailboxPickerProps {
accountId: string | null;
value: unknown;
onChange: (value: string) => void;
readOnly: boolean;
control: ControlProps;
}
export function MailboxPicker({ accountId, value, onChange, readOnly, control }: MailboxPickerProps) {
export function MailboxPicker({ type, value, onChange, readOnly, control }: WidgetProps) {
const { t } = useTranslation();
const mailboxes = useMailboxOptions(accountId);
const current = typeof value === 'string' ? value : '';
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');
if (mailboxes.status !== 'ready') {
return (
<BufferedInput
{...control}
value={current}
onCommit={onChange}
readOnly={readOnly}
disabled={mailboxes.status === 'loading'}
placeholder={t('mailRules.mailboxId', 'Mailbox id')}
/>
);
}
const { options } = mailboxes;
const selected = options.find((option) => option.id === current);
return (
<Select value={current} onValueChange={onChange} disabled={readOnly}>
<SelectTrigger {...control} className="w-full">
<SelectValue placeholder={t('mailRules.chooseMailbox', 'Choose a mailbox')}>
{selected ? selected.path.join(' / ') : undefined}
</SelectValue>
</SelectTrigger>
<SelectContent>
{current && !selected && (
<SelectItem value={current}>
{t('mailRules.unknownMailbox', 'Unknown mailbox ({{id}})', { id: current })}
</SelectItem>
)}
{options.map((option) => (
<SelectItem key={option.id} value={option.id} textValue={option.path.join(' / ')}>
<span style={{ paddingInlineStart: `${option.depth * INDENT_REM}rem` }}>{option.name}</span>
</SelectItem>
<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')}
/>
))}
</SelectContent>
</Select>
</div>
);
}
+218 -239
View File
@@ -4,106 +4,60 @@
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
*/
import { useRef, useState, type KeyboardEvent, type ReactNode } from 'react';
import { useState, type ReactNode } from 'react';
import { useTranslation } from 'react-i18next';
import { AlertTriangle, ChevronRight } from 'lucide-react';
import { FieldError, FieldRow } from '@/components/forms/FieldRow';
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 { embeddedEntries, resolveEmbedded } from '@/lib/embeddedSchema';
import { cn } from '@/lib/utils';
import { isRecord, resolveEmbedded } from '@/lib/embeddedSchema';
import { buildNewObjectValue } from '@/lib/schemaResolver';
import type { ViewRenderProps } from '@/components/views/DynamicView';
import type { Field, FieldTypeObjectList } from '@/types/schema';
import { useRuleAccountId } from '../account';
import { listEntries } from '../builder';
import { mailboxNameResolver } from '../mailboxes';
import { appendItem, listEntries, type ListItems } from '../builder';
import { mailboxNamer } from '../mailboxes';
import {
hasRejectAction,
hasScheduleCondition,
isRejectAllowed,
MAIL_RULE_ACTION_OBJECT,
hasOtherAction,
MAIL_RULE_ACTIONS_OBJECT,
needsAction,
MAIL_RULE_CONDITION_OBJECT,
MAIL_RULE_OBJECT,
MAIL_RULE_CONDITIONS_OBJECT,
parseCustomBody,
REJECT_ACTION,
ruleIssues,
type ConditionGroup,
type RuleIssue,
} from '../model';
import { useMailboxOptions } from '../queries';
import { ruleIssueMessage, ruleSentence, summarizeCustomRule } from '../summary';
import { RuleItemList } from './RuleItemList';
import { ActionForm } from './ActionForm';
import { RuleItemList, type RuleItemListProps } from './RuleItemList';
const TRAILING_FIELDS = new Set(['stopProcessing', 'timeZone']);
const RULE_ERROR_FIELDS = ['matchAll', 'conditions', 'exceptions'] as const;
const STOP_PROCESSING = 'stopProcessing';
const TOGGLE_KEYS = new Set(['ArrowLeft', 'ArrowRight', 'ArrowUp', 'ArrowDown']);
function listBounds(field: Field | undefined): { minItems?: number; maxItems?: number } {
const type = field?.type as FieldTypeObjectList | undefined;
return type?.type === 'objectList' ? { minItems: type.minItems, maxItems: type.maxItems } : {};
}
function MatchModeToggle({
matchAll,
onChange,
readOnly,
}: {
matchAll: boolean;
onChange: (matchAll: boolean) => void;
readOnly: boolean;
}) {
const { t } = useTranslation();
const options = [
{ value: true, label: t('mailRules.builder.all', 'all') },
{ value: false, label: t('mailRules.builder.any', 'any') },
];
const onKeyDown = (event: KeyboardEvent<HTMLSpanElement>) => {
if (readOnly || !TOGGLE_KEYS.has(event.key)) return;
event.preventDefault();
onChange(!matchAll);
event.currentTarget.querySelector<HTMLButtonElement>('[aria-checked="false"]')?.focus();
};
function Step({ number, heading, children }: { number: number; heading: string; children: ReactNode }) {
return (
<span
role="radiogroup"
aria-label={t('mailRules.builder.matchMode', 'Conditions that must match')}
className="inline-flex rounded-lg bg-muted p-0.5 align-middle"
onKeyDown={onKeyDown}
>
{options.map((option) => (
<button
key={String(option.value)}
type="button"
role="radio"
aria-checked={matchAll === option.value}
tabIndex={matchAll === option.value ? 0 : -1}
disabled={readOnly}
onClick={() => onChange(option.value)}
className={cn(
'rounded-md px-2.5 py-0.5 text-sm font-semibold transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring',
matchAll === option.value ? 'bg-primary text-primary-foreground' : 'text-muted-foreground',
)}
<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"
>
{option.label}
</button>
))}
</span>
);
}
function Step({ heading, title, children }: { heading: string; title?: ReactNode; children: ReactNode }) {
return (
<section className="space-y-2 py-3">
<h3 className={title ? 'sr-only' : 'text-[13.5px] font-semibold'}>{heading}</h3>
{title && <div className="text-[13.5px] font-semibold">{title}</div>}
{children}
{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;
@@ -119,178 +73,203 @@ function IssueList({ issues }: { issues: readonly RuleIssue[] }) {
);
}
export function RuleBuilderRow({ data: body, errors, readOnly, onFieldChange: set }: FieldRenderProps) {
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 exceptionsButton = useRef<HTMLButtonElement>(null);
const custom = parseCustomBody(body);
const resolved = resolveEmbedded(schema, MAIL_RULE_OBJECT, body);
const entries = resolved ? embeddedEntries(resolved) : [];
const fieldOf = (name: string) => entries.find((entry) => entry.formField.name === name);
const [exceptionsExpanded, setExceptionsExpanded] = useState<boolean | null>(null);
const missing = new Set(
errors.conditions || errors.exceptions || errors.actions ? missingNestedFields(schema, MAIL_RULE_OBJECT, body) : [],
);
const errorOf = (name: string) => (missing.has(name) ? undefined : errors[name]);
const [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 hasReject = hasRejectAction(custom);
const rejectBlocked =
custom.actions.length > 1
? t('mailRules.builder.rejectNotAlone', 'Reject must be the only action.')
: isRejectAllowed(custom)
? undefined
: t(
'mailRules.builder.rejectNeedsAuthentication',
'Reject needs all conditions to match, including an authenticated sender.',
);
const disabledActions = rejectBlocked ? new Map([[REJECT_ACTION, rejectBlocked]]) : undefined;
const conditionLabel = (n: number) => t('mailRules.builder.conditionN', 'Condition {{n}}', { n });
const exceptionLabel = (n: number) => t('mailRules.builder.exceptionN', 'Exception {{n}}', { n });
const actionLabel = (n: number) => t('mailRules.builder.actionN', 'Action {{n}}', { n });
const showExceptions = !!errors.exceptions || (exceptionsExpanded ?? custom.exceptions.length > 0);
const exceptionsId = `${fieldIds(idPrefix, ['exceptions']).inputId}-list`;
const actionsErrorId = fieldIds(idPrefix, ['actions']).errorId;
const ruleErrorField = RULE_ERROR_FIELDS.find((name) => errorOf(name));
const actionsError =
errors.actions &&
(custom.actions.length === 0
? t('mailRules.builder.actionRequired', 'Add at least one action.')
: errorOf('actions'));
const changeExceptions = (next: unknown) => {
if (custom.exceptions.length > 0 && listEntries(next).length === 0) exceptionsButton.current?.focus();
set('exceptions', next);
const 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>
);
};
const trailing = entries.filter(
({ formField }) =>
TRAILING_FIELDS.has(formField.name) && (formField.name !== 'timeZone' || hasScheduleCondition(custom)),
);
return (
<div className="divide-y divide-border" data-testid="mail-rule-builder">
{ruleErrorField && (
<div className="py-3">
<FieldError id={fieldIds(idPrefix, [ruleErrorField]).errorId} error={errorOf(ruleErrorField)} />
</div>
)}
<Step
heading={
custom.conditions.length >= 2
? t('mailRules.builder.conditions', 'Conditions')
: custom.conditions.length === 1
? t('mailRules.builder.ifOne', 'If this condition matches')
: t('mailRules.builder.ifNone', 'For every message')
}
title={
custom.conditions.length >= 2 && (
<span className="flex flex-wrap items-center gap-1.5">
{t('mailRules.builder.ifPrefix', 'If')}
<MatchModeToggle
matchAll={custom.matchAll}
onChange={(matchAll) => set('matchAll', matchAll)}
readOnly={readOnly}
/>
{t('mailRules.builder.ifSuffix', 'of these conditions match')}
</span>
)
}
>
{custom.conditions.length === 0 && (
<p className="text-[12.5px] text-muted-foreground">
{t('mailRules.builder.noConditions', 'Without conditions the rule applies to every message.')}
</p>
)}
<RuleItemList
name="conditions"
objectName={MAIL_RULE_CONDITION_OBJECT}
value={body.conditions}
onChange={(next) => set('conditions', next)}
readOnly={readOnly}
invalid={!!errors.conditions}
{...listBounds(fieldOf('conditions')?.field)}
itemLabel={conditionLabel}
addLabel={t('mailRules.builder.addCondition', 'Add condition')}
/>
</Step>
<div className="space-y-1" data-testid="mail-rule-builder">
<RulePreview body={body} incomplete={needsAction(actions)} />
<section className="py-3">
<button
ref={exceptionsButton}
type="button"
aria-expanded={showExceptions}
aria-controls={exceptionsId}
onClick={() => setExceptionsExpanded(!showExceptions)}
className="flex items-center gap-1.5 rounded-md text-[13.5px] font-semibold focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
>
<ChevronRight
className={cn('size-4 text-dim transition-transform', showExceptions && 'rotate-90')}
aria-hidden="true"
<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}
/>
{t('mailRules.builder.except', 'Except if any of these match')}
{!showExceptions && custom.exceptions.length > 0 && (
<span className="font-normal text-muted-foreground">({custom.exceptions.length})</span>
<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>
)}
</button>
{showExceptions && (
<div id={exceptionsId} className="mt-2">
<RuleItemList
name="exceptions"
objectName={MAIL_RULE_CONDITION_OBJECT}
value={body.exceptions}
onChange={changeExceptions}
readOnly={readOnly}
invalid={!!errors.exceptions}
{...listBounds(fieldOf('exceptions')?.field)}
itemLabel={exceptionLabel}
addLabel={t('mailRules.builder.addException', 'Add exception')}
/>
</div>
)}
</section>
</Step>
<Step heading={t('mailRules.builder.then', 'Then')}>
<RuleItemList
name="actions"
objectName={MAIL_RULE_ACTION_OBJECT}
value={body.actions}
onChange={(next) => set('actions', next)}
readOnly={readOnly}
invalid={!!errors.actions}
{...listBounds(fieldOf('actions')?.field)}
canAddMore={!hasReject}
itemLabel={actionLabel}
addLabel={t('mailRules.builder.addAction', 'Add action')}
disabledVariants={disabledActions}
/>
<FieldError id={actionsErrorId} error={actionsError} />
</Step>
{trailing.length > 0 && (
<div className="@container">
{trailing.map(({ formField, field }) =>
hasReject && formField.name === STOP_PROCESSING ? (
<div key={formField.name}>
<FieldRow field={field} formField={formField} value={true} onChange={() => {}} readOnly />
<p className="pb-3 text-[12.5px] text-muted-foreground">
{t('mailRules.builder.rejectStops', 'A rule that rejects mail always stops processing more rules.')}
</p>
</div>
) : (
<FieldRow
key={formField.name}
field={field}
formField={formField}
value={body[formField.name]}
onChange={(next) => set(formField.name, next)}
error={errors[formField.name]}
readOnly={readOnly}
/>
),
)}
</div>
)}
<IssueList issues={issues} />
<IssueList issues={issues} />
</div>
</div>
);
}
@@ -302,7 +281,7 @@ export function RuleSummaryRow({ schema, data }: ViewRenderProps) {
const ctx = {
t,
schema,
mailboxName: mailboxes.status === 'ready' ? mailboxNameResolver(mailboxes.options) : undefined,
mailboxName: mailboxNamer(t, mailboxes.status === 'ready' ? mailboxes.options : undefined),
};
return (
<ValueRow
@@ -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>
);
}
+110 -132
View File
@@ -17,33 +17,32 @@ import { FieldControl } from '@/components/forms/widgets/FieldControl';
import { embeddedEntries, resolveEmbedded, switchVariantValues } from '@/lib/embeddedSchema';
import { formatList } from '@/lib/format';
import { buildEmbeddedDefaults, buildNewObjectValue } from '@/lib/schemaResolver';
import { useRuleAccountId } from '../account';
import {
appendItem,
isInlineField,
KEYWORD_TEST_SCHEMA,
KEYWORDS_FIELD,
listEntries,
MAILBOX_FIELD,
MAILBOX_SCHEMA,
removeItem,
replaceItem,
type ListItems,
} from '../builder';
import { MailboxPicker } from './MailboxPicker';
import { KeywordInput } from './KeywordInput';
import { RuleFieldRow } from './RuleFieldRow';
const NO_MISSING: ReadonlySet<string> = new Set();
interface RuleItemListProps {
export interface RuleItemListProps {
name: string;
objectName: string;
value: unknown;
onChange: (value: unknown) => void;
onChange: (value: ListItems) => void;
readOnly: boolean;
invalid: boolean;
minItems?: number;
maxItems?: number;
canAddMore?: boolean;
itemLabel: (n: number) => string;
addLabel: string;
disabledVariants?: ReadonlyMap<string, string>;
joiner?: string;
}
interface RuleItemProps {
@@ -55,24 +54,13 @@ interface RuleItemProps {
onRemove: (() => void) | null;
readOnly: boolean;
invalid: boolean;
disabledVariants?: ReadonlyMap<string, string>;
joiner?: string;
}
function RuleItem({
objectName,
itemKey,
item,
label,
onChange,
onRemove,
readOnly,
invalid,
disabledVariants,
}: RuleItemProps) {
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 accountId = useRuleAccountId();
const [initial, setInitial] = useState({ baseline, item });
if (initial.baseline !== baseline) setInitial({ baseline, item });
const resolved = resolveEmbedded(schema, objectName, item);
@@ -96,66 +84,55 @@ function RuleItem({
};
return (
<li className="rounded-xl bg-card px-3 py-2.5 shadow-tile" data-testid="mail-rule-item">
<div className="flex flex-wrap items-center gap-2">
<Select value={variant} onValueChange={changeVariant} disabled={readOnly}>
<SelectTrigger
id={fieldIds(idPrefix, [...path, '@type']).inputId}
aria-label={label}
className="min-w-0 flex-1 gap-2 sm:min-w-56 sm:max-w-sm sm:flex-none"
>
<SelectValue />
</SelectTrigger>
<SelectContent>
{(resolved.variants ?? []).map((option) => {
const reason = option.name !== variant ? disabledVariants?.get(option.name) : undefined;
return (
<SelectItem key={option.name} value={option.name} disabled={!!reason}>
{reason ? (
<span className="flex flex-col">
<span>{option.label}</span>
<span className="text-xs text-muted-foreground">{reason}</span>
</span>
) : (
option.label
)}
</SelectItem>
);
})}
</SelectContent>
</Select>
{inline.map(({ formField, field }) => {
const ids = fieldIds(idPrefix, [...path, formField.name]);
const fieldValue = item[formField.name];
const setValue = (next: unknown) => onChange({ ...item, [formField.name]: next });
const isMissing = missing.has(formField.name);
const control = {
id: ids.inputId,
'aria-label': `${label}: ${formField.label}`,
'aria-invalid': isMissing || undefined,
'aria-describedby': isMissing ? itemErrorId : undefined,
};
const isMailbox = schemaName === MAILBOX_SCHEMA && formField.name === MAILBOX_FIELD;
return (
<div
key={formField.name}
className="order-2 flex min-w-0 flex-1 basis-full items-center gap-2 sm:order-none sm:basis-40"
<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"
>
{!isMailbox && field.type.type !== 'enum' && (
<label htmlFor={ids.inputId} className="shrink-0 text-[12.5px] text-muted-foreground">
{formField.label}
</label>
)}
<div className="min-w-0 flex-1">
{isMailbox ? (
<MailboxPicker
accountId={accountId}
value={fieldValue}
onChange={setValue}
readOnly={readOnly}
control={control}
/>
) : (
<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}
@@ -167,52 +144,56 @@ function RuleItem({
control={control}
/>
</FieldScopeProvider>
)}
</div>
</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>
);
})}
{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>
{missingInline.length > 0 && (
<div className="mt-1.5">
<FieldError
id={itemErrorId}
error={t('mailRules.builder.missingFields', 'Fill in {{fields}}.', {
fields: formatList(missingInline.map(({ formField }) => formField.label)),
})}
/>
</div>
)}
{block.length > 0 && (
<FieldScopeProvider name={itemKey} readOnly={readOnly}>
<EnclosingSchemaContext value={resolved.schemaName}>
<div className="@container mt-1 divide-y divide-border [&>[data-slot=field-row]]:py-3">
{block.map(({ formField, field }) => (
<FieldRow
key={formField.name}
field={field}
formField={formField}
value={item[formField.name]}
onChange={(next) => onChange({ ...item, [formField.name]: next })}
error={missing.has(formField.name) ? requiredMessage : undefined}
/>
))}
</div>
</EnclosingSchemaContext>
</FieldScopeProvider>
)}
</li>
);
}
@@ -224,33 +205,30 @@ export function RuleItemList({
onChange,
readOnly,
invalid,
minItems,
maxItems,
canAddMore = true,
itemLabel,
addLabel,
disabledVariants,
joiner,
}: RuleItemListProps) {
const { schema } = useFormContext();
const entries = listEntries(value);
const canRemove = !readOnly && (minItems == null || entries.length > minItems);
const canAdd = !readOnly && canAddMore && (maxItems == null || entries.length < maxItems);
const canAdd = !readOnly && (maxItems == null || entries.length < maxItems);
return (
<FieldScopeProvider name={name} readOnly={readOnly}>
{entries.length > 0 && (
<ol className="space-y-2">
<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={canRemove ? () => onChange(removeItem(value, key)) : null}
onRemove={readOnly ? null : () => onChange(removeItem(value, key))}
readOnly={readOnly}
invalid={invalid}
disabledVariants={disabledVariants}
/>
))}
</ol>
+16
View File
@@ -4,10 +4,14 @@
* 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;
@@ -73,3 +77,15 @@ export function mailboxNameResolver(options: readonly MailboxOption[]): (id: str
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 });
}
+128 -56
View File
@@ -11,7 +11,8 @@ import type { JmapObject } from '@/services/jmap/client';
export const MAIL_RULE_OBJECT = 'x:MailRule';
export const MAIL_RULE_CONDITION_OBJECT = 'x:MailRuleCondition';
export const MAIL_RULE_ACTION_OBJECT = 'x:MailRuleAction';
export const MAIL_RULE_CONDITIONS_OBJECT = 'x:MailRuleConditions';
export const MAIL_RULE_ACTIONS_OBJECT = 'x:MailRuleActions';
const FORWARD_PERMISSIONS = ['jmapSieveScriptCreate', 'jmapSieveScriptUpdate', 'sievePutScript'] as const;
@@ -23,21 +24,43 @@ export interface MailRule {
body: Record<string, unknown>;
}
export interface CustomRuleBody {
matchAll: boolean;
conditions: Record<string, unknown>[];
exceptions: Record<string, unknown>[];
actions: 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;
timeZone: string | null;
}
export type RuleIssue =
'rejectNotAlone' | 'rejectNeedsAuthentication' | 'forwardingNotAllowed' | 'scheduleTooManySlots';
export interface CustomRuleBody {
conditions: RuleConditions;
actions: RuleActions;
}
export const MAX_SCHEDULE_SLOTS = 14;
const SCHEDULE_CONDITION = 'Schedule';
export const REJECT_ACTION = 'Reject';
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;
@@ -147,57 +170,108 @@ export function reorderPositions(
return changes;
}
export function parseCustomBody(body: Record<string, unknown>): CustomRuleBody {
const list = (value: unknown) => jmapMapToArray<unknown>(value).filter(isRecord);
const conditions = list(body.conditions);
export function newRuleValues(position: number): JmapObject {
return {
matchAll: conditions.length < 2 || body.matchAll !== false,
conditions,
exceptions: list(body.exceptions),
actions: list(body.actions),
stopProcessing: body.stopProcessing === true,
timeZone: typeof body.timeZone === 'string' && body.timeZone !== '' ? body.timeZone : null,
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 hasVariant(items: readonly Record<string, unknown>[], type: string): boolean {
return items.some((item) => variantType(item) === type);
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 hasScheduleCondition(custom: CustomRuleBody): boolean {
return hasVariant(custom.conditions, SCHEDULE_CONDITION) || hasVariant(custom.exceptions, SCHEDULE_CONDITION);
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 mergedScheduleOverflow(items: readonly Record<string, unknown>[]): boolean {
let run = 0;
for (const item of items) {
if (variantType(item) !== SCHEDULE_CONDITION) {
run = 0;
continue;
}
run += jmapMapToArray<unknown>(item.slots).length;
if (run > MAX_SCHEDULE_SLOTS) return true;
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 false;
return actions[set].filter((keyword) => !flags.has(keyword));
}
export function hasRejectAction(custom: CustomRuleBody): boolean {
return hasVariant(custom.actions, REJECT_ACTION);
}
export function isRejectAllowed(custom: CustomRuleBody): boolean {
return custom.matchAll && hasVariant(custom.conditions, 'SenderAuthenticated');
}
function redirectTargets(custom: CustomRuleBody): number {
return custom.actions.reduce(
(total, action) => total + (variantType(action) === 'Redirect' ? setValues(action.addresses).length : 0),
0,
export function 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(parseCustomBody(body));
return redirectTargets(parseActions(body.actions));
}
export function canForward(checkers: Pick<PermissionCheckers, 'hasPermission'>): boolean {
@@ -209,15 +283,13 @@ export function ruleIssues(
checkers: Pick<PermissionCheckers, 'hasPermission'>,
): RuleIssue[] {
const issues: RuleIssue[] = [];
const custom = parseCustomBody(rule.body);
if (hasRejectAction(custom)) {
if (custom.actions.length > 1) issues.push('rejectNotAlone');
if (!isRejectAllowed(custom)) issues.push('rejectNeedsAuthentication');
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 (mergedScheduleOverflow(custom.exceptions) || (!custom.matchAll && mergedScheduleOverflow(custom.conditions))) {
issues.push('scheduleTooManySlots');
}
if (rule.isEnabled && redirectTargets(custom) > 0 && !canForward(checkers)) {
if (rule.isEnabled && redirectTargets(actions) > 0 && !canForward(checkers)) {
issues.push('forwardingNotAllowed');
}
return issues;
+347 -82
View File
@@ -18,13 +18,18 @@ import { MINUTES_PER_DAY, localTimeFromMinutes, parseLocalTime } from '@/lib/loc
import { jmapMapToArray } from '@/lib/jmapUtils';
import { getEnumVariant } from '@/lib/schemaResolver';
import type { Schema } from '@/types/schema';
import { fallbackMailboxName } from './mailboxes';
import {
MAIL_RULE_ACTION_OBJECT,
hasFlag,
isEveryMessageReply,
MAIL_RULE_CONDITION_OBJECT,
MAX_SCHEDULE_SLOTS,
MAX_SIZE_KB,
otherKeywords,
parseCustomBody,
setValues,
variantType,
type FlagAction,
type RuleActions,
type RuleIssue,
} from './model';
@@ -37,13 +42,75 @@ export interface SummaryContext {
}
export interface RuleSummary {
conditions: string[];
matchAll: boolean;
exceptions: string[];
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;
@@ -53,13 +120,61 @@ function quoted(ctx: SummaryContext, value: string): string {
return ctx.t('mailRules.summary.quoted', '“{{value}}”', { value });
}
function quotedValues(ctx: SummaryContext, value: unknown): string {
function quotedValues(
ctx: SummaryContext,
values: readonly string[],
type: 'conjunction' | 'disjunction' = 'disjunction',
): string {
return formatList(
setValues(value).map((item) => quoted(ctx, item)),
'disjunction',
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 });
@@ -68,7 +183,7 @@ function detailed(ctx: SummaryContext, label: string, detail: string): string {
function operatorTest(ctx: SummaryContext, enumName: string, item: Record<string, unknown>): string {
return ctx.t('mailRules.summary.test', '{{operator}} {{values}}', {
operator: enumLabel(ctx.schema, enumName, item.operator),
values: quotedValues(ctx, item.values),
values: quotedValues(ctx, setValues(item.values)),
});
}
@@ -91,7 +206,7 @@ function scheduleSlots(ctx: SummaryContext, value: unknown): string {
end: slotEnd(slot.end),
}),
);
return slots.join('; ');
return formatList(slots, 'unit');
}
export function conditionPhrase(ctx: SummaryContext, condition: Record<string, unknown>): string {
@@ -123,11 +238,9 @@ export function conditionPhrase(ctx: SummaryContext, condition: Record<string, u
return detailed(ctx, label, enumLabel(ctx.schema, 'MailRuleSentToMePlacement', condition.placement));
case 'SizeOver':
case 'SizeUnder':
return detailed(
ctx,
label,
typeof condition.kilobytes === 'number' ? formatSize(condition.kilobytes * KILOBYTE) : '',
);
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':
@@ -146,95 +259,247 @@ export function conditionPhrase(ctx: SummaryContext, condition: Record<string, u
}
}
function mailboxPhrase(ctx: SummaryContext, value: unknown): string {
if (typeof value !== 'string' || value === '') return '';
return quoted(ctx, ctx.mailboxName?.(value) ?? value);
function mailboxNames(ctx: SummaryContext, ids: readonly string[]): string {
return quotedValues(
ctx,
ids.map((id) => ctx.mailboxName?.(id) ?? fallbackMailboxName(ctx.t, id)),
'conjunction',
);
}
export function actionPhrase(ctx: SummaryContext, action: Record<string, unknown>): string {
const type = variantType(action) ?? '';
const label = variantLabel(ctx.schema, MAIL_RULE_ACTION_OBJECT, type) ?? type;
switch (type) {
case 'MoveTo':
case 'CopyTo':
return detailed(ctx, label, mailboxPhrase(ctx, action.mailboxId));
case 'AddKeywords':
return detailed(ctx, label, quotedValues(ctx, action.keywords));
case 'Redirect': {
const addresses = formatList(setValues(action.addresses));
const detail =
action.keepCopy === false
? ctx.t('mailRules.summary.withoutCopy', '{{addresses}} without keeping a copy', { addresses })
: addresses;
return detailed(ctx, label, detail);
}
case 'SetImportance':
return detailed(ctx, label, enumLabel(ctx.schema, 'MailRuleImportanceLevel', action.level));
case 'Reply':
return detailed(
ctx,
label,
typeof action.subject === 'string' && action.subject ? quoted(ctx, action.subject) : '',
);
case 'Reject':
return detailed(ctx, label, typeof action.reason === 'string' && action.reason ? quoted(ctx, action.reason) : '');
default:
return label;
export function 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 custom = parseCustomBody(body);
const { conditions, actions } = parseCustomBody(body);
const phrase = (condition: Record<string, unknown>) => conditionPhrase(ctx, condition);
return {
conditions: custom.conditions.map((condition) => conditionPhrase(ctx, condition)),
matchAll: custom.matchAll,
exceptions: custom.exceptions.map((condition) => conditionPhrase(ctx, condition)),
actions: custom.actions.map((action) => actionPhrase(ctx, action)),
stopProcessing: custom.stopProcessing,
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,
};
}
export function ruleSentence(ctx: SummaryContext, summary: RuleSummary): string {
const { t } = ctx;
let when =
summary.conditions.length === 0
? t('mailRules.summary.always', 'For every message')
: t('mailRules.summary.if', 'If {{conditions}}', {
conditions: formatList(summary.conditions, summary.matchAll ? 'conjunction' : 'disjunction'),
});
if (summary.exceptions.length > 0) {
when = t('mailRules.summary.except', '{{when}}, except if {{exceptions}}', {
when,
exceptions: formatList(summary.exceptions, 'disjunction'),
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'),
});
}
const actions =
summary.actions.length === 0 ? t('mailRules.summary.noActions', 'do nothing') : formatList(summary.actions);
const then = summary.stopProcessing
? t('mailRules.summary.thenStop', 'then {{actions}} and stop processing more rules', { actions })
: t('mailRules.summary.then', 'then {{actions}}', { actions });
return t('mailRules.summary.sentence', '{{when}}, {{then}}.', { when, then });
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 'rejectNeedsAuthentication':
return t(
'mailRules.issue.rejectNeedsAuthentication',
'A rule that rejects mail must match all conditions and require an authenticated sender.',
);
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 'scheduleTooManySlots':
return t(
'mailRules.issue.scheduleTooManySlots',
'Adjacent schedule conditions are combined into one, which can have at most {{max}} time slots.',
{ max: MAX_SCHEDULE_SLOTS },
);
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),
});
}
}
+126 -27
View File
@@ -151,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",
@@ -517,20 +522,58 @@
"detail": "{{label}}: {{detail}}",
"test": "{{operator}} {{values}}",
"slot": "{{days}} {{start}}–{{end}}",
"withoutCopy": "{{addresses}} without keeping a copy",
"always": "For every message",
"if": "If {{conditions}}",
"except": "{{when}}, except if {{exceptions}}",
"noActions": "do nothing",
"then": "then {{actions}}",
"thenStop": "then {{actions}} and stop processing more rules",
"sentence": "{{when}}, {{then}}."
"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.",
"rejectNeedsAuthentication": "A rule that rejects mail must match all conditions and require an authenticated sender.",
"forwardingNotAllowed": "Your account is not allowed to forward mail, so this rule cannot be saved while it is enabled.",
"scheduleTooManySlots": "Adjacent schedule conditions are combined into one, which can have at most {{max}} time slots."
"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}}",
@@ -558,30 +601,86 @@
"chooseMailbox": "Choose a mailbox",
"unknownMailbox": "Unknown mailbox ({{id}})",
"builder": {
"all": "all",
"any": "any",
"matchMode": "Conditions that must match",
"rejectNeedsAuthentication": "Reject needs all conditions to match, including an authenticated sender.",
"conditionN": "Condition {{n}}",
"exceptionN": "Exception {{n}}",
"actionN": "Action {{n}}",
"ifPrefix": "If",
"ifSuffix": "of these conditions match",
"ifOne": "If this condition matches",
"ifNone": "For every message",
"noConditions": "Without conditions the rule applies to every message.",
"noConditions": "No conditions: the rule applies to every message.",
"addCondition": "Add condition",
"except": "Except if any of these match",
"addException": "Add exception",
"then": "Then",
"addAction": "Add action",
"conditions": "Conditions",
"rejectNotAlone": "Reject must be the only action.",
"rejectStops": "A rule that rejects mail always stops processing more rules.",
"actionRequired": "Add at least one action.",
"missingFields": "Fill in {{fields}}."
"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}}"
"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",
+4 -4
View File
@@ -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;
+25
View File
@@ -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;
}
+4 -1
View File
@@ -235,7 +235,10 @@ export function localeClock(): LocaleClock {
const listFormats = new Map<string, Intl.ListFormat>();
export function formatList(items: readonly string[], type: 'conjunction' | 'disjunction' = 'conjunction'): string {
export function formatList(
items: readonly string[],
type: 'conjunction' | 'disjunction' | 'unit' = 'conjunction',
): string {
const locale = getFormatLocale();
const key = `${locale}|${type}`;
let fmt = listFormats.get(key);
-1
View File
@@ -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);
+11 -1
View File
@@ -168,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;
}