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!

Autosave settings on change

Blue Mouseac6aab1c3797
diff --git a/web/app/components/Header/index.tsx b/web/app/components/Header/index.tsx
index d18fe70e8..e4c014b9e 100644
--- a/web/app/components/Header/index.tsx
+++ b/web/app/components/Header/index.tsx
@@ -678,7 +678,7 @@ interface HeaderProps {
const Header = ({ refPage, transparent }: HeaderProps) => {
const { t } = useTranslation('common')
- const { isAuthenticated, user, logout } = useAuth()
+ const { isAuthenticated, logout } = useAuth()
const [mobileMenuOpen, setMobileMenuOpen] = useState(false)
const [feedbackOpen, setFeedbackOpen] = useState(false)
const { theme, setTheme } = useTheme()
diff --git a/web/app/pages/Project/Settings/ProjectSettings.tsx b/web/app/pages/Project/Settings/ProjectSettings.tsx
index f5d5d6b34..728cb1066 100644
--- a/web/app/pages/Project/Settings/ProjectSettings.tsx
+++ b/web/app/pages/Project/Settings/ProjectSettings.tsx
@@ -26,7 +26,7 @@ import {
BellRingingIcon,
GlobeIcon,
} from '@phosphor-icons/react'
-import React, { useState, useEffect, useMemo, useRef } from 'react'
+import React, { useState, useEffect, useMemo, useRef, useCallback } from 'react'
import { Trans, useTranslation } from 'react-i18next'
import {
useLoaderData,
@@ -78,6 +78,7 @@ import SettingsSidebar, { SettingsTabConfig } from './SettingsSidebar'
const MAX_NAME_LENGTH = 50
const MAX_ORIGINS_LENGTH = 300
const MAX_IPBLACKLIST_LENGTH = 300
+const AUTOSAVE_DEBOUNCE_MS = 700
const DELETE_DATA_MODAL_TABS = [
{
@@ -323,6 +324,83 @@ interface Form extends Partial<Omit<Project, 'brandKeywords'>> {
const DEFAULT_PROJECT_NAME = 'Untitled Project'
+const PROJECT_TEXT_AUTOSAVE_TOASTS = {
+ name: 'project.settings.autosave.name',
+ origins: 'project.settings.autosave.origins',
+ ipBlacklist: 'project.settings.autosave.ipBlacklist',
+ websiteUrl: 'project.settings.autosave.websiteUrl',
+ brandKeywords: 'project.settings.autosave.brandKeywords',
+} as const
+
+type ProjectTextAutosaveField = keyof typeof PROJECT_TEXT_AUTOSAVE_TOASTS
+
+const isProjectTextAutosaveField = (
+ field: string,
+): field is ProjectTextAutosaveField =>
+ Object.prototype.hasOwnProperty.call(PROJECT_TEXT_AUTOSAVE_TOASTS, field)
+
+const getFormFromProject = (project: Project): Form => ({
+ name: project.name || '',
+ id: project.id,
+ public: project.public || false,
+ isPasswordProtected: project.isPasswordProtected || false,
+ origins: _isString(project.origins)
+ ? project.origins
+ : _join(project.origins, ', '),
+ ipBlacklist: _isString(project.ipBlacklist)
+ ? project.ipBlacklist
+ : _join(project.ipBlacklist, ', '),
+ countryBlacklist: project.countryBlacklist || [],
+ active: project.active !== false,
+ botsProtectionLevel:
+ (project.botsProtectionLevel as 'off' | 'basic' | 'strict') || 'basic',
+ gscPropertyUri: project.gscPropertyUri || null,
+ websiteUrl: project.websiteUrl || null,
+ brandKeywords: project.brandKeywords?.join(', ') || '',
+ captchaDifficulty: project.captchaDifficulty || 4,
+ captchaDifficultyMode: project.captchaDifficultyMode || 'manual',
+})
+
+const normaliseProjectAutosaveValue = (value: unknown) =>
+ JSON.stringify(value ?? null)
+
+const buildProjectAutosaveFormData = (updates: Partial<Form>) => {
+ const formData = new FormData()
+ formData.set('intent', 'update-project')
+
+ Object.entries(updates).forEach(([field, value]) => {
+ if (value === undefined) return
+
+ if (field === 'countryBlacklist') {
+ formData.set(field, JSON.stringify(value || []))
+ return
+ }
+
+ if (
+ field === 'active' ||
+ field === 'public' ||
+ field === 'isPasswordProtected'
+ ) {
+ formData.set(field, value ? 'true' : 'false')
+ return
+ }
+
+ if (field === 'captchaDifficulty') {
+ formData.set(field, String(value))
+ return
+ }
+
+ if (field === 'password') {
+ if (value) formData.set(field, String(value))
+ return
+ }
+
+ formData.set(field, value === null ? '' : String(value))
+ })
+
+ return formData
+}
+
const ProjectSettings = () => {
const { user } = useAuth()
@@ -334,30 +412,14 @@ const ProjectSettings = () => {
requestOrigin: string | null
}>()
const fetcher = useFetcher<ProjectSettingsActionData>()
+ const autosaveFetcher = useFetcher<ProjectSettingsActionData>()
const gscFetcher = useFetcher<ProjectSettingsActionData>()
const { fetchFilters } = useFiltersProxy()
const [project, setProject] = useState<Project>(initialProject)
- const [form, setForm] = useState<Form>(() => ({
- name: initialProject.name || '',
- id: initialProject.id,
- public: initialProject.public || false,
- isPasswordProtected: initialProject.isPasswordProtected || false,
- origins: _isString(initialProject.origins)
- ? initialProject.origins
- : _join(initialProject.origins, ', '),
- ipBlacklist: _isString(initialProject.ipBlacklist)
- ? initialProject.ipBlacklist
- : _join(initialProject.ipBlacklist, ', '),
- countryBlacklist: initialProject.countryBlacklist || [],
- active: initialProject.active !== false,
- botsProtectionLevel:
- (initialProject.botsProtectionLevel as 'off' | 'basic' | 'strict') ||
- 'basic',
- gscPropertyUri: initialProject.gscPropertyUri || null,
- websiteUrl: initialProject.websiteUrl || null,
- brandKeywords: initialProject.brandKeywords?.join(', ') || '',
- }))
+ const [form, setForm] = useState<Form>(() =>
+ getFormFromProject(initialProject),
+ )
const [validated, setValidated] = useState(false)
const [errors, setErrors] = useState<{
name?: string
@@ -373,12 +435,23 @@ const ProjectSettings = () => {
const [showReset, setShowReset] = useState(false)
const [isDeleting, setIsDeleting] = useState(false)
const [isResetting, setIsResetting] = useState(false)
- const [isSaving, setIsSaving] = useState(false)
const [showTransfer, setShowTransfer] = useState(false)
const [transferEmail, setTransferEmail] = useState('')
const [dateRange, setDateRange] = useState<Date[]>([])
const [tab, setTab] = useState(DELETE_DATA_MODAL_TABS[0].name)
const [showProtected, setShowProtected] = useState(false)
+ const lastSavedForm = useRef<Form>(getFormFromProject(initialProject))
+ const lastHandledAutosaveData = useRef<ProjectSettingsActionData | null>(null)
+ const activeAutosave = useRef<{
+ updates: Partial<Form>
+ toastKey: string
+ } | null>(null)
+ const pendingAutosave = useRef<{
+ updates: Partial<Form>
+ toastKey: string
+ } | null>(null)
+ const autosaveTimeout = useRef<ReturnType<typeof setTimeout> | null>(null)
+ const hadCaptchaSecretBeforeRegeneration = useRef(false)
const [searchParams, setSearchParams] = useSearchParams()
@@ -753,7 +826,6 @@ const ProjectSettings = () => {
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [])
- // Handle fetcher responses
useEffect(() => {
if (fetcher.data?.success) {
const { intent, project: updatedProject } = fetcher.data
@@ -762,7 +834,6 @@ const ProjectSettings = () => {
if (intent === 'update-project') {
if (updatedProject) {
- // Merge with existing project to preserve fields like 'role' that aren't returned from update
setProject((prev) =>
prev ? { ...prev, ...updatedProject } : updatedProject,
)
@@ -774,7 +845,7 @@ const ProjectSettings = () => {
}
}
setBeenSubmitted(false)
- toast.success(t('project.settings.updated'))
+ toast.success(t('project.settings.autosave.updated'))
} else if (intent === 'delete-project') {
toast.success(t('project.settings.deleted'))
navigate(routes.dashboard)
@@ -794,55 +865,30 @@ const ProjectSettings = () => {
updatedProject?.captchaSecretKey
) {
setCaptchaSecretKey(updatedProject.captchaSecretKey)
- toast.success(t('project.settings.updated'))
+ toast.success(
+ t(
+ hadCaptchaSecretBeforeRegeneration.current
+ ? 'project.settings.captcha.keyRegenerated'
+ : 'project.settings.captcha.keyGenerated',
+ ),
+ )
} else if (intent === 'assign-organisation') {
- toast.success(t('apiNotifications.projectAssigned'))
+ toast.success(t('project.settings.autosave.organisation'))
}
- setIsSaving(false)
setIsDeleting(false)
setIsResetting(false)
} else if (fetcher.data?.fieldErrors) {
setErrors(fetcher.data.fieldErrors)
- setIsSaving(false)
setIsDeleting(false)
setIsResetting(false)
} else if (fetcher.data?.error) {
toast.error(fetcher.data.error)
- setIsSaving(false)
setIsDeleting(false)
setIsResetting(false)
}
}, [fetcher.data, t, navigate])
- const onSubmit = (data: Form) => {
- if (fetcher.state === 'submitting') return
-
- setIsSaving(true)
- const formData = new FormData()
- formData.set('intent', 'update-project')
- if (data.name) formData.set('name', data.name)
- formData.set('active', data.active ? 'true' : 'false')
- formData.set('public', data.public ? 'true' : 'false')
- formData.set(
- 'isPasswordProtected',
- data.isPasswordProtected ? 'true' : 'false',
- )
- if (data.password) formData.set('password', data.password)
- if (data.origins !== null) formData.set('origins', data.origins)
- if (data.ipBlacklist !== null) formData.set('ipBlacklist', data.ipBlacklist)
- if (data.botsProtectionLevel)
- formData.set('botsProtectionLevel', data.botsProtectionLevel)
- if (data.countryBlacklist)
- formData.set('countryBlacklist', JSON.stringify(data.countryBlacklist))
- if (data.websiteUrl !== undefined)
- formData.set('websiteUrl', data.websiteUrl || '')
- if (data.brandKeywords !== undefined)
- formData.set('brandKeywords', data.brandKeywords || '')
-
- fetcher.submit(formData, { method: 'post' })
- }
-
const onDelete = () => {
setShowDelete(false)
@@ -897,12 +943,12 @@ const ProjectSettings = () => {
const onRegenerateCaptchaKey = () => {
if (fetcher.state === 'submitting') return
+ hadCaptchaSecretBeforeRegeneration.current = Boolean(captchaSecretKey)
const formData = new FormData()
formData.set('intent', 'regenerate-captcha-key')
fetcher.submit(formData, { method: 'post' })
}
- // Wrapper for reset that handles tab logic
const handleReset = () => {
if (fetcher.state === 'submitting') return
@@ -926,49 +972,132 @@ const ProjectSettings = () => {
}
}
- const validate = () => {
- const allErrors: {
- name?: string
- origins?: string
- ipBlacklist?: string
- password?: string
- websiteUrl?: string
- } = {}
-
- if (_isEmpty(form.name)) {
- allErrors.name = t('project.settings.noNameError')
- }
+ const getValidationErrors = useCallback(
+ (data: Form) => {
+ const allErrors: {
+ name?: string
+ origins?: string
+ ipBlacklist?: string
+ password?: string
+ websiteUrl?: string
+ } = {}
+
+ if (_isEmpty(data.name)) {
+ allErrors.name = t('project.settings.noNameError')
+ }
- if (_size(form.name) > MAX_NAME_LENGTH) {
- allErrors.name = t('project.settings.pxCharsError', {
- amount: MAX_NAME_LENGTH,
- })
- }
+ if (_size(data.name) > MAX_NAME_LENGTH) {
+ allErrors.name = t('project.settings.pxCharsError', {
+ amount: MAX_NAME_LENGTH,
+ })
+ }
- if (_size(form.origins) > MAX_ORIGINS_LENGTH) {
- allErrors.origins = t('project.settings.oxCharsError', {
- amount: MAX_ORIGINS_LENGTH,
- })
- }
+ if (_size(data.origins) > MAX_ORIGINS_LENGTH) {
+ allErrors.origins = t('project.settings.oxCharsError', {
+ amount: MAX_ORIGINS_LENGTH,
+ })
+ }
- if (_size(form.ipBlacklist) > MAX_IPBLACKLIST_LENGTH) {
- allErrors.ipBlacklist = t('project.settings.oxCharsError', {
- amount: MAX_IPBLACKLIST_LENGTH,
- })
- }
+ if (_size(data.ipBlacklist) > MAX_IPBLACKLIST_LENGTH) {
+ allErrors.ipBlacklist = t('project.settings.oxCharsError', {
+ amount: MAX_IPBLACKLIST_LENGTH,
+ })
+ }
- // Validate websiteUrl if provided
- if (form.websiteUrl && form.websiteUrl.trim()) {
- try {
- const url = new URL(form.websiteUrl.trim())
- if (!['http:', 'https:'].includes(url.protocol)) {
+ if (data.websiteUrl && data.websiteUrl.trim()) {
+ try {
+ const url = new URL(data.websiteUrl.trim())
+ if (!['http:', 'https:'].includes(url.protocol)) {
+ allErrors.websiteUrl = t('project.settings.invalidUrl')
+ }
+ } catch {
allErrors.websiteUrl = t('project.settings.invalidUrl')
}
- } catch {
- allErrors.websiteUrl = t('project.settings.invalidUrl')
}
+
+ return allErrors
+ },
+ [t],
+ )
+
+ const hasProjectAutosaveChange = useCallback((updates: Partial<Form>) => {
+ return Object.entries(updates).some(([field, value]) => {
+ if (field === 'password') return Boolean(value)
+
+ return (
+ normaliseProjectAutosaveValue(
+ lastSavedForm.current[field as keyof Form],
+ ) !== normaliseProjectAutosaveValue(value)
+ )
+ })
+ }, [])
+
+ const flushProjectAutosave = useCallback(() => {
+ if (autosaveTimeout.current) {
+ clearTimeout(autosaveTimeout.current)
+ autosaveTimeout.current = null
}
+ const autosave = pendingAutosave.current
+ if (autosaveFetcher.state !== 'idle' || !autosave) return
+
+ activeAutosave.current = autosave
+ pendingAutosave.current = null
+
+ autosaveFetcher.submit(buildProjectAutosaveFormData(autosave.updates), {
+ method: 'post',
+ })
+ }, [autosaveFetcher])
+
+ const queueProjectAutosave = useCallback(
+ (
+ updates: Partial<Form>,
+ toastKey = 'project.settings.autosave.updated',
+ immediate = false,
+ ) => {
+ const nextForm = { ...form, ...updates }
+ const allErrors = getValidationErrors(nextForm)
+ const hasUpdatedFieldError = Object.keys(updates).some(
+ (field) => allErrors[field as keyof typeof allErrors],
+ )
+
+ setErrors(allErrors)
+
+ if (hasUpdatedFieldError) {
+ setBeenSubmitted(true)
+ return
+ }
+
+ if (!hasProjectAutosaveChange(updates)) return
+
+ pendingAutosave.current = {
+ updates: {
+ ...pendingAutosave.current?.updates,
+ ...updates,
+ },
+ toastKey,
+ }
+
+ if (autosaveTimeout.current) {
+ clearTimeout(autosaveTimeout.current)
+ autosaveTimeout.current = null
+ }
+
+ if (immediate) {
+ flushProjectAutosave()
+ return
+ }
+
+ autosaveTimeout.current = setTimeout(
+ flushProjectAutosave,
+ AUTOSAVE_DEBOUNCE_MS,
+ )
+ },
+ [flushProjectAutosave, form, getValidationErrors, hasProjectAutosaveChange],
+ )
+
+ const validate = () => {
+ const allErrors = getValidationErrors(form)
const valid = _isEmpty(_keys(allErrors))
setErrors(allErrors)
@@ -977,7 +1106,70 @@ const ProjectSettings = () => {
useEffect(() => {
validate()
- }, [form]) // eslint-disable-line
+ }, [form, getValidationErrors]) // eslint-disable-line
+
+ useEffect(() => {
+ return () => {
+ if (autosaveTimeout.current) {
+ clearTimeout(autosaveTimeout.current)
+ }
+ }
+ }, [])
+
+ useEffect(() => {
+ if (
+ autosaveFetcher.state === 'idle' &&
+ pendingAutosave.current &&
+ lastHandledAutosaveData.current === autosaveFetcher.data
+ ) {
+ flushProjectAutosave()
+ }
+ }, [autosaveFetcher.data, autosaveFetcher.state, flushProjectAutosave])
+
+ useEffect(() => {
+ if (autosaveFetcher.state !== 'idle' || !autosaveFetcher.data) return
+ if (lastHandledAutosaveData.current === autosaveFetcher.data) return
+ lastHandledAutosaveData.current = autosaveFetcher.data
+
+ if (autosaveFetcher.data.success) {
+ const { project: updatedProject } = autosaveFetcher.data
+ const autosave = activeAutosave.current
+
+ if (updatedProject) {
+ setProject((prev) =>
+ prev ? { ...prev, ...updatedProject } : updatedProject,
+ )
+ }
+
+ if (autosave) {
+ const savedUpdates = { ...autosave.updates }
+ delete savedUpdates.password
+ lastSavedForm.current = {
+ ...lastSavedForm.current,
+ ...savedUpdates,
+ }
+ toast.success(t(autosave.toastKey))
+ }
+
+ activeAutosave.current = null
+ if (pendingAutosave.current) {
+ flushProjectAutosave()
+ }
+ return
+ }
+
+ activeAutosave.current = null
+
+ if (autosaveFetcher.data.fieldErrors) {
+ setErrors(autosaveFetcher.data.fieldErrors)
+ setBeenSubmitted(true)
+ } else if (autosaveFetcher.data.error) {
+ toast.error(autosaveFetcher.data.error)
+ }
+ if (pendingAutosave.current) {
+ flushProjectAutosave()
+ }
+ }, [autosaveFetcher.data, autosaveFetcher.state, flushProjectAutosave, t])
const handleInput = (event: React.ChangeEvent<HTMLInputElement>) => {
const { target } = event
@@ -987,6 +1179,37 @@ const ProjectSettings = () => {
...oldForm,
[target.name]: value,
}))
+
+ if (isProjectTextAutosaveField(target.name)) {
+ queueProjectAutosave(
+ { [target.name]: value } as Partial<Form>,
+ PROJECT_TEXT_AUTOSAVE_TOASTS[target.name],
+ )
+ }
+ }
+
+ const handleInputBlur = (event: React.FocusEvent<HTMLInputElement>) => {
+ const { name, value } = event.currentTarget
+
+ if (!isProjectTextAutosaveField(name)) return
+
+ queueProjectAutosave(
+ { [name]: value } as Partial<Form>,
+ PROJECT_TEXT_AUTOSAVE_TOASTS[name],
+ true,
+ )
+ }
+
+ const handleFieldAutosave = (
+ updates: Partial<Form>,
+ toastKey: string,
+ immediate = true,
+ ) => {
+ setForm((oldForm) => ({
+ ...oldForm,
+ ...updates,
+ }))
+ queueProjectAutosave(updates, toastKey, immediate)
}
const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => {
@@ -995,23 +1218,24 @@ const ProjectSettings = () => {
setBeenSubmitted(true)
if (validated) {
- onSubmit(form)
+ flushProjectAutosave()
}
}
- const onProtected = async () => {
+ const onProtected = () => {
setBeenSubmitted(true)
if (validated) {
- await onSubmit({
- ...form,
- isPasswordProtected: true,
- })
-
- setForm((prev) => ({
- ...prev,
+ setForm((oldForm) => ({
+ ...oldForm,
isPasswordProtected: true,
+ password: undefined,
}))
+ queueProjectAutosave(
+ { isPasswordProtected: true, password: form.password },
+ 'project.settings.autosave.passwordProtection',
+ true,
+ )
setShowProtected(false)
}
@@ -1088,6 +1312,7 @@ const ProjectSettings = () => {
errors={errors}
beenSubmitted={beenSubmitted}
handleInput={handleInput}
+ handleBlur={handleInputBlur}
/>
) : null}
@@ -1097,20 +1322,20 @@ const ProjectSettings = () => {
errors={errors}
beenSubmitted={beenSubmitted}
handleInput={handleInput}
+ handleBlur={handleInputBlur}
botsProtectionLevels={botsProtectionLevels}
setBotsLevel={(name) =>
- setForm((prevForm) => ({
- ...prevForm,
- // cast to maintain allowed literal types
- botsProtectionLevel: name as any,
- }))
+ handleFieldAutosave(
+ { botsProtectionLevel: name as any },
+ 'project.settings.autosave.botsProtectionLevel',
+ )
}
countryBlacklist={form.countryBlacklist || []}
setCountryBlacklist={(countries) =>
- setForm((prevForm) => ({
- ...prevForm,
- countryBlacklist: countries,
- }))
+ handleFieldAutosave(
+ { countryBlacklist: countries },
+ 'project.settings.autosave.countryBlacklist',
+ )
}
/>
) : null}
@@ -1123,15 +1348,21 @@ const ProjectSettings = () => {
onAssignOrganisation={assignOrganisation}
openPasswordModal={() => setShowProtected(true)}
handleInput={handleInput}
+ onPublicChange={(checked) =>
+ handleFieldAutosave(
+ { public: checked },
+ 'project.settings.autosave.public',
+ )
+ }
+ onPasswordProtectionChange={(checked) =>
+ handleFieldAutosave(
+ { isPasswordProtected: checked },
+ 'project.settings.autosave.passwordProtection',
+ )
+ }
sharableLink={sharableLink}
/>
) : null}
-
- <div className='mt-4 flex flex-wrap justify-center gap-2 sm:justify-between'>
- <Button type='submit' loading={isSaving}>
- {t('common.save')}
- </Button>
- </div>
</form>
) : null}
@@ -1324,6 +1555,13 @@ const ProjectSettings = () => {
...prevForm,
gscPropertyUri: item.key,
}))
+ gscFetcher.submit(
+ {
+ intent: 'gsc-set-property',
+ propertyUri: item.key,
+ },
+ { method: 'post' },
+ )
}}
title={
form.gscPropertyUri ||
@@ -1338,29 +1576,6 @@ const ProjectSettings = () => {
: undefined
}
/>
-
- <Button
- type='button'
- className='max-w-max'
- onClick={() => {
- if (!form.gscPropertyUri) return
- gscFetcher.submit(
- {
- intent: 'gsc-set-property',
- propertyUri: form.gscPropertyUri,
- },
- { method: 'post' },
- )
- }}
- loading={
- gscFetcher.state !== 'idle'
- ? gscFetcher.formData?.get('intent') ===
- 'gsc-set-property'
- : undefined
- }
- >
- {t('common.save')}
- </Button>
</div>
)}
@@ -1496,36 +1711,25 @@ const ProjectSettings = () => {
}) => {
if (item.value === 'auto') {
setCaptchaDifficultyMode('auto')
+ handleFieldAutosave(
+ { captchaDifficultyMode: 'auto' },
+ 'project.settings.autosave.captchaDifficulty',
+ )
return
}
setCaptchaDifficultyMode('manual')
setCaptchaDifficulty(item.value)
+ handleFieldAutosave(
+ {
+ captchaDifficulty: item.value,
+ captchaDifficultyMode: 'manual',
+ },
+ 'project.settings.autosave.captchaDifficulty',
+ )
}}
title={selectedCaptchaDifficultyItem.label}
/>
- <Button
- type='button'
- className='mt-4'
- loading={fetcher.state === 'submitting'}
- onClick={() => {
- const formData = new FormData()
- formData.set('intent', 'update-project')
- if (captchaDifficultyMode === 'manual') {
- formData.set(
- 'captchaDifficulty',
- captchaDifficulty.toString(),
- )
- }
- formData.set(
- 'captchaDifficultyMode',
- captchaDifficultyMode,
- )
- fetcher.submit(formData, { method: 'post' })
- }}
- >
- {t('common.save')}
- </Button>
</div>
</>
) : (
@@ -1564,9 +1768,11 @@ const ProjectSettings = () => {
<DangerZone
isActive={Boolean(form.active)}
onToggleActive={(active) =>
- setForm((prev) => ({ ...prev, active }))
+ handleFieldAutosave(
+ { active },
+ 'project.settings.autosave.status',
+ )
}
- isSaving={isSaving}
setShowTransfer={setShowTransfer}
setShowReset={setShowReset}
setShowDelete={setShowDelete}
diff --git a/web/app/pages/Project/Settings/tabs/AccessSettings.tsx b/web/app/pages/Project/Settings/tabs/AccessSettings.tsx
index e8956c73d..a6f902391 100644
--- a/web/app/pages/Project/Settings/tabs/AccessSettings.tsx
+++ b/web/app/pages/Project/Settings/tabs/AccessSettings.tsx
@@ -18,6 +18,8 @@ interface AccessSettingsProps {
onAssignOrganisation: (id?: string) => Promise<void>
openPasswordModal: () => void
handleInput: (e: React.ChangeEvent<HTMLInputElement>) => void
+ onPublicChange: (checked: boolean) => void
+ onPasswordProtectionChange: (checked: boolean) => void
sharableLink: string
}
@@ -28,6 +30,8 @@ const AccessSettings = ({
onAssignOrganisation,
openPasswordModal,
handleInput,
+ onPublicChange,
+ onPasswordProtectionChange,
sharableLink,
}: AccessSettingsProps) => {
const { t } = useTranslation('common')
@@ -51,10 +55,7 @@ const AccessSettings = ({
checked={Boolean(form.public)}
onChange={(checked) => {
if (!form.isPasswordProtected || !checked) {
- setForm((prev: any) => ({
- ...prev,
- public: checked,
- }))
+ onPublicChange(checked)
}
}}
name='public'
@@ -68,10 +69,7 @@ const AccessSettings = ({
checked={Boolean(form.isPasswordProtected)}
onChange={(checked) => {
if (!checked) {
- setForm((prev: any) => ({
- ...prev,
- isPasswordProtected: false,
- }))
+ onPasswordProtectionChange(false)
return
}
diff --git a/web/app/pages/Project/Settings/tabs/DangerZone.tsx b/web/app/pages/Project/Settings/tabs/DangerZone.tsx
index c47437aae..aa769bcf4 100644
--- a/web/app/pages/Project/Settings/tabs/DangerZone.tsx
+++ b/web/app/pages/Project/Settings/tabs/DangerZone.tsx
@@ -28,7 +28,6 @@ const DangerAction = ({ title, description, action }: DangerActionProps) => (
interface DangerZoneProps {
isActive: boolean
onToggleActive: (active: boolean) => void
- isSaving: boolean
setShowTransfer: (show: boolean) => void
setShowReset: (show: boolean) => void
setShowDelete: (show: boolean) => void
@@ -39,7 +38,6 @@ interface DangerZoneProps {
const DangerZone = ({
isActive,
onToggleActive,
- isSaving,
setShowTransfer,
setShowReset,
setShowDelete,
@@ -64,11 +62,6 @@ const DangerZone = ({
classes={{ hint: 'max-w-prose' }}
/>
</div>
- <div className='mt-4'>
- <Button type='submit' loading={isSaving}>
- {t('common.save')}
- </Button>
- </div>
</section>
<section className='mt-8'>
diff --git a/web/app/pages/Project/Settings/tabs/General.tsx b/web/app/pages/Project/Settings/tabs/General.tsx
index b73098e10..5a4c227af 100644
--- a/web/app/pages/Project/Settings/tabs/General.tsx
+++ b/web/app/pages/Project/Settings/tabs/General.tsx
@@ -17,6 +17,7 @@ interface GeneralProps {
}
beenSubmitted: boolean
handleInput: (e: React.ChangeEvent<HTMLInputElement>) => void
+ handleBlur: (e: React.FocusEvent<HTMLInputElement>) => void
}
const General = ({
@@ -24,6 +25,7 @@ const General = ({
errors,
beenSubmitted,
handleInput,
+ handleBlur,
}: GeneralProps) => {
const { t } = useTranslation('common')
@@ -40,6 +42,7 @@ const General = ({
placeholder='My awesome project'
className='mt-2'
onChange={handleInput}
+ onBlur={handleBlur}
error={beenSubmitted ? errors.name : null}
/>
<Input
@@ -59,6 +62,7 @@ const General = ({
placeholder={t('project.settings.websiteUrlPlaceholder')}
className='mt-4'
onChange={handleInput}
+ onBlur={handleBlur}
error={beenSubmitted ? errors.websiteUrl : null}
/>
<Input
@@ -69,6 +73,7 @@ const General = ({
placeholder={t('project.settings.brandKeywordsPlaceholder')}
className='mt-4'
onChange={handleInput}
+ onBlur={handleBlur}
error={null}
/>
</>
diff --git a/web/app/pages/Project/Settings/tabs/Revenue.tsx b/web/app/pages/Project/Settings/tabs/Revenue.tsx
index 3062f86fd..d97889ffa 100644
--- a/web/app/pages/Project/Settings/tabs/Revenue.tsx
+++ b/web/app/pages/Project/Settings/tabs/Revenue.tsx
@@ -1,5 +1,5 @@
import { ArrowUpRightIcon, ArrowSquareOutIcon } from '@phosphor-icons/react'
-import React, { useEffect, useState } from 'react'
+import React, { useEffect, useRef, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { useFetcher } from 'react-router'
import { toast } from 'sonner'
@@ -88,6 +88,7 @@ const Revenue = ({ projectId }: Props) => {
})
const [selectedCurrency, setSelectedCurrency] =
useState<RevenueCurrency>('USD')
+ const pendingCurrency = useRef<RevenueCurrency | null>(null)
const isConnecting =
fetcher.state !== 'idle' &&
@@ -96,10 +97,6 @@ const Revenue = ({ projectId }: Props) => {
const isDisconnecting =
fetcher.state !== 'idle' &&
fetcher.formData?.get('intent') === 'disconnect-revenue'
- const isSavingCurrency =
- fetcher.state !== 'idle' &&
- fetcher.formData?.get('intent') === 'update-revenue-currency'
-
useEffect(() => {
fetcher.submit(
{ intent: 'get-revenue-status' },
@@ -147,10 +144,11 @@ const Revenue = ({ projectId }: Props) => {
} else if (intent === 'update-revenue-currency') {
if (success) {
toast.success(t('project.settings.revenue.currencyUpdated'))
- setStatus((prev) =>
- prev ? { ...prev, currency: selectedCurrency } : prev,
- )
+ const currency = pendingCurrency.current || selectedCurrency
+ setStatus((prev) => (prev ? { ...prev, currency } : prev))
+ pendingCurrency.current = null
} else if (error) {
+ pendingCurrency.current = null
toast.error(error)
}
}
@@ -187,11 +185,12 @@ const Revenue = ({ projectId }: Props) => {
)
}
- const handleCurrencyChange = () => {
+ const handleCurrencyChange = (currency: RevenueCurrency) => {
if (!status?.connected) return
+ pendingCurrency.current = currency
fetcher.submit(
- { intent: 'update-revenue-currency', currency: selectedCurrency },
+ { intent: 'update-revenue-currency', currency },
{ method: 'POST', action: `/projects/settings/${projectId}` },
)
}
@@ -349,17 +348,11 @@ const Revenue = ({ projectId }: Props) => {
`${item.code} – ${item.name} (${item.symbol})`
}
selectedItem={selectedCurrencyItem}
- onSelect={(item) => setSelectedCurrency(item.code)}
+ onSelect={(item) => {
+ setSelectedCurrency(item.code)
+ handleCurrencyChange(item.code)
+ }}
/>
- <Button
- type='button'
- className='max-w-max'
- onClick={handleCurrencyChange}
- loading={isSavingCurrency}
- disabled={!isConnected}
- >
- {t('common.save')}
- </Button>
</div>
<a
diff --git a/web/app/pages/Project/Settings/tabs/Shields.tsx b/web/app/pages/Project/Settings/tabs/Shields.tsx
index b39f3bd82..f5b79fc8c 100644
--- a/web/app/pages/Project/Settings/tabs/Shields.tsx
+++ b/web/app/pages/Project/Settings/tabs/Shields.tsx
@@ -30,6 +30,7 @@ interface ShieldsProps {
}
beenSubmitted: boolean
handleInput: (e: React.ChangeEvent<HTMLInputElement>) => void
+ handleBlur: (e: React.FocusEvent<HTMLInputElement>) => void
botsProtectionLevels: readonly BotsProtectionLevelOption[]
setBotsLevel: (name: string) => void
countryBlacklist: string[]
@@ -41,6 +42,7 @@ const Shields = ({
errors,
beenSubmitted,
handleInput,
+ handleBlur,
botsProtectionLevels,
setBotsLevel,
countryBlacklist,
@@ -119,6 +121,7 @@ const Shields = ({
value={form.origins || ''}
className='mt-2'
onChange={handleInput}
+ onBlur={handleBlur}
error={beenSubmitted ? errors.origins : null}
/>
<Input
@@ -129,6 +132,7 @@ const Shields = ({
value={form.ipBlacklist || ''}
className='mt-4'
onChange={handleInput}
+ onBlur={handleBlur}
error={beenSubmitted ? errors.ipBlacklist : null}
/>
<div className='mt-4'>
diff --git a/web/app/pages/UserSettings/UserSettings.tsx b/web/app/pages/UserSettings/UserSettings.tsx
index d00a013bb..5199b5d7c 100644
--- a/web/app/pages/UserSettings/UserSettings.tsx
+++ b/web/app/pages/UserSettings/UserSettings.tsx
@@ -20,7 +20,14 @@ import {
CreditCardIcon,
} from '@phosphor-icons/react'
import _round from 'lodash/round'
-import React, { useState, useEffect, memo, useMemo, useRef } from 'react'
+import React, {
+ useState,
+ useEffect,
+ memo,
+ useMemo,
+ useRef,
+ useCallback,
+} from 'react'
import { useTranslation, Trans } from 'react-i18next'
import {
useNavigate,
@@ -259,6 +266,7 @@ const UserSettings = () => {
i18n: { language },
} = useTranslation('common')
const fetcher = useFetcher<UserSettingsActionData>()
+ const profileAutosaveFetcher = useFetcher<UserSettingsActionData>()
const metainfoFetcher = useFetcher<UserSettingsActionData>()
const [searchParams, setSearchParams] = useSearchParams()
@@ -417,6 +425,18 @@ const UserSettings = () => {
const [deletionPassword, setDeletionPassword] = useState('')
const lastHandledData = useRef<UserSettingsActionData | null>(null)
+ const lastHandledProfileAutosaveData = useRef<UserSettingsActionData | null>(
+ null,
+ )
+ const profileUpdateToast = useRef('profileSettings.updated')
+ const activeProfileAutosave = useRef<{
+ additionalData: Record<string, unknown>
+ toastKey: string
+ } | null>(null)
+ const pendingProfileAutosave = useRef<{
+ additionalData: Record<string, unknown>
+ toastKey: string
+ } | null>(null)
const passwordChangedRef = useRef(false)
const pendingPasswordChangeRef = useRef(false)
const pendingToggles = useRef<Map<string, boolean>>(new Map())
@@ -444,26 +464,26 @@ const UserSettings = () => {
}
mergeUser(updatedUser)
- toast.success(t('profileSettings.updated'))
+ toast.success(t(profileUpdateToast.current))
+ profileUpdateToast.current = 'profileSettings.updated'
- // If password was changed, log out the user
if (passwordChangedRef.current) {
passwordChangedRef.current = false
logout()
}
} else if (intent === 'generate-api-key' && apiKey) {
mergeUser({ apiKey })
- toast.success(t('profileSettings.updated'))
+ toast.success(t('profileSettings.autosave.apiKeyGenerated'))
} else if (intent === 'delete-api-key') {
mergeUser({ apiKey: null })
- toast.success(t('profileSettings.updated'))
+ toast.success(t('profileSettings.autosave.apiKeyDeleted'))
} else if (intent === 'toggle-live-visitors' && updatedUser) {
pendingToggles.current.delete('live-visitors')
mergeUser(updatedUser)
- toast.success(t('profileSettings.updated'))
+ toast.success(t('profileSettings.autosave.liveVisitors'))
} else if (intent === 'toggle-login-notifications') {
pendingToggles.current.delete('login-notifications')
- toast.success(t('profileSettings.updated'))
+ toast.success(t('profileSettings.autosave.loginNotifications'))
} else if (intent === 'confirm-email') {
setCookie(CONFIRMATION_TIMEOUT, true, 600)
toast.success(t('profileSettings.confSent'))
@@ -510,6 +530,99 @@ const UserSettings = () => {
}
}, [fetcher.data, fetcher.state, mergeUser, t, logout, navigate, loadUser])
+ const flushProfileAutosave = useCallback(() => {
+ const autosave = pendingProfileAutosave.current
+ if (profileAutosaveFetcher.state !== 'idle' || !autosave) return
+
+ activeProfileAutosave.current = autosave
+ pendingProfileAutosave.current = null
+
+ const formData = new FormData()
+ formData.set('intent', 'update-profile')
+ formData.set('email', user?.email || '')
+
+ if (autosave.additionalData.timezone) {
+ formData.set('timezone', autosave.additionalData.timezone as string)
+ }
+
+ if (autosave.additionalData.timeFormat) {
+ formData.set('timeFormat', autosave.additionalData.timeFormat as string)
+ }
+
+ if (autosave.additionalData.reportFrequency) {
+ formData.set(
+ 'reportFrequency',
+ autosave.additionalData.reportFrequency as string,
+ )
+ }
+
+ profileAutosaveFetcher.submit(formData, { method: 'post' })
+ }, [profileAutosaveFetcher, user?.email])
+
+ useEffect(() => {
+ if (
+ profileAutosaveFetcher.state === 'idle' &&
+ pendingProfileAutosave.current &&
+ lastHandledProfileAutosaveData.current === profileAutosaveFetcher.data
+ ) {
+ flushProfileAutosave()
+ }
+ }, [
+ flushProfileAutosave,
+ profileAutosaveFetcher.data,
+ profileAutosaveFetcher.state,
+ ])
+
+ useEffect(() => {
+ if (profileAutosaveFetcher.state !== 'idle' || !profileAutosaveFetcher.data)
+ return
+ if (lastHandledProfileAutosaveData.current === profileAutosaveFetcher.data)
+ return
+ lastHandledProfileAutosaveData.current = profileAutosaveFetcher.data
+
+ if (profileAutosaveFetcher.data.success) {
+ const { intent, user: updatedUser } = profileAutosaveFetcher.data
+
+ if (intent === 'update-profile' && updatedUser) {
+ mergeUser(updatedUser)
+ toast.success(
+ t(
+ activeProfileAutosave.current?.toastKey ||
+ 'profileSettings.updated',
+ ),
+ )
+ activeProfileAutosave.current = null
+ }
+
+ if (pendingProfileAutosave.current) {
+ flushProfileAutosave()
+ }
+ return
+ }
+
+ activeProfileAutosave.current = null
+
+ if (profileAutosaveFetcher.data.error) {
+ const translated = t(
+ `apiNotifications.${profileAutosaveFetcher.data.error}`,
+ )
+ toast.error(
+ translated !== `apiNotifications.${profileAutosaveFetcher.data.error}`
+ ? translated
+ : profileAutosaveFetcher.data.error,
+ )
+ }
+ if (pendingProfileAutosave.current) {
+ flushProfileAutosave()
+ }
+ }, [
+ flushProfileAutosave,
+ profileAutosaveFetcher.data,
+ profileAutosaveFetcher.state,
+ mergeUser,
+ t,
+ ])
+
const errors = useMemo(() => {
const allErrors: Record<string, string> = {}
@@ -563,9 +676,11 @@ const UserSettings = () => {
additionalData?: Record<string, unknown>,
skipValidation = false,
includePassword = false,
+ toastKey = 'profileSettings.updated',
) => {
if (!skipValidation && !validated) return
+ profileUpdateToast.current = toastKey
const formData = new FormData()
formData.set('intent', 'update-profile')
formData.set('email', form.email || user?.email || '')
@@ -588,6 +703,21 @@ const UserSettings = () => {
fetcher.submit(formData, { method: 'post' })
}
+ const submitProfileAutosave = (
+ additionalData: Record<string, unknown>,
+ toastKey: string,
+ ) => {
+ pendingProfileAutosave.current = {
+ additionalData: {
+ ...pendingProfileAutosave.current?.additionalData,
+ ...additionalData,
+ },
+ toastKey,
+ }
+
+ flushProfileAutosave()
+ }
+
const handleSubmit = (
e: React.FormEvent<HTMLFormElement> | null,
force?: boolean,
@@ -607,7 +737,14 @@ const UserSettings = () => {
return
}
- submitProfileUpdate(undefined, false, hasPasswordUpdateInput)
+ submitProfileUpdate(
+ undefined,
+ false,
+ hasPasswordUpdateInput,
+ hasPasswordUpdateInput
+ ? 'profileSettings.autosave.password'
+ : 'profileSettings.updated',
+ )
}
}
@@ -616,7 +753,12 @@ const UserSettings = () => {
if (!form.email || errors.email) return
- submitProfileUpdate(undefined, true)
+ submitProfileUpdate(
+ undefined,
+ true,
+ false,
+ 'profileSettings.autosave.email',
+ )
}
const handlePasswordSubmit = () => {
@@ -633,8 +775,12 @@ const UserSettings = () => {
setIsPasswordChangeModalOpened(true)
}
- const handleTimezoneSave = () => {
- submitProfileUpdate({ timezone })
+ const handleTimezoneChange = (value: string) => {
+ setTimezone(value)
+ submitProfileAutosave(
+ { timezone: value },
+ 'profileSettings.autosave.timezone',
+ )
}
const handleShowLiveVisitorsSave = (checked: boolean) => {
@@ -667,8 +813,12 @@ const UserSettings = () => {
mergeUser({ receiveLoginNotifications: checked })
}
- const handleReportSave = () => {
- submitProfileUpdate({ reportFrequency })
+ const handleReportFrequencyChange = (frequency: string) => {
+ setReportFrequency(frequency)
+ submitProfileAutosave(
+ { reportFrequency: frequency },
+ 'profileSettings.autosave.reportFrequency',
+ )
}
const onAccountDelete = () => {
@@ -709,8 +859,14 @@ const UserSettings = () => {
fetcher.submit(formData, { method: 'post' })
}
- const setAsyncTimeFormat = () => {
- submitProfileUpdate({ timeFormat: form.timeFormat })
+ const handleTimeFormatChange = (
+ timeFormat: NonNullable<Form['timeFormat']>,
+ ) => {
+ setForm((prev) => ({
+ ...prev,
+ timeFormat,
+ }))
+ submitProfileAutosave({ timeFormat }, 'profileSettings.autosave.timeFormat')
}
const toggleShowEmailFields = () => {
@@ -1184,14 +1340,10 @@ const UserSettings = () => {
description={t('profileSettings.timezoneDesc')}
>
<div className='max-w-md'>
- <TimezonePicker value={timezone} onChange={setTimezone} />
- <Button
- size='lg'
- className='mt-4'
- onClick={handleTimezoneSave}
- >
- {t('common.save')}
- </Button>
+ <TimezonePicker
+ value={timezone}
+ onChange={handleTimezoneChange}
+ />
</div>
</SettingsSection>
@@ -1205,18 +1357,15 @@ const UserSettings = () => {
title={t(`profileSettings.${form.timeFormat}`)}
className='w-full'
items={translatedTimeFormat}
- onSelect={(f) =>
- setForm((prev) => ({
- ...prev,
- timeFormat:
- timeFormatArray[
- _findIndex(
- translatedTimeFormat,
- (freq) => freq === f,
- )
- ],
- }))
- }
+ onSelect={(f) => {
+ const nextTimeFormat = timeFormatArray[
+ _findIndex(translatedTimeFormat, (freq) => freq === f)
+ ] as NonNullable<Form['timeFormat']> | undefined
+
+ if (!nextTimeFormat) return
+
+ handleTimeFormatChange(nextTimeFormat)
+ }}
capitalise
selectedItem={
translatedTimeFormat[
@@ -1227,13 +1376,6 @@ const UserSettings = () => {
]
}
/>
- <Button
- size='lg'
- className='mt-4'
- onClick={setAsyncTimeFormat}
- >
- {t('common.save')}
- </Button>
</div>
</SettingsSection>
@@ -1606,16 +1748,17 @@ const UserSettings = () => {
label={t('profileSettings.email')}
className='w-full'
items={translatedFrequencies}
- onSelect={(f) =>
- setReportFrequency(
+ onSelect={(f) => {
+ const nextFrequency =
reportFrequencies[
_findIndex(
translatedFrequencies,
(freq) => freq === f,
)
- ],
- )
- }
+ ]
+
+ handleReportFrequencyChange(nextFrequency)
+ }}
capitalise
selectedItem={
translatedFrequencies[
@@ -1626,13 +1769,6 @@ const UserSettings = () => {
]
}
/>
- <Button
- size='lg'
- className='mt-4'
- onClick={handleReportSave}
- >
- {t('common.save')}
- </Button>
</div>
</SettingsSection>
@@ -1795,7 +1931,12 @@ const UserSettings = () => {
setIsPasswordChangeModalOpened(false)
pendingPasswordChangeRef.current = hasPasswordUpdateInput
passwordChangedRef.current = false
- submitProfileUpdate(undefined, true, hasPasswordUpdateInput)
+ submitProfileUpdate(
+ undefined,
+ true,
+ hasPasswordUpdateInput,
+ 'profileSettings.autosave.password',
+ )
}}
closeText={t('common.cancel')}
submitText={t('common.continue')}
diff --git a/web/public/locales/en.json b/web/public/locales/en.json
index 274c76fa9..af48e1b36 100644
--- a/web/public/locales/en.json
+++ b/web/public/locales/en.json
@@ -901,6 +901,17 @@
"reportSent": "The GDPR data report has been sent to your email address.",
"tryAgainInXDays": "Please, try again later. You can request a GDPR Export only once per {{amount}} days.",
"updated": "Your account settings have been updated",
+ "autosave": {
+ "email": "Email change confirmation sent",
+ "password": "Password updated",
+ "timezone": "Timezone updated",
+ "timeFormat": "Time format updated",
+ "reportFrequency": "Email report frequency updated",
+ "liveVisitors": "Live visitors title setting updated",
+ "loginNotifications": "Login notifications updated",
+ "apiKeyGenerated": "API key generated",
+ "apiKeyDeleted": "API key deleted"
+ },
"confTimeout": "An email has already been sent, check your mailbox or try again in a few minutes",
"confSent": "An account confirmation link has been sent to your email",
"noConfLeft": "Unfortunately, you've ran out of your email confirmation requests.\nPlease make sure you are able to receive e-mails and check your SPAM folder again for messages.\nYou may try to use a different email address or contact our customer support service.",
@@ -2366,6 +2377,21 @@
"learnMore": "Learn how we block bots"
},
"updated": "The project's settings were updated",
+ "autosave": {
+ "name": "Project name updated",
+ "websiteUrl": "Website URL updated",
+ "brandKeywords": "Brand keywords updated",
+ "origins": "Allowed origins updated",
+ "ipBlacklist": "IP blacklist updated",
+ "countryBlacklist": "Country blacklist updated",
+ "botsProtectionLevel": "Bot traffic filtering updated",
+ "public": "Public dashboard setting updated",
+ "passwordProtection": "Password protection updated",
+ "status": "Project status updated",
+ "captchaDifficulty": "CAPTCHA difficulty updated",
+ "organisation": "Project organisation updated",
+ "updated": "Project setting updated"
+ },
"created": "The project has been created",
"pxCharsError": "Project name cannot be longer than {{amount}} characters.",
"oxCharsError": "A list of allowed origins has to be smaller than {{amount}} symbols.",