📈 Open source, privacy-first web analytics — a cookie-less Google Analytics alternative with built-in error tracking and performance monitoring. Self-host it or use our cloud. Get started for free!
TypeScript chartsclickhousedockergdprgoogle-analyticsmetricsmonitoringmysqlnestjsprivacyredisself-hostedselfhostedstatisticstailwindcssweb-analyticswebanalyticswebsite
Rich text alert editor
Blue Mouse40b74dd9dd50
diff --git a/backend/apps/cloud/src/alert/dto/alert.dto.ts b/backend/apps/cloud/src/alert/dto/alert.dto.tsindex 7556170c2..684cd7318 100644--- a/backend/apps/cloud/src/alert/dto/alert.dto.ts+++ b/backend/apps/cloud/src/alert/dto/alert.dto.ts@@ -86,7 +86,7 @@ class AlertBaseDTO {@ApiProperty({ type: [String] })@IsArray()- @IsUUID('4', { each: true })+ @IsUUID('all', { each: true })@IsOptional()channelIds?: string[]diff --git a/backend/apps/cloud/src/notification-channel/dispatchers/channel-dispatcher.service.ts b/backend/apps/cloud/src/notification-channel/dispatchers/channel-dispatcher.service.tsindex f6ae43e15..a55381653 100644--- a/backend/apps/cloud/src/notification-channel/dispatchers/channel-dispatcher.service.ts+++ b/backend/apps/cloud/src/notification-channel/dispatchers/channel-dispatcher.service.ts@@ -47,9 +47,10 @@ export class ChannelDispatcherService {async dispatch(channels: NotificationChannel[],message: RenderedAlertMessage,+ options: { ignoreVerification?: boolean } = {},): Promise<void> {const tasks = channels- .filter((c) => this.isVerifiedAndActive(c))+ .filter((c) => options.ignoreVerification || this.isVerifiedAndActive(c)).map(async (channel) => {const dispatcher = this.registry.get(channel.type)if (!dispatcher) {diff --git a/backend/apps/cloud/src/notification-channel/notification-channel.controller.ts b/backend/apps/cloud/src/notification-channel/notification-channel.controller.tsindex 031641aab..df4badc19 100644--- a/backend/apps/cloud/src/notification-channel/notification-channel.controller.ts+++ b/backend/apps/cloud/src/notification-channel/notification-channel.controller.ts@@ -107,7 +107,7 @@ export class NotificationChannelController {@Patch('/:id')@Auth()async update(- @Param('id', new ParseUUIDPipe({ version: '4' })) id: string,+ @Param('id', new ParseUUIDPipe()) id: string,@Body() dto: UpdateChannelDTO,@CurrentUserId() userId: string,) {@@ -122,7 +122,7 @@ export class NotificationChannelController {@Delete('/:id')@Auth()async remove(- @Param('id', new ParseUUIDPipe({ version: '4' })) id: string,+ @Param('id', new ParseUUIDPipe()) id: string,@CurrentUserId() userId: string,) {await this.channelService.delete(id, userId)@@ -133,17 +133,21 @@ export class NotificationChannelController {@Post('/:id/test')@Auth()async sendTest(- @Param('id', new ParseUUIDPipe({ version: '4' })) id: string,+ @Param('id', new ParseUUIDPipe()) id: string,@CurrentUserId() userId: string,) {const channel = await this.channelService.findById(id)if (!channel) throw new NotFoundException('Channel not found')await this.channelService.ensureCallerCanManage(channel, userId)- await this.dispatcherService.dispatch([channel], {- body: 'This is a test notification from Swetrix. Your channel is wired up correctly!',- subject: 'Swetrix test notification',- context: { test: true },- })+ await this.dispatcherService.dispatch(+ [channel],+ {+ body: 'This is a test notification from Swetrix. Your channel is wired up correctly!',+ subject: 'Swetrix test notification',+ context: { test: true },+ },+ { ignoreVerification: true },+ )return { ok: true }}@@ -151,7 +155,7 @@ export class NotificationChannelController {@Post('/:id/verify')@Auth()async kickoffVerification(- @Param('id', new ParseUUIDPipe({ version: '4' })) id: string,+ @Param('id', new ParseUUIDPipe()) id: string,@CurrentUserId() userId: string,) {const channel = await this.channelService.findById(id)diff --git a/web/app/components/NotificationChannels/NotificationChannels.tsx b/web/app/components/NotificationChannels/NotificationChannels.tsxindex 856716bf1..b3c91b9eb 100644--- a/web/app/components/NotificationChannels/NotificationChannels.tsx+++ b/web/app/components/NotificationChannels/NotificationChannels.tsx@@ -1,11 +1,10 @@import {- CheckCircleIcon,- ClockIcon,+ ArrowSquareOutIcon,+ BellSimpleRingingIcon,PaperPlaneTiltIcon,PencilSimpleIcon,PlusIcon,TrashIcon,- XCircleIcon,} from '@phosphor-icons/react'import _map from 'lodash/map'import { memo, useCallback, useEffect, useMemo, useRef, useState } from 'react'@@ -18,17 +17,15 @@ import type {NotificationChannelType,} from '~/lib/models/NotificationChannel'import type { NotificationChannelActionData } from '~/routes/notification-channel'+import { Badge } from '~/ui/Badge'import Button from '~/ui/Button'-import Discord from '~/ui/icons/Discord'-import Slack from '~/ui/icons/Slack'-import Telegram from '~/ui/icons/Telegram'import Input from '~/ui/Input'import Loader from '~/ui/Loader'import Modal from '~/ui/Modal'-import Select from '~/ui/Select'import { Text } from '~/ui/Text'import EnableWebPushButton from './EnableWebPushButton'+import { ChannelTypeIcon, summariseConfig } from './utils'type ChannelScope = 'user' | 'organisation' | 'project'@@ -55,13 +52,6 @@ const ALL_TYPES: NotificationChannelType[] = [const TG_BOT_URL = 'https://t.me/swetrixbot'-const ChannelTypeIcon = ({ type }: { type: NotificationChannelType }) => {- if (type === 'telegram') return <Telegram className='size-5 shrink-0' />- if (type === 'discord') return <Discord className='size-5 shrink-0' />- if (type === 'slack') return <Slack className='size-5 shrink-0' />- return null-}-interface ChannelFormState {name: stringtype: NotificationChannelType@@ -109,46 +99,22 @@ const ChannelStatusPill = ({ channel }: { channel: NotificationChannel }) => {if (isUnsubscribed) {return (- <span className='inline-flex items-center gap-1.5 text-sm text-amber-600 dark:text-amber-400'>- <XCircleIcon className='size-4' aria-hidden />- {t('notificationChannels.statusUnsubscribed')}- </span>+ <Badge+ colour='red'+ label={t('notificationChannels.statusUnsubscribed')}+ />)}if (channel.isVerified) {return (- <span className='inline-flex items-center gap-1.5 text-sm text-emerald-600 dark:text-emerald-400'>- <CheckCircleIcon className='size-4' aria-hidden />- {t('notificationChannels.statusVerified')}- </span>+ <Badge colour='green' label={t('notificationChannels.statusVerified')} />)}return (- <span className='inline-flex items-center gap-1.5 text-sm text-amber-600 dark:text-amber-400'>- <ClockIcon className='size-4' aria-hidden />- {t('notificationChannels.statusPending')}- </span>+ <Badge colour='yellow' label={t('notificationChannels.statusPending')} />)}-const summariseConfig = (channel: NotificationChannel): string => {- const cfg = channel.config as Record<string, any>- switch (channel.type) {- case 'email':- return cfg?.address || ''- case 'telegram':- return cfg?.chatId ? `chat ${cfg.chatId}` : ''- case 'slack':- case 'discord':- case 'webhook':- return cfg?.url || ''- case 'webpush':- return cfg?.userAgent || cfg?.endpoint || ''- default:- return ''- }-}-const NotificationChannels = ({scope,organisationId,@@ -371,115 +337,174 @@ const NotificationChannels = ({) : null}{isLoaded && channels.length === 0 && !isFormOpen ? (- <Text as='p' size='sm' colour='secondary' className='mt-4'>- {t('notificationChannels.empty')}- </Text>+ <div className='mt-6 rounded-lg border border-dashed border-gray-300 bg-gray-50/40 p-8 text-center dark:border-slate-700 dark:bg-slate-900/30'>+ <div className='mx-auto flex size-12 items-center justify-center rounded-lg bg-white ring-1 ring-gray-200 ring-inset dark:bg-slate-950 dark:ring-slate-700'>+ <BellSimpleRingingIcon+ className='size-6 text-slate-500 dark:text-slate-400'+ weight='duotone'+ />+ </div>+ <Text as='p' size='base' weight='semibold' className='mt-4'>+ {t('notificationChannels.emptyTitle')}+ </Text>+ <Text+ as='p'+ size='sm'+ colour='secondary'+ className='mx-auto mt-1 max-w-md'+ >+ {t('notificationChannels.emptyDescription')}+ </Text>+ <div className='mt-5 flex justify-center'>+ <Button+ primary+ regular+ onClick={() => {+ setForm(blankForm(allowedTypes[0]))+ setCreating(true)+ }}+ >+ <span className='inline-flex items-center gap-1'>+ <PlusIcon className='size-4' aria-hidden />+ {t('notificationChannels.add')}+ </span>+ </Button>+ </div>+ </div>) : null}{isLoaded && channels.length > 0 ? (- <div className='mt-4 overflow-hidden rounded-lg border border-gray-200 bg-white dark:border-slate-800 dark:bg-slate-950'>- <table className='min-w-full divide-y divide-gray-200 dark:divide-slate-800'>- <thead className='bg-gray-50 dark:bg-slate-900'>- <tr>- <th className='px-4 py-2 text-left text-xs font-bold tracking-wider text-gray-900 uppercase dark:text-white'>- {t('common.name')}- </th>- <th className='px-4 py-2 text-left text-xs font-bold tracking-wider text-gray-900 uppercase dark:text-white'>- {t('common.type')}- </th>- <th className='px-4 py-2 text-left text-xs font-bold tracking-wider text-gray-900 uppercase dark:text-white'>- {t('common.details')}- </th>- <th className='px-4 py-2 text-left text-xs font-bold tracking-wider text-gray-900 uppercase dark:text-white'>- {t('common.status')}- </th>- <th className='px-4 py-2' />- </tr>- </thead>- <tbody className='divide-y divide-gray-200 bg-white dark:divide-slate-800 dark:bg-slate-950'>- {_map(channels, (channel) => (- <tr- key={channel.id}- className='hover:bg-gray-50 dark:hover:bg-slate-900/50'- >- <td className='px-4 py-3 align-top text-sm'>- <div className='flex items-center gap-2'>- <ChannelTypeIcon type={channel.type} />- <span className='font-medium text-gray-900 dark:text-gray-100'>- {channel.name}- </span>- </div>- </td>- <td className='px-4 py-3 align-top text-sm text-gray-700 capitalize dark:text-gray-300'>- {t(`notificationChannels.types.${channel.type}` as any) ||- channel.type}- </td>- <td className='px-4 py-3 align-top text-sm text-gray-600 dark:text-gray-400'>- <span className='font-mono break-all'>- {summariseConfig(channel)}+ <ul className='mt-4 space-y-2'>+ {_map(channels, (channel) => {+ const summary = summariseConfig(channel)+ const canVerify =+ !channel.isVerified &&+ (channel.type === 'email' || channel.type === 'webhook')++ return (+ <li+ key={channel.id}+ className='group flex flex-col gap-3 rounded-lg border border-gray-200 p-3 transition-colors hover:border-gray-300 sm:flex-row sm:items-center sm:gap-4 sm:p-4 dark:border-slate-800 dark:hover:border-slate-700'+ >+ <div className='flex size-10 shrink-0 items-center justify-center rounded-md bg-gray-100 dark:bg-slate-800/80'>+ <ChannelTypeIcon type={channel.type} />+ </div>+ <div className='min-w-0 flex-1'>+ <div className='flex items-center gap-2'>+ <Text+ as='span'+ weight='semibold'+ className='truncate text-gray-900 dark:text-gray-100'+ >+ {channel.name}+ </Text>+ <span className='shrink-0 rounded-md bg-gray-100 px-1.5 py-0.5 text-[10px] font-semibold tracking-wide text-gray-600 uppercase dark:bg-slate-800 dark:text-gray-300'>+ {t(`notificationChannels.types.${channel.type}` as any) ||+ channel.type}</span>- </td>- <td className='px-4 py-3 align-top text-sm'>+ </div>+ <div className='mt-1 flex flex-wrap items-center gap-x-2 gap-y-1'>+ {summary ? (+ <span className='truncate font-mono text-xs text-gray-500 dark:text-gray-400'>+ {summary}+ </span>+ ) : null}<ChannelStatusPill channel={channel} />- </td>- <td className='px-4 py-3 text-right align-top text-sm'>- <div className='flex flex-wrap items-center justify-end gap-2'>- <Button- small- secondary- onClick={() => onTest(channel)}- disabled={isMutating}- title={t('notificationChannels.test')}- >- <PaperPlaneTiltIcon className='size-4' aria-hidden />- </Button>- {!channel.isVerified &&- (channel.type === 'email' ||- channel.type === 'webhook') ? (- <Button- small- secondary- onClick={() => onVerify(channel)}- disabled={isMutating}- >- {t('notificationChannels.verify')}- </Button>- ) : null}- <Button- small- secondary- onClick={() => onEdit(channel)}- disabled={isMutating}- title={t('common.edit')}- >- <PencilSimpleIcon className='size-4' aria-hidden />- </Button>- <Button- small- danger- onClick={() => setPendingDelete(channel)}- disabled={isMutating}- title={t('common.delete')}- >- <TrashIcon className='size-4' aria-hidden />- </Button>- </div>- </td>- </tr>- ))}- </tbody>- </table>- </div>+ </div>+ </div>+ <div className='flex shrink-0 flex-wrap items-center gap-1.5'>+ {canVerify ? (+ <Button+ small+ secondary+ onClick={() => onVerify(channel)}+ disabled={isMutating}+ >+ {t('notificationChannels.verify')}+ </Button>+ ) : null}+ <button+ type='button'+ onClick={() => onTest(channel)}+ disabled={isMutating}+ title={t('notificationChannels.test')}+ className='inline-flex size-8 items-center justify-center rounded-md text-gray-500 transition-colors hover:bg-gray-100 hover:text-gray-800 disabled:opacity-50 dark:text-gray-400 dark:hover:bg-slate-800 dark:hover:text-gray-100'+ >+ <PaperPlaneTiltIcon className='size-4' aria-hidden />+ </button>+ <button+ type='button'+ onClick={() => onEdit(channel)}+ disabled={isMutating}+ title={t('common.edit')}+ className='inline-flex size-8 items-center justify-center rounded-md text-gray-500 transition-colors hover:bg-gray-100 hover:text-gray-800 disabled:opacity-50 dark:text-gray-400 dark:hover:bg-slate-800 dark:hover:text-gray-100'+ >+ <PencilSimpleIcon className='size-4' aria-hidden />+ </button>+ <button+ type='button'+ onClick={() => setPendingDelete(channel)}+ disabled={isMutating}+ title={t('common.delete')}+ className='inline-flex size-8 items-center justify-center rounded-md text-gray-500 transition-colors hover:bg-red-50 hover:text-red-600 disabled:opacity-50 dark:text-gray-400 dark:hover:bg-red-500/10 dark:hover:text-red-400'+ >+ <TrashIcon className='size-4' aria-hidden />+ </button>+ </div>+ </li>+ )+ })}+ </ul>) : null}{isFormOpen ? (- <div className='mt-4 rounded-lg border border-gray-200 bg-white p-4 dark:border-slate-800 dark:bg-slate-950'>+ <div className='mt-4 rounded-lg border border-gray-200 p-4 dark:border-slate-800'><Text as='h4' size='base' weight='bold'>{editing? t('notificationChannels.editTitle'): t('notificationChannels.createTitle')}</Text>- <div className='mt-3 grid grid-cols-1 gap-3 sm:grid-cols-2'>++ {!editing ? (+ <div className='mt-4'>+ <Text+ as='p'+ size='xs'+ weight='semibold'+ colour='secondary'+ className='tracking-wider uppercase'+ >+ {t('notificationChannels.typeLabel')}+ </Text>+ <div className='mt-2 grid grid-cols-2 gap-2 sm:grid-cols-3 lg:grid-cols-6'>+ {typeOptions.map((opt) => {+ const isActive = form.type === opt.type+ return (+ <button+ key={opt.type}+ type='button'+ onClick={() =>+ setForm((prev) => ({ ...prev, type: opt.type }))+ }+ aria-pressed={isActive}+ className={`flex flex-col items-center gap-2 rounded-md px-2 py-3 text-center ring-1 transition-colors ring-inset ${+ isActive+ ? 'bg-slate-900/3 ring-slate-900 dark:bg-slate-100/5 dark:ring-slate-100'+ : 'ring-gray-300 hover:bg-gray-50 dark:ring-slate-700/80 dark:hover:bg-slate-900/40'+ }`}+ >+ <ChannelTypeIcon type={opt.type} className='size-6' />+ <span className='text-xs font-medium text-gray-900 dark:text-gray-100'>+ {opt.label}+ </span>+ </button>+ )+ })}+ </div>+ </div>+ ) : null}++ <div className='mt-4'><Inputlabel={t('common.name')}value={form.name}@@ -488,23 +513,6 @@ const NotificationChannels = ({}placeholder='My alerts channel'/>- <div className={editing ? 'pointer-events-none opacity-50' : ''}>- <Select- label={t('notificationChannels.typeLabel')}- items={typeOptions.map((o) => o.label)}- title={- typeOptions.find((o) => o.type === form.type)?.label ||- form.type- }- onSelect={(label) => {- const found = typeOptions.find((o) => o.label === label)- if (found) setForm((prev) => ({ ...prev, type: found.type }))- }}- selectedItem={- typeOptions.find((o) => o.type === form.type)?.label- }- />- </div></div><div className='mt-3 grid grid-cols-1 gap-3'>@@ -521,10 +529,12 @@ const NotificationChannels = ({/>) : null}{form.type === 'telegram' ? (- <>+ <div className='space-y-2'><Input- label={t('profileSettings.chatID')}+ label={t('notificationChannels.telegram.chatId')}value={form.chatId}+ inputMode='numeric'+ placeholder='123456789'onChange={(e) =>setForm((prev) => ({ ...prev, chatId: e.target.value }))}@@ -532,7 +542,16 @@ const NotificationChannels = ({bot: TG_BOT_URL,})}/>- </>+ <a+ href={TG_BOT_URL}+ target='_blank'+ rel='noopener noreferrer'+ className='inline-flex items-center gap-1.5 text-xs font-medium text-indigo-600 hover:underline dark:text-indigo-400'+ >+ <ArrowSquareOutIcon className='size-3.5' aria-hidden />+ {t('notificationChannels.telegram.openBot')}+ </a>+ </div>) : null}{form.type === 'slack' ||form.type === 'discord' ||diff --git a/web/app/components/NotificationChannels/utils.tsx b/web/app/components/NotificationChannels/utils.tsxnew file mode 100644index 000000000..9b0ebabb0--- /dev/null+++ b/web/app/components/NotificationChannels/utils.tsx@@ -0,0 +1,73 @@+import {+ BellRingingIcon,+ EnvelopeSimpleIcon,+ GlobeIcon,+} from '@phosphor-icons/react'++import type {+ NotificationChannel,+ NotificationChannelType,+} from '~/lib/models/NotificationChannel'+import Discord from '~/ui/icons/Discord'+import Slack from '~/ui/icons/Slack'+import Telegram from '~/ui/icons/Telegram'++interface ChannelTypeIconProps {+ type: NotificationChannelType+ className?: string+}++export const ChannelTypeIcon = ({+ type,+ className = 'size-5 shrink-0',+}: ChannelTypeIconProps) => {+ switch (type) {+ case 'telegram':+ return <Telegram className={className} />+ case 'discord':+ return <Discord className={className} />+ case 'slack':+ return <Slack className={className} />+ case 'email':+ return (+ <EnvelopeSimpleIcon+ className={`${className} text-slate-500 dark:text-slate-400`}+ weight='duotone'+ />+ )+ case 'webpush':+ return (+ <BellRingingIcon+ className={`${className} text-amber-500 dark:text-amber-400`}+ weight='duotone'+ />+ )+ case 'webhook':+ return (+ <GlobeIcon+ className={`${className} text-emerald-500 dark:text-emerald-400`}+ weight='duotone'+ />+ )+ default:+ return null+ }+}++export const summariseConfig = (channel: NotificationChannel): string => {+ const cfg = (channel.config || {}) as Record<string, any>+ switch (channel.type) {+ case 'email':+ return cfg.address || ''+ case 'telegram':+ return cfg.chatId ? `Chat ${cfg.chatId}` : ''+ case 'slack':+ case 'discord':+ case 'webhook':+ return cfg.url || ''+ case 'webpush':+ return cfg.userAgent || cfg.endpoint || ''+ default:+ return ''+ }+}diff --git a/web/app/pages/Project/Settings/Alerts/AlertTemplateEditor.tsx b/web/app/pages/Project/Settings/Alerts/AlertTemplateEditor.tsxindex 98de7957e..f21b2e0c5 100644--- a/web/app/pages/Project/Settings/Alerts/AlertTemplateEditor.tsx+++ b/web/app/pages/Project/Settings/Alerts/AlertTemplateEditor.tsx@@ -1,4 +1,4 @@-import { CodeIcon, EyeIcon } from '@phosphor-icons/react'+import { CodeIcon, EyeIcon, PlusIcon } from '@phosphor-icons/react'import { marked } from 'marked'import { useEffect, useMemo, useRef, useState } from 'react'import { useTranslation } from 'react-i18next'@@ -6,9 +6,13 @@ import { useFetcher } from 'react-router'import sanitizeHtml from 'sanitize-html'import type { ProjectViewActionData } from '~/routes/projects.$id'+import Button from '~/ui/Button'import Input from '~/ui/Input'import { Text } from '~/ui/Text'-import Textarea from '~/ui/Textarea'++import RichTemplateInput, {+ type TemplateVariableInfo,+} from './RichTemplateInput'interface TemplateVariablesResponse {variables: string[]@@ -205,6 +209,20 @@ const AlertTemplateEditor = ({[variables, sampleValues],)+ const variableInfos = useMemo<TemplateVariableInfo[]>(+ () =>+ variables.map((name) => {+ const key = `alert.template.variables.${name}` as const+ const translated = t(key as any)+ return {+ name,+ description:+ translated && translated !== key ? translated : undefined,+ }+ }),+ [variables, t],+ )+const previewBodyHtml = useMemo(() => renderMarkdown(interpolate(body || defaultTemplate || '', sample)),[body, defaultTemplate, sample],@@ -225,20 +243,23 @@ const AlertTemplateEditor = ({{t('alert.template.description')}</Text></div>- <button- type='button'- className='inline-flex items-center gap-1 rounded-md border border-gray-200 bg-white px-2.5 py-1.5 text-xs text-gray-700 transition-colors hover:bg-gray-50 dark:border-slate-700 dark:bg-slate-900 dark:text-gray-200 dark:hover:bg-slate-800'+ <Button+ secondary+ smallonClick={() => setShowPreview((v) => !v)}+ className='self-start sm:self-auto'>- {showPreview ? (- <CodeIcon className='size-3.5' aria-hidden />- ) : (- <EyeIcon className='size-3.5' aria-hidden />- )}- {showPreview- ? t('alert.template.editMode')- : t('alert.template.previewMode')}- </button>+ <span className='inline-flex items-center gap-1'>+ {showPreview ? (+ <CodeIcon className='size-3.5' aria-hidden />+ ) : (+ <EyeIcon className='size-3.5' aria-hidden />+ )}+ {showPreview+ ? t('alert.template.editMode')+ : t('alert.template.previewMode')}+ </span>+ </Button></div>{showSubject ? (@@ -255,32 +276,43 @@ const AlertTemplateEditor = ({{!showPreview ? (<><div className='mt-4'>- <Textarea+ <RichTemplateInputref={bodyRef as any}label={t('alert.template.body')}- rows={6}+ rows={7}value={body}placeholder={defaultTemplate || ''}- onChange={(e) => onBodyChange(e.target.value)}+ onChange={onBodyChange}+ variables={variableInfos}hint={t('alert.template.bodyHint')}/></div>- {variables.length > 0 ? (- <div className='mt-3'>- <Text as='p' size='sm' weight='medium'>+ {variableInfos.length > 0 ? (+ <div className='mt-4'>+ <Text+ as='p'+ size='xs'+ weight='semibold'+ colour='secondary'+ className='tracking-wider uppercase'+ >{t('alert.template.insertVariable')}</Text><div className='mt-2 flex flex-wrap gap-1.5'>- {variables.map((name) => (+ {variableInfos.map((variable) => (<buttontype='button'- key={name}- onClick={() => insertAtCursor(`{{${name}}}`)}- title={name}- className='inline-flex items-center gap-1 rounded-md border border-gray-200 bg-gray-50 px-2 py-0.5 font-mono text-xs text-gray-700 transition-colors hover:bg-gray-100 dark:border-slate-700 dark:bg-slate-900 dark:text-gray-200 dark:hover:bg-slate-800'+ key={variable.name}+ onClick={() => insertAtCursor(`{{${variable.name}}}`)}+ title={variable.description || variable.name}+ className='group inline-flex items-center gap-1 rounded-md bg-indigo-50 px-2 py-0.5 font-mono text-[11px] text-indigo-700 ring-1 ring-indigo-100 transition-all hover:bg-indigo-100 hover:ring-indigo-300 dark:bg-indigo-500/15 dark:text-indigo-200 dark:ring-indigo-400/20 dark:hover:bg-indigo-500/25'>- {`{{${name}}}`}+ <PlusIcon+ className='size-3 opacity-60 transition-opacity group-hover:opacity-100'+ aria-hidden+ />+ {variable.name}</button>))}</div>@@ -294,7 +326,7 @@ const AlertTemplateEditor = ({<Text as='p' size='sm' weight='medium' className='mb-1'>{t('alert.template.emailSubject')}</Text>- <div className='rounded-md border border-gray-200 bg-gray-50 px-3 py-2 text-sm dark:border-slate-700 dark:bg-slate-900'>+ <div className='rounded-md bg-gray-50 px-3 py-2 text-sm ring-1 ring-gray-300 ring-inset dark:bg-slate-900 dark:ring-slate-700/80'>{previewSubject}</div></div>@@ -304,7 +336,7 @@ const AlertTemplateEditor = ({{t('alert.template.preview')}</Text><div- className='alert-preview prose prose-sm max-w-none rounded-md border border-gray-200 bg-gray-50 px-3 py-2 text-sm dark:border-slate-700 dark:bg-slate-900 dark:prose-invert [&_a]:text-indigo-600 [&_a]:underline dark:[&_a]:text-indigo-400 [&_p]:my-1 [&_p:first-child]:mt-0 [&_p:last-child]:mb-0'+ className='alert-preview prose prose-sm max-w-none rounded-md bg-gray-50 px-3 py-2 text-sm ring-1 ring-gray-300 ring-inset dark:bg-slate-900 dark:ring-slate-700/80 dark:prose-invert [&_a]:text-indigo-600 [&_a]:underline dark:[&_a]:text-indigo-400 [&_p]:my-1 [&_p:first-child]:mt-0 [&_p:last-child]:mb-0'dangerouslySetInnerHTML={{ __html: previewBodyHtml }}/></div>diff --git a/web/app/pages/Project/Settings/Alerts/ProjectAlertsSettings.tsx b/web/app/pages/Project/Settings/Alerts/ProjectAlertsSettings.tsxindex b40b44363..f7ac953be 100644--- a/web/app/pages/Project/Settings/Alerts/ProjectAlertsSettings.tsx+++ b/web/app/pages/Project/Settings/Alerts/ProjectAlertsSettings.tsx@@ -1,4 +1,9 @@-import { WarningOctagonIcon, XCircleIcon } from '@phosphor-icons/react'+import {+ CheckCircleIcon,+ ClockIcon,+ WarningOctagonIcon,+ XCircleIcon,+} from '@phosphor-icons/react'import _findKey from 'lodash/findKey'import _isEmpty from 'lodash/isEmpty'import _keys from 'lodash/keys'@@ -16,7 +21,6 @@ import { toast } from 'sonner'import { QUERY_CONDITION, QUERY_METRIC, QUERY_TIME } from '~/lib/constants'import { Alerts } from '~/lib/models/Alerts'import type { NotificationChannel } from '~/lib/models/NotificationChannel'-import DashboardHeader from '~/pages/Project/View/components/DashboardHeader'import { useAuth } from '~/providers/AuthProvider'import type { NotificationChannelActionData } from '~/routes/notification-channel'import type { ProjectViewActionData } from '~/routes/projects.$id'@@ -25,12 +29,17 @@ import Checkbox from '~/ui/Checkbox'import Input from '~/ui/Input'import Loader from '~/ui/Loader'import Modal from '~/ui/Modal'-import MultiSelect from '~/ui/MultiSelect'import Select from '~/ui/Select'import { Text } from '~/ui/Text'import routes from '~/utils/routes'+import {+ ChannelTypeIcon,+ summariseConfig,+} from '~/components/NotificationChannels/utils'+import AlertTemplateEditor from './AlertTemplateEditor'+import { BackButton } from '../../View/components/BackButton'const CHANNELS_TAB = `?tab=channels`const PROJECT_CHANNELS_LINK = (projectId: string) =>@@ -43,7 +52,7 @@ interface ProjectAlertsSettingsProps {isSettings?: booleanonClose?: () => voidonSave?: () => void- backLink?: string+ backLink: string}const ProjectAlertsSettings = ({@@ -419,13 +428,7 @@ const ProjectAlertsSettings = ({return (<div>- <DashboardHeader- backLink={backLink}- showLiveVisitors={false}- showSearchButton={false}- showRefreshButton={false}- showPeriodSelector={false}- />+ <BackButton className='mb-2 max-w-max' to={backLink} /><Textas='h2'size='xl'@@ -480,20 +483,22 @@ const ProjectAlertsSettings = ({) : null}{!authLoading && availableChannels.length === 0 ? (- <div className='mt-2 flex items-center rounded-sm bg-blue-50 px-5 py-3 text-base whitespace-pre-wrap dark:bg-slate-900 dark:text-gray-50'>- <WarningOctagonIcon className='mr-1 h-5 w-5' />- <Trans- t={t}- i18nKey='alert.noChannels'- components={{- url: (- <Link- to={PROJECT_CHANNELS_LINK(projectId)}- className='text-blue-600 hover:underline dark:text-blue-500'- />- ),- }}- />+ <div className='mt-4 flex items-start gap-3 rounded-lg border border-amber-200 bg-amber-50 px-4 py-3 dark:border-amber-500/20 dark:bg-amber-500/10'>+ <WarningOctagonIcon className='mt-0.5 size-5 shrink-0 text-amber-600 dark:text-amber-400' />+ <p className='text-sm text-amber-800 dark:text-amber-200'>+ <Trans+ t={t}+ i18nKey='alert.noChannels'+ components={{+ url: (+ <Link+ to={PROJECT_CHANNELS_LINK(projectId)}+ className='font-medium underline hover:text-amber-900 dark:hover:text-amber-100'+ />+ ),+ }}+ />+ </p></div>) : null}{(form.channelIds || []).map((id) => (@@ -509,107 +514,124 @@ const ProjectAlertsSettings = ({name='emailSubjectTemplate'value={form.emailSubjectTemplate || ''}/>- <Input- name='name'- label={t('alert.name')}- value={form.name || ''}- placeholder={t('alert.name')}- className='mt-4'- onChange={handleInput}- error={beenSubmitted ? errors.name : null}- />- <Checkbox- checked={Boolean(form.active)}- onChange={(checked) =>- setForm((prev) => ({- ...prev,- active: checked,- }))- }- classes={{- label: 'mt-4',- }}- label={t('alert.enabled')}- hint={t('alert.enabledHint')}- />- <div className='mt-4'>- <Select- id='queryMetric'- label={t('alert.metric')}- items={_values(queryMetricTMapping)}- title={- form.queryMetric ? queryMetricTMapping[form.queryMetric] : ''- }- onSelect={(item) => {- const key = _findKey(- queryMetricTMapping,- (predicate) => predicate === item,- )-- // @ts-expect-error- setForm((prevForm) => ({- ...prevForm,- queryMetric: key,- }))- }}- capitalise- selectedItem={- form.queryMetric- ? queryMetricTMapping[form.queryMetric]- : undefined- }- />- </div>- {form.queryMetric === QUERY_METRIC.CUSTOM_EVENTS ? (- <Input- name='queryCustomEvent'- label={t('alert.customEvent')}- value={form.queryCustomEvent || ''}- placeholder={t('alert.customEvent')}- className='mt-4'- onChange={handleInput}- error={beenSubmitted ? errors.queryCustomEvent : null}- />- ) : null}- {form.queryMetric === QUERY_METRIC.CUSTOM_EVENTS ? (++ <div className='mt-6 rounded-lg border border-gray-200 p-4 dark:border-slate-800'>+ <Text as='h3' size='base' weight='bold'>+ {t('alert.sections.basics')}+ </Text>+ <Text as='p' size='sm' colour='secondary' className='mt-0.5'>+ {t('alert.sections.basicsDescription')}+ </Text>+ <div className='mt-4 max-w-md'>+ <Input+ name='name'+ label={t('alert.name')}+ value={form.name || ''}+ placeholder={t('alert.name')}+ onChange={handleInput}+ error={beenSubmitted ? errors.name : null}+ />+ </div><Checkbox- checked={Boolean(form.alertOnEveryCustomEvent)}- onChange={(checked) =>- setForm((prev) => ({- ...prev,- alertOnEveryCustomEvent: checked,- }))- }classes={{label: 'mt-4',}}- label={t('alert.alertOnEveryCustomEvent')}- hint={t('alert.alertOnEveryCustomEventHint')}- />- ) : null}- {form.queryMetric === QUERY_METRIC.ERRORS ? (- <Checkbox- checked={Boolean(form.alertOnNewErrorsOnly)}+ checked={Boolean(form.active)}onChange={(checked) =>setForm((prev) => ({...prev,- alertOnNewErrorsOnly: checked,+ active: checked,}))}- classes={{- label: 'mt-4',- }}- label={t('alert.newErrorsOnly')}- hint={t('alert.newErrorsOnlyHint')}+ label={t('alert.enabled')}/>- ) : null}- {form.queryMetric !== QUERY_METRIC.ERRORS &&- !(- form.queryMetric === QUERY_METRIC.CUSTOM_EVENTS &&- form.alertOnEveryCustomEvent- ) ? (- <>- <div className='mt-4'>+ </div>++ <div className='mt-6 rounded-lg border border-gray-200 p-4 dark:border-slate-800'>+ <Text as='h3' size='base' weight='bold'>+ {t('alert.sections.trigger')}+ </Text>+ <Text as='p' size='sm' colour='secondary' className='mt-0.5'>+ {t('alert.sections.triggerDescription')}+ </Text>++ <div className='mt-4'>+ <Select+ id='queryMetric'+ label={t('alert.metric')}+ items={_values(queryMetricTMapping)}+ title={+ form.queryMetric ? queryMetricTMapping[form.queryMetric] : ''+ }+ onSelect={(item) => {+ const key = _findKey(+ queryMetricTMapping,+ (predicate) => predicate === item,+ )++ // @ts-expect-error+ setForm((prevForm) => ({+ ...prevForm,+ queryMetric: key,+ }))+ }}+ capitalise+ selectedItem={+ form.queryMetric+ ? queryMetricTMapping[form.queryMetric]+ : undefined+ }+ />+ </div>+ {form.queryMetric === QUERY_METRIC.CUSTOM_EVENTS ? (+ <Input+ name='queryCustomEvent'+ label={t('alert.customEvent')}+ value={form.queryCustomEvent || ''}+ placeholder={t('alert.customEvent')}+ className='mt-4'+ onChange={handleInput}+ error={beenSubmitted ? errors.queryCustomEvent : null}+ />+ ) : null}+ {form.queryMetric === QUERY_METRIC.CUSTOM_EVENTS ? (+ <Checkbox+ checked={Boolean(form.alertOnEveryCustomEvent)}+ onChange={(checked) =>+ setForm((prev) => ({+ ...prev,+ alertOnEveryCustomEvent: checked,+ }))+ }+ classes={{+ label: 'mt-4',+ }}+ label={t('alert.alertOnEveryCustomEvent')}+ hint={t('alert.alertOnEveryCustomEventHint')}+ />+ ) : null}+ {form.queryMetric === QUERY_METRIC.ERRORS ? (+ <Checkbox+ checked={Boolean(form.alertOnNewErrorsOnly)}+ onChange={(checked) =>+ setForm((prev) => ({+ ...prev,+ alertOnNewErrorsOnly: checked,+ }))+ }+ classes={{+ label: 'mt-4',+ }}+ label={t('alert.newErrorsOnly')}+ hint={t('alert.newErrorsOnlyHint')}+ />+ ) : null}+ {form.queryMetric !== QUERY_METRIC.ERRORS &&+ !(+ form.queryMetric === QUERY_METRIC.CUSTOM_EVENTS &&+ form.alertOnEveryCustomEvent+ ) ? (+ <div className='mt-4 grid grid-cols-1 gap-4 sm:grid-cols-3'><Selectid='queryCondition'label={t('alert.condition')}@@ -638,17 +660,14 @@ const ProjectAlertsSettings = ({: queryConditionTMapping[QUERY_CONDITION.GREATER_THAN]}/>- </div>- <Input- name='queryValue'- label={t('alert.threshold')}- value={form.queryValue ?? ''}- placeholder='10'- className='mt-4'- onChange={handleInput}- error={beenSubmitted ? errors.queryValue : null}- />- <div className='mt-4'>+ <Input+ name='queryValue'+ label={t('alert.threshold')}+ value={form.queryValue ?? ''}+ placeholder='10'+ onChange={handleInput}+ error={beenSubmitted ? errors.queryValue : null}+ /><Selectid='queryTime'label={t('alert.time')}@@ -678,9 +697,10 @@ const ProjectAlertsSettings = ({}/></div>- </>- ) : null}- <div className='mt-6'>+ ) : null}+ </div>++ <div className='mt-6 rounded-lg border border-gray-200 p-4 dark:border-slate-800'><Text as='h3' size='base' weight='bold'>{t('alert.channels.heading')}</Text>@@ -688,35 +708,19 @@ const ProjectAlertsSettings = ({{t('alert.channels.description')}</Text><div className='mt-3'>- <MultiSelect- placeholder={t('alert.channels.placeholder')}- items={availableChannels}- keyExtractor={(c: NotificationChannel) => c.id}- labelExtractor={(c: NotificationChannel) =>- `${c.name} (${c.type})`- }- itemExtractor={(c: NotificationChannel) =>- `${c.name} — ${c.type}${c.isVerified ? '' : ' (unverified)'}`- }- label={availableChannels.filter((c) =>- (form.channelIds || []).includes(c.id),- )}- onSelect={(c: NotificationChannel) => {+ <ChannelPicker+ available={availableChannels}+ selected={new Set(form.channelIds || [])}+ onToggle={(channel) => {setForm((prev) => {const ids = new Set(prev.channelIds || [])- if (ids.has(c.id)) ids.delete(c.id)- else ids.add(c.id)+ if (ids.has(channel.id)) ids.delete(channel.id)+ else ids.add(channel.id)return { ...prev, channelIds: Array.from(ids) }})}}- onRemove={(c: NotificationChannel) => {- setForm((prev) => ({- ...prev,- channelIds: (prev.channelIds || []).filter(- (id) => id !== c.id,- ),- }))- }}+ projectChannelsLink={PROJECT_CHANNELS_LINK(projectId)}+ t={t}/></div></div>@@ -813,4 +817,124 @@ const ProjectAlertsSettings = ({)}+interface ChannelPickerProps {+ available: NotificationChannel[]+ selected: Set<string>+ onToggle: (channel: NotificationChannel) => void+ projectChannelsLink: string+ t: (key: string, options?: any) => string+}++const ChannelPicker = ({+ available,+ selected,+ onToggle,+ projectChannelsLink,+ t,+}: ChannelPickerProps) => {+ if (available.length === 0) {+ return (+ <div className='rounded-md border border-dashed border-gray-300 bg-gray-50/50 p-4 text-center dark:border-slate-700 dark:bg-slate-900/30'>+ <Text as='p' size='sm' colour='secondary'>+ {t('alert.channels.placeholder')}+ </Text>+ <Link+ to={projectChannelsLink}+ className='mt-1 inline-block text-sm text-indigo-600 hover:underline dark:text-indigo-400'+ >+ {t('notificationChannels.add')}+ </Link>+ </div>+ )+ }++ return (+ <div className='grid grid-cols-1 gap-2 sm:grid-cols-2'>+ {available.map((channel) => {+ const isSelected = selected.has(channel.id)+ const summary = summariseConfig(channel)+ const isUnsubscribed =+ channel.type === 'email' &&+ (channel.config as { unsubscribed?: boolean })?.unsubscribed === true+ return (+ <button+ key={channel.id}+ type='button'+ onClick={() => onToggle(channel)}+ aria-pressed={isSelected}+ className={`flex items-center gap-3 rounded-md p-3 text-left ring-1 transition-colors ring-inset ${+ isSelected+ ? 'bg-slate-900/3 ring-slate-900 dark:bg-slate-100/5 dark:ring-slate-100'+ : 'ring-gray-300 hover:bg-gray-50 dark:ring-slate-700/80 dark:hover:bg-slate-900/40'+ }`}+ >+ <div className='flex size-9 shrink-0 items-center justify-center rounded-md bg-gray-100 dark:bg-slate-800/80'>+ <ChannelTypeIcon type={channel.type} />+ </div>+ <div className='min-w-0 flex-1'>+ <div className='flex items-center gap-1.5 leading-5'>+ <Text+ as='span'+ size='sm'+ weight='semibold'+ className='truncate text-gray-900 dark:text-gray-100'+ >+ {channel.name}+ </Text>+ {isUnsubscribed ? (+ <XCircleIcon+ className='size-4 shrink-0 text-amber-500'+ weight='fill'+ aria-hidden+ />+ ) : channel.isVerified ? (+ <CheckCircleIcon+ className='size-4 shrink-0 text-emerald-500'+ weight='fill'+ aria-hidden+ />+ ) : (+ <ClockIcon+ className='size-4 shrink-0 text-amber-500'+ weight='fill'+ aria-hidden+ />+ )}+ </div>+ <span className='mt-0.5 block truncate font-mono text-xs text-gray-500 dark:text-gray-400'>+ {summary ||+ t(`notificationChannels.types.${channel.type}` as any)}+ </span>+ </div>+ <div+ className={`flex size-4 shrink-0 items-center justify-center rounded-sm ring-1 transition-colors ring-inset ${+ isSelected+ ? 'bg-slate-900 ring-slate-900 dark:bg-slate-100 dark:ring-slate-100'+ : 'ring-gray-300 dark:ring-slate-700/80'+ }`}+ aria-hidden+ >+ {isSelected ? (+ <svg+ viewBox='0 0 12 12'+ className='size-3 text-white dark:text-slate-900'+ fill='none'+ stroke='currentColor'+ strokeWidth='2.5'+ >+ <path+ strokeLinecap='round'+ strokeLinejoin='round'+ d='M2 6.5l2.5 2.5 5.5-5.5'+ />+ </svg>+ ) : null}+ </div>+ </button>+ )+ })}+ </div>+ )+}+export default ProjectAlertsSettingsdiff --git a/web/app/pages/Project/Settings/Alerts/ProjectAlertsView.tsx b/web/app/pages/Project/Settings/Alerts/ProjectAlertsView.tsxindex b96baa4f8..7d65dad10 100644--- a/web/app/pages/Project/Settings/Alerts/ProjectAlertsView.tsx+++ b/web/app/pages/Project/Settings/Alerts/ProjectAlertsView.tsx@@ -38,18 +38,22 @@ import routes from '~/utils/routes'import ProjectAlertsSettings from './ProjectAlertsSettings'-const NoNotificationChannelSet = () => {+const NoNotificationChannelSet = ({+ channelsLink,+}: {+ channelsLink: string+}) => {const { t } = useTranslation('common')return (- <div className='mb-4 flex items-center gap-3 rounded-lg border border-yellow-200 bg-yellow-50 px-4 py-3 dark:border-yellow-500/20 dark:bg-yellow-500/10'>- <WarningOctagonIcon className='size-5 shrink-0 text-yellow-600 dark:text-yellow-500' />- <p className='flex-1 text-sm text-yellow-800 dark:text-yellow-200'>+ <div className='mb-4 flex flex-col gap-3 rounded-lg border border-amber-200 bg-amber-50 px-4 py-3 sm:flex-row sm:items-center dark:border-amber-500/20 dark:bg-amber-500/10'>+ <WarningOctagonIcon className='size-5 shrink-0 text-amber-600 dark:text-amber-400' />+ <p className='flex-1 text-sm text-amber-800 dark:text-amber-200'>{t('alert.noNotificationChannel')}</p><Link- to={routes.user_settings}- className='shrink-0 rounded-md bg-yellow-600 px-3 py-1.5 text-sm font-medium text-white transition-colors hover:bg-yellow-700 dark:bg-yellow-600 dark:hover:bg-yellow-500'+ to={channelsLink}+ className='shrink-0 self-start rounded-md bg-amber-600 px-3 py-1.5 text-sm font-medium text-white transition-colors hover:bg-amber-700 sm:self-auto dark:bg-amber-600 dark:hover:bg-amber-500'>{t('common.fixIt')}</Link>@@ -495,7 +499,11 @@ const ProjectAlertsInner = ({</div>) : (<>- {!isIntegrationLinked ? <NoNotificationChannelSet /> : null}+ {!isIntegrationLinked ? (+ <NoNotificationChannelSet+ channelsLink={`/projects/${projectId}/settings?tab=channels`}+ />+ ) : null}{/* Header with add button */}<div className='mb-4 flex items-center justify-between'>diff --git a/web/app/pages/Project/Settings/Alerts/RichTemplateInput.tsx b/web/app/pages/Project/Settings/Alerts/RichTemplateInput.tsxnew file mode 100644index 000000000..fee295c64--- /dev/null+++ b/web/app/pages/Project/Settings/Alerts/RichTemplateInput.tsx@@ -0,0 +1,631 @@+import { Description, Field, Label } from '@headlessui/react'+import cx from 'clsx'+import {+ forwardRef,+ useCallback,+ useEffect,+ useImperativeHandle,+ useLayoutEffect,+ useMemo,+ useRef,+ useState,+} from 'react'++import { cn } from '~/utils/generic'++export interface TemplateVariableInfo {+ name: string+ description?: string+}++interface RichTemplateInputProps {+ value: string+ onChange: (value: string) => void+ variables: TemplateVariableInfo[]+ label?: string+ hint?: React.ReactNode+ rows?: number+ placeholder?: string+ className?: string+}++interface ParsedToken {+ start: number+ end: number+ name: string+ known: boolean+}++const TOKEN_REGEX = /\{\{\s*([\w_]+)\s*\}\}/g++const parseTokens = (text: string, knownNames: Set<string>): ParsedToken[] => {+ const tokens: ParsedToken[] = []+ let m: RegExpExecArray | null+ TOKEN_REGEX.lastIndex = 0+ while ((m = TOKEN_REGEX.exec(text)) !== null) {+ tokens.push({+ start: m.index,+ end: m.index + m[0].length,+ name: m[1],+ known: knownNames.has(m[1]),+ })+ }+ return tokens+}++const buildSegments = (+ text: string,+ tokens: ParsedToken[],+): React.ReactNode[] => {+ const nodes: React.ReactNode[] = []+ let cursor = 0+ tokens.forEach((tok, idx) => {+ if (tok.start > cursor) {+ nodes.push(<span key={`t-${idx}`}>{text.slice(cursor, tok.start)}</span>)+ }+ nodes.push(+ <span+ key={`v-${idx}-${tok.start}`}+ data-template-token={tok.name}+ data-token-known={tok.known ? 'true' : 'false'}+ className={cx(+ 'rounded-[3px] ring-1 transition-colors',+ tok.known+ ? 'bg-indigo-50 text-indigo-700 ring-indigo-200/80 dark:bg-indigo-500/15 dark:text-indigo-200 dark:ring-indigo-400/30'+ : 'bg-amber-50 text-amber-700 ring-amber-200/80 dark:bg-amber-500/10 dark:text-amber-200 dark:ring-amber-400/30',+ )}+ >+ {text.slice(tok.start, tok.end)}+ </span>,+ )+ cursor = tok.end+ })+ if (cursor < text.length) {+ nodes.push(<span key='tail'>{text.slice(cursor)}</span>)+ }+ // Trailing newline rendering quirk — textareas reserve a line for trailing \n+ if (text.endsWith('\n')) {+ nodes.push(<span key='nl'>{'\u200b'}</span>)+ }+ return nodes+}++interface SuggestionState {+ query: string+ anchorStart: number // index of first `{` of the trigger+ caret: { left: number; top: number; lineHeight: number } | null+}++interface HoverState {+ name: string+ description?: string+ rect: DOMRect+}++const useCaretCoordinates = () => {+ const mirrorRef = useRef<HTMLDivElement | null>(null)++ useEffect(() => {+ if (typeof document === 'undefined') return+ if (mirrorRef.current) return+ const div = document.createElement('div')+ div.setAttribute('aria-hidden', 'true')+ div.style.position = 'absolute'+ div.style.visibility = 'hidden'+ div.style.whiteSpace = 'pre-wrap'+ div.style.wordWrap = 'break-word'+ div.style.overflow = 'hidden'+ div.style.top = '0'+ div.style.left = '0'+ div.style.pointerEvents = 'none'+ document.body.appendChild(div)+ mirrorRef.current = div+ return () => {+ document.body.removeChild(div)+ mirrorRef.current = null+ }+ }, [])++ return useCallback(+ (+ ta: HTMLTextAreaElement,+ pos: number,+ ): { left: number; top: number; lineHeight: number } => {+ const div = mirrorRef.current+ if (!div) return { left: 0, top: 0, lineHeight: 18 }+ const cs = getComputedStyle(ta)+ const props = [+ 'boxSizing',+ 'width',+ 'height',+ 'overflowX',+ 'overflowY',+ 'borderTopWidth',+ 'borderRightWidth',+ 'borderBottomWidth',+ 'borderLeftWidth',+ 'borderStyle',+ 'paddingTop',+ 'paddingRight',+ 'paddingBottom',+ 'paddingLeft',+ 'fontStyle',+ 'fontVariant',+ 'fontWeight',+ 'fontStretch',+ 'fontSize',+ 'fontSizeAdjust',+ 'lineHeight',+ 'fontFamily',+ 'textAlign',+ 'textTransform',+ 'textIndent',+ 'textDecoration',+ 'letterSpacing',+ 'wordSpacing',+ 'tabSize',+ ] as const+ props.forEach((p) => {+ ;(div.style as any)[p] = cs[p]+ })+ div.style.width = ta.clientWidth + 'px'+ div.style.height = 'auto'+ div.textContent = ta.value.slice(0, pos)+ const span = document.createElement('span')+ span.textContent = ta.value.slice(pos) || '.'+ div.appendChild(span)+ const spanRect = span.getBoundingClientRect()+ const divRect = div.getBoundingClientRect()+ const lineHeight =+ parseFloat(cs.lineHeight) || parseFloat(cs.fontSize) * 1.2+ const left = spanRect.left - divRect.left+ const top = spanRect.top - divRect.top+ div.removeChild(span)+ return { left, top, lineHeight }+ },+ [],+ )+}++const RichTemplateInput = forwardRef<+ HTMLTextAreaElement,+ RichTemplateInputProps+>(+ (+ {+ value,+ onChange,+ variables,+ label,+ hint,+ rows = 6,+ placeholder,+ className,+ },+ ref,+ ) => {+ const taRef = useRef<HTMLTextAreaElement | null>(null)+ useImperativeHandle(ref, () => taRef.current as HTMLTextAreaElement)+ const mirrorRef = useRef<HTMLDivElement | null>(null)+ const wrapperRef = useRef<HTMLDivElement | null>(null)+ const getCaret = useCaretCoordinates()++ const [scrollTop, setScrollTop] = useState(0)+ const [scrollLeft, setScrollLeft] = useState(0)+ const [suggestion, setSuggestion] = useState<SuggestionState | null>(null)+ const [activeIndex, setActiveIndex] = useState(0)+ const [hover, setHover] = useState<HoverState | null>(null)+ const hoverDebounceRef = useRef<number | null>(null)++ const knownNames = useMemo(+ () => new Set(variables.map((v) => v.name)),+ [variables],+ )+ const descriptions = useMemo(() => {+ const m = new Map<string, string | undefined>()+ variables.forEach((v) => m.set(v.name, v.description))+ return m+ }, [variables])+ const tokens = useMemo(+ () => parseTokens(value, knownNames),+ [value, knownNames],+ )+ const segments = useMemo(+ () => buildSegments(value, tokens),+ [value, tokens],+ )++ const filteredVariables = useMemo(() => {+ if (!suggestion) return []+ const q = suggestion.query.toLowerCase()+ const list = variables.filter((v) => v.name.toLowerCase().includes(q))+ list.sort((a, b) => {+ const ai = a.name.toLowerCase().indexOf(q)+ const bi = b.name.toLowerCase().indexOf(q)+ if (ai === bi) return a.name.localeCompare(b.name)+ return ai - bi+ })+ return list+ }, [suggestion, variables])++ useEffect(() => {+ if (!suggestion) return+ if (filteredVariables.length === 0) {+ setActiveIndex(0)+ return+ }+ if (activeIndex >= filteredVariables.length) {+ setActiveIndex(0)+ }+ }, [filteredVariables, activeIndex, suggestion])++ const closeSuggestions = useCallback(() => {+ setSuggestion(null)+ setActiveIndex(0)+ }, [])++ const updateSuggestionFromCursor = useCallback(() => {+ const ta = taRef.current+ if (!ta) return+ const pos = ta.selectionStart ?? value.length+ if (pos !== ta.selectionEnd) {+ closeSuggestions()+ return+ }+ const text = ta.value++ // Walk backwards from cursor through identifier characters.+ let identStart = pos+ while (identStart > 0 && /[\w_]/.test(text[identStart - 1])) {+ identStart--+ }+ // Optional whitespace between `{` and identifier+ let braceEnd = identStart+ while (braceEnd > 0 && /\s/.test(text[braceEnd - 1])) {+ braceEnd--+ }+ // Need at least one `{` immediately before+ if (braceEnd === 0 || text[braceEnd - 1] !== '{') {+ closeSuggestions()+ return+ }+ let anchor = braceEnd - 1+ // Consume an optional second `{`+ if (anchor > 0 && text[anchor - 1] === '{') {+ anchor--+ }+ const query = text.slice(identStart, pos)+ const caret = getCaret(ta, pos)+ setSuggestion({+ query,+ anchorStart: anchor,+ caret,+ })+ }, [closeSuggestions, getCaret, value])++ const insertSuggestion = useCallback(+ (name: string) => {+ const ta = taRef.current+ if (!ta || !suggestion) return+ const pos = ta.selectionStart ?? ta.value.length+ const before = ta.value.slice(0, suggestion.anchorStart)+ const after = ta.value.slice(pos)+ // If next chars are `}}` or `}`, consume them so we don't end up with `}}}}`+ let trimmedAfter = after+ if (trimmedAfter.startsWith('}}')) {+ trimmedAfter = trimmedAfter.slice(2)+ } else if (trimmedAfter.startsWith('}')) {+ trimmedAfter = trimmedAfter.slice(1)+ }+ const insertion = `{{${name}}}`+ const next = before + insertion + trimmedAfter+ onChange(next)+ const newPos = before.length + insertion.length+ requestAnimationFrame(() => {+ ta.focus()+ ta.setSelectionRange(newPos, newPos)+ })+ closeSuggestions()+ },+ [closeSuggestions, onChange, suggestion],+ )++ // Sync mirror scroll+ const onScroll = useCallback(() => {+ const ta = taRef.current+ if (!ta) return+ setScrollTop(ta.scrollTop)+ setScrollLeft(ta.scrollLeft)+ }, [])++ useLayoutEffect(() => {+ const m = mirrorRef.current+ if (!m) return+ m.scrollTop = scrollTop+ m.scrollLeft = scrollLeft+ }, [scrollTop, scrollLeft, segments])++ const onKeyDown = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {+ if (suggestion && filteredVariables.length > 0) {+ if (e.key === 'ArrowDown') {+ e.preventDefault()+ setActiveIndex((i) => (i + 1) % filteredVariables.length)+ return+ }+ if (e.key === 'ArrowUp') {+ e.preventDefault()+ setActiveIndex(+ (i) =>+ (i - 1 + filteredVariables.length) % filteredVariables.length,+ )+ return+ }+ if (e.key === 'Enter' || e.key === 'Tab') {+ e.preventDefault()+ const item = filteredVariables[activeIndex]+ if (item) insertSuggestion(item.name)+ return+ }+ if (e.key === 'Escape') {+ e.preventDefault()+ closeSuggestions()+ return+ }+ }+ }++ const onChangeInternal = (e: React.ChangeEvent<HTMLTextAreaElement>) => {+ onChange(e.target.value)+ // Defer until value propagates; we check via the textarea ref directly+ // so we don't depend on stale closures.+ setTimeout(updateSuggestionFromCursor, 0)+ }++ const onSelectionChange = () => {+ updateSuggestionFromCursor()+ }++ const handleMouseMove = (e: React.MouseEvent<HTMLTextAreaElement>) => {+ if (typeof document === 'undefined') return+ // Use the underlying mirror to find the token at this point.+ // The textarea is on top with transparent text; the mirror is behind.+ const el = document.elementFromPoint(e.clientX, e.clientY)+ let target = el as HTMLElement | null+ while (target && !target.dataset?.templateToken) {+ target = target.parentElement+ }+ if (+ !target ||+ !target.dataset.templateToken ||+ !mirrorRef.current?.contains(target)+ ) {+ if (hoverDebounceRef.current !== null) {+ window.clearTimeout(hoverDebounceRef.current)+ hoverDebounceRef.current = null+ }+ if (hover) setHover(null)+ return+ }+ const name = target.dataset.templateToken+ const rect = target.getBoundingClientRect()+ if (hover && hover.name === name && hover.rect.top === rect.top) return+ if (hoverDebounceRef.current !== null) {+ window.clearTimeout(hoverDebounceRef.current)+ }+ hoverDebounceRef.current = window.setTimeout(() => {+ setHover({+ name,+ description: descriptions.get(name),+ rect,+ })+ }, 80)+ }++ const handleMouseLeave = () => {+ if (hoverDebounceRef.current !== null) {+ window.clearTimeout(hoverDebounceRef.current)+ hoverDebounceRef.current = null+ }+ setHover(null)+ }++ useEffect(() => {+ const handler = (e: MouseEvent) => {+ const w = wrapperRef.current+ if (!w) return+ if (!w.contains(e.target as Node)) closeSuggestions()+ }+ document.addEventListener('mousedown', handler)+ return () => document.removeEventListener('mousedown', handler)+ }, [closeSuggestions])++ const taClass =+ 'block w-full resize-y rounded-md border-0 bg-transparent text-sm text-transparent caret-slate-900 ring-1 ring-inset ring-gray-300 placeholder:text-gray-400 selection:bg-slate-900/20 focus:ring-slate-900 focus:outline-none dark:caret-gray-100 dark:ring-slate-700/80 dark:placeholder:text-gray-500 dark:selection:bg-slate-100/25 dark:focus:ring-slate-300'++ const sharedTextStyle: React.CSSProperties = {+ padding: '0.5rem 0.75rem',+ lineHeight: '1.45',+ }++ return (+ <Field as='div' className={className}>+ {label ? (+ <Label className='mb-1 flex text-sm font-medium text-gray-900 dark:text-gray-200'>+ {label}+ </Label>+ ) : null}+ <div ref={wrapperRef} className='relative'>+ <div+ ref={mirrorRef}+ aria-hidden='true'+ className='pointer-events-none absolute inset-0 overflow-hidden rounded-md text-sm wrap-break-word whitespace-pre-wrap text-gray-900 dark:text-gray-100'+ style={{+ ...sharedTextStyle,+ fontFamily: 'inherit',+ wordBreak: 'break-word',+ }}+ >+ {segments}+ </div>+ <textarea+ ref={taRef}+ rows={rows}+ value={value}+ onChange={onChangeInternal}+ onScroll={onScroll}+ onKeyDown={onKeyDown}+ onKeyUp={onSelectionChange}+ onClick={onSelectionChange}+ onSelect={onSelectionChange}+ onBlur={() => closeSuggestions()}+ onMouseMove={handleMouseMove}+ onMouseLeave={handleMouseLeave}+ placeholder={placeholder}+ spellCheck={false}+ autoComplete='off'+ autoCorrect='off'+ autoCapitalize='off'+ className={cn(taClass, 'relative')}+ style={{+ ...sharedTextStyle,+ lineHeight: '1.45',+ fontFamily: 'inherit',+ }}+ />+ {suggestion && filteredVariables.length > 0 ? (+ <SuggestionMenu+ variables={filteredVariables}+ activeIndex={activeIndex}+ onPick={insertSuggestion}+ caret={suggestion.caret}+ />+ ) : null}+ {hover ? (+ <HoverTooltip+ name={hover.name}+ description={hover.description}+ rect={hover.rect}+ wrapperEl={wrapperRef.current}+ />+ ) : null}+ </div>+ {hint ? (+ <Description className='mt-2 text-xs whitespace-pre-line text-gray-500 dark:text-gray-300'>+ {hint}+ </Description>+ ) : null}+ </Field>+ )+ },+)++RichTemplateInput.displayName = 'RichTemplateInput'++interface SuggestionMenuProps {+ variables: TemplateVariableInfo[]+ activeIndex: number+ onPick: (name: string) => void+ caret: { left: number; top: number; lineHeight: number } | null+}++const SuggestionMenu = ({+ variables,+ activeIndex,+ onPick,+ caret,+}: SuggestionMenuProps) => {+ const ref = useRef<HTMLDivElement | null>(null)++ useLayoutEffect(() => {+ const item = ref.current?.querySelector<HTMLElement>(`[data-active="true"]`)+ if (item) {+ item.scrollIntoView({ block: 'nearest' })+ }+ }, [activeIndex])++ if (!caret) return null++ return (+ <div+ ref={ref}+ className='absolute z-30 max-h-64 w-72 overflow-auto rounded-lg bg-white py-1 shadow-lg ring-1 ring-gray-200 dark:bg-slate-900 dark:ring-slate-700'+ style={{+ top: caret.top + caret.lineHeight + 4,+ left: caret.left,+ }}+ role='listbox'+ >+ {variables.map((v, i) => (+ <button+ key={v.name}+ data-active={i === activeIndex ? 'true' : 'false'}+ type='button'+ onMouseDown={(e) => {+ e.preventDefault()+ onPick(v.name)+ }}+ role='option'+ aria-selected={i === activeIndex}+ className={cx(+ 'flex w-full flex-col items-start gap-0.5 px-3 py-2 text-left transition-colors',+ i === activeIndex+ ? 'bg-slate-900 text-white dark:bg-slate-100 dark:text-slate-900'+ : 'text-gray-800 hover:bg-gray-100 dark:text-gray-100 dark:hover:bg-slate-800',+ )}+ >+ <span className='font-mono text-xs'>+ {`{{`}+ <span className='font-semibold'>{v.name}</span>+ {`}}`}+ </span>+ {v.description ? (+ <span+ className={cx(+ 'text-[11px] leading-snug',+ i === activeIndex+ ? 'text-slate-200 dark:text-slate-600'+ : 'text-gray-500 dark:text-gray-400',+ )}+ >+ {v.description}+ </span>+ ) : null}+ </button>+ ))}+ </div>+ )+}++interface HoverTooltipProps {+ name: string+ description?: string+ rect: DOMRect+ wrapperEl: HTMLElement | null+}++const HoverTooltip = ({+ name,+ description,+ rect,+ wrapperEl,+}: HoverTooltipProps) => {+ if (!wrapperEl) return null+ const wrapperRect = wrapperEl.getBoundingClientRect()+ const top = rect.top - wrapperRect.top - 8+ const left = rect.left - wrapperRect.left + rect.width / 2++ return (+ <div+ role='tooltip'+ className='pointer-events-none absolute z-40 -translate-x-1/2 -translate-y-full rounded-md bg-slate-900 px-3 py-1.5 text-xs text-white ring-1 ring-slate-900/80 dark:bg-slate-800'+ style={{ top, left }}+ >+ <div className='font-mono text-[11px] text-slate-300'>{`{{${name}}}`}</div>+ <div className='mt-0.5 max-w-64 leading-snug'>+ {description || 'Unknown variable'}+ </div>+ </div>+ )+}++export default RichTemplateInputdiff --git a/web/public/locales/en.json b/web/public/locales/en.jsonindex 72824f91b..c824fa5d4 100644--- a/web/public/locales/en.json+++ b/web/public/locales/en.json@@ -1179,6 +1179,12 @@"errors": "Errors"},"noChannels": "No notification channels are linked to this project yet. Add one in <url>Notification channels</url>.",+ "sections": {+ "basics": "Alert basics",+ "basicsDescription": "Give the alert a clear name and choose whether it's currently active.",+ "trigger": "Trigger",+ "triggerDescription": "Pick the metric and the condition that fires the alert."+ },"channels": {"heading": "Notification channels","description": "Pick which channels should receive this alert. Channels are managed in your account, organisation, or project settings.",@@ -1186,23 +1192,49 @@},"template": {"heading": "Message template",- "description": "Customise the message Swetrix sends when this alert fires. Use the variables below to inject data from the alert context.",+ "description": "Customise the message Swetrix sends when this alert fires. Type { or pick a variable below to insert dynamic values.","body": "Message body",- "bodyHint": "Markdown is supported. Leave empty to use the default template.",+ "bodyHint": "Markdown is supported. Type { to insert a variable. Leave blank to use the default template.","emailSubject": "Email subject","emailSubjectPlaceholder": "Swetrix alert: {{alert_name}}",- "insertVariable": "Insert variable",+ "insertVariable": "Available variables","preview": "Preview","previewMode": "Preview",- "editMode": "Edit"+ "editMode": "Edit",+ "noVariables": "No variables match",+ "unknownVariable": "Unknown variable. Type { to see all available variables.",+ "variables": {+ "alert_name": "The alert's name as configured in this form.",+ "project_name": "The project this alert belongs to.",+ "project_id": "The project's unique identifier.",+ "dashboard_url": "Direct link to the project dashboard.",+ "value": "The metric value that triggered the alert.",+ "threshold": "The threshold the value was compared against.",+ "condition": "The comparison operator (e.g. greater than).",+ "time_window": "The time window the metric was measured over.",+ "views": "Number of page views in the window.",+ "unique_views": "Number of unique sessions in the window.",+ "online_count": "Currently online users.",+ "event_name": "Custom event name.",+ "event_count": "Number of times the event fired.",+ "every_event_mode": "\"yes\" if the alert fires on every occurrence.",+ "error_count": "Number of errors that triggered the alert.",+ "error_message": "The error message text.",+ "error_name": "The error's class or name.",+ "errors_url": "Direct link to the project's errors view.",+ "is_new_only": "\"yes\" if the alert only fires for first-seen errors."+ }}},"notificationChannels": {"heading": "Notification channels",- "description": "Connect channels (Email, Telegram, Discord, Slack, Webhook, Web push) and pick them per alert.",- "userScopeDescription": "Channels you connect here are visible across your projects.",+ "description": "Wire up email, Telegram, Discord, Slack, custom webhooks or browser push, then attach them to alerts.",+ "userScopeDescription": "Channels you connect here are available across all of your projects.",+ "details": "Where it sends","add": "Add channel","empty": "No channels yet. Connect one to start receiving alerts.",+ "emptyTitle": "No channels connected",+ "emptyDescription": "Connect a channel below to start receiving alerts when your traffic, errors or events cross a threshold.","createTitle": "Connect a channel","editTitle": "Edit channel","deleteTitle": "Remove channel?",@@ -1233,7 +1265,9 @@"hint": "We'll send a confirmation email before this channel can be used."},"telegram": {- "hint": "Open {{bot}} and send /start. The bot will reply with your chat ID."+ "chatId": "Telegram chat ID",+ "hint": "Open {{bot}} on Telegram and send /start. The bot will reply with your numeric chat ID — paste it here.",+ "openBot": "Open bot"},"webhook": {"secret": "Signing secret (optional)",