Skip to content

📈 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!

feat: User feedback modal

Blue Mousee992cd15f733
diff --git a/backend/.env.example b/backend/.env.example
index 4fae334ff..a665fd4f2 100644
--- a/backend/.env.example
+++ b/backend/.env.example
@@ -114,6 +114,9 @@ OPENROUTER_API_KEY=
SWETRIX_PID=STEzHcB1rALV
+SWETRIX_CDN_URL=https://cdn.swetrix.com
+SWETRIX_CDN_TOKEN=
+
# Managed reverse proxy ("Bypass adblockers") edge auth
# Shared secret the proxy.swetrix.org edge box sends in `X-Edge-Api-Key` to
# call the /v1/proxy-domain/allow and /v1/proxy-domain/active endpoints.
diff --git a/backend/apps/cloud/src/user/dto/create-feedback.dto.ts b/backend/apps/cloud/src/user/dto/create-feedback.dto.ts
new file mode 100644
index 000000000..3fb2e059a
--- /dev/null
+++ b/backend/apps/cloud/src/user/dto/create-feedback.dto.ts
@@ -0,0 +1,13 @@
+import { ApiProperty } from '@nestjs/swagger'
+import { IsNotEmpty, IsString, MaxLength } from 'class-validator'
+
+export class CreateFeedbackDTO {
+ @ApiProperty({
+ example: 'I would love to see...',
+ required: true,
+ })
+ @IsString()
+ @IsNotEmpty()
+ @MaxLength(2000)
+ message: string
+}
diff --git a/backend/apps/cloud/src/user/entities/user-feedback.entity.ts b/backend/apps/cloud/src/user/entities/user-feedback.entity.ts
new file mode 100644
index 000000000..971b3feba
--- /dev/null
+++ b/backend/apps/cloud/src/user/entities/user-feedback.entity.ts
@@ -0,0 +1,24 @@
+import {
+ Column,
+ CreateDateColumn,
+ Entity,
+ PrimaryGeneratedColumn,
+} from 'typeorm'
+
+@Entity()
+export class UserFeedback {
+ @PrimaryGeneratedColumn('uuid')
+ id: string
+
+ @Column('varchar', { length: 36 })
+ userId: string
+
+ @Column('text')
+ message: string
+
+ @Column('json')
+ attachmentUrls: string[]
+
+ @CreateDateColumn()
+ createdAt: Date
+}
diff --git a/backend/apps/cloud/src/user/user.controller.ts b/backend/apps/cloud/src/user/user.controller.ts
index ad77cf206..ffca0dbfe 100644
--- a/backend/apps/cloud/src/user/user.controller.ts
+++ b/backend/apps/cloud/src/user/user.controller.ts
@@ -10,13 +10,22 @@ import {
HttpCode,
BadRequestException,
UseGuards,
+ UseInterceptors,
ConflictException,
Headers,
Ip,
NotFoundException,
+ UploadedFiles,
} from '@nestjs/common'
+import { FilesInterceptor } from '@nestjs/platform-express'
import { Request } from 'express'
-import { ApiTags, ApiResponse, ApiBearerAuth } from '@nestjs/swagger'
+import {
+ ApiTags,
+ ApiResponse,
+ ApiBearerAuth,
+ ApiBody,
+ ApiConsumes,
+} from '@nestjs/swagger'
import dayjs from 'dayjs'
import utc from 'dayjs/plugin/utc'
import _map from 'lodash/map'
@@ -53,6 +62,7 @@ import { LetterTemplate } from '../mailer/letter'
import { AppLoggerService } from '../logger/logger.service'
import { DeleteSelfDTO } from './dto/delete-self.dto'
import { CancelSubscriptionDTO } from './dto/cancel-subscription.dto'
+import { CreateFeedbackDTO } from './dto/create-feedback.dto'
import { checkRateLimit, getIPDetails, getIPFromHeaders } from '../common/utils'
import { IUsageInfo, IMetaInfo } from './interfaces'
import { ReportFrequency } from '../project/enums'
@@ -63,6 +73,8 @@ dayjs.extend(utc)
const UNPAID_PLANS = [PlanCode.free, PlanCode.trial, PlanCode.none]
const ORGANISATION_INVITE_EXPIRE_HOURS = 7 * 24 // 7 days
+const FEEDBACK_ATTACHMENTS_LIMIT = 7
+const FEEDBACK_ATTACHMENT_MAX_SIZE = 5 * 1024 * 1024
@ApiTags('User')
@Controller('user')
@@ -189,6 +201,72 @@ export class UserController {
await this.userService.update(userId, { apiKey: null })
}
+ @ApiBearerAuth()
+ @Post('/feedback')
+ @ApiConsumes('multipart/form-data')
+ @ApiBody({
+ schema: {
+ type: 'object',
+ properties: {
+ message: { type: 'string' },
+ attachments: {
+ type: 'array',
+ items: { type: 'string', format: 'binary' },
+ },
+ },
+ required: ['message'],
+ },
+ })
+ @UseInterceptors(
+ FilesInterceptor('attachments', FEEDBACK_ATTACHMENTS_LIMIT, {
+ limits: { fileSize: FEEDBACK_ATTACHMENT_MAX_SIZE },
+ fileFilter: (_req, file, callback) => {
+ if (!file.mimetype.startsWith('image/')) {
+ return callback(
+ new BadRequestException('Only image attachments are allowed'),
+ false,
+ )
+ }
+
+ callback(null, true)
+ },
+ }),
+ )
+ async createFeedback(
+ @CurrentUserId() userId: string,
+ @Body() body: CreateFeedbackDTO,
+ @UploadedFiles() files: Express.Multer.File[],
+ @Headers() headers: Record<string, string>,
+ @Ip() requestIp: string,
+ ) {
+ this.logger.log({ userId }, 'POST /user/feedback')
+
+ const ip = getIPFromHeaders(headers) || requestIp || ''
+ const userAgent = headers['user-agent'] || ''
+ const message = body.message.trim()
+
+ if (!message) {
+ throw new BadRequestException('Feedback cannot be empty')
+ }
+
+ const feedback = await this.userService.saveUserFeedback(
+ userId,
+ message,
+ files,
+ )
+
+ await trackCustom(ip, userAgent, {
+ ev: 'FEEDBACK_LEFT',
+ meta: {
+ attachment_count: feedback.attachmentUrls.length,
+ },
+ })
+
+ return {
+ id: feedback.id,
+ }
+ }
+
@ApiBearerAuth()
@Delete('/')
@HttpCode(204)
diff --git a/backend/apps/cloud/src/user/user.module.ts b/backend/apps/cloud/src/user/user.module.ts
index db69ddc04..864c00f48 100644
--- a/backend/apps/cloud/src/user/user.module.ts
+++ b/backend/apps/cloud/src/user/user.module.ts
@@ -12,6 +12,7 @@ import { ProjectModule } from '../project/project.module'
import { RefreshToken } from './entities/refresh-token.entity'
import { DeleteFeedback } from './entities/delete-feedback.entity'
import { CancellationFeedback } from './entities/cancellation-feedback.entity'
+import { UserFeedback } from './entities/user-feedback.entity'
import { Message } from '../integrations/telegram/entities/message.entity'
import { OrganisationModule } from '../organisation/organisation.module'
@@ -22,6 +23,7 @@ import { OrganisationModule } from '../organisation/organisation.module'
RefreshToken,
DeleteFeedback,
CancellationFeedback,
+ UserFeedback,
Message,
]),
ActionTokensModule,
diff --git a/backend/apps/cloud/src/user/user.service.ts b/backend/apps/cloud/src/user/user.service.ts
index 3a7f55099..993cbb827 100644
--- a/backend/apps/cloud/src/user/user.service.ts
+++ b/backend/apps/cloud/src/user/user.service.ts
@@ -2,6 +2,7 @@ import {
Injectable,
BadRequestException,
InternalServerErrorException,
+ ServiceUnavailableException,
} from '@nestjs/common'
import { InjectRepository } from '@nestjs/typeorm'
import {
@@ -36,6 +37,7 @@ import { UserProfileDTO } from './dto/user.dto'
import { RefreshToken } from './entities/refresh-token.entity'
import { DeleteFeedback } from './entities/delete-feedback.entity'
import { CancellationFeedback } from './entities/cancellation-feedback.entity'
+import { UserFeedback } from './entities/user-feedback.entity'
import { UserGoogleDTO } from './dto/user-google.dto'
import { UserGithubDTO } from './dto/user-github.dto'
import { EMAIL_ACTION_ENCRYPTION_KEY } from '../common/constants'
@@ -99,6 +101,49 @@ const CURRENCY_BY_COUNTRY = {
}
const { PADDLE_VENDOR_ID, PADDLE_API_KEY } = process.env
+const DEFAULT_CDN_URL = 'https://cdn.swetrix.com'
+
+type CdnFileResponse =
+ | string
+ | {
+ url?: string
+ filename?: string
+ id?: string
+ }
+
+const normaliseCdnUrl = (baseUrl: string, value: CdnFileResponse) => {
+ if (typeof value === 'string') {
+ return value.startsWith('http') ? value : `${baseUrl}/file/${value}`
+ }
+
+ if (value.url) {
+ return value.url
+ }
+
+ const filename = value.filename || value.id
+ return filename ? `${baseUrl}/file/${filename}` : null
+}
+
+const getCdnFiles = (payload: unknown): CdnFileResponse[] => {
+ if (Array.isArray(payload)) {
+ return payload
+ }
+
+ if (!payload || typeof payload !== 'object') {
+ return []
+ }
+
+ const data = payload as Record<string, unknown>
+
+ for (const key of ['files', 'urls', 'filenames', 'data']) {
+ const value = data[key]
+ if (Array.isArray(value)) {
+ return value as CdnFileResponse[]
+ }
+ }
+
+ return []
+}
@Injectable()
export class UserService {
@@ -111,6 +156,8 @@ export class UserService {
private readonly deleteFeedbackRepository: Repository<DeleteFeedback>,
@InjectRepository(CancellationFeedback)
private readonly cancellationFeedbackRepository: Repository<CancellationFeedback>,
+ @InjectRepository(UserFeedback)
+ private readonly userFeedbackRepository: Repository<UserFeedback>,
private readonly organisationService: OrganisationService,
) {}
@@ -240,6 +287,62 @@ export class UserService {
})
}
+ private async uploadFeedbackAttachments(files: Express.Multer.File[]) {
+ if (_isEmpty(files)) {
+ return []
+ }
+
+ const token = process.env.SWETRIX_CDN_TOKEN
+ if (!token) {
+ throw new ServiceUnavailableException('CDN uploads are not configured')
+ }
+
+ const baseUrl = (process.env.SWETRIX_CDN_URL || DEFAULT_CDN_URL).replace(
+ /\/$/,
+ '',
+ )
+ const formData = new FormData()
+ formData.append('token', token)
+
+ for (const file of files) {
+ formData.append(
+ 'files',
+ new Blob([file.buffer as unknown as BlobPart], {
+ type: file.mimetype,
+ }),
+ file.originalname,
+ )
+ }
+
+ const response = await fetch(`${baseUrl}/file/multiple`, {
+ method: 'POST',
+ body: formData,
+ })
+
+ if (!response.ok) {
+ throw new ServiceUnavailableException('Failed to upload attachments')
+ }
+
+ const payload = await response.json()
+ return getCdnFiles(payload)
+ .map((file) => normaliseCdnUrl(baseUrl, file))
+ .filter((url): url is string => Boolean(url))
+ }
+
+ public async saveUserFeedback(
+ userId: string,
+ message: string,
+ files: Express.Multer.File[] = [],
+ ) {
+ const attachmentUrls = await this.uploadFeedbackAttachments(files)
+
+ return this.userFeedbackRepository.save({
+ userId,
+ message,
+ attachmentUrls,
+ })
+ }
+
public async findDeleteFeedback(id: string) {
return this.deleteFeedbackRepository.findOne({ where: { id } })
}
diff --git a/backend/migrations/mysql/2026_05_23_user_feedback.sql b/backend/migrations/mysql/2026_05_23_user_feedback.sql
new file mode 100644
index 000000000..1d8c7d796
--- /dev/null
+++ b/backend/migrations/mysql/2026_05_23_user_feedback.sql
@@ -0,0 +1,10 @@
+CREATE TABLE IF NOT EXISTS `user_feedback` (
+ `id` varchar(36) NOT NULL,
+ `userId` varchar(36) NOT NULL,
+ `message` text NOT NULL,
+ `attachmentUrls` json NOT NULL,
+ `createdAt` datetime(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6),
+ PRIMARY KEY (`id`),
+ KEY `IDX_user_feedback_user` (`userId`),
+ KEY `IDX_user_feedback_createdAt` (`createdAt`)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
diff --git a/web/app/components/FeedbackModal.tsx b/web/app/components/FeedbackModal.tsx
new file mode 100644
index 000000000..abfe2ddd5
--- /dev/null
+++ b/web/app/components/FeedbackModal.tsx
@@ -0,0 +1,314 @@
+import { XIcon } from '@phosphor-icons/react'
+import type { ClipboardEvent } from 'react'
+import { useCallback, useEffect, useRef, useState } from 'react'
+import { useTranslation } from 'react-i18next'
+import { useFetcher } from 'react-router'
+import { toast } from 'sonner'
+
+import type { FeedbackActionData } from '~/routes/feedback'
+import Button from '~/ui/Button'
+import FileUpload from '~/ui/FileUpload'
+import Modal from '~/ui/Modal'
+import { Text } from '~/ui/Text'
+import Textarea from '~/ui/Textarea'
+import routes from '~/utils/routes'
+
+interface FeedbackModalProps {
+ isOpened: boolean
+ onClose: () => void
+}
+
+interface AttachmentItem {
+ id: string
+ file: File
+ previewUrl: string
+}
+
+const ACCEPTED_IMAGE_TYPES = [
+ 'image/png',
+ 'image/jpeg',
+ 'image/webp',
+ 'image/gif',
+]
+const ACCEPTED_IMAGE_INPUT = ACCEPTED_IMAGE_TYPES.join(',')
+const MAX_ATTACHMENTS = 7
+const MAX_ATTACHMENT_SIZE = 5 * 1024 * 1024
+const MAX_MESSAGE_LENGTH = 2000
+
+const formatFileSize = (bytes: number) => {
+ if (bytes < 1024) return `${bytes} B`
+ if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`
+ return `${(bytes / (1024 * 1024)).toFixed(1)} MB`
+}
+
+const getAttachmentId = (file: File) => {
+ if (typeof crypto !== 'undefined' && crypto.randomUUID) {
+ return crypto.randomUUID()
+ }
+
+ return `${file.name}-${file.lastModified}-${Math.random()}`
+}
+
+const FeedbackModal = ({ isOpened, onClose }: FeedbackModalProps) => {
+ const { t } = useTranslation('common')
+ const fetcher = useFetcher<FeedbackActionData>()
+ const [message, setMessage] = useState('')
+ const [attachments, setAttachments] = useState<AttachmentItem[]>([])
+ const [error, setError] = useState<string | null>(null)
+ const attachmentsRef = useRef<AttachmentItem[]>([])
+ const handledDataRef = useRef<FeedbackActionData | undefined>(undefined)
+ const isSubmitting = fetcher.state !== 'idle'
+
+ useEffect(() => {
+ attachmentsRef.current = attachments
+ }, [attachments])
+
+ useEffect(
+ () => () => {
+ attachmentsRef.current.forEach((attachment) => {
+ URL.revokeObjectURL(attachment.previewUrl)
+ })
+ },
+ [],
+ )
+
+ const resetForm = useCallback(() => {
+ setMessage('')
+ setError(null)
+ setAttachments((prev) => {
+ prev.forEach((attachment) => {
+ URL.revokeObjectURL(attachment.previewUrl)
+ })
+ return []
+ })
+ }, [])
+
+ useEffect(() => {
+ if (
+ fetcher.state !== 'idle' ||
+ !fetcher.data ||
+ handledDataRef.current === fetcher.data
+ ) {
+ return
+ }
+
+ handledDataRef.current = fetcher.data
+
+ if (fetcher.data.error) {
+ toast.error(fetcher.data.error)
+ return
+ }
+
+ if (fetcher.data.success) {
+ toast.success(t('feedback.sent'))
+ resetForm()
+ onClose()
+ }
+ }, [fetcher.data, fetcher.state, onClose, resetForm, t])
+
+ const addFiles = useCallback(
+ (files: File[]) => {
+ if (!files.length) return
+
+ const validFiles = files.filter((file) => {
+ if (!ACCEPTED_IMAGE_TYPES.includes(file.type)) {
+ toast.error(t('feedback.errors.imageOnly'))
+ return false
+ }
+
+ if (file.size > MAX_ATTACHMENT_SIZE) {
+ toast.error(
+ t('feedback.errors.imageTooLarge', {
+ size: formatFileSize(MAX_ATTACHMENT_SIZE),
+ }),
+ )
+ return false
+ }
+
+ return true
+ })
+
+ if (!validFiles.length) return
+
+ setAttachments((prev) => {
+ const remainingSlots = MAX_ATTACHMENTS - prev.length
+
+ if (remainingSlots <= 0) {
+ toast.error(
+ t('feedback.errors.tooManyImages', { count: MAX_ATTACHMENTS }),
+ )
+ return prev
+ }
+
+ if (validFiles.length > remainingSlots) {
+ toast.error(
+ t('feedback.errors.tooManyImages', { count: MAX_ATTACHMENTS }),
+ )
+ }
+
+ const next = validFiles.slice(0, remainingSlots).map((file) => ({
+ id: getAttachmentId(file),
+ file,
+ previewUrl: URL.createObjectURL(file),
+ }))
+
+ return [...prev, ...next]
+ })
+ },
+ [t],
+ )
+
+ const removeAttachment = useCallback((id: string) => {
+ setAttachments((prev) => {
+ const attachment = prev.find((item) => item.id === id)
+ if (attachment) {
+ URL.revokeObjectURL(attachment.previewUrl)
+ }
+
+ return prev.filter((item) => item.id !== id)
+ })
+ }, [])
+
+ const handlePaste = useCallback(
+ (event: ClipboardEvent<HTMLDivElement>) => {
+ const files = Array.from(event.clipboardData.files).filter((file) =>
+ file.type.startsWith('image/'),
+ )
+
+ if (!files.length) return
+
+ event.preventDefault()
+ addFiles(files)
+ },
+ [addFiles],
+ )
+
+ const handleSubmit = useCallback(() => {
+ const trimmedMessage = message.trim()
+
+ if (!trimmedMessage) {
+ setError(t('feedback.errors.messageRequired'))
+ return
+ }
+
+ if (trimmedMessage.length > MAX_MESSAGE_LENGTH) {
+ setError(
+ t('feedback.errors.messageTooLong', { count: MAX_MESSAGE_LENGTH }),
+ )
+ return
+ }
+
+ setError(null)
+
+ const formData = new FormData()
+ formData.set('message', trimmedMessage)
+
+ attachments.forEach(({ file }) => {
+ formData.append('attachments', file)
+ })
+
+ fetcher.submit(formData, {
+ method: 'POST',
+ action: routes.feedback,
+ encType: 'multipart/form-data',
+ })
+ }, [attachments, fetcher, message, t])
+
+ const handleClose = useCallback(() => {
+ if (isSubmitting) return
+ resetForm()
+ onClose()
+ }, [isSubmitting, onClose, resetForm])
+
+ return (
+ <Modal
+ title={t('feedback.title')}
+ message={
+ <div className='space-y-4' onPaste={handlePaste}>
+ <Text as='p' size='sm' colour='secondary'>
+ {t('feedback.description')}
+ </Text>
+ <Textarea
+ value={message}
+ rows={5}
+ maxLength={MAX_MESSAGE_LENGTH}
+ placeholder={t('feedback.placeholder')}
+ aria-label={t('feedback.inputLabel')}
+ error={error || false}
+ disabled={isSubmitting}
+ classes={{ textarea: 'min-h-32 resize-none' }}
+ onChange={(event) => {
+ setMessage(event.target.value)
+ if (error) setError(null)
+ }}
+ />
+ <FileUpload
+ accept={ACCEPTED_IMAGE_INPUT}
+ variant='mini'
+ multiple
+ disabled={isSubmitting || attachments.length >= MAX_ATTACHMENTS}
+ onFile={(file) => addFiles([file])}
+ onFiles={addFiles}
+ label={t('feedback.addImage')}
+ hint={t('feedback.addImageHint')}
+ className='rounded-lg'
+ />
+ {attachments.length ? (
+ <div className='grid grid-cols-2 gap-2 sm:grid-cols-3'>
+ {attachments.map((attachment) => (
+ <div
+ key={attachment.id}
+ className='group relative overflow-hidden rounded-lg bg-gray-50 ring-1 ring-gray-200/80 dark:bg-slate-900 dark:ring-slate-700/60'
+ >
+ <img
+ src={attachment.previewUrl}
+ alt=''
+ className='aspect-video w-full object-cover'
+ />
+ <div className='flex min-w-0 items-center justify-between gap-2 px-2 py-1.5'>
+ <Text
+ as='span'
+ size='xxs'
+ colour='muted'
+ className='min-w-0 truncate'
+ title={attachment.file.name}
+ >
+ {attachment.file.name}
+ </Text>
+ <Text
+ as='span'
+ size='xxs'
+ colour='muted'
+ className='shrink-0'
+ >
+ {formatFileSize(attachment.file.size)}
+ </Text>
+ </div>
+ <Button
+ variant='icon'
+ size='xs'
+ aria-label={t('feedback.removeImage')}
+ disabled={isSubmitting}
+ className='absolute top-1 right-1 bg-white/95 p-1 text-gray-700 ring-1 ring-gray-200 hover:bg-gray-100 dark:bg-slate-950/95 dark:text-gray-200 dark:ring-slate-700 dark:hover:bg-slate-900'
+ onClick={() => removeAttachment(attachment.id)}
+ >
+ <XIcon className='size-3.5' aria-hidden='true' />
+ </Button>
+ </div>
+ ))}
+ </div>
+ ) : null}
+ </div>
+ }
+ isOpened={isOpened}
+ onClose={handleClose}
+ onSubmit={handleSubmit}
+ submitText={t('feedback.send')}
+ submitDisabled={isSubmitting || !message.trim()}
+ isLoading={isSubmitting}
+ size='regular'
+ />
+ )
+}
+
+export default FeedbackModal
diff --git a/web/app/components/Header/index.tsx b/web/app/components/Header/index.tsx
index 7835dc906..c16eebdae 100644
--- a/web/app/components/Header/index.tsx
+++ b/web/app/components/Header/index.tsx
@@ -40,6 +40,7 @@ import {
SquaresFourIcon,
TagIcon,
BookOpenIcon,
+ ChatTextIcon,
} from '@phosphor-icons/react'
import { memo, Fragment, useState, useRef } from 'react'
import { useTranslation } from 'react-i18next'
@@ -59,6 +60,7 @@ import {
import { useAuth } from '~/providers/AuthProvider'
import { useTheme } from '~/providers/ThemeProvider'
import Flag from '~/ui/Flag'
+import FeedbackModal from '~/components/FeedbackModal'
import SwetrixLogo from '~/ui/icons/SwetrixLogo'
import { Text } from '~/ui/Text'
import routes from '~/utils/routes'
@@ -265,7 +267,13 @@ const SolutionsMenu = () => {
)
}
-const ProfileMenu = ({ logoutHandler }: { logoutHandler: () => void }) => {
+const ProfileMenu = ({
+ logoutHandler,
+ openFeedback,
+}: {
+ logoutHandler: () => void
+ openFeedback: () => void
+}) => {
const { user } = useAuth()
const {
t,
@@ -375,6 +383,17 @@ const ProfileMenu = ({ logoutHandler }: { logoutHandler: () => void }) => {
)}
</Disclosure>
+ {!isSelfhosted ? (
+ <MenuItem>
+ <Link
+ to={routes.billing}
+ className='flex items-center gap-2 rounded-md p-2 text-sm text-gray-700 transition-colors hover:bg-gray-200 dark:text-gray-50 dark:hover:bg-slate-900/60'
+ >
+ <CreditCardIcon className='h-4 w-4' />
+ {t('common.billing')}
+ </Link>
+ </MenuItem>
+ ) : null}
{isSelfhosted ? (
<MenuItem>
<a
@@ -400,13 +419,14 @@ const ProfileMenu = ({ logoutHandler }: { logoutHandler: () => void }) => {
)}
{!isSelfhosted ? (
<MenuItem>
- <Link
- to={routes.billing}
- className='flex items-center gap-2 rounded-md p-2 text-sm text-gray-700 transition-colors hover:bg-gray-200 dark:text-gray-50 dark:hover:bg-slate-900/60'
+ <button
+ type='button'
+ className='flex w-full items-center gap-2 rounded-md p-2 text-left text-sm text-gray-700 transition-colors hover:bg-gray-200 dark:text-gray-50 dark:hover:bg-slate-900/60'
+ onClick={openFeedback}
>
- <CreditCardIcon className='h-4 w-4' />
- {t('common.billing')}
- </Link>
+ <ChatTextIcon className='h-4 w-4' />
+ {t('feedback.giveFeedback')}
+ </button>
</MenuItem>
) : null}
@@ -492,10 +512,12 @@ const AuthedHeader = ({
logoutHandler,
colourBackground,
openMenu,
+ openFeedback,
}: {
logoutHandler: () => void
colourBackground: boolean
openMenu: () => void
+ openFeedback: () => void
}) => {
const { t } = useTranslation('common')
@@ -536,7 +558,10 @@ const AuthedHeader = ({
</div>
<div className='ml-1 hidden flex-wrap items-center justify-center space-y-1 space-x-2 sm:space-y-0 lg:ml-10 lg:flex lg:space-x-2'>
<CommunityLinks />
- <ProfileMenu logoutHandler={logoutHandler} />
+ <ProfileMenu
+ logoutHandler={logoutHandler}
+ openFeedback={openFeedback}
+ />
</div>
<div className='flex items-center justify-center space-x-3 lg:hidden'>
<button
@@ -655,6 +680,7 @@ const Header = ({ refPage, transparent }: HeaderProps) => {
const { t } = useTranslation('common')
const { isAuthenticated, user, logout } = useAuth()
const [mobileMenuOpen, setMobileMenuOpen] = useState(false)
+ const [feedbackOpen, setFeedbackOpen] = useState(false)
const { theme, setTheme } = useTheme()
const solutions = getSolutions(t)
@@ -668,6 +694,11 @@ const Header = ({ refPage, transparent }: HeaderProps) => {
setMobileMenuOpen(true)
}
+ const openFeedback = () => {
+ setMobileMenuOpen(false)
+ setFeedbackOpen(true)
+ }
+
return (
<Popover>
<BannerManager />
@@ -678,6 +709,7 @@ const Header = ({ refPage, transparent }: HeaderProps) => {
logoutHandler={logoutHandler}
colourBackground={!transparent}
openMenu={openMenu}
+ openFeedback={openFeedback}
/>
) : (
<NotAuthedHeader
@@ -879,6 +911,16 @@ const Header = ({ refPage, transparent }: HeaderProps) => {
{t('common.dashboard')}
</Link>
) : null}
+ {isAuthenticated && !isSelfhosted ? (
+ <button
+ type='button'
+ onClick={openFeedback}
+ className='-mx-3 flex w-full items-center gap-2 rounded-lg px-3 py-2 text-base leading-7 font-semibold text-gray-900 transition-colors hover:bg-gray-400/20 dark:text-gray-50 dark:hover:bg-slate-700/50'
+ >
+ <ChatTextIcon className='h-5 w-5' />
+ {t('feedback.giveFeedback')}
+ </button>
+ ) : null}
</div>
<div className='space-y-2 py-3'>
{isAuthenticated ? (
@@ -938,6 +980,12 @@ const Header = ({ refPage, transparent }: HeaderProps) => {
</div>
</DialogPanel>
</Dialog>
+ {isAuthenticated && !isSelfhosted ? (
+ <FeedbackModal
+ isOpened={feedbackOpen}
+ onClose={() => setFeedbackOpen(false)}
+ />
+ ) : null}
</Popover>
)
}
diff --git a/web/app/pages/Contact/index.tsx b/web/app/pages/Contact/index.tsx
index 67acc4da5..8f8d23207 100644
--- a/web/app/pages/Contact/index.tsx
+++ b/web/app/pages/Contact/index.tsx
@@ -1,6 +1,8 @@
import { ArrowSquareOutIcon } from '@phosphor-icons/react'
+import { useState } from 'react'
import { useTranslation, Trans } from 'react-i18next'
+import FeedbackModal from '~/components/FeedbackModal'
import {
CONTACT_EMAIL,
TWITTER_URL,
@@ -8,7 +10,9 @@ import {
DISCORD_URL,
DOCS_URL,
BOOK_A_CALL_URL,
+ isSelfhosted,
} from '~/lib/constants'
+import { useAuth } from '~/providers/AuthProvider'
import { Text } from '~/ui/Text'
interface PanelProps {
@@ -39,6 +43,9 @@ const Panel = ({ href, title, description }: PanelProps) => (
const Contact = () => {
const { t } = useTranslation('common')
+ const { isAuthenticated } = useAuth()
+ const [feedbackOpen, setFeedbackOpen] = useState(false)
+ const showFeedback = isAuthenticated && !isSelfhosted
return (
<div className='min-h-min-footer bg-gray-50 dark:bg-slate-950'>
@@ -73,6 +80,23 @@ const Contact = () => {
}}
/>
</Text>
+ {showFeedback ? (
+ <Text as='p' size='lg' className='mt-4'>
+ <Trans
+ t={t}
+ i18nKey='contact.feedback.desc'
+ components={{
+ feedback: (
+ <button
+ type='button'
+ onClick={() => setFeedbackOpen(true)}
+ className='font-medium underline decoration-dashed hover:decoration-solid'
+ />
+ ),
+ }}
+ />
+ </Text>
+ ) : null}
<div className='mt-8 grid grid-cols-1 gap-6 md:grid-cols-2 lg:col-span-2 lg:gap-8'>
<Panel
href={DOCS_URL}
@@ -86,6 +110,12 @@ const Contact = () => {
/>
</div>
</div>
+ {showFeedback ? (
+ <FeedbackModal
+ isOpened={feedbackOpen}
+ onClose={() => setFeedbackOpen(false)}
+ />
+ ) : null}
</div>
)
}
diff --git a/web/app/routes/feedback.ts b/web/app/routes/feedback.ts
new file mode 100644
index 000000000..0598fbbc4
--- /dev/null
+++ b/web/app/routes/feedback.ts
@@ -0,0 +1,66 @@
+import type { ActionFunctionArgs } from 'react-router'
+import { data } from 'react-router'
+
+import { serverFetch } from '~/api/api.server'
+import { isSelfhosted } from '~/lib/constants'
+import {
+ createHeadersWithCookies,
+ redirectIfNotAuthenticated,
+} from '~/utils/session.server'
+
+export interface FeedbackActionData {
+ success?: boolean
+ error?: string
+}
+
+export async function loader() {
+ return data(null, { status: 404 })
+}
+
+const getErrorMessage = (error: string | string[] | null) => {
+ if (Array.isArray(error)) {
+ return error.join(', ')
+ }
+
+ return error || 'Something went wrong, please try again'
+}
+
+export async function action({ request }: ActionFunctionArgs) {
+ if (isSelfhosted) {
+ return data<FeedbackActionData>({ error: 'Not found' }, { status: 404 })
+ }
+
+ redirectIfNotAuthenticated(request)
+
+ const formData = await request.formData()
+ const message = formData.get('message')?.toString().trim()
+
+ if (!message) {
+ return data<FeedbackActionData>(
+ { error: 'Please enter your feedback' },
+ { status: 400 },
+ )
+ }
+
+ formData.set('message', message)
+
+ const result = await serverFetch(request, 'user/feedback', {
+ method: 'POST',
+ body: formData,
+ })
+
+ if (result.error) {
+ return data<FeedbackActionData>(
+ { error: getErrorMessage(result.error) },
+ {
+ status: result.status,
+ headers: createHeadersWithCookies(result.cookies),
+ },
+ )
+ }
+
+ return data<FeedbackActionData>(
+ { success: true },
+ { headers: createHeadersWithCookies(result.cookies) },
+ )
+}
diff --git a/web/app/ui/FileUpload.tsx b/web/app/ui/FileUpload.tsx
index 80a4e54a6..dd052bd06 100644
--- a/web/app/ui/FileUpload.tsx
+++ b/web/app/ui/FileUpload.tsx
@@ -9,7 +9,10 @@ interface FileUploadProps {
accept?: string
disabled?: boolean
loading?: boolean
+ variant?: 'regular' | 'mini'
+ multiple?: boolean
onFile: (file: File) => void
+ onFiles?: (files: File[]) => void
label?: React.ReactNode
hint?: React.ReactNode
className?: string
@@ -19,7 +22,10 @@ export default function FileUpload({
accept,
disabled,
loading,
+ variant = 'regular',
+ multiple,
onFile,
+ onFiles,
label,
hint,
className,
@@ -29,13 +35,28 @@ export default function FileUpload({
const [dragOver, setDragOver] = useState(false)
const isDisabled = disabled || loading
+ const isMini = variant === 'mini'
- const handleFile = useCallback(
- (file: File | undefined) => {
- if (!file || isDisabled) return
- onFile(file)
+ const handleFiles = useCallback(
+ (files: FileList | File[] | null | undefined) => {
+ if (!files || isDisabled) return
+
+ const selectedFiles = Array.from(files)
+ if (!selectedFiles.length) return
+
+ if (multiple) {
+ if (onFiles) {
+ onFiles(selectedFiles)
+ return
+ }
+
+ selectedFiles.forEach(onFile)
+ return
+ }
+
+ onFile(selectedFiles[0])
},
- [isDisabled, onFile],
+ [isDisabled, multiple, onFile, onFiles],
)
const handleDragOver = useCallback(
@@ -59,25 +80,26 @@ export default function FileUpload({
e.stopPropagation()
setDragOver(false)
if (isDisabled) return
- handleFile(e.dataTransfer.files?.[0])
+ handleFiles(e.dataTransfer.files)
},
- [isDisabled, handleFile],
+ [isDisabled, handleFiles],
)
const handleChange = useCallback(
(e: React.ChangeEvent<HTMLInputElement>) => {
- handleFile(e.target.files?.[0])
+ handleFiles(e.target.files)
e.target.value = ''
},
- [handleFile],
+ [handleFiles],
)
return (
<label
htmlFor={inputId}
className={cn(
- 'group relative flex cursor-pointer flex-col items-center justify-center rounded-xl border-2 border-dashed p-6 text-center transition-[background-color,border-color,box-shadow] duration-200 ease-out',
+ 'group relative flex cursor-pointer items-center justify-center rounded-xl border-2 border-dashed transition-[background-color,border-color,box-shadow] duration-200 ease-out',
'focus-within:ring-2 focus-within:ring-slate-900 focus-within:ring-offset-2 dark:focus-within:ring-slate-300 dark:focus-within:ring-offset-slate-950',
+ isMini ? 'flex-row gap-3 p-3 text-left' : 'flex-col p-6 text-center',
isDisabled
? 'cursor-not-allowed border-gray-200 bg-gray-50/50 dark:border-slate-800 dark:bg-slate-900/40'
: dragOver
@@ -96,29 +118,48 @@ export default function FileUpload({
type='file'
className='sr-only'
accept={accept}
+ multiple={multiple}
disabled={isDisabled}
onChange={handleChange}
/>
{loading ? (
- <div className='space-y-2'>
- <SpinnerIcon className='mx-auto size-8 animate-spin text-gray-400 dark:text-gray-500' />
+ <div
+ className={cn(
+ isMini
+ ? 'flex min-w-0 items-center gap-3'
+ : 'space-y-2 text-center',
+ )}
+ >
+ <SpinnerIcon
+ className={cn(
+ 'animate-spin text-gray-400 dark:text-gray-500',
+ isMini ? 'size-5 shrink-0' : 'mx-auto size-8',
+ )}
+ />
{label && (
<Text
as='p'
size='sm'
colour='inherit'
- className='text-gray-500 dark:text-gray-400'
+ className='min-w-0 text-gray-500 dark:text-gray-400'
>
{label}
</Text>
)}
</div>
) : (
- <div className='space-y-2'>
+ <div
+ className={cn(
+ isMini
+ ? 'flex min-w-0 items-center gap-3'
+ : 'space-y-2 text-center',
+ )}
+ >
<div
className={cn(
- 'mx-auto flex size-10 items-center justify-center rounded-lg bg-gray-100 text-gray-500 transition-colors duration-200 ease-out dark:bg-slate-800/80 dark:text-gray-400',
+ 'flex shrink-0 items-center justify-center rounded-lg bg-gray-100 text-gray-500 transition-colors duration-200 ease-out dark:bg-slate-800/80 dark:text-gray-400',
+ isMini ? 'size-8' : 'mx-auto size-10',
!isDisabled &&
'group-hover:bg-gray-200 group-hover:text-gray-700 dark:group-hover:bg-slate-800 dark:group-hover:text-gray-200',
dragOver &&
@@ -131,16 +172,18 @@ export default function FileUpload({
aria-hidden='true'
/>
</div>
- {label && (
- <Text as='p' size='sm' weight='medium' colour='primary'>
- {label}
- </Text>
- )}
- {hint && (
- <Text as='p' size='xs' colour='muted'>
- {hint}
- </Text>
- )}
+ <div className='min-w-0'>
+ {label && (
+ <Text as='p' size='sm' weight='medium' colour='primary'>
+ {label}
+ </Text>
+ )}
+ {hint && (
+ <Text as='p' size='xs' colour='muted'>
+ {hint}
+ </Text>
+ )}
+ </div>
</div>
)}
</label>
diff --git a/web/app/utils/routes.ts b/web/app/utils/routes.ts
index 31a5a1d0b..dfa873cc5 100644
--- a/web/app/utils/routes.ts
+++ b/web/app/utils/routes.ts
@@ -26,6 +26,7 @@ const routes = Object.freeze({
security: '/security',
terms: '/terms',
contact: '/contact',
+ feedback: '/feedback',
transfer_confirm: '/project/transfer/confirm',
transfer_reject: '/project/transfer/cancel',
socialised: '/socialised',
diff --git a/web/public/locales/en.json b/web/public/locales/en.json
index 00216de88..502c1b467 100644
--- a/web/public/locales/en.json
+++ b/web/public/locales/en.json
@@ -2802,6 +2802,28 @@
"demo": {
"title": "Book a demo call",
"desc": "Book a demo with our team to see how Swetrix can solve your problems"
+ },
+ "feedback": {
+ "desc": "Have product feedback, bugs, or ideas? <feedback>Give feedback</feedback> and include screenshots if useful."
+ }
+ },
+ "feedback": {
+ "giveFeedback": "Give feedback",
+ "title": "Share feedback",
+ "description": "Tell us what felt confusing, what broke, or what would make Swetrix better for you.",
+ "inputLabel": "Your feedback",
+ "placeholder": "Add a few details so we can understand the context...",
+ "addImage": "Add screenshot (optional)",
+ "addImageHint": "Drop or paste an image here",
+ "removeImage": "Remove image",
+ "send": "Send feedback",
+ "sent": "Thanks for the feedback!",
+ "errors": {
+ "messageRequired": "Please enter your feedback",
+ "messageTooLong": "Feedback must be {{count}} characters or fewer",
+ "imageOnly": "Please attach images only",
+ "imageTooLarge": "Image must be {{size}} or smaller",
+ "tooManyImages": "You can attach up to {{count}} images"
}
},
"open": {