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!

Migrate from prettier to oxfmt

Blue Mouse2a5898df7c9f
diff --git a/.github/workflows/pull_request.yml b/.github/workflows/pull_request.yml
index 23a13703f..738387a0c 100644
--- a/.github/workflows/pull_request.yml
+++ b/.github/workflows/pull_request.yml
@@ -28,6 +28,9 @@ jobs:
- name: Backend Lint Validation
run: npm run lint
working-directory: backend
+ - name: Backend Code Formatting Validation
+ run: npm run format:check
+ working-directory: backend
- name: Backend TypeScript Validation
run: npm run lint:tsc
working-directory: backend
@@ -57,7 +60,7 @@ jobs:
run: npm run lint
working-directory: web
- name: Web Code Formatting Validation
- run: npm run format
+ run: npm run format:check
working-directory: web
- name: Web TypeScript Validation
run: npm run typecheck
diff --git a/.vscode/extensions.json b/.vscode/extensions.json
index c67ec6d1b..99e2f7ddf 100644
--- a/.vscode/extensions.json
+++ b/.vscode/extensions.json
@@ -1,3 +1,3 @@
{
- "recommendations": ["esbenp.prettier-vscode", "oxc.oxc-vscode"]
+ "recommendations": ["oxc.oxc-vscode"]
}
diff --git a/backend/.oxfmtrc.json b/backend/.oxfmtrc.json
new file mode 100644
index 000000000..97b623470
--- /dev/null
+++ b/backend/.oxfmtrc.json
@@ -0,0 +1,10 @@
+{
+ "printWidth": 80,
+ "useTabs": false,
+ "tabWidth": 2,
+ "trailingComma": "all",
+ "semi": false,
+ "singleQuote": true,
+ "bracketSpacing": true,
+ "arrowParens": "always"
+}
diff --git a/backend/.prettierrc b/backend/.prettierrc
deleted file mode 100644
index 9292994a8..000000000
--- a/backend/.prettierrc
+++ /dev/null
@@ -1,6 +0,0 @@
-{
- "semi": false,
- "singleQuote": true,
- "trailingComma": "all",
- "arrowParens": "avoid"
-}
\ No newline at end of file
diff --git a/backend/apps/cloud/src/action-tokens/action-token.entity.ts b/backend/apps/cloud/src/action-tokens/action-token.entity.ts
index a57b26eee..5e9f1d57d 100644
--- a/backend/apps/cloud/src/action-tokens/action-token.entity.ts
+++ b/backend/apps/cloud/src/action-tokens/action-token.entity.ts
@@ -23,7 +23,7 @@ export class ActionToken {
@PrimaryGeneratedColumn('uuid')
id: string
- @ManyToOne(() => User, user => user.actionTokens, { onDelete: 'CASCADE' })
+ @ManyToOne(() => User, (user) => user.actionTokens, { onDelete: 'CASCADE' })
user: User
@CreateDateColumn()
diff --git a/backend/apps/cloud/src/ai/ai-chat.service.ts b/backend/apps/cloud/src/ai/ai-chat.service.ts
index e24d67fb2..b03e079e6 100644
--- a/backend/apps/cloud/src/ai/ai-chat.service.ts
+++ b/backend/apps/cloud/src/ai/ai-chat.service.ts
@@ -101,7 +101,7 @@ export class AiChatService {
}
private generateChatName(messages: ChatMessage[]): string {
- const firstUserMessage = messages.find(m => m.role === 'user')
+ const firstUserMessage = messages.find((m) => m.role === 'user')
if (firstUserMessage) {
const content = firstUserMessage.content.trim()
return content.length > 100 ? content.slice(0, 97) + '...' : content
diff --git a/backend/apps/cloud/src/ai/ai.controller.ts b/backend/apps/cloud/src/ai/ai.controller.ts
index 73c1e30d8..a6f8fab12 100644
--- a/backend/apps/cloud/src/ai/ai.controller.ts
+++ b/backend/apps/cloud/src/ai/ai.controller.ts
@@ -147,8 +147,8 @@ export class AiController {
})
const messages = chatDto.messages
- .filter(m => m.content && m.content.trim().length > 0)
- .map(m => ({
+ .filter((m) => m.content && m.content.trim().length > 0)
+ .map((m) => ({
role: m.role as 'user' | 'assistant',
content: m.content,
}))
@@ -387,7 +387,7 @@ export class AiController {
query.limit ?? 5,
)
- return chats.map(chat => ({
+ return chats.map((chat) => ({
id: chat.id,
name: chat.name,
created: chat.created,
@@ -431,7 +431,7 @@ export class AiController {
)
return {
- chats: result.chats.map(chat => ({
+ chats: result.chats.map((chat) => ({
id: chat.id,
name: chat.name,
created: chat.created,
diff --git a/backend/apps/cloud/src/ai/ai.service.ts b/backend/apps/cloud/src/ai/ai.service.ts
index 6c17bde82..ae06adf8f 100644
--- a/backend/apps/cloud/src/ai/ai.service.ts
+++ b/backend/apps/cloud/src/ai/ai.service.ts
@@ -254,7 +254,7 @@ Available columns for filters:
.optional()
.describe('Measure type for performance data'),
}),
- execute: async params => {
+ execute: async (params) => {
if (!params.dataType) {
return { error: 'dataType is required' }
}
@@ -307,7 +307,7 @@ Available columns for filters:
.describe('Start date (YYYY-MM-DD format)'),
to: z.string().optional().describe('End date (YYYY-MM-DD format)'),
}),
- execute: async params => {
+ execute: async (params) => {
this.logger.log(
{ pid: project.id, goalId: params.goalId, period: params.period },
'Tool: getGoalStats called',
@@ -344,7 +344,7 @@ Available columns for filters:
.describe('Start date (YYYY-MM-DD format)'),
to: z.string().optional().describe('End date (YYYY-MM-DD format)'),
}),
- execute: async params => {
+ execute: async (params) => {
if (!params.funnelId) {
return { error: 'funnelId is required' }
}
@@ -401,8 +401,12 @@ Available columns for filters:
name: project.name,
created: project.created,
captchaEnabled: !!project.captchaSecretKey,
- funnels: _map(funnels, f => ({ id: f.id, name: f.name, steps: f.steps })),
- goals: _map(goals, g => ({
+ funnels: _map(funnels, (f) => ({
+ id: f.id,
+ name: f.name,
+ steps: f.steps,
+ })),
+ goals: _map(goals, (g) => ({
id: g.id,
name: g.name,
type: g.type,
@@ -540,7 +544,7 @@ Available columns for filters:
...filterConditions.params,
},
})
- .then(r => r.json())
+ .then((r) => r.json())
// Get chart data
const chartQuery = `
@@ -567,7 +571,7 @@ Available columns for filters:
...filterConditions.params,
},
})
- .then(r => r.json())
+ .then((r) => r.json())
// Get top pages
const pagesQuery = `
@@ -586,7 +590,7 @@ Available columns for filters:
query: pagesQuery,
query_params: { pid, groupFrom, groupTo, ...filterConditions.params },
})
- .then(r => r.json())
+ .then((r) => r.json())
// Get top countries
const countriesQuery = `
@@ -606,7 +610,7 @@ Available columns for filters:
query: countriesQuery,
query_params: { pid, groupFrom, groupTo, ...filterConditions.params },
})
- .then(r => r.json())
+ .then((r) => r.json())
// Get top referrers
const referrersQuery = `
@@ -626,7 +630,7 @@ Available columns for filters:
query: referrersQuery,
query_params: { pid, groupFrom, groupTo, ...filterConditions.params },
})
- .then(r => r.json())
+ .then((r) => r.json())
// Get browsers
const browsersQuery = `
@@ -646,7 +650,7 @@ Available columns for filters:
query: browsersQuery,
query_params: { pid, groupFrom, groupTo, ...filterConditions.params },
})
- .then(r => r.json())
+ .then((r) => r.json())
// Get devices
const devicesQuery = `
@@ -665,7 +669,7 @@ Available columns for filters:
query: devicesQuery,
query_params: { pid, groupFrom, groupTo, ...filterConditions.params },
})
- .then(r => r.json())
+ .then((r) => r.json())
return {
overall: overallData[0] || {},
@@ -731,7 +735,7 @@ Available columns for filters:
...filterConditions.params,
},
})
- .then(r => r.json())
+ .then((r) => r.json())
// Get chart data
const chartQuery = `
@@ -758,7 +762,7 @@ Available columns for filters:
...filterConditions.params,
},
})
- .then(r => r.json())
+ .then((r) => r.json())
return {
overall: overallData[0] || {},
@@ -793,7 +797,7 @@ Available columns for filters:
query: overallQuery,
query_params: { pid, groupFrom, groupTo },
})
- .then(r => r.json())
+ .then((r) => r.json())
// Get top errors
const topErrorsQuery = `
@@ -815,7 +819,7 @@ Available columns for filters:
query: topErrorsQuery,
query_params: { pid, groupFrom, groupTo },
})
- .then(r => r.json())
+ .then((r) => r.json())
return {
overall: overallData[0] || {},
@@ -884,7 +888,7 @@ Available columns for filters:
groupTo: groupToUTC,
},
})
- .then(r => r.json())
+ .then((r) => r.json())
return {
goal: { id: goal.id, name: goal.name, type: goal.type },
@@ -899,7 +903,7 @@ Available columns for filters:
})
const results = await Promise.all(
- goals.map(async goal => {
+ goals.map(async (goal) => {
const table = goal.type === 'custom_event' ? 'customEV' : 'analytics'
const matchCondition =
goal.matchType === 'exact'
@@ -928,7 +932,7 @@ Available columns for filters:
groupTo: groupToUTC,
},
})
- .then(r => r.json())
+ .then((r) => r.json())
return {
id: goal.id,
diff --git a/backend/apps/cloud/src/alert/alert.controller.ts b/backend/apps/cloud/src/alert/alert.controller.ts
index 19ca56bd3..8f3cf1fce 100644
--- a/backend/apps/cloud/src/alert/alert.controller.ts
+++ b/backend/apps/cloud/src/alert/alert.controller.ts
@@ -113,7 +113,7 @@ export class AlertController {
)
// @ts-expect-error
- result.results = _map(result.results, alert => ({
+ result.results = _map(result.results, (alert) => ({
..._omit(alert, ['project']),
pid: alert.project.id,
}))
@@ -167,7 +167,7 @@ export class AlertController {
'You are not allowed to add alerts to this project',
)
- const pids = _map(user.projects, userProject => userProject.id)
+ const pids = _map(user.projects, (userProject) => userProject.id)
const alertsCount = await this.alertService.count({
where: { project: { id: In(pids) } },
})
diff --git a/backend/apps/cloud/src/alert/entity/alert.entity.ts b/backend/apps/cloud/src/alert/entity/alert.entity.ts
index 257610d38..a6eba843a 100644
--- a/backend/apps/cloud/src/alert/entity/alert.entity.ts
+++ b/backend/apps/cloud/src/alert/entity/alert.entity.ts
@@ -9,7 +9,7 @@ export class Alert {
@PrimaryGeneratedColumn('uuid')
id: string
- @ManyToOne(() => Project, project => project.alerts)
+ @ManyToOne(() => Project, (project) => project.alerts)
project: Project
@ApiProperty()
diff --git a/backend/apps/cloud/src/analytics/analytics.controller.ts b/backend/apps/cloud/src/analytics/analytics.controller.ts
index adb340521..3c3648312 100644
--- a/backend/apps/cloud/src/analytics/analytics.controller.ts
+++ b/backend/apps/cloud/src/analytics/analytics.controller.ts
@@ -908,7 +908,7 @@ export class AnalyticsController {
const validPids = []
- const validationPromises = _map(pidsArray, async currentPID => {
+ const validationPromises = _map(pidsArray, async (currentPID) => {
await this.analyticsService.checkProjectAccess(
currentPID,
uid,
@@ -970,7 +970,7 @@ export class AnalyticsController {
measure = DEFAULT_MEASURE
}
- const validationPromises = _map(pidsArray, async currentPID => {
+ const validationPromises = _map(pidsArray, async (currentPID) => {
await this.analyticsService.checkProjectAccess(
currentPID,
uid,
@@ -1033,7 +1033,7 @@ export class AnalyticsController {
const validPids = []
- const validationPromises = _map(pidsArray, async currentPID => {
+ const validationPromises = _map(pidsArray, async (currentPID) => {
await this.analyticsService.checkProjectAccess(
currentPID,
uid,
@@ -1060,12 +1060,12 @@ export class AnalyticsController {
const result = {}
- const keyCountPromises = _map(validPids, async currentPID => {
+ const keyCountPromises = _map(validPids, async (currentPID) => {
result[currentPID] =
await this.analyticsService.getOnlineUserCount(currentPID)
})
- await Promise.all(keyCountPromises).catch(reason => {
+ await Promise.all(keyCountPromises).catch((reason) => {
this.logger.error(`[GET /analytics/hb] ${reason}`)
throw new InternalServerErrorException(
'An error occured while calculating heartbeat statistics',
@@ -1143,7 +1143,7 @@ export class AnalyticsController {
since,
},
})
- .then(resultSet => resultSet.json())
+ .then((resultSet) => resultSet.json())
return data
}
diff --git a/backend/apps/cloud/src/analytics/analytics.service.ts b/backend/apps/cloud/src/analytics/analytics.service.ts
index 1f244c862..35f9d5a5e 100644
--- a/backend/apps/cloud/src/analytics/analytics.service.ts
+++ b/backend/apps/cloud/src/analytics/analytics.service.ts
@@ -665,7 +665,7 @@ export class AnalyticsService {
removeCyclicDependencies(links: IUserFlowLink[]): IUserFlowLink[] {
const visited = new Set<string>()
- return links.filter(link => {
+ return links.filter((link) => {
const key = `${link.source}_${link.target}`
if (visited.has(key)) {
return false
@@ -723,7 +723,7 @@ export class AnalyticsService {
query,
query_params: params,
})
- .then(res => res.json<IUserFlowLink>())
+ .then((res) => res.json<IUserFlowLink>())
if (_isEmpty(data)) {
const empty = { nodes: [], links: [] }
@@ -795,7 +795,7 @@ export class AnalyticsService {
)
}
- if (_some(pages, page => !_isString(page))) {
+ if (_some(pages, (page) => !_isString(page))) {
throw new UnprocessableEntityException(
'Pages array must contain string values only',
)
@@ -821,7 +821,7 @@ export class AnalyticsService {
query: `SELECT min(created) AS firstCreated FROM ${table} WHERE pid = {pid:FixedString(12)}`,
query_params: { pid },
})
- .then(res => res.json<{ firstCreated?: string }>())
+ .then((res) => res.json<{ firstCreated?: string }>())
const firstCreated = fromData?.[0]?.firstCreated
@@ -861,7 +861,7 @@ export class AnalyticsService {
const { column, filter, isExclusive, isContains = false } = curr
if (_isArray(filter)) {
- const filterArray = _map(filter, f => ({
+ const filterArray = _map(filter, (f) => ({
column,
filter: f,
isExclusive,
@@ -1041,7 +1041,7 @@ export class AnalyticsService {
`(domain(ref) != '' AND (lower(domain(ref)) = {${dp}:String} OR endsWith(lower(domain(ref)), concat('.', {${dp}:String})))) OR (domain(ref) = '' AND (lower(ref) = {${dp}:String} OR endsWith(lower(ref), concat('.', {${dp}:String}))))`,
)
}
- const combined = parts.map(p => `(${p})`).join(' OR ')
+ const combined = parts.map((p) => `(${p})`).join(' OR ')
query += isExclusive ? `NOT (${combined})` : `(${combined})`
continue
}
@@ -1117,9 +1117,7 @@ export class AnalyticsService {
}
} else {
query += isArrayDataset
- ? `indexOf(${sqlColumn}, {${param}:String}) ${
- isExclusive ? '=' : '>'
- } 0`
+ ? `indexOf(${sqlColumn}, {${param}:String}) ${isExclusive ? '=' : '>'} 0`
: `${isExclusive ? 'NOT ' : ''}${sqlColumn} = {${param}:String}`
}
}
@@ -1262,7 +1260,7 @@ export class AnalyticsService {
query,
query_params: { psid, pid },
})
- .then(resultSet =>
+ .then((resultSet) =>
resultSet.json<{
firstSeen: string | null
}>(),
@@ -1315,7 +1313,7 @@ export class AnalyticsService {
query,
query_params: { psid, pid, cutoff },
})
- .then(resultSet => resultSet.json())
+ .then((resultSet) => resultSet.json())
return data.length > 0
} catch (error) {
@@ -1341,7 +1339,7 @@ export class AnalyticsService {
query,
query_params: { psid, pid },
})
- .then(resultSet => resultSet.json<{ duration: number }>())
+ .then((resultSet) => resultSet.json<{ duration: number }>())
return data[0]?.duration ?? null
} catch (error) {
@@ -1425,7 +1423,7 @@ export class AnalyticsService {
}
generateEmptyFunnel(pages: string[]): IFunnel[] {
- return _map(pages, value => ({
+ return _map(pages, (value) => ({
value,
events: 0,
eventsPerc: 0,
@@ -1488,7 +1486,7 @@ export class AnalyticsService {
query,
query_params: { ...params, ...pageParams },
})
- .then(resultSet => resultSet.json<IFunnelCHResponse>())
+ .then((resultSet) => resultSet.json<IFunnelCHResponse>())
if (_isEmpty(data)) {
return this.generateEmptyFunnel(pages)
@@ -1515,7 +1513,7 @@ export class AnalyticsService {
query,
query_params: { pid, groupFrom, groupTo },
})
- .then(resultSet => resultSet.json<{ c: number }>())
+ .then((resultSet) => resultSet.json<{ c: number }>())
return data[0]?.c || 0
}
@@ -1621,7 +1619,7 @@ export class AnalyticsService {
query,
query_params: { pid, groupFrom, groupTo },
})
- .then(resultSet => resultSet.json<{ cc: string; count: number }>())
+ .then((resultSet) => resultSet.json<{ cc: string; count: number }>())
return data[0] || null
}
@@ -1662,7 +1660,7 @@ export class AnalyticsService {
query,
query_params: { pids, groupFrom, groupTo },
})
- .then(resultSet =>
+ .then((resultSet) =>
resultSet.json<{ pid: string; cc: string; count: any }>(),
)
@@ -1700,7 +1698,7 @@ export class AnalyticsService {
query,
query_params: { pid, groupFrom, groupTo },
})
- .then(resultSet =>
+ .then((resultSet) =>
resultSet.json<{ count: number; uniqueErrors: number }>(),
)
@@ -1733,7 +1731,7 @@ export class AnalyticsService {
query,
query_params: { pids, groupFrom, groupTo },
})
- .then(resultSet =>
+ .then((resultSet) =>
resultSet.json<{
pid: string
count: any
@@ -1780,7 +1778,9 @@ export class AnalyticsService {
query,
query_params: { pids, groupFrom, groupTo },
})
- .then(resultSet => resultSet.json<{ pid: string; totalSessions: any }>())
+ .then((resultSet) =>
+ resultSet.json<{ pid: string; totalSessions: any }>(),
+ )
const result: Record<string, number> = {}
for (const row of data || []) {
@@ -1830,7 +1830,7 @@ export class AnalyticsService {
const [filtersQuery, filtersParams, , customEVFilterApplied] =
this.getFiltersQuery(filters, DataType.ANALYTICS)
- const promises = pids.map(async pid => {
+ const promises = pids.map(async (pid) => {
try {
if (period === 'all') {
let queryAll = `
@@ -1899,7 +1899,7 @@ export class AnalyticsService {
...filtersParams,
},
})
- .then(resultSet => resultSet.json<BirdseyeCHResponse>())
+ .then((resultSet) => resultSet.json<BirdseyeCHResponse>())
let bounceRate = 0
@@ -2131,7 +2131,7 @@ export class AnalyticsService {
...filtersParams,
},
})
- .then(resultSet => resultSet.json<BirdseyeCHResponse>())
+ .then((resultSet) => resultSet.json<BirdseyeCHResponse>())
data = _sortBy(data, 'sortOrder')
@@ -2250,7 +2250,7 @@ export class AnalyticsService {
query,
query_params: { ...paramsData.params, timezone: safeTimezone },
})
- .then(resultSet => resultSet.json<TrafficCEFilterCHResponse>())
+ .then((resultSet) => resultSet.json<TrafficCEFilterCHResponse>())
const visits =
this.extractCustomEventsChartData(data, xShifted)?._unknown_event || []
@@ -2269,7 +2269,7 @@ export class AnalyticsService {
query,
query_params: { ...paramsData.params, timezone: safeTimezone },
})
- .then(resultSet => resultSet.json<TrafficCHResponse>())
+ .then((resultSet) => resultSet.json<TrafficCHResponse>())
const { visits } = this.extractChartData(data, xShifted)
@@ -2315,10 +2315,10 @@ export class AnalyticsService {
const cols = ['dns', 'tls', 'conn', 'response', 'render', 'domLoad', 'ttfb']
const columnSelectors = cols
- .map(col => `${MEASURES_MAP[measure]}(${col}) as ${col}`)
+ .map((col) => `${MEASURES_MAP[measure]}(${col}) as ${col}`)
.join(', ')
- const promises = pids.map(async pid => {
+ const promises = pids.map(async (pid) => {
try {
if (period === 'all') {
const queryAll = `SELECT ${columnSelectors} FROM performance WHERE pid = {pid:FixedString(12)} ${filtersQuery}`
@@ -2331,7 +2331,9 @@ export class AnalyticsService {
...filtersParams,
},
})
- .then(resultSet => resultSet.json<Partial<PerformanceCHResponse>>())
+ .then((resultSet) =>
+ resultSet.json<Partial<PerformanceCHResponse>>(),
+ )
result[pid] = {
current: {
@@ -2398,7 +2400,7 @@ export class AnalyticsService {
...filtersParams,
},
})
- .then(resultSet => resultSet.json<Partial<PerformanceCHResponse>>())
+ .then((resultSet) => resultSet.json<Partial<PerformanceCHResponse>>())
data = _sortBy(data, 'sortOrder')
@@ -2492,7 +2494,7 @@ export class AnalyticsService {
query,
query_params: { pid },
})
- .then(resultSet => resultSet.json<any>())
+ .then((resultSet) => resultSet.json<any>())
return _map(data, 'page')
}
@@ -2510,7 +2512,7 @@ export class AnalyticsService {
pid,
},
})
- .then(resultSet => resultSet.json())
+ .then((resultSet) => resultSet.json())
return _map(data, type)
}
@@ -2531,7 +2533,7 @@ export class AnalyticsService {
pid,
},
})
- .then(resultSet => resultSet.json())
+ .then((resultSet) => resultSet.json())
return _map(data, type)
}
@@ -2556,9 +2558,9 @@ export class AnalyticsService {
query,
query_params: { pid },
})
- .then(resultSet => resultSet.json<Record<string, string>[]>())
+ .then((resultSet) => resultSet.json<Record<string, string>[]>())
- return data.map(row => ({
+ return data.map((row) => ({
name: row[column],
version: row[safeVersionCol],
}))
@@ -2578,7 +2580,7 @@ export class AnalyticsService {
: !_isEmpty(
_find(
parsedFilters,
- filter =>
+ (filter) =>
(filter.column === 'pg' || filter.column === 'host') &&
!filter.isExclusive,
),
@@ -2599,7 +2601,7 @@ export class AnalyticsService {
}
// Build a single query combining all metrics
- const withClauses = columns.map(col => {
+ const withClauses = columns.map((col) => {
const baseQuery = generateParamsQuery(
col,
subQuery,
@@ -2627,7 +2629,7 @@ export class AnalyticsService {
extra_fields
FROM (
${columns
- .map(col => {
+ .map((col) => {
let extraField = `CAST([] AS Array(Nullable(String))) as extra_fields`
if (col === 'rg') {
@@ -2659,9 +2661,9 @@ export class AnalyticsService {
query,
query_params: paramsData.params,
})
- .then(resultSet => resultSet.json<any>())
+ .then((resultSet) => resultSet.json<any>())
- const params = Object.fromEntries(columns.map(col => [col, []]))
+ const params = Object.fromEntries(columns.map((col) => [col, []]))
const { length } = data
@@ -3102,7 +3104,7 @@ export class AnalyticsService {
const cols = ['dns', 'tls', 'conn', 'response', 'render', 'domLoad', 'ttfb']
const columnSelectors = cols
- .map(col => `${MEASURES_MAP[measure]}(${col}) as ${col}`)
+ .map((col) => `${MEASURES_MAP[measure]}(${col}) as ${col}`)
.join(', ')
return `
@@ -3135,7 +3137,9 @@ export class AnalyticsService {
const cols = ['dns', 'tls', 'conn', 'response', 'render', 'domLoad', 'ttfb']
const columnSelectors = cols
- .map(col => `quantilesExactInclusive(0.5, 0.75, 0.95)(${col}) as ${col}`)
+ .map(
+ (col) => `quantilesExactInclusive(0.5, 0.75, 0.95)(${col}) as ${col}`,
+ )
.join(', ')
return `
@@ -3312,7 +3316,7 @@ export class AnalyticsService {
query,
query_params: paramsData.params,
})
- .then(resultSet => resultSet.json<any>())
+ .then((resultSet) => resultSet.json<any>())
return data || []
}
@@ -3342,7 +3346,7 @@ export class AnalyticsService {
query,
query_params: paramsData.params,
})
- .then(resultSet => resultSet.json<any>())
+ .then((resultSet) => resultSet.json<any>())
return data || []
}
@@ -3400,7 +3404,7 @@ export class AnalyticsService {
query,
query_params: { ...paramsData.params, timezone: safeTimezone },
})
- .then(resultSet => resultSet.json<TrafficCEFilterCHResponse>())
+ .then((resultSet) => resultSet.json<TrafficCEFilterCHResponse>())
const uniques =
this.extractCustomEventsChartData(data, xShifted)?._unknown_event || []
@@ -3428,7 +3432,7 @@ export class AnalyticsService {
query,
query_params: { ...paramsData.params, timezone: safeTimezone },
})
- .then(resultSet => resultSet.json<TrafficCHResponse>())
+ .then((resultSet) => resultSet.json<TrafficCHResponse>())
const { visits, uniques, sdur } = this.extractChartData(data, xShifted)
@@ -3541,19 +3545,19 @@ export class AnalyticsService {
query: pageviewsQuery,
query_params: queryParams,
})
- .then(resultSet => resultSet.json<any>()),
+ .then((resultSet) => resultSet.json<any>()),
clickhouse
.query({
query: customEventsQuery,
query_params: queryParams,
})
- .then(resultSet => resultSet.json<any>()),
+ .then((resultSet) => resultSet.json<any>()),
clickhouse
.query({
query: errorsQuery,
query_params: queryParams,
})
- .then(resultSet => resultSet.json<any>()),
+ .then((resultSet) => resultSet.json<any>()),
])
const pageviews = this.extractCountsForSessionChart(
@@ -3581,15 +3585,15 @@ export class AnalyticsService {
x: xShifted,
}
- if (_some(pageviews, count => count > 0)) {
+ if (_some(pageviews, (count) => count > 0)) {
chartOutput.pageviews = pageviews
}
- if (_some(customEvents, count => count > 0)) {
+ if (_some(customEvents, (count) => count > 0)) {
chartOutput.customEvents = customEvents
}
- if (_some(errors, count => count > 0)) {
+ if (_some(errors, (count) => count > 0)) {
chartOutput.errors = errors
}
@@ -3676,7 +3680,7 @@ export class AnalyticsService {
'captcha',
)
- if (!_some(_values(params), val => !_isEmpty(val))) {
+ if (!_some(_values(params), (val) => !_isEmpty(val))) {
throw new BadRequestException(
'There are no parameters for the specified time frames',
)
@@ -3703,7 +3707,7 @@ export class AnalyticsService {
query,
query_params: { ...paramsData.params, timezone: safeTimezone },
})
- .then(resultSet => resultSet.json<TrafficCEFilterCHResponse>())
+ .then((resultSet) => resultSet.json<TrafficCEFilterCHResponse>())
const { count } = this.extractCaptchaChartData(data, xShifted)
chart = {
@@ -3745,7 +3749,7 @@ export class AnalyticsService {
'errors',
)
- if (!_some(_values(params), val => !_isEmpty(val))) {
+ if (!_some(_values(params), (val) => !_isEmpty(val))) {
throw new BadRequestException(
'There are no error details for specified time frame',
)
@@ -3767,7 +3771,7 @@ export class AnalyticsService {
query,
query_params: paramsData.params,
})
- .then(resultSet => resultSet.json<TrafficCEFilterCHResponse>())
+ .then((resultSet) => resultSet.json<TrafficCEFilterCHResponse>())
const { count, affectedUsers } = this.extractErrorsChartData(data, x)
chart = {
@@ -3897,7 +3901,7 @@ export class AnalyticsService {
query,
query_params: { ...paramsData.params, timezone: safeTimezone },
})
- .then(resultSet => resultSet.json())
+ .then((resultSet) => resultSet.json())
return {
x: xShifted,
@@ -3916,7 +3920,7 @@ export class AnalyticsService {
query,
query_params: { ...paramsData.params, timezone: safeTimezone },
})
- .then(resultSet => resultSet.json<PerformanceCHResponse>())
+ .then((resultSet) => resultSet.json<PerformanceCHResponse>())
return {
x: xShifted,
@@ -3949,7 +3953,7 @@ export class AnalyticsService {
measure,
)
- if (!_some(_values(params), val => !_isEmpty(val))) {
+ if (!_some(_values(params), (val) => !_isEmpty(val))) {
throw new BadRequestException(
'There are no parameters for the specified time frames',
)
@@ -3990,7 +3994,7 @@ export class AnalyticsService {
query,
query_params: params.params,
})
- .then(resultSet => resultSet.json<CustomsCHResponse>())
+ .then((resultSet) => resultSet.json<CustomsCHResponse>())
const size = _size(data)
for (let i = 0; i < size; ++i) {
@@ -4028,7 +4032,7 @@ export class AnalyticsService {
query,
query_params: params.params,
})
- .then(resultSet => resultSet.json<PropertiesCHResponse>())
+ .then((resultSet) => resultSet.json<PropertiesCHResponse>())
const size = _size(data)
for (let i = 0; i < size; ++i) {
@@ -4125,7 +4129,7 @@ export class AnalyticsService {
query,
query_params: paramsData.params,
})
- .then(resultSet => resultSet.json<IAggregatedMetadata>())
+ .then((resultSet) => resultSet.json<IAggregatedMetadata>())
return {
result,
@@ -4227,7 +4231,7 @@ export class AnalyticsService {
query,
query_params: paramsData.params,
})
- .then(resultSet => resultSet.json<IAggregatedMetadata>())
+ .then((resultSet) => resultSet.json<IAggregatedMetadata>())
return {
result,
@@ -4273,7 +4277,7 @@ export class AnalyticsService {
since,
},
})
- .then(resultSet => resultSet.json<{ count: string }>())
+ .then((resultSet) => resultSet.json<{ count: string }>())
return Number(data[0]?.count || 0)
} catch (error) {
@@ -4330,7 +4334,7 @@ export class AnalyticsService {
customEvents: customEvents || [],
},
})
- .then(resultSet => resultSet.json<CustomsCHAggregatedResponse>())
+ .then((resultSet) => resultSet.json<CustomsCHAggregatedResponse>())
const events = this.extractCustomEventsChartData(data, xShifted)
@@ -4375,8 +4379,10 @@ export class AnalyticsService {
(page.type === 'sale' || page.type === 'refund') &&
processedMetadata
) {
- const amountEntry = processedMetadata.find(m => m.key === 'amount')
- const currencyEntry = processedMetadata.find(m => m.key === 'currency')
+ const amountEntry = processedMetadata.find((m) => m.key === 'amount')
+ const currencyEntry = processedMetadata.find(
+ (m) => m.key === 'currency',
+ )
let amount: number | undefined
@@ -4391,7 +4397,7 @@ export class AnalyticsService {
return {
...page,
metadata: processedMetadata.filter(
- m => m.key !== 'amount' && m.key !== 'currency',
+ (m) => m.key !== 'amount' && m.key !== 'currency',
),
amount,
currency: currencyEntry ? currencyEntry.value : undefined,
@@ -4552,7 +4558,7 @@ export class AnalyticsService {
query: queryPages,
query_params: paramsData.params,
})
- .then(resultSet => resultSet.json<IPageflow>())
+ .then((resultSet) => resultSet.json<IPageflow>())
let details = (
await clickhouse
@@ -4560,7 +4566,7 @@ export class AnalyticsService {
query: querySessionDetails,
query_params: paramsData.params,
})
- .then(resultSet => resultSet.json())
+ .then((resultSet) => resultSet.json())
.then(({ data }) => data)
)[0] as any
@@ -4571,7 +4577,7 @@ export class AnalyticsService {
query: querySessionDuration,
query_params: paramsData.params,
})
- .then(resultSet =>
+ .then((resultSet) =>
resultSet.json<{
duration: number | null
lastSeen: string | null
@@ -4626,7 +4632,7 @@ export class AnalyticsService {
query: querySessionDetailsFromCustomEV,
query_params: paramsData.params,
})
- .then(resultSet => resultSet.json())
+ .then((resultSet) => resultSet.json())
.then(({ data }) => data)
)[0]
}
@@ -4909,7 +4915,7 @@ export class AnalyticsService {
skip,
},
})
- .then(resultSet => resultSet.json())
+ .then((resultSet) => resultSet.json())
return data
}
@@ -5016,7 +5022,7 @@ export class AnalyticsService {
query,
query_params: { pid, ...paramsData.params, take, skip },
})
- .then(resultSet => resultSet.json())
+ .then((resultSet) => resultSet.json())
return data
.filter((profile: any) => profile.profileId)
@@ -5122,22 +5128,22 @@ export class AnalyticsService {
] = await Promise.all([
clickhouse
.query({ query: querySessionCount, query_params: params })
- .then(resultSet => resultSet.json()),
+ .then((resultSet) => resultSet.json()),
clickhouse
.query({ query: queryAvgDuration, query_params: params })
- .then(resultSet => resultSet.json()),
+ .then((resultSet) => resultSet.json()),
clickhouse
.query({ query: queryPageviews, query_params: params })
- .then(resultSet => resultSet.json()),
+ .then((resultSet) => resultSet.json()),
clickhouse
.query({ query: queryEvents, query_params: params })
- .then(resultSet => resultSet.json()),
+ .then((resultSet) => resultSet.json()),
clickhouse
.query({ query: queryDetails, query_params: params })
- .then(resultSet => resultSet.json()),
+ .then((resultSet) => resultSet.json()),
clickhouse
.query({ query: queryRevenue, query_params: params })
- .then(resultSet => resultSet.json()),
+ .then((resultSet) => resultSet.json()),
])
const sessionCount = (sessionCountResult.data[0] || {}) as Record<
@@ -5187,7 +5193,7 @@ export class AnalyticsService {
query,
query_params: { pid, profileId, limit: Number(limit) },
})
- .then(resultSet => resultSet.json())
+ .then((resultSet) => resultSet.json())
return data as { page: string; count: number }[]
}
@@ -5220,7 +5226,7 @@ export class AnalyticsService {
query,
query_params: { pid, profileId, startDate },
})
- .then(resultSet => resultSet.json())
+ .then((resultSet) => resultSet.json())
return data as { date: string; count: number }[]
}
@@ -5282,13 +5288,13 @@ export class AnalyticsService {
const [pageviewsResult, eventsResult, errorsResult] = await Promise.all([
clickhouse
.query({ query: queryPageviews, query_params: params })
- .then(resultSet => resultSet.json()),
+ .then((resultSet) => resultSet.json()),
clickhouse
.query({ query: queryEvents, query_params: params })
- .then(resultSet => resultSet.json()),
+ .then((resultSet) => resultSet.json()),
clickhouse
.query({ query: queryErrors, query_params: params })
- .then(resultSet => resultSet.json()),
+ .then((resultSet) => resultSet.json()),
])
// Merge all timestamps and create aligned data
@@ -5325,9 +5331,9 @@ export class AnalyticsService {
return {
x: sortedTimes,
- pageviews: sortedTimes.map(t => pageviewsMap.get(t) || 0),
- customEvents: sortedTimes.map(t => eventsMap.get(t) || 0),
- errors: sortedTimes.map(t => errorsMap.get(t) || 0),
+ pageviews: sortedTimes.map((t) => pageviewsMap.get(t) || 0),
+ customEvents: sortedTimes.map((t) => eventsMap.get(t) || 0),
+ errors: sortedTimes.map((t) => errorsMap.get(t) || 0),
}
}
@@ -5440,7 +5446,7 @@ export class AnalyticsService {
skip,
},
})
- .then(resultSet => resultSet.json())
+ .then((resultSet) => resultSet.json())
return data as object[]
}
@@ -5510,7 +5516,7 @@ export class AnalyticsService {
skip,
},
})
- .then(resultSet => resultSet.json())
+ .then((resultSet) => resultSet.json())
return data
}
@@ -5609,21 +5615,21 @@ export class AnalyticsService {
query: queryErrorDetails,
query_params: paramsData.params,
})
- .then(resultSet => resultSet.json<any>())
+ .then((resultSet) => resultSet.json<any>())
.then(({ data }) => data[0]),
clickhouse
.query({
query: queryFirstLastSeen,
query_params: paramsData.params,
})
- .then(resultSet => resultSet.json<any>())
+ .then((resultSet) => resultSet.json<any>())
.then(({ data }) => data[0]),
clickhouse
.query({
query: queryMetadata,
query_params: paramsData.params,
})
- .then(resultSet => resultSet.json<IAggregatedMetadata>())
+ .then((resultSet) => resultSet.json<IAggregatedMetadata>())
.then(({ data }) => data),
])
@@ -5764,28 +5770,28 @@ export class AnalyticsService {
query: queryTotalSessions,
query_params: paramsData.params,
})
- .then(resultSet => resultSet.json<any>())
+ .then((resultSet) => resultSet.json<any>())
.then(({ data }) => data[0]),
clickhouse
.query({
query: queryErrorStats,
query_params: paramsWithTimezone,
})
- .then(resultSet => resultSet.json<any>())
+ .then((resultSet) => resultSet.json<any>())
.then(({ data }) => data[0]),
clickhouse
.query({
query: queryMostFrequentError,
query_params: paramsWithTimezone,
})
- .then(resultSet => resultSet.json<any>())
+ .then((resultSet) => resultSet.json<any>())
.then(({ data }) => data[0] || null),
clickhouse
.query({
query: queryChart,
query_params: paramsWithTimezone,
})
- .then(resultSet => resultSet.json<any>())
+ .then((resultSet) => resultSet.json<any>())
.then(({ data }) => data),
])
@@ -5883,11 +5889,11 @@ export class AnalyticsService {
const [countResult, sessionsResult] = await Promise.all([
clickhouse
.query({ query: queryCount, query_params: params })
- .then(resultSet => resultSet.json<any>())
+ .then((resultSet) => resultSet.json<any>())
.then(({ data }) => data[0]),
clickhouse
.query({ query: querySessions, query_params: params })
- .then(resultSet => resultSet.json<any>())
+ .then((resultSet) => resultSet.json<any>())
.then(({ data }) => data),
])
@@ -5930,7 +5936,7 @@ export class AnalyticsService {
query,
query_params: { ...params, pid },
})
- .then(resultSet => resultSet.json())
+ .then((resultSet) => resultSet.json())
.then(({ data }) => data)
)[0]
} catch (reason) {
@@ -6020,7 +6026,7 @@ export class AnalyticsService {
.query({
query,
})
- .then(resultSet => resultSet.json())
+ .then((resultSet) => resultSet.json())
// @ts-expect-error
const events = data.reduce((total, row) => total + row.count, 0) as number
@@ -6070,7 +6076,7 @@ export class AnalyticsService {
const results = []
await Promise.all(
- customEvents.map(async event => {
+ customEvents.map(async (event) => {
const result = await this.getMetaResult(
pid,
event,
@@ -6084,7 +6090,7 @@ export class AnalyticsService {
}),
)
- return results.filter(r => !!r)
+ return results.filter((r) => !!r)
}
async getMetaResult(
@@ -6204,7 +6210,7 @@ export class AnalyticsService {
query: `${queryCurrent} UNION ALL ${queryPrevious}`,
query_params: params,
})
- .then(resultSet =>
+ .then((resultSet) =>
resultSet.json<{
sortOrder: 1 | 2
key: string
diff --git a/backend/apps/cloud/src/analytics/decorators/validate-project-ids.decorator.ts b/backend/apps/cloud/src/analytics/decorators/validate-project-ids.decorator.ts
index c7048ef44..29abc118b 100644
--- a/backend/apps/cloud/src/analytics/decorators/validate-project-ids.decorator.ts
+++ b/backend/apps/cloud/src/analytics/decorators/validate-project-ids.decorator.ts
@@ -26,7 +26,7 @@ export function ValidateProjectIds(validationOptions?: ValidationOptions) {
return false
}
- return value.every(pid => PID_REGEX.test(pid))
+ return value.every((pid) => PID_REGEX.test(pid))
},
defaultMessage() {
return 'One of the provided Project IDs (pids) is incorrect'
diff --git a/backend/apps/cloud/src/analytics/dto/events.dto.ts b/backend/apps/cloud/src/analytics/dto/events.dto.ts
index 92089a249..769d5d8e5 100644
--- a/backend/apps/cloud/src/analytics/dto/events.dto.ts
+++ b/backend/apps/cloud/src/analytics/dto/events.dto.ts
@@ -75,7 +75,7 @@ export class MetadataValueType implements ValidatorConstraintInterface {
validate(metadata: Record<string, string>) {
const values = _values(metadata)
- return !_some(values, value => typeof value !== 'string')
+ return !_some(values, (value) => typeof value !== 'string')
}
}
diff --git a/backend/apps/cloud/src/analytics/dto/get-heartbeat-stats.ts b/backend/apps/cloud/src/analytics/dto/get-heartbeat-stats.ts
index da5513721..fa03a6881 100644
--- a/backend/apps/cloud/src/analytics/dto/get-heartbeat-stats.ts
+++ b/backend/apps/cloud/src/analytics/dto/get-heartbeat-stats.ts
@@ -5,13 +5,13 @@ import { ValidateProjectIds } from '../decorators/validate-project-ids.decorator
export class GetHeartbeatStatsDto {
@ApiProperty({ description: 'Array of project IDs', required: false })
- @ValidateIf(o => o.pids || !o.pid)
+ @ValidateIf((o) => o.pids || !o.pid)
@IsOptional()
@ValidateProjectIds()
pids?: string[]
@ApiProperty({ description: 'Single project ID', required: false })
- @ValidateIf(o => !o.pids || o.pid)
+ @ValidateIf((o) => !o.pids || o.pid)
@IsOptional()
@Matches(PID_REGEX, { message: 'The provided Project ID (pid) is incorrect' })
pid?: string
diff --git a/backend/apps/cloud/src/analytics/dto/get-overall-stats.dto.ts b/backend/apps/cloud/src/analytics/dto/get-overall-stats.dto.ts
index 92104b02d..d6730606c 100644
--- a/backend/apps/cloud/src/analytics/dto/get-overall-stats.dto.ts
+++ b/backend/apps/cloud/src/analytics/dto/get-overall-stats.dto.ts
@@ -14,13 +14,13 @@ import { ValidateProjectIds } from '../decorators/validate-project-ids.decorator
export class GetOverallStatsDto {
@ApiProperty({ description: 'Array of project IDs', required: false })
- @ValidateIf(o => o.pids || !o.pid)
+ @ValidateIf((o) => o.pids || !o.pid)
@IsOptional()
@ValidateProjectIds()
pids?: string[]
@ApiProperty({ description: 'Single project ID', required: false })
- @ValidateIf(o => !o.pids || o.pid)
+ @ValidateIf((o) => !o.pids || o.pid)
@IsOptional()
@Matches(PID_REGEX, { message: 'The provided Project ID (pid) is incorrect' })
pid?: string
diff --git a/backend/apps/cloud/src/analytics/dto/patch-status.dto.ts b/backend/apps/cloud/src/analytics/dto/patch-status.dto.ts
index 44a8dc921..94c0984fa 100644
--- a/backend/apps/cloud/src/analytics/dto/patch-status.dto.ts
+++ b/backend/apps/cloud/src/analytics/dto/patch-status.dto.ts
@@ -25,7 +25,7 @@ export class PatchStatusDto {
example: 'c138c2b1826d9fec65d230e471ab2c25',
description: 'Error id',
})
- @ValidateIf(o => !o.eids || o.eid)
+ @ValidateIf((o) => !o.eids || o.eid)
@IsNotEmpty()
@IsString()
eid: string
@@ -37,7 +37,7 @@ export class PatchStatusDto {
],
description: 'Error id list',
})
- @ValidateIf(o => o.eids || !o.eid)
+ @ValidateIf((o) => o.eids || !o.eid)
@IsNotEmpty()
@IsArray()
@IsString({ each: true })
diff --git a/backend/apps/cloud/src/analytics/utils/referrers.map.ts b/backend/apps/cloud/src/analytics/utils/referrers.map.ts
index d77afd773..ac8d4b40b 100644
--- a/backend/apps/cloud/src/analytics/utils/referrers.map.ts
+++ b/backend/apps/cloud/src/analytics/utils/referrers.map.ts
@@ -31,7 +31,7 @@ const loadMap = (): ReferrerJson[] => {
export const getDomainsForRefName = (name: string): string[] | null => {
const list = loadMap()
- const found = list.find(g => g.name.toLowerCase() === name.toLowerCase())
+ const found = list.find((g) => g.name.toLowerCase() === name.toLowerCase())
if (!found) return null
return found.patterns
}
diff --git a/backend/apps/cloud/src/auth/auth.service.ts b/backend/apps/cloud/src/auth/auth.service.ts
index 3aeffdd13..ac395c0cd 100644
--- a/backend/apps/cloud/src/auth/auth.service.ts
+++ b/backend/apps/cloud/src/auth/auth.service.ts
@@ -92,7 +92,7 @@ export class AuthService {
}
private async createSha1Hash(text: string): Promise<string> {
- return new Promise(resolve => {
+ return new Promise((resolve) => {
const sha1sum = createHash('sha1')
.update(text)
.digest('hex')
@@ -130,7 +130,7 @@ export class AuthService {
const needle = `${lastChars}:`
return String(response.data)
.split('\n')
- .some(line => line.startsWith(needle))
+ .some((line) => line.startsWith(needle))
} catch (error) {
console.error(
`[ERROR][AuthService -> checkIfLeaked]: ${error} (prefix ${firstFiveChars})`,
@@ -159,9 +159,7 @@ export class AuthService {
})
}
- const verificationLink = `${this.configService.get('CLIENT_URL')}/verify/${
- actionToken.id
- }`
+ const verificationLink = `${this.configService.get('CLIENT_URL')}/verify/${actionToken.id}`
await this.mailerService.sendEmail(email, LetterTemplate.SignUp, {
url: verificationLink,
@@ -947,7 +945,7 @@ export class AuthService {
throw new BadRequestException('No email address found')
}
- email = _find(emails, e => e.primary).email
+ email = _find(emails, (e) => e.primary).email
} catch (reason) {
console.error(
`[ERROR][AuthService -> processGithubCode -> axios.get (emails)]: ${reason}`,
diff --git a/backend/apps/cloud/src/blog/blog.service.ts b/backend/apps/cloud/src/blog/blog.service.ts
index 8537d722e..ec2834483 100644
--- a/backend/apps/cloud/src/blog/blog.service.ts
+++ b/backend/apps/cloud/src/blog/blog.service.ts
@@ -26,7 +26,7 @@ const getSlugFromFilename = (filename: string) => filename.substring(11)
const getDateFromFilename = (filename: string) => filename.substring(0, 10)
const findFilenameBySlug = (list: string[], handle: string) => {
- return _find(list, item => _endsWith(item, `-${handle}.md`))
+ return _find(list, (item) => _endsWith(item, `-${handle}.md`))
}
interface IParseFontMatter {
@@ -76,8 +76,8 @@ const getFileNames = async (category?: string): Promise<string[]> => {
const dirents = await fs.readdir(pathToRead, { withFileTypes: true })
return _map(
- _filter(dirents, d => d.isFile() && _endsWith(d.name, '.md')),
- d => d.name,
+ _filter(dirents, (d) => d.isFile() && _endsWith(d.name, '.md')),
+ (d) => d.name,
)
} catch {
return []
@@ -127,12 +127,12 @@ const getArticlesMetaData = async () => {
withFileTypes: true,
})
const filtered = _map(
- _filter(dirents, d => d.isFile() && _endsWith(d.name, '.md')),
- d => d.name,
+ _filter(dirents, (d) => d.isFile() && _endsWith(d.name, '.md')),
+ (d) => d.name,
)
const articles = await Promise.all(
- _map(filtered, async filename => {
+ _map(filtered, async (filename) => {
try {
const file = await fs.readFile(resolveBlogPostsPath(filename))
const { attributes }: IParseFontMatter = parseFrontMatter(
@@ -155,7 +155,7 @@ const getArticlesMetaData = async () => {
)
return _sortBy(
- _filter(articles, a => !!a),
+ _filter(articles, (a) => !!a),
['_date'],
).reverse()
} catch {
@@ -224,14 +224,14 @@ export class BlogService {
return []
}
- const directories = _filter(dirents, d => d.isDirectory())
+ const directories = _filter(dirents, (d) => d.isDirectory())
const markdownFiles = _filter(
dirents,
- d => d.isFile() && _endsWith(d.name, '.md'),
+ (d) => d.isFile() && _endsWith(d.name, '.md'),
)
const processedFiles = await Promise.all(
- _map(markdownFiles, async filename => {
+ _map(markdownFiles, async (filename) => {
const actualFilename = filename.name ?? filename
const slug = _replace(actualFilename, /\.md$/, '')
diff --git a/backend/apps/cloud/src/common/templates/en/2fa-turned-off.html b/backend/apps/cloud/src/common/templates/en/2fa-turned-off.html
index 24e81f6d9..87b751855 100644
--- a/backend/apps/cloud/src/common/templates/en/2fa-turned-off.html
+++ b/backend/apps/cloud/src/common/templates/en/2fa-turned-off.html
@@ -1,3 +1,5 @@
-This is an email to let you know the 2FA (two-factor authentication) has been turned off for your Swetrix account.
-<br/>
-If you have not done so, please reply to this email so we could assist you in securing your account.
+This is an email to let you know the 2FA (two-factor authentication) has been
+turned off for your Swetrix account.
+<br />
+If you have not done so, please reply to this email so we could assist you in
+securing your account.
diff --git a/backend/apps/cloud/src/common/templates/en/2fa-turned-on.html b/backend/apps/cloud/src/common/templates/en/2fa-turned-on.html
index 92bb10508..0eec49f6e 100644
--- a/backend/apps/cloud/src/common/templates/en/2fa-turned-on.html
+++ b/backend/apps/cloud/src/common/templates/en/2fa-turned-on.html
@@ -1,3 +1,5 @@
-This is an email to let you know the 2FA (two-factor authentication) has been turned on for your Swetrix account.
-<br/>
-If you have not done so, please reply to this email so we could assist you in securing your account.
+This is an email to let you know the 2FA (two-factor authentication) has been
+turned on for your Swetrix account.
+<br />
+If you have not done so, please reply to this email so we could assist you in
+securing your account.
diff --git a/backend/apps/cloud/src/common/templates/en/customer_project-invitation.html b/backend/apps/cloud/src/common/templates/en/customer_project-invitation.html
index 6b78b7d5d..cc4b63f15 100644
--- a/backend/apps/cloud/src/common/templates/en/customer_project-invitation.html
+++ b/backend/apps/cloud/src/common/templates/en/customer_project-invitation.html
@@ -1,11 +1,14 @@
-<a href="mailto:{{email}}">{{email}}</a> has invited you to the {{name}} website analytics dashboard with the role {{role}} on Swetrix.
-<br/>
-Click the button below to accept the invitation or ignore this email if you do not want to join the project.
-<br/>
-The invitation will expire in {{expiration}} hours.
-<br/>
-<a href="{{url}}" target="_blank">Accept invitation</a>
-<br/>
-If you are having trouble with the button above, copy and paste the URL below directly into your web browser:
-<br/>
-{{url}}
+<a href="mailto:{{email}}">{{email}}</a> has invited you to the {{name}} website
+analytics dashboard with the role {{role}} on Swetrix.
+<br />
+Click the button below to accept the invitation or ignore this email if you do
+not want to join the project.
+<br />
+The invitation will expire in {{expiration}} hours.
+<br />
+<a href="{{url}}" target="_blank">Accept invitation</a>
+<br />
+If you are having trouble with the button above, copy and paste the URL below
+directly into your web browser:
+<br />
+{{url}}
diff --git a/backend/apps/cloud/src/common/templates/en/customer_sign-up.html b/backend/apps/cloud/src/common/templates/en/customer_sign-up.html
index 23054afa4..62eb0694c 100644
--- a/backend/apps/cloud/src/common/templates/en/customer_sign-up.html
+++ b/backend/apps/cloud/src/common/templates/en/customer_sign-up.html
@@ -1,6 +1,9 @@
-Hello and welcome to Swetrix! We're excited to have you with us.<br/>
-Swetrix is an ethical and powerful web analytics platform that respects your privacy and data.<br/><br/>
-To get started, please <a href="{{url}}">click here</a> verify your email address.<br/><br/>
-If you’re having trouble with the link above, copy and paste the URL below directly into your web browser:<br/>
-{{url}}<br/><br/>
-If you did not request this email, feel free to ignore it :)
+Hello and welcome to Swetrix! We're excited to have you with us.<br />
+Swetrix is an ethical and powerful web analytics platform that respects your
+privacy and data.<br /><br />
+To get started, please <a href="{{url}}">click here</a> verify your email
+address.<br /><br />
+If you’re having trouble with the link above, copy and paste the URL below
+directly into your web browser:<br />
+{{url}}<br /><br />
+If you did not request this email, feel free to ignore it :)
diff --git a/backend/apps/cloud/src/common/templates/en/dashboard-locked-exceeding-limits.html b/backend/apps/cloud/src/common/templates/en/dashboard-locked-exceeding-limits.html
index 7f71ae68f..60efbed4c 100644
--- a/backend/apps/cloud/src/common/templates/en/dashboard-locked-exceeding-limits.html
+++ b/backend/apps/cloud/src/common/templates/en/dashboard-locked-exceeding-limits.html
@@ -1,14 +1,20 @@
-Hi! A week ago we contacted you regarding your website traffic exceeding your Swetrix subscription{{#if hitPercentageLimit}} by over {{percentageLimit}}% this month{{else}} for two consecutive months{{/if}}.
+Hi! A week ago we contacted you regarding your website traffic exceeding your
+Swetrix subscription{{#if hitPercentageLimit}} by over {{percentageLimit}}% this
+month{{else}} for two consecutive months{{/if}}. <br /><br />
+Your subscription is still active, we're still counting your stats and we
+haven't deleted any of your data, but as you've outgrown your subscription tier,
+we'd like to ask you to upgrade to a tier that reflects your new traffic
+volumes. Once you have upgraded to an appropriate tier, your dashboard access
+will be restored immediately. A detailed usage report can be found on the
+<a href="{{billingUrl}}" target="_blank">billing page</a>. <br /><br />
+{{#ifEquals user.planCode "10m"}} Your usage exceeds our standard plans, so
+please reply to this email to receive a tailored offering and resolve this
+issue.
<br /><br />
-Your subscription is still active, we're still counting your stats and we haven't deleted any of your data, but as you've outgrown your subscription tier, we'd like to ask you to upgrade to a tier that reflects your new traffic volumes. Once you have upgraded to an appropriate tier, your dashboard access will be restored immediately. A detailed usage report can be found on the <a href="{{billingUrl}}" target="_blank">billing page</a>.
+Thank you again for using Swetrix. {{/ifEquals}} {{#ifNotEquals user.planCode
+"10m"}} We recommend that you upgrade to the {{suggestedPlanLimit}} events per
+month plan to keep up with your usage. The cost of the plan will be prorated to
+reflect the amount you have already paid for your current subscription plan.
<br /><br />
-{{#ifEquals user.planCode "10m"}}
-Your usage exceeds our standard plans, so please reply to this email to receive a tailored offering and resolve this issue.
-<br /><br />
-Thank you again for using Swetrix.
-{{/ifEquals}}
-{{#ifNotEquals user.planCode "10m"}}
-We recommend that you upgrade to the {{suggestedPlanLimit}} events per month plan to keep up with your usage. The cost of the plan will be prorated to reflect the amount you have already paid for your current subscription plan.
-<br /><br />
-Thank you for using Swetrix, please reply to this email if you have any questions or need help with anything.
-{{/ifNotEquals}}
+Thank you for using Swetrix, please reply to this email if you have any
+questions or need help with anything. {{/ifNotEquals}}
diff --git a/backend/apps/cloud/src/common/templates/en/dashboard-locked-payment-failure.html b/backend/apps/cloud/src/common/templates/en/dashboard-locked-payment-failure.html
index 5849bf23e..0df7c54e4 100644
--- a/backend/apps/cloud/src/common/templates/en/dashboard-locked-payment-failure.html
+++ b/backend/apps/cloud/src/common/templates/en/dashboard-locked-payment-failure.html
@@ -1,3 +1,9 @@
-There was a problem with your last Swetrix subscription payment. We're still counting your stats and we haven't deleted any of your data, but due to the payment issue we've had to temporarily lock your analytics dashboard. Once you have updated your payment information, your dashboard access will be restored immediately. Please visit the <a href="{{billingUrl}}" target="_blank">billing page</a> for more details.
+There was a problem with your last Swetrix subscription payment. We're still
+counting your stats and we haven't deleted any of your data, but due to the
+payment issue we've had to temporarily lock your analytics dashboard. Once you
+have updated your payment information, your dashboard access will be restored
+immediately. Please visit the
+<a href="{{billingUrl}}" target="_blank">billing page</a> for more details.
<br /><br />
-Thank you for being a Swetrix subscriber, please reply to this email if you have any questions or need help with anything.
+Thank you for being a Swetrix subscriber, please reply to this email if you have
+any questions or need help with anything.
diff --git a/backend/apps/cloud/src/common/templates/en/mailaddress-change_confirmation.html b/backend/apps/cloud/src/common/templates/en/mailaddress-change_confirmation.html
index e7cc219f6..c7ae05b0f 100644
--- a/backend/apps/cloud/src/common/templates/en/mailaddress-change_confirmation.html
+++ b/backend/apps/cloud/src/common/templates/en/mailaddress-change_confirmation.html
@@ -1,9 +1,11 @@
You have requested a change of your email address at swetrix.com
-<br/>
-The new email will only be applied after you have confirmed this action by clicking the link below.
-<br/>
-<br/>
+<br />
+The new email will only be applied after you have confirmed this action by
+clicking the link below.
+<br />
+<br />
<a href="{{url}}" target="_blank">Confirm email update.</a>
-<br/>
-<br/>
-If you have not changed your email, please ignore this email or reply to it so we could assist you in securing your account.
+<br />
+<br />
+If you have not changed your email, please ignore this email or reply to it so
+we could assist you in securing your account.
diff --git a/backend/apps/cloud/src/common/templates/en/mailaddress-change_information.html b/backend/apps/cloud/src/common/templates/en/mailaddress-change_information.html
index 821075dad..a66e910e0 100644
--- a/backend/apps/cloud/src/common/templates/en/mailaddress-change_information.html
+++ b/backend/apps/cloud/src/common/templates/en/mailaddress-change_information.html
@@ -1,4 +1,5 @@
Your email address at swetrix.com has been updated.
-<br/>
-<br/>
-If you have not done so, please reply to this email so we could assist you in securing your account.
+<br />
+<br />
+If you have not done so, please reply to this email so we could assist you in
+securing your account.
diff --git a/backend/apps/cloud/src/common/templates/en/organisation-invitation.html b/backend/apps/cloud/src/common/templates/en/organisation-invitation.html
index f928c8f7c..72ed4830e 100644
--- a/backend/apps/cloud/src/common/templates/en/organisation-invitation.html
+++ b/backend/apps/cloud/src/common/templates/en/organisation-invitation.html
@@ -1,11 +1,14 @@
-<a href="mailto:{{email}}">{{email}}</a> has invited you to join the {{name}} organisation with the role {{role}} on Swetrix.
-<br/>
-Click the button below to accept the invitation or ignore this email if you do not want to join the organisation.
-<br/>
+<a href="mailto:{{email}}">{{email}}</a> has invited you to join the {{name}}
+organisation with the role {{role}} on Swetrix.
+<br />
+Click the button below to accept the invitation or ignore this email if you do
+not want to join the organisation.
+<br />
The invitation will expire in {{expiration}} hours.
-<br/>
+<br />
<a href="{{url}}" target="_blank">Accept invitation</a>
-<br/>
-If you are having trouble with the button above, copy and paste the URL below directly into your web browser:
-<br/>
-{{url}}
\ No newline at end of file
+<br />
+If you are having trouble with the button above, copy and paste the URL below
+directly into your web browser:
+<br />
+{{url}}
diff --git a/backend/apps/cloud/src/common/templates/en/password-change_confirmation.html b/backend/apps/cloud/src/common/templates/en/password-change_confirmation.html
index ed7a440e3..49a3d609d 100644
--- a/backend/apps/cloud/src/common/templates/en/password-change_confirmation.html
+++ b/backend/apps/cloud/src/common/templates/en/password-change_confirmation.html
@@ -1,7 +1,9 @@
You have changed your password at swetrix.com
-<br/>
-The new password will only be applied after you have confirmed this action by clicking the link below.
+<br />
+The new password will only be applied after you have confirmed this action by
+clicking the link below.
<a href="{{url}}" target="_blank">Confirm password change</a>
-<br/>
-<br/>
-If you have not changed your password, please ignore this email or reply to it so we could assist you in securing your account.
+<br />
+<br />
+If you have not changed your password, please ignore this email or reply to it
+so we could assist you in securing your account.
diff --git a/backend/apps/cloud/src/common/templates/en/password-change_information.html b/backend/apps/cloud/src/common/templates/en/password-change_information.html
index c1a62d489..b33d5c1a6 100644
--- a/backend/apps/cloud/src/common/templates/en/password-change_information.html
+++ b/backend/apps/cloud/src/common/templates/en/password-change_information.html
@@ -1,4 +1,5 @@
Your password at swetrix.com has been changed.
-<br/>
-<br/>
-If you have not done so, please reply to this email so we could assist you in securing your account.
+<br />
+<br />
+If you have not done so, please reply to this email so we could assist you in
+securing your account.
diff --git a/backend/apps/cloud/src/common/templates/en/project-report.html b/backend/apps/cloud/src/common/templates/en/project-report.html
index 45203d5bb..02bd123f2 100644
--- a/backend/apps/cloud/src/common/templates/en/project-report.html
+++ b/backend/apps/cloud/src/common/templates/en/project-report.html
@@ -1,371 +1,829 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
+ <head>
+ <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
+ <title>
+ Swetrix {{#ifEquals type "w"}}Weekly{{/ifEquals}}{{#ifEquals type
+ "M"}}Monthly{{/ifEquals}}{{#ifEquals type "Q"}}Quarterly{{/ifEquals}}
+ Project Report
+ </title>
+ </head>
-<head>
- <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
- <title>Swetrix {{#ifEquals type "w"}}Weekly{{/ifEquals}}{{#ifEquals type "M"}}Monthly{{/ifEquals}}{{#ifEquals type
- "Q"}}Quarterly{{/ifEquals}} Project Report</title>
-</head>
-
-<body style="margin: 0; padding: 0; background-color: #f0f4f7;">
- <table cellpadding="0" cellspacing="0" border="0" width="100%"
- style="background: #f0f4f7; min-width: 340px; font-size: 1px; line-height: normal;">
- <tr>
- <td align="center" valign="top" bgcolor="#f0f4f7">
- <!--[if (gte mso 9)|(IE)]>
+ <body style="margin: 0; padding: 0; background-color: #f0f4f7">
+ <table
+ cellpadding="0"
+ cellspacing="0"
+ border="0"
+ width="100%"
+ style="
+ background: #f0f4f7;
+ min-width: 340px;
+ font-size: 1px;
+ line-height: normal;
+ "
+ >
+ <tr>
+ <td align="center" valign="top" bgcolor="#f0f4f7">
+ <!--[if (gte mso 9)|(IE)]>
<table border="0" cellspacing="0" cellpadding="0">
<tr><td align="center" valign="top" width="750"><![endif]-->
- <table cellpadding="0" cellspacing="0" border="0" width="750"
- style="width: 100%; max-width: 750px; min-width: 340px; background: #f0f4f7;">
- <tr>
- <td width="25" style="width: 25px; max-width: 25px; min-width: 25px;">&nbsp;</td>
- <td align="center" valign="top" style="background: #ffffff;">
- <table cellpadding="0" cellspacing="0" border="0" width="100%"
- style="width: 100% !important; min-width: 100%; max-width: 100%; background: #f0f4f7;">
- <tr>
- <td align="right" valign="top">
- <div style="height: 25px; line-height: 25px; font-size: 23px;">&nbsp;</div>
- </td>
- </tr>
- </table>
- <table cellpadding="0" cellspacing="0" border="0" width="88%"
- style="width: 88% !important; min-width: 88%; max-width: 88%;">
- <tr>
- <td align="center" valign="top">
- <div style="height: 40px; line-height: 40px; font-size: 38px;">&nbsp;</div>
- <a href="https://swetrix.com" target="_blank"
- style="display: block; max-width: 173px;text-decoration: none;">
- <img src="https://swetrix.com/assets/logo_blue.png" alt="Swetrix" width="175" border="0"
- style="display: block; width: 175px; font-size: 32px;" />
- </a>
- <div style="height: 40px; line-height: 40px; font-size: 40px;">&nbsp;</div>
- </td>
- </tr>
- </table>
- <table cellpadding="0" cellspacing="0" border="0" width="88%"
- style="width: 88% !important; min-width: 88%; max-width: 88%;">
- <tr>
- <td align="center" valign="top">
- <font align="center"
- style="font-size: 52px; line-height: 55px; font-weight: 300; letter-spacing: -1.5px;">
- <span align="center"
- style="font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen', 'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue', sans-serif; font-size: 38px; color: #1a1a1a; font-weight: 600;">
- Your {{#ifEquals type "w"}}Weekly{{/ifEquals}}{{#ifEquals type
- "M"}}Monthly{{/ifEquals}}{{#ifEquals type "Q"}}Quarterly{{/ifEquals}} Report
- </span>
- </font>
- <div style="height: 8px; line-height: 8px; font-size: 6px;">&nbsp;</div>
- <font style="font-size: 36px; line-height: 45px; font-weight: 300; letter-spacing: -1px;">
- <span style="
- font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen', 'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue', sans-serif;
- color: #5e5e5e;
- font-size: 18px;
- line-height: 28px;
- font-weight: 400;
- ">
- {{date}}
- </span>
- </font>
- <div style="height: 30px; line-height: 30px; font-size: 28px;">&nbsp;</div>
+ <table
+ cellpadding="0"
+ cellspacing="0"
+ border="0"
+ width="750"
+ style="
+ width: 100%;
+ max-width: 750px;
+ min-width: 340px;
+ background: #f0f4f7;
+ "
+ >
+ <tr>
+ <td
+ width="25"
+ style="width: 25px; max-width: 25px; min-width: 25px"
+ >
+ &nbsp;
+ </td>
+ <td align="center" valign="top" style="background: #ffffff">
+ <table
+ cellpadding="0"
+ cellspacing="0"
+ border="0"
+ width="100%"
+ style="
+ width: 100% !important;
+ min-width: 100%;
+ max-width: 100%;
+ background: #f0f4f7;
+ "
+ >
+ <tr>
+ <td align="right" valign="top">
+ <div
+ style="height: 25px; line-height: 25px; font-size: 23px"
+ >
+ &nbsp;
+ </div>
+ </td>
+ </tr>
+ </table>
+ <table
+ cellpadding="0"
+ cellspacing="0"
+ border="0"
+ width="88%"
+ style="width: 88% !important; min-width: 88%; max-width: 88%"
+ >
+ <tr>
+ <td align="center" valign="top">
+ <div
+ style="height: 40px; line-height: 40px; font-size: 38px"
+ >
+ &nbsp;
+ </div>
+ <a
+ href="https://swetrix.com"
+ target="_blank"
+ style="
+ display: block;
+ max-width: 173px;
+ text-decoration: none;
+ "
+ >
+ <img
+ src="https://swetrix.com/assets/logo_blue.png"
+ alt="Swetrix"
+ width="175"
+ border="0"
+ style="display: block; width: 175px; font-size: 32px"
+ />
+ </a>
+ <div
+ style="height: 40px; line-height: 40px; font-size: 40px"
+ >
+ &nbsp;
+ </div>
+ </td>
+ </tr>
+ </table>
+ <table
+ cellpadding="0"
+ cellspacing="0"
+ border="0"
+ width="88%"
+ style="width: 88% !important; min-width: 88%; max-width: 88%"
+ >
+ <tr>
+ <td align="center" valign="top">
+ <font
+ align="center"
+ style="
+ font-size: 52px;
+ line-height: 55px;
+ font-weight: 300;
+ letter-spacing: -1.5px;
+ "
+ >
+ <span
+ align="center"
+ style="
+ font-family:
+ -apple-system, BlinkMacSystemFont, 'Segoe UI',
+ 'Roboto', 'Oxygen', 'Ubuntu', 'Cantarell',
+ 'Fira Sans', 'Droid Sans', 'Helvetica Neue',
+ sans-serif;
+ font-size: 38px;
+ color: #1a1a1a;
+ font-weight: 600;
+ "
+ >
+ Your {{#ifEquals type
+ "w"}}Weekly{{/ifEquals}}{{#ifEquals type
+ "M"}}Monthly{{/ifEquals}}{{#ifEquals type
+ "Q"}}Quarterly{{/ifEquals}} Report
+ </span>
+ </font>
+ <div
+ style="height: 8px; line-height: 8px; font-size: 6px"
+ >
+ &nbsp;
+ </div>
+ <font
+ style="
+ font-size: 36px;
+ line-height: 45px;
+ font-weight: 300;
+ letter-spacing: -1px;
+ "
+ >
+ <span
+ style="
+ font-family:
+ -apple-system, BlinkMacSystemFont, 'Segoe UI',
+ 'Roboto', 'Oxygen', 'Ubuntu', 'Cantarell',
+ 'Fira Sans', 'Droid Sans', 'Helvetica Neue',
+ sans-serif;
+ color: #5e5e5e;
+ font-size: 18px;
+ line-height: 28px;
+ font-weight: 400;
+ "
+ >
+ {{date}}
+ </span>
+ </font>
+ <div
+ style="height: 30px; line-height: 30px; font-size: 28px"
+ >
+ &nbsp;
+ </div>
- {{#each projects}}
- <!-- Project Card -->
- <table cellpadding="0" cellspacing="0" border="0" width="100%"
- style="background: #f8fafc; border-radius: 12px; margin-bottom: 24px; border: 1px solid #e2e8f0;">
- <tr>
- <td style="padding: 24px;">
- <!-- Project Name -->
- <table cellpadding="0" cellspacing="0" border="0" width="100%">
- <tr>
- <td>
- <span style="
- font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen', 'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue', sans-serif;
- font-size: 22px;
- font-weight: 600;
- color: #1e293b;
- ">{{name}}</span>
- {{#if topCountry}}
- <span style="
- font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen', 'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue', sans-serif;
- font-size: 14px;
- color: #64748b;
- margin-left: 8px;
- ">Top country: {{topCountry}}</span>
- {{/if}}
- </td>
- </tr>
- </table>
- <div style="height: 20px; line-height: 20px; font-size: 18px;">&nbsp;</div>
+ {{#each projects}}
+ <!-- Project Card -->
+ <table
+ cellpadding="0"
+ cellspacing="0"
+ border="0"
+ width="100%"
+ style="
+ background: #f8fafc;
+ border-radius: 12px;
+ margin-bottom: 24px;
+ border: 1px solid #e2e8f0;
+ "
+ >
+ <tr>
+ <td style="padding: 24px">
+ <!-- Project Name -->
+ <table
+ cellpadding="0"
+ cellspacing="0"
+ border="0"
+ width="100%"
+ >
+ <tr>
+ <td>
+ <span
+ style="
+ font-family:
+ -apple-system, BlinkMacSystemFont,
+ 'Segoe UI', 'Roboto', 'Oxygen',
+ 'Ubuntu', 'Cantarell', 'Fira Sans',
+ 'Droid Sans', 'Helvetica Neue',
+ sans-serif;
+ font-size: 22px;
+ font-weight: 600;
+ color: #1e293b;
+ "
+ >{{name}}</span
+ >
+ {{#if topCountry}}
+ <span
+ style="
+ font-family:
+ -apple-system, BlinkMacSystemFont,
+ 'Segoe UI', 'Roboto', 'Oxygen',
+ 'Ubuntu', 'Cantarell', 'Fira Sans',
+ 'Droid Sans', 'Helvetica Neue',
+ sans-serif;
+ font-size: 14px;
+ color: #64748b;
+ margin-left: 8px;
+ "
+ >Top country: {{topCountry}}</span
+ >
+ {{/if}}
+ </td>
+ </tr>
+ </table>
+ <div
+ style="
+ height: 20px;
+ line-height: 20px;
+ font-size: 18px;
+ "
+ >
+ &nbsp;
+ </div>
- <!-- Primary Metrics Grid -->
- <table cellpadding="0" cellspacing="0" border="0" width="100%">
- <tr>
- <!-- Active Users -->
- <td width="33%" valign="top" style="padding-right: 12px;">
- <table cellpadding="0" cellspacing="0" border="0" width="100%"
- style="background: #ffffff; border-radius: 8px; border: 1px solid #e2e8f0;">
- <tr>
- <td style="padding: 16px;">
- <span style="
- font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen', 'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue', sans-serif;
- font-size: 12px;
- font-weight: 500;
- color: #64748b;
- text-transform: uppercase;
- letter-spacing: 0.5px;
- ">Active Users</span>
- <div style="height: 8px; line-height: 8px; font-size: 6px;">&nbsp;</div>
- <span style="
- font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen', 'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue', sans-serif;
- font-size: 28px;
- font-weight: 700;
- color: #0f172a;
- ">{{data.activeUsers}}</span>
- <span style="
+ <!-- Primary Metrics Grid -->
+ <table
+ cellpadding="0"
+ cellspacing="0"
+ border="0"
+ width="100%"
+ >
+ <tr>
+ <!-- Active Users -->
+ <td
+ width="33%"
+ valign="top"
+ style="padding-right: 12px"
+ >
+ <table
+ cellpadding="0"
+ cellspacing="0"
+ border="0"
+ width="100%"
+ style="
+ background: #ffffff;
+ border-radius: 8px;
+ border: 1px solid #e2e8f0;
+ "
+ >
+ <tr>
+ <td style="padding: 16px">
+ <span
+ style="
+ font-family:
+ -apple-system, BlinkMacSystemFont,
+ 'Segoe UI', 'Roboto', 'Oxygen',
+ 'Ubuntu', 'Cantarell',
+ 'Fira Sans', 'Droid Sans',
+ 'Helvetica Neue', sans-serif;
+ font-size: 12px;
+ font-weight: 500;
+ color: #64748b;
+ text-transform: uppercase;
+ letter-spacing: 0.5px;
+ "
+ >Active Users</span
+ >
+ <div
+ style="
+ height: 8px;
+ line-height: 8px;
+ font-size: 6px;
+ "
+ >
+ &nbsp;
+ </div>
+ <span
+ style="
+ font-family:
+ -apple-system, BlinkMacSystemFont,
+ 'Segoe UI', 'Roboto', 'Oxygen',
+ 'Ubuntu', 'Cantarell',
+ 'Fira Sans', 'Droid Sans',
+ 'Helvetica Neue', sans-serif;
+ font-size: 28px;
+ font-weight: 700;
+ color: #0f172a;
+ "
+ >{{data.activeUsers}}</span
+ >
+ <span
+ style="
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen', 'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue', sans-serif;
font-size: 14px;
font-weight: 500;
margin-left: 6px;
{{#greater data.percChangeUsers 0}}color: #059669;{{else}}{{#less data.percChangeUsers 0}}color: #DC2626;{{else}}color: #64748b;{{/less}}{{/greater}}
- ">{{#greater data.percChangeUsers 0}}+{{/greater}}{{data.percChangeUsers}}%</span>
- </td>
- </tr>
- </table>
- </td>
- <!-- Unique Visitors -->
- <td width="33%" valign="top" style="padding-right: 12px;">
- <table cellpadding="0" cellspacing="0" border="0" width="100%"
- style="background: #ffffff; border-radius: 8px; border: 1px solid #e2e8f0;">
- <tr>
- <td style="padding: 16px;">
- <span style="
- font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen', 'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue', sans-serif;
- font-size: 12px;
- font-weight: 500;
- color: #64748b;
- text-transform: uppercase;
- letter-spacing: 0.5px;
- ">Unique Visitors</span>
- <div style="height: 8px; line-height: 8px; font-size: 6px;">&nbsp;</div>
- <span style="
- font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen', 'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue', sans-serif;
- font-size: 28px;
- font-weight: 700;
- color: #0f172a;
- ">{{data.uniqueVisitors}}</span>
- <span style="
+ "
+ >{{#greater data.percChangeUsers
+ 0}}+{{/greater}}{{data.percChangeUsers}}%</span
+ >
+ </td>
+ </tr>
+ </table>
+ </td>
+ <!-- Unique Visitors -->
+ <td
+ width="33%"
+ valign="top"
+ style="padding-right: 12px"
+ >
+ <table
+ cellpadding="0"
+ cellspacing="0"
+ border="0"
+ width="100%"
+ style="
+ background: #ffffff;
+ border-radius: 8px;
+ border: 1px solid #e2e8f0;
+ "
+ >
+ <tr>
+ <td style="padding: 16px">
+ <span
+ style="
+ font-family:
+ -apple-system, BlinkMacSystemFont,
+ 'Segoe UI', 'Roboto', 'Oxygen',
+ 'Ubuntu', 'Cantarell',
+ 'Fira Sans', 'Droid Sans',
+ 'Helvetica Neue', sans-serif;
+ font-size: 12px;
+ font-weight: 500;
+ color: #64748b;
+ text-transform: uppercase;
+ letter-spacing: 0.5px;
+ "
+ >Unique Visitors</span
+ >
+ <div
+ style="
+ height: 8px;
+ line-height: 8px;
+ font-size: 6px;
+ "
+ >
+ &nbsp;
+ </div>
+ <span
+ style="
+ font-family:
+ -apple-system, BlinkMacSystemFont,
+ 'Segoe UI', 'Roboto', 'Oxygen',
+ 'Ubuntu', 'Cantarell',
+ 'Fira Sans', 'Droid Sans',
+ 'Helvetica Neue', sans-serif;
+ font-size: 28px;
+ font-weight: 700;
+ color: #0f172a;
+ "
+ >{{data.uniqueVisitors}}</span
+ >
+ <span
+ style="
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen', 'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue', sans-serif;
font-size: 14px;
font-weight: 500;
margin-left: 6px;
{{#greater data.percChangeUnique 0}}color: #059669;{{else}}{{#less data.percChangeUnique 0}}color: #DC2626;{{else}}color: #64748b;{{/less}}{{/greater}}
- ">{{#greater data.percChangeUnique 0}}+{{/greater}}{{data.percChangeUnique}}%</span>
- </td>
- </tr>
- </table>
- </td>
- <!-- Pageviews -->
- <td width="33%" valign="top">
- <table cellpadding="0" cellspacing="0" border="0" width="100%"
- style="background: #ffffff; border-radius: 8px; border: 1px solid #e2e8f0;">
- <tr>
- <td style="padding: 16px;">
- <span style="
- font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen', 'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue', sans-serif;
- font-size: 12px;
- font-weight: 500;
- color: #64748b;
- text-transform: uppercase;
- letter-spacing: 0.5px;
- ">Pageviews</span>
- <div style="height: 8px; line-height: 8px; font-size: 6px;">&nbsp;</div>
- <span style="
- font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen', 'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue', sans-serif;
- font-size: 28px;
- font-weight: 700;
- color: #0f172a;
- ">{{data.pageviews}}</span>
- <span style="
+ "
+ >{{#greater data.percChangeUnique
+ 0}}+{{/greater}}{{data.percChangeUnique}}%</span
+ >
+ </td>
+ </tr>
+ </table>
+ </td>
+ <!-- Pageviews -->
+ <td width="33%" valign="top">
+ <table
+ cellpadding="0"
+ cellspacing="0"
+ border="0"
+ width="100%"
+ style="
+ background: #ffffff;
+ border-radius: 8px;
+ border: 1px solid #e2e8f0;
+ "
+ >
+ <tr>
+ <td style="padding: 16px">
+ <span
+ style="
+ font-family:
+ -apple-system, BlinkMacSystemFont,
+ 'Segoe UI', 'Roboto', 'Oxygen',
+ 'Ubuntu', 'Cantarell',
+ 'Fira Sans', 'Droid Sans',
+ 'Helvetica Neue', sans-serif;
+ font-size: 12px;
+ font-weight: 500;
+ color: #64748b;
+ text-transform: uppercase;
+ letter-spacing: 0.5px;
+ "
+ >Pageviews</span
+ >
+ <div
+ style="
+ height: 8px;
+ line-height: 8px;
+ font-size: 6px;
+ "
+ >
+ &nbsp;
+ </div>
+ <span
+ style="
+ font-family:
+ -apple-system, BlinkMacSystemFont,
+ 'Segoe UI', 'Roboto', 'Oxygen',
+ 'Ubuntu', 'Cantarell',
+ 'Fira Sans', 'Droid Sans',
+ 'Helvetica Neue', sans-serif;
+ font-size: 28px;
+ font-weight: 700;
+ color: #0f172a;
+ "
+ >{{data.pageviews}}</span
+ >
+ <span
+ style="
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen', 'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue', sans-serif;
font-size: 14px;
font-weight: 500;
margin-left: 6px;
{{#greater data.percChangePageviews 0}}color: #059669;{{else}}{{#less data.percChangePageviews 0}}color: #DC2626;{{else}}color: #64748b;{{/less}}{{/greater}}
- ">{{#greater data.percChangePageviews 0}}+{{/greater}}{{data.percChangePageviews}}%</span>
- </td>
- </tr>
- </table>
- </td>
- </tr>
- </table>
+ "
+ >{{#greater data.percChangePageviews
+ 0}}+{{/greater}}{{data.percChangePageviews}}%</span
+ >
+ </td>
+ </tr>
+ </table>
+ </td>
+ </tr>
+ </table>
- <div style="height: 12px; line-height: 12px; font-size: 10px;">&nbsp;</div>
+ <div
+ style="
+ height: 12px;
+ line-height: 12px;
+ font-size: 10px;
+ "
+ >
+ &nbsp;
+ </div>
- <!-- Secondary Metrics -->
- <table cellpadding="0" cellspacing="0" border="0" width="100%">
- <tr>
- <!-- Avg. Session Duration -->
- <td width="50%" valign="top" style="padding-right: 12px;">
- <table cellpadding="0" cellspacing="0" border="0" width="100%"
- style="background: #ffffff; border-radius: 8px; border: 1px solid #e2e8f0;">
- <tr>
- <td style="padding: 14px 16px;">
- <span style="
- font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen', 'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue', sans-serif;
- font-size: 12px;
- font-weight: 500;
- color: #64748b;
- text-transform: uppercase;
- letter-spacing: 0.5px;
- ">Avg. Session</span>
- <span style="
- font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen', 'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue', sans-serif;
- font-size: 18px;
- font-weight: 600;
- color: #0f172a;
- float: right;
- ">{{data.avgDuration}}</span>
- </td>
- </tr>
- </table>
- </td>
- <!-- Bounce Rate -->
- <td width="50%" valign="top">
- <table cellpadding="0" cellspacing="0" border="0" width="100%"
- style="background: #ffffff; border-radius: 8px; border: 1px solid #e2e8f0;">
- <tr>
- <td style="padding: 14px 16px;">
- <span style="
- font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen', 'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue', sans-serif;
- font-size: 12px;
- font-weight: 500;
- color: #64748b;
- text-transform: uppercase;
- letter-spacing: 0.5px;
- ">Bounce Rate</span>
- <span style="
- font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen', 'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue', sans-serif;
- font-size: 18px;
- font-weight: 600;
- color: #0f172a;
- float: right;
- ">{{data.bounceRate}}%</span>
- </td>
- </tr>
- </table>
- </td>
- </tr>
- </table>
-
- {{#if goals}}
- <div style="height: 16px; line-height: 16px; font-size: 14px;">&nbsp;</div>
- <!-- Goals Section -->
- <table cellpadding="0" cellspacing="0" border="0" width="100%"
- style="background: #ecfdf5; border-radius: 8px; border: 1px solid #a7f3d0;">
- <tr>
- <td style="padding: 14px 16px;">
- <span style="
- font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen', 'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue', sans-serif;
- font-size: 12px;
- font-weight: 600;
- color: #059669;
- text-transform: uppercase;
- letter-spacing: 0.5px;
- ">Goal Conversions</span>
- <div style="height: 10px; line-height: 10px; font-size: 8px;">&nbsp;</div>
- {{#each goals}}
- <div style="
- font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen', 'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue', sans-serif;
- font-size: 14px;
- color: #065f46;
- margin-bottom: 4px;
- ">
- <strong>{{name}}:</strong> {{conversions}} conversions ({{conversionRate}}% rate)
- </div>
- {{/each}}
- </td>
- </tr>
- </table>
- {{/if}}
-
- {{#if errors}}
- <div style="height: 12px; line-height: 12px; font-size: 10px;">&nbsp;</div>
- <!-- Errors Section -->
- <table cellpadding="0" cellspacing="0" border="0" width="100%"
- style="background: #fef2f2; border-radius: 8px; border: 1px solid #fecaca;">
- <tr>
- <td style="padding: 14px 16px;">
- <span style="
- font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen', 'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue', sans-serif;
- font-size: 12px;
- font-weight: 600;
- color: #dc2626;
- text-transform: uppercase;
- letter-spacing: 0.5px;
- ">Errors Detected</span>
- <span style="
- font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen', 'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue', sans-serif;
- font-size: 14px;
- color: #991b1b;
- float: right;
- ">{{errors.count}} total ({{errors.uniqueErrors}} unique)</span>
- </td>
- </tr>
- </table>
- {{/if}}
- </td>
- </tr>
- </table>
- {{/each}}
+ <!-- Secondary Metrics -->
+ <table
+ cellpadding="0"
+ cellspacing="0"
+ border="0"
+ width="100%"
+ >
+ <tr>
+ <!-- Avg. Session Duration -->
+ <td
+ width="50%"
+ valign="top"
+ style="padding-right: 12px"
+ >
+ <table
+ cellpadding="0"
+ cellspacing="0"
+ border="0"
+ width="100%"
+ style="
+ background: #ffffff;
+ border-radius: 8px;
+ border: 1px solid #e2e8f0;
+ "
+ >
+ <tr>
+ <td style="padding: 14px 16px">
+ <span
+ style="
+ font-family:
+ -apple-system, BlinkMacSystemFont,
+ 'Segoe UI', 'Roboto', 'Oxygen',
+ 'Ubuntu', 'Cantarell',
+ 'Fira Sans', 'Droid Sans',
+ 'Helvetica Neue', sans-serif;
+ font-size: 12px;
+ font-weight: 500;
+ color: #64748b;
+ text-transform: uppercase;
+ letter-spacing: 0.5px;
+ "
+ >Avg. Session</span
+ >
+ <span
+ style="
+ font-family:
+ -apple-system, BlinkMacSystemFont,
+ 'Segoe UI', 'Roboto', 'Oxygen',
+ 'Ubuntu', 'Cantarell',
+ 'Fira Sans', 'Droid Sans',
+ 'Helvetica Neue', sans-serif;
+ font-size: 18px;
+ font-weight: 600;
+ color: #0f172a;
+ float: right;
+ "
+ >{{data.avgDuration}}</span
+ >
+ </td>
+ </tr>
+ </table>
+ </td>
+ <!-- Bounce Rate -->
+ <td width="50%" valign="top">
+ <table
+ cellpadding="0"
+ cellspacing="0"
+ border="0"
+ width="100%"
+ style="
+ background: #ffffff;
+ border-radius: 8px;
+ border: 1px solid #e2e8f0;
+ "
+ >
+ <tr>
+ <td style="padding: 14px 16px">
+ <span
+ style="
+ font-family:
+ -apple-system, BlinkMacSystemFont,
+ 'Segoe UI', 'Roboto', 'Oxygen',
+ 'Ubuntu', 'Cantarell',
+ 'Fira Sans', 'Droid Sans',
+ 'Helvetica Neue', sans-serif;
+ font-size: 12px;
+ font-weight: 500;
+ color: #64748b;
+ text-transform: uppercase;
+ letter-spacing: 0.5px;
+ "
+ >Bounce Rate</span
+ >
+ <span
+ style="
+ font-family:
+ -apple-system, BlinkMacSystemFont,
+ 'Segoe UI', 'Roboto', 'Oxygen',
+ 'Ubuntu', 'Cantarell',
+ 'Fira Sans', 'Droid Sans',
+ 'Helvetica Neue', sans-serif;
+ font-size: 18px;
+ font-weight: 600;
+ color: #0f172a;
+ float: right;
+ "
+ >{{data.bounceRate}}%</span
+ >
+ </td>
+ </tr>
+ </table>
+ </td>
+ </tr>
+ </table>
- <!-- Tip Section -->
- <table cellpadding="0" cellspacing="0" border="0" width="100%"
- style="background: #fffbeb; border-radius: 8px; border: 1px solid #fde68a; margin-top: 8px;">
- <tr>
- <td style="padding: 16px;">
- <span style="
- font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen', 'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue', sans-serif;
- font-size: 14px;
- color: #92400e;
- line-height: 1.6;
- ">
- <span style="font-size: 16px;">💡</span> <strong>Tip:</strong> {{tip}}
- </span>
- </td>
- </tr>
- </table>
+ {{#if goals}}
+ <div
+ style="
+ height: 16px;
+ line-height: 16px;
+ font-size: 14px;
+ "
+ >
+ &nbsp;
+ </div>
+ <!-- Goals Section -->
+ <table
+ cellpadding="0"
+ cellspacing="0"
+ border="0"
+ width="100%"
+ style="
+ background: #ecfdf5;
+ border-radius: 8px;
+ border: 1px solid #a7f3d0;
+ "
+ >
+ <tr>
+ <td style="padding: 14px 16px">
+ <span
+ style="
+ font-family:
+ -apple-system, BlinkMacSystemFont,
+ 'Segoe UI', 'Roboto', 'Oxygen',
+ 'Ubuntu', 'Cantarell', 'Fira Sans',
+ 'Droid Sans', 'Helvetica Neue',
+ sans-serif;
+ font-size: 12px;
+ font-weight: 600;
+ color: #059669;
+ text-transform: uppercase;
+ letter-spacing: 0.5px;
+ "
+ >Goal Conversions</span
+ >
+ <div
+ style="
+ height: 10px;
+ line-height: 10px;
+ font-size: 8px;
+ "
+ >
+ &nbsp;
+ </div>
+ {{#each goals}}
+ <div
+ style="
+ font-family:
+ -apple-system, BlinkMacSystemFont,
+ 'Segoe UI', 'Roboto', 'Oxygen',
+ 'Ubuntu', 'Cantarell', 'Fira Sans',
+ 'Droid Sans', 'Helvetica Neue',
+ sans-serif;
+ font-size: 14px;
+ color: #065f46;
+ margin-bottom: 4px;
+ "
+ >
+ <strong>{{name}}:</strong> {{conversions}}
+ conversions ({{conversionRate}}% rate)
+ </div>
+ {{/each}}
+ </td>
+ </tr>
+ </table>
+ {{/if}} {{#if errors}}
+ <div
+ style="
+ height: 12px;
+ line-height: 12px;
+ font-size: 10px;
+ "
+ >
+ &nbsp;
+ </div>
+ <!-- Errors Section -->
+ <table
+ cellpadding="0"
+ cellspacing="0"
+ border="0"
+ width="100%"
+ style="
+ background: #fef2f2;
+ border-radius: 8px;
+ border: 1px solid #fecaca;
+ "
+ >
+ <tr>
+ <td style="padding: 14px 16px">
+ <span
+ style="
+ font-family:
+ -apple-system, BlinkMacSystemFont,
+ 'Segoe UI', 'Roboto', 'Oxygen',
+ 'Ubuntu', 'Cantarell', 'Fira Sans',
+ 'Droid Sans', 'Helvetica Neue',
+ sans-serif;
+ font-size: 12px;
+ font-weight: 600;
+ color: #dc2626;
+ text-transform: uppercase;
+ letter-spacing: 0.5px;
+ "
+ >Errors Detected</span
+ >
+ <span
+ style="
+ font-family:
+ -apple-system, BlinkMacSystemFont,
+ 'Segoe UI', 'Roboto', 'Oxygen',
+ 'Ubuntu', 'Cantarell', 'Fira Sans',
+ 'Droid Sans', 'Helvetica Neue',
+ sans-serif;
+ font-size: 14px;
+ color: #991b1b;
+ float: right;
+ "
+ >{{errors.count}} total
+ ({{errors.uniqueErrors}} unique)</span
+ >
+ </td>
+ </tr>
+ </table>
+ {{/if}}
+ </td>
+ </tr>
+ </table>
+ {{/each}}
- <div style="height: 24px; line-height: 24px; font-size: 22px;">&nbsp;</div>
+ <!-- Tip Section -->
+ <table
+ cellpadding="0"
+ cellspacing="0"
+ border="0"
+ width="100%"
+ style="
+ background: #fffbeb;
+ border-radius: 8px;
+ border: 1px solid #fde68a;
+ margin-top: 8px;
+ "
+ >
+ <tr>
+ <td style="padding: 16px">
+ <span
+ style="
+ font-family:
+ -apple-system, BlinkMacSystemFont, 'Segoe UI',
+ 'Roboto', 'Oxygen', 'Ubuntu', 'Cantarell',
+ 'Fira Sans', 'Droid Sans', 'Helvetica Neue',
+ sans-serif;
+ font-size: 14px;
+ color: #92400e;
+ line-height: 1.6;
+ "
+ >
+ <span style="font-size: 16px">💡</span>
+ <strong>Tip:</strong> {{tip}}
+ </span>
+ </td>
+ </tr>
+ </table>
- <!-- Unsubscribe -->
- <table cellpadding="0" cellspacing="0" border="0" width="100%">
- <tr>
- <td align="center" style="padding-bottom: 24px;">
- <span style="
- font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen', 'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue', sans-serif;
- font-size: 13px;
- color: #94a3b8;
- ">
- Don't want these emails? <a href="{{unsubscribeUrl}}" target="_blank"
- style="color: #64748b; text-decoration: underline;">Unsubscribe</a>
- </span>
- </td>
- </tr>
- </table>
+ <div
+ style="height: 24px; line-height: 24px; font-size: 22px"
+ >
+ &nbsp;
+ </div>
- </td>
- </tr>
- </table>
- </td>
- <td width="25" style="width: 25px; max-width: 25px; min-width: 25px;">&nbsp;</td>
- </tr>
- </table>
- <!--[if (gte mso 9)|(IE)]>
+ <!-- Unsubscribe -->
+ <table
+ cellpadding="0"
+ cellspacing="0"
+ border="0"
+ width="100%"
+ >
+ <tr>
+ <td align="center" style="padding-bottom: 24px">
+ <span
+ style="
+ font-family:
+ -apple-system, BlinkMacSystemFont, 'Segoe UI',
+ 'Roboto', 'Oxygen', 'Ubuntu', 'Cantarell',
+ 'Fira Sans', 'Droid Sans', 'Helvetica Neue',
+ sans-serif;
+ font-size: 13px;
+ color: #94a3b8;
+ "
+ >
+ Don't want these emails?
+ <a
+ href="{{unsubscribeUrl}}"
+ target="_blank"
+ style="
+ color: #64748b;
+ text-decoration: underline;
+ "
+ >Unsubscribe</a
+ >
+ </span>
+ </td>
+ </tr>
+ </table>
+ </td>
+ </tr>
+ </table>
+ </td>
+ <td
+ width="25"
+ style="width: 25px; max-width: 25px; min-width: 25px"
+ >
+ &nbsp;
+ </td>
+ </tr>
+ </table>
+ <!--[if (gte mso 9)|(IE)]>
</td></tr>
</table><![endif]-->
- </td>
- </tr>
- </table>
-</body>
-
+ </td>
+ </tr>
+ </table>
+ </body>
</html>
diff --git a/backend/apps/cloud/src/common/templates/en/project-subscriber-invitation.html b/backend/apps/cloud/src/common/templates/en/project-subscriber-invitation.html
index 01cf865a0..0ea20a039 100644
--- a/backend/apps/cloud/src/common/templates/en/project-subscriber-invitation.html
+++ b/backend/apps/cloud/src/common/templates/en/project-subscriber-invitation.html
@@ -1,6 +1,8 @@
-A Swetrix user has invited you to join the {{projectName}} website analytics reports email subscription.
-<br/>
-<br/>
-Click the button below to accept the invitation or ignore this email if you do not want to receive updates from this project.
-<br/>
+A Swetrix user has invited you to join the {{projectName}} website analytics
+reports email subscription.
+<br />
+<br />
+Click the button below to accept the invitation or ignore this email if you do
+not want to receive updates from this project.
+<br />
<a href="{{url}}" target="_blank">Accept invitation</a>
diff --git a/backend/apps/cloud/src/common/templates/en/project-transfer.html b/backend/apps/cloud/src/common/templates/en/project-transfer.html
index e451c151c..e0d961eae 100644
--- a/backend/apps/cloud/src/common/templates/en/project-transfer.html
+++ b/backend/apps/cloud/src/common/templates/en/project-transfer.html
@@ -1,13 +1,17 @@
A Swetrix user wants to transfer of the {{name}} project to your account.
-<br/>
-If you accept the invitation, this project well be transferred to your account and the previous owner will be added as an administator (you will be able to edit project admins and viewers in the project settings).
<br />
-<a href="{{confirmUrl}}" target="_blank">Accept transfer</a> | <a href="{{cancelUrl}}" target="_blank">Decline transfer</a>
-<br /><br />
-If you are having trouble with the button above, copy and paste the URL below directly into your web browser to accept transfer:
+If you accept the invitation, this project well be transferred to your account
+and the previous owner will be added as an administator (you will be able to
+edit project admins and viewers in the project settings).
+<br />
+<a href="{{confirmUrl}}" target="_blank">Accept transfer</a> |
+<a href="{{cancelUrl}}" target="_blank">Decline transfer</a> <br /><br />
+If you are having trouble with the button above, copy and paste the URL below
+directly into your web browser to accept transfer:
<br />
{{confirmUrl}}
<br /><br />
-Or copy and paste the URL below directly into your web browser to decline transfer:
-<br/>
+Or copy and paste the URL below directly into your web browser to decline
+transfer:
+<br />
{{cancelUrl}}
diff --git a/backend/apps/cloud/src/common/templates/en/subscription-cancelled.html b/backend/apps/cloud/src/common/templates/en/subscription-cancelled.html
index 04b41aa9e..bc8c8c88d 100644
--- a/backend/apps/cloud/src/common/templates/en/subscription-cancelled.html
+++ b/backend/apps/cloud/src/common/templates/en/subscription-cancelled.html
@@ -1 +1,5 @@
-Hi, we've noticed that you've cancelled your Swetrix subscription. We'd like to get your feedback on why you decided to cancel and if there's anything we can do to improve our service. We are funded entirely by our subscribers and we'd really appreciate your feedback! Please feel free to reply to this email and thank you for your time :)
+Hi, we've noticed that you've cancelled your Swetrix subscription. We'd like to
+get your feedback on why you decided to cancel and if there's anything we can do
+to improve our service. We are funded entirely by our subscribers and we'd
+really appreciate your feedback! Please feel free to reply to this email and
+thank you for your time :)
diff --git a/backend/apps/cloud/src/common/templates/en/tier-warning.html b/backend/apps/cloud/src/common/templates/en/tier-warning.html
index 868078241..dd140315c 100644
--- a/backend/apps/cloud/src/common/templates/en/tier-warning.html
+++ b/backend/apps/cloud/src/common/templates/en/tier-warning.html
@@ -1,13 +1,16 @@
First of all, thank you for using Swetrix!
-<br/>
-You have used more than {{amount}}% of the available events per your tier for this month, that's a lot of traffic, congratulations!
-<br/>
-That means that in case you use 100% of the available events until the end of the month, all the subsequent traffic will not be saved.
-<br/>
+<br />
+You have used more than {{amount}}% of the available events per your tier for
+this month, that's a lot of traffic, congratulations!
+<br />
+That means that in case you use 100% of the available events until the end of
+the month, all the subsequent traffic will not be saved.
+<br />
To avoid this we recommend that you upgrade your tier on the Billing page.
-<br/>
-<br/>
+<br />
+<br />
<a href="{{url}}" target="_blank">Upgrade</a>
-<br/>
-<br/>
-Please reply back to this email in case you have any questions or need assistance.
+<br />
+<br />
+Please reply back to this email in case you have any questions or need
+assistance.
diff --git a/backend/apps/cloud/src/common/templates/en/trial-ends-tomorrow.html b/backend/apps/cloud/src/common/templates/en/trial-ends-tomorrow.html
index 2782b35cc..771e806d5 100644
--- a/backend/apps/cloud/src/common/templates/en/trial-ends-tomorrow.html
+++ b/backend/apps/cloud/src/common/templates/en/trial-ends-tomorrow.html
@@ -1,6 +1,12 @@
-Your free Swetrix trial ends tomorrow, we hope that you enjoyed using Swetrix and liked the experience of using a service that respects user privacy, does not annoy your users with cookie banners and keeps your website as fast as possible :)
-<br/>
-If you wish to continue using Swetrix and receiving all the needed analytics data easily, you'll need to <a href="{{url}}" target="_blank">upgrade</a> your account to one of our subscription plans.
-<br/>
-<br/>
-Please reply back to this email in case you have any questions or need assistance.
+Your free Swetrix trial ends tomorrow, we hope that you enjoyed using Swetrix
+and liked the experience of using a service that respects user privacy, does not
+annoy your users with cookie banners and keeps your website as fast as possible
+:)
+<br />
+If you wish to continue using Swetrix and receiving all the needed analytics
+data easily, you'll need to <a href="{{url}}" target="_blank">upgrade</a> your
+account to one of our subscription plans.
+<br />
+<br />
+Please reply back to this email in case you have any questions or need
+assistance.
diff --git a/backend/apps/cloud/src/common/templates/en/trial-expired.html b/backend/apps/cloud/src/common/templates/en/trial-expired.html
index 13d3a6ffa..b905c94e9 100644
--- a/backend/apps/cloud/src/common/templates/en/trial-expired.html
+++ b/backend/apps/cloud/src/common/templates/en/trial-expired.html
@@ -1,7 +1,10 @@
-Your free Swetrix trial has ended, we hope you have enjoyed using Swetrix so far!
-<br/><br/>
-Please upgrade your account to one of our subscription tiers to continue receiving analytics insights about your website while respecting your users' privacy.
-<br/><br/>
+Your free Swetrix trial has ended, we hope you have enjoyed using Swetrix so
+far! <br /><br />
+Please upgrade your account to one of our subscription tiers to continue
+receiving analytics insights about your website while respecting your users'
+privacy.
+<br /><br />
<a href="{{url}}" target="_blank">Upgrade</a>
-<br/><br/>
-Please reply back to this email in case you have any questions or need assistance.
+<br /><br />
+Please reply back to this email in case you have any questions or need
+assistance.
diff --git a/backend/apps/cloud/src/common/templates/en/usage-over-limit.html b/backend/apps/cloud/src/common/templates/en/usage-over-limit.html
index a6f4ae098..b4d7020f4 100644
--- a/backend/apps/cloud/src/common/templates/en/usage-over-limit.html
+++ b/backend/apps/cloud/src/common/templates/en/usage-over-limit.html
@@ -1,23 +1,34 @@
-Hi! First of all, thanks a lot for {{#ifEquals user.planCode "trial"}}giving Swetrix a try!{{/ifEquals}}{{#ifNotEquals user.planCode "trial"}}being a Swetrix subscriber.{{/ifNotEquals}}
+Hi! First of all, thanks a lot for {{#ifEquals user.planCode "trial"}}giving
+Swetrix a try!{{/ifEquals}}{{#ifNotEquals user.planCode "trial"}}being a Swetrix
+subscriber.{{/ifNotEquals}} <br /><br />
+We'd like to inform you that your traffic has exceeded your subscription
+plan{{#if hitPercentageLimit}} by over {{percentageLimit}}% this month{{else}}
+for two consecutive months{{/if}}.
<br /><br />
-We'd like to inform you that your traffic has exceeded your subscription plan{{#if hitPercentageLimit}} by over {{percentageLimit}}% this month{{else}} for two consecutive months{{/if}}.
+In order to continue using Swetrix and have access to your stats, we kindly ask
+you to upgrade your subscription plan to reflect your usage. If you don't take
+action to upgrade your account to a new plan within the next
+{{upgradePeriodDays}} days, access to your stats will be temporarily blocked
+(please note that we will not stop collecting data, just block your account
+until the issue is resolved).
<br /><br />
-In order to continue using Swetrix and have access to your stats, we kindly ask you to upgrade your subscription plan to reflect your usage. If you don't take action to upgrade your account to a new plan within the next {{upgradePeriodDays}} days, access to your stats will be temporarily blocked (please note that we will not stop collecting data, just block your account until the issue is resolved).
+{{#if hitPercentageLimit}} This month you have used {{thisMonthUsage}} billable
+events, which exceeds your plan limit by more than {{percentageLimit}}%.
+{{else}} This month you have used {{thisMonthUsage}} billable events, the month
+before that you used {{lastMonthUsage}} events. {{/if}} Billable events include
+pageviews, custom events and CAPTCHA events. A detailed usage report can be
+found on the <a href="{{billingUrl}}" target="_blank">billing page</a>.
<br /><br />
-{{#if hitPercentageLimit}}
-This month you have used {{thisMonthUsage}} billable events, which exceeds your plan limit by more than {{percentageLimit}}%.
-{{else}}
-This month you have used {{thisMonthUsage}} billable events, the month before that you used {{lastMonthUsage}} events.
-{{/if}}
-Billable events include pageviews, custom events and CAPTCHA events. A detailed usage report can be found on the <a href="{{billingUrl}}" target="_blank">billing page</a>.
+{{#ifEquals user.planCode "10m"}} Your usage exceeds our standard plans, so
+please reply to this email to receive a tailored offering and resolve this
+issue.
<br /><br />
-{{#ifEquals user.planCode "10m"}}
-Your usage exceeds our standard plans, so please reply to this email to receive a tailored offering and resolve this issue.
+Thank you again for using Swetrix and sorry for the inconvenience. {{/ifEquals}}
+{{#ifNotEquals user.planCode "10m"}} We recommend that you upgrade to the
+{{suggestedPlanLimit}} events per month plan to keep up with your usage. The
+cost of the plan will be prorated to reflect the amount you have already paid
+for your current subscription plan.
<br /><br />
-Thank you again for using Swetrix and sorry for the inconvenience.
-{{/ifEquals}}
-{{#ifNotEquals user.planCode "10m"}}
-We recommend that you upgrade to the {{suggestedPlanLimit}} events per month plan to keep up with your usage. The cost of the plan will be prorated to reflect the amount you have already paid for your current subscription plan.
-<br /><br />
-Thank you again for using Swetrix and sorry for the inconvenience, please reply to this email if you have any questions or need help with anything.
+Thank you again for using Swetrix and sorry for the inconvenience, please reply
+to this email if you have any questions or need help with anything.
{{/ifNotEquals}}
diff --git a/backend/apps/cloud/src/experiment/bayesian.ts b/backend/apps/cloud/src/experiment/bayesian.ts
index a7e83931c..93e78b555 100644
--- a/backend/apps/cloud/src/experiment/bayesian.ts
+++ b/backend/apps/cloud/src/experiment/bayesian.ts
@@ -43,7 +43,7 @@ function seedFromVariants(
): number {
const normalized = [...variants]
.sort((a, b) => a.key.localeCompare(b.key))
- .map(v => `${v.key}:${v.exposures}:${v.conversions}`)
+ .map((v) => `${v.key}:${v.exposures}:${v.conversions}`)
.join('|')
return (fnv1a32(normalized) ^ (simulations >>> 0)) >>> 0
}
@@ -125,7 +125,7 @@ export function calculateBayesianProbabilities(
simulations = Math.max(1, Math.floor(simulations))
- const sanitizedVariants = variants.map(v => {
+ const sanitizedVariants = variants.map((v) => {
const exposures = Math.max(0, Math.floor(v.exposures))
const conversions = Math.min(
Math.max(0, Math.floor(v.conversions)),
@@ -144,7 +144,7 @@ export function calculateBayesianProbabilities(
)
if (totalExposures === 0) {
const prob = 1 / sanitizedVariants.length
- return new Map(sanitizedVariants.map(v => [v.key, prob]))
+ return new Map(sanitizedVariants.map((v) => [v.key, prob]))
}
const wins = new Map<string, number>()
diff --git a/backend/apps/cloud/src/experiment/entity/experiment-variant.entity.ts b/backend/apps/cloud/src/experiment/entity/experiment-variant.entity.ts
index c7ed0daa0..2c37f7c3f 100644
--- a/backend/apps/cloud/src/experiment/entity/experiment-variant.entity.ts
+++ b/backend/apps/cloud/src/experiment/entity/experiment-variant.entity.ts
@@ -35,7 +35,7 @@ export class ExperimentVariant {
isControl: boolean
@ApiProperty({ type: () => Experiment })
- @ManyToOne(() => Experiment, experiment => experiment.variants, {
+ @ManyToOne(() => Experiment, (experiment) => experiment.variants, {
onDelete: 'CASCADE',
})
@JoinColumn()
diff --git a/backend/apps/cloud/src/experiment/entity/experiment.entity.ts b/backend/apps/cloud/src/experiment/entity/experiment.entity.ts
index 35b919d64..81a218f71 100644
--- a/backend/apps/cloud/src/experiment/entity/experiment.entity.ts
+++ b/backend/apps/cloud/src/experiment/entity/experiment.entity.ts
@@ -107,7 +107,7 @@ export class Experiment {
endedAt: Date | null
@ApiProperty({ type: () => Project })
- @ManyToOne(() => Project, project => project.experiments)
+ @ManyToOne(() => Project, (project) => project.experiments)
@JoinColumn()
project: Project
@@ -122,7 +122,7 @@ export class Experiment {
goal: Goal | null
@ApiProperty({ type: () => [ExperimentVariant] })
- @OneToMany(() => ExperimentVariant, variant => variant.experiment, {
+ @OneToMany(() => ExperimentVariant, (variant) => variant.experiment, {
cascade: true,
})
variants: ExperimentVariant[]
diff --git a/backend/apps/cloud/src/experiment/experiment.controller.ts b/backend/apps/cloud/src/experiment/experiment.controller.ts
index 1a133344b..735534a36 100644
--- a/backend/apps/cloud/src/experiment/experiment.controller.ts
+++ b/backend/apps/cloud/src/experiment/experiment.controller.ts
@@ -124,7 +124,7 @@ export class ExperimentController {
const mappedResults: ExperimentDto[] = _map(
result.results,
- experiment =>
+ (experiment) =>
({
..._omit(experiment, ['project', 'goal', 'featureFlag']),
pid: projectId,
@@ -244,7 +244,7 @@ export class ExperimentController {
)
}
- const controlVariants = experimentDto.variants.filter(v => v.isControl)
+ const controlVariants = experimentDto.variants.filter((v) => v.isControl)
if (controlVariants.length !== 1) {
throw new BadRequestException(
'An experiment must have exactly one control variant',
@@ -252,7 +252,7 @@ export class ExperimentController {
}
const totalPercentage = _sum(
- experimentDto.variants.map(v => v.rolloutPercentage),
+ experimentDto.variants.map((v) => v.rolloutPercentage),
)
if (totalPercentage !== 100) {
throw new BadRequestException(
@@ -324,7 +324,7 @@ export class ExperimentController {
experiment.featureFlagKey = experimentDto.featureFlagKey || null
experiment.featureFlag = existingFeatureFlag
- experiment.variants = experimentDto.variants.map(v => {
+ experiment.variants = experimentDto.variants.map((v) => {
const variant = new ExperimentVariant()
variant.name = v.name
variant.key = v.key
@@ -335,7 +335,7 @@ export class ExperimentController {
})
const newExperiment = await this.dataSource.transaction(
- async transactionalEntityManager => {
+ async (transactionalEntityManager) => {
const createdExperiment = await this.experimentService.create(
experiment,
transactionalEntityManager,
@@ -428,7 +428,7 @@ export class ExperimentController {
}
}
- await this.dataSource.transaction(async transactionalEntityManager => {
+ await this.dataSource.transaction(async (transactionalEntityManager) => {
if (experimentDto.variants) {
if (experimentDto.variants.length < 2) {
throw new BadRequestException(
@@ -436,7 +436,9 @@ export class ExperimentController {
)
}
- const controlVariants = experimentDto.variants.filter(v => v.isControl)
+ const controlVariants = experimentDto.variants.filter(
+ (v) => v.isControl,
+ )
if (controlVariants.length !== 1) {
throw new BadRequestException(
'An experiment must have exactly one control variant',
@@ -444,7 +446,7 @@ export class ExperimentController {
}
const totalPercentage = _sum(
- experimentDto.variants.map(v => v.rolloutPercentage),
+ experimentDto.variants.map((v) => v.rolloutPercentage),
)
if (totalPercentage !== 100) {
throw new BadRequestException(
@@ -533,7 +535,7 @@ export class ExperimentController {
featureFlag,
}
- Object.keys(updatePayload).forEach(key => {
+ Object.keys(updatePayload).forEach((key) => {
if (updatePayload[key] === undefined) {
delete updatePayload[key]
}
@@ -651,7 +653,7 @@ export class ExperimentController {
}
try {
- await this.dataSource.transaction(async transactionalEntityManager => {
+ await this.dataSource.transaction(async (transactionalEntityManager) => {
let featureFlag = experiment.featureFlag
if (!featureFlag) {
if (experiment.featureFlagMode === FeatureFlagMode.CREATE) {
@@ -928,7 +930,7 @@ export class ExperimentController {
try {
const result = await clickhouse
.query({ query: exposuresQuery, query_params: exposuresParams })
- .then(resultSet =>
+ .then((resultSet) =>
resultSet.json<{ variantKey: string; exposures: number }>(),
)
exposuresData = result.data
@@ -997,7 +999,7 @@ export class ExperimentController {
try {
const result = await clickhouse
.query({ query: conversionsQuery, query_params: conversionsParams })
- .then(resultSet =>
+ .then((resultSet) =>
resultSet.json<{ variantKey: string; conversions: number }>(),
)
conversionsData = result.data
@@ -1007,13 +1009,13 @@ export class ExperimentController {
}
const exposuresMap = new Map(
- exposuresData.map(e => [e.variantKey, Number(e.exposures)]),
+ exposuresData.map((e) => [e.variantKey, Number(e.exposures)]),
)
const conversionsMap = new Map(
- conversionsData.map(c => [c.variantKey, Number(c.conversions)]),
+ conversionsData.map((c) => [c.variantKey, Number(c.conversions)]),
)
- const controlVariant = experiment.variants.find(v => v.isControl)
+ const controlVariant = experiment.variants.find((v) => v.isControl)
const controlExposures = controlVariant
? exposuresMap.get(controlVariant.key) || 0
: 0
@@ -1023,7 +1025,7 @@ export class ExperimentController {
const controlRate =
controlExposures > 0 ? controlConversions / controlExposures : 0
- const variantData = experiment.variants.map(v => ({
+ const variantData = experiment.variants.map((v) => ({
key: v.key,
exposures: exposuresMap.get(v.key) || 0,
conversions: conversionsMap.get(v.key) || 0,
@@ -1031,7 +1033,7 @@ export class ExperimentController {
const probabilities = calculateBayesianProbabilities(variantData)
- const variantResults: VariantResultDto[] = experiment.variants.map(v => {
+ const variantResults: VariantResultDto[] = experiment.variants.map((v) => {
const exposures = exposuresMap.get(v.key) || 0
const conversions = conversionsMap.get(v.key) || 0
const conversionRate = exposures > 0 ? conversions / exposures : 0
@@ -1058,8 +1060,8 @@ export class ExperimentController {
}
})
- const totalExposures = _sum(variantResults.map(v => v.exposures))
- const totalConversions = _sum(variantResults.map(v => v.conversions))
+ const totalExposures = _sum(variantResults.map((v) => v.exposures))
+ const totalConversions = _sum(variantResults.map((v) => v.conversions))
let highestProbVariant: VariantResultDto | null = null
let hasWinner = false
@@ -1168,7 +1170,7 @@ export class ExperimentController {
try {
const result = await clickhouse
.query({ query: exposuresQuery, query_params: queryParams })
- .then(resultSet => resultSet.json())
+ .then((resultSet) => resultSet.json())
exposuresData = result.data as any[]
} catch (err) {
this.logger.warn({ err }, 'Failed to get time-bucketed exposures')
@@ -1241,14 +1243,14 @@ export class ExperimentController {
query: conversionsQuery,
query_params: { ...queryParams, goalValue, ...metaParams },
})
- .then(resultSet => resultSet.json())
+ .then((resultSet) => resultSet.json())
conversionsData = result.data as any[]
} catch (err) {
this.logger.warn({ err }, 'Failed to get time-bucketed conversions')
}
}
- const variantKeys = experiment.variants.map(v => v.key)
+ const variantKeys = experiment.variants.map((v) => v.key)
const winProbability: Record<string, number[]> = {}
for (const key of variantKeys) {
@@ -1302,7 +1304,7 @@ export class ExperimentController {
}
}
- const variantData = variantKeys.map(key => ({
+ const variantData = variantKeys.map((key) => ({
key,
exposures: cumulativeExposures[key],
conversions: cumulativeConversions[key],
diff --git a/backend/apps/cloud/src/experiment/experiment.service.ts b/backend/apps/cloud/src/experiment/experiment.service.ts
index 6e269d168..523317ab7 100644
--- a/backend/apps/cloud/src/experiment/experiment.service.ts
+++ b/backend/apps/cloud/src/experiment/experiment.service.ts
@@ -152,7 +152,7 @@ export class ExperimentService {
experiment: { id: experiment.id },
})
- const variants = variantsData.map(v => {
+ const variants = variantsData.map((v) => {
const variant = new ExperimentVariant()
variant.name = v.name
variant.key = v.key
diff --git a/backend/apps/cloud/src/feature-flag/entity/feature-flag.entity.ts b/backend/apps/cloud/src/feature-flag/entity/feature-flag.entity.ts
index 43aee23ea..f5926b994 100644
--- a/backend/apps/cloud/src/feature-flag/entity/feature-flag.entity.ts
+++ b/backend/apps/cloud/src/feature-flag/entity/feature-flag.entity.ts
@@ -53,7 +53,7 @@ export class FeatureFlag {
enabled: boolean
@ApiProperty({ type: () => Project })
- @ManyToOne(() => Project, project => project.featureFlags)
+ @ManyToOne(() => Project, (project) => project.featureFlags)
@JoinColumn()
project: Project
diff --git a/backend/apps/cloud/src/feature-flag/feature-flag.controller.ts b/backend/apps/cloud/src/feature-flag/feature-flag.controller.ts
index 39ccb93b5..229336136 100644
--- a/backend/apps/cloud/src/feature-flag/feature-flag.controller.ts
+++ b/backend/apps/cloud/src/feature-flag/feature-flag.controller.ts
@@ -114,7 +114,7 @@ export class FeatureFlagController {
)
// @ts-expect-error
- result.results = _map(result.results, flag => ({
+ result.results = _map(result.results, (flag) => ({
..._omit(flag, ['project']),
pid: projectId,
}))
@@ -335,13 +335,13 @@ export class FeatureFlagController {
// Determine experiment variants for flags linked to running experiments
const experimentVariants = new Map<string, string>()
const flagsWithExperiments = flags.filter(
- f => f.experimentId && evaluatedFlags[f.key],
+ (f) => f.experimentId && evaluatedFlags[f.key],
)
if (flagsWithExperiments.length > 0) {
// Get running experiments for these flags
const experiments = await this.experimentService.find({
- where: flagsWithExperiments.map(f => ({
+ where: flagsWithExperiments.map((f) => ({
id: f.experimentId,
status: ExperimentStatus.RUNNING,
})),
@@ -356,7 +356,7 @@ export class FeatureFlagController {
)
const variantKey = getExperimentVariant(
experiment.id,
- sortedVariants.map(v => ({
+ sortedVariants.map((v) => ({
key: v.key,
rolloutPercentage: v.rolloutPercentage,
})),
@@ -376,7 +376,7 @@ export class FeatureFlagController {
evaluatedFlags,
profileId,
experimentVariants,
- ).catch(err => {
+ ).catch((err) => {
this.logger.error({ err }, 'Failed to track flag evaluations')
})
@@ -406,7 +406,7 @@ export class FeatureFlagController {
const now = new Date().toISOString().slice(0, 19).replace('T', ' ')
- const values = flags.map(flag => ({
+ const values = flags.map((flag) => ({
pid,
flagId: flag.id,
flagKey: flag.key,
@@ -605,7 +605,7 @@ export class FeatureFlagController {
try {
const { data } = await clickhouse
.query({ query: statsQuery, query_params: queryParams })
- .then(resultSet =>
+ .then((resultSet) =>
resultSet.json<{
evaluations: number
profileCount: number
@@ -748,7 +748,7 @@ export class FeatureFlagController {
const [profilesResult, countResult] = await Promise.all([
clickhouse
.query({ query: profilesQuery, query_params: queryParams })
- .then(resultSet =>
+ .then((resultSet) =>
resultSet.json<{
profileId: string
lastEvaluated: string
@@ -758,10 +758,10 @@ export class FeatureFlagController {
),
clickhouse
.query({ query: countQuery, query_params: queryParams })
- .then(resultSet => resultSet.json<{ total: number }>()),
+ .then((resultSet) => resultSet.json<{ total: number }>()),
])
- const profiles = profilesResult.data.map(row => ({
+ const profiles = profilesResult.data.map((row) => ({
profileId: row.profileId,
isIdentified: row.profileId.startsWith('usr_'),
lastResult: row.lastResult === 1,
diff --git a/backend/apps/cloud/src/goal/entity/goal.entity.ts b/backend/apps/cloud/src/goal/entity/goal.entity.ts
index 342c8d21d..628178639 100644
--- a/backend/apps/cloud/src/goal/entity/goal.entity.ts
+++ b/backend/apps/cloud/src/goal/entity/goal.entity.ts
@@ -65,7 +65,7 @@ export class Goal {
active: boolean
@ApiProperty({ type: () => Project })
- @ManyToOne(() => Project, project => project.goals)
+ @ManyToOne(() => Project, (project) => project.goals)
@JoinColumn()
project: Project
diff --git a/backend/apps/cloud/src/goal/goal.controller.ts b/backend/apps/cloud/src/goal/goal.controller.ts
index 1230051c1..ea5f40e6c 100644
--- a/backend/apps/cloud/src/goal/goal.controller.ts
+++ b/backend/apps/cloud/src/goal/goal.controller.ts
@@ -150,7 +150,7 @@ export class GoalController {
)
// @ts-expect-error
- result.results = _map(result.results, goal => ({
+ result.results = _map(result.results, (goal) => ({
..._omit(goal, ['project']),
pid: goal.project.id,
}))
@@ -454,7 +454,7 @@ export class GoalController {
const { data: conversionsData } = await clickhouse
.query({ query: conversionsQuery, query_params: queryParams })
- .then(resultSet =>
+ .then((resultSet) =>
resultSet.json<{ conversions: number; uniqueSessions: number }>(),
)
@@ -479,7 +479,7 @@ export class GoalController {
groupTo: groupToUTC,
},
})
- .then(resultSet => resultSet.json<{ totalSessions: number }>())
+ .then((resultSet) => resultSet.json<{ totalSessions: number }>())
const totalSessions = totalData[0]?.totalSessions || 1
const conversionRate = _round((uniqueSessions / totalSessions) * 100, 2)
@@ -501,7 +501,7 @@ export class GoalController {
const { data: previousData } = await clickhouse
.query({ query: conversionsQuery, query_params: previousQueryParams })
- .then(resultSet =>
+ .then((resultSet) =>
resultSet.json<{ conversions: number; uniqueSessions: number }>(),
)
@@ -689,7 +689,7 @@ export class GoalController {
const { data } = await clickhouse
.query({ query: chartQuery, query_params: queryParams })
- .then(resultSet =>
+ .then((resultSet) =>
resultSet.json<{
year: number
month?: number
diff --git a/backend/apps/cloud/src/goal/goal.service.ts b/backend/apps/cloud/src/goal/goal.service.ts
index e5d9e317e..ea59c9f52 100644
--- a/backend/apps/cloud/src/goal/goal.service.ts
+++ b/backend/apps/cloud/src/goal/goal.service.ts
@@ -39,7 +39,7 @@ export class GoalService {
if (search && search.trim()) {
const searchPattern = `%${search.trim()}%`
// Use array of where conditions for OR with the base where conditions
- finalWhere = normalizedWhere.flatMap(condition => [
+ finalWhere = normalizedWhere.flatMap((condition) => [
{ ...condition, name: ILike(searchPattern) },
{ ...condition, value: ILike(searchPattern) },
])
diff --git a/backend/apps/cloud/src/integrations/telegram/scene/projects.scene.ts b/backend/apps/cloud/src/integrations/telegram/scene/projects.scene.ts
index e064c26d1..6fc7bd1c4 100644
--- a/backend/apps/cloud/src/integrations/telegram/scene/projects.scene.ts
+++ b/backend/apps/cloud/src/integrations/telegram/scene/projects.scene.ts
@@ -47,7 +47,7 @@ export class ProjectsScene {
await context.reply(
'Projects',
Markup.keyboard([
- ...projects.map(project => [project.name]),
+ ...projects.map((project) => [project.name]),
['🔙 Back'],
]).resize(),
)
@@ -106,10 +106,7 @@ export class ProjectsScene {
`\n` +
`Public: \`${project.public ? 'yes' : 'no'}\`` +
`\n` +
- `Created: \`${dayjs
- .utc(project.created)
- .tz(user.timezone)
- .format('YYYY-MM-DD HH:mm:ss')}\`` +
+ `Created: \`${dayjs.utc(project.created).tz(user.timezone).format('YYYY-MM-DD HH:mm:ss')}\`` +
`\n\n` +
`*Analytics (last 7 days)*` +
`\n` +
diff --git a/backend/apps/cloud/src/integrations/telegram/telegram.module.ts b/backend/apps/cloud/src/integrations/telegram/telegram.module.ts
index 0a5fb4487..1a471a11a 100644
--- a/backend/apps/cloud/src/integrations/telegram/telegram.module.ts
+++ b/backend/apps/cloud/src/integrations/telegram/telegram.module.ts
@@ -34,7 +34,7 @@ const shouldBotBeLaunched = isPrimaryNode() && isPrimaryClusterNode()
UserModule,
ProjectModule,
AnalyticsModule,
- ].filter(m => !!m),
+ ].filter((m) => !!m),
providers: [
TelegramUpdate,
StartScene,
diff --git a/backend/apps/cloud/src/og-image/og-image.service.ts b/backend/apps/cloud/src/og-image/og-image.service.ts
index bd68dea2a..b278b86fe 100644
--- a/backend/apps/cloud/src/og-image/og-image.service.ts
+++ b/backend/apps/cloud/src/og-image/og-image.service.ts
@@ -233,7 +233,7 @@ export class OgImageService implements OnModuleDestroy {
} catch (error) {
lastError = error
// Small backoff before retrying
- await new Promise(r => setTimeout(r, attempt * 500))
+ await new Promise((r) => setTimeout(r, attempt * 500))
}
}
throw lastError instanceof Error
@@ -280,7 +280,7 @@ export class OgImageService implements OnModuleDestroy {
try {
await page.setJavaScriptEnabled(false)
await page.setRequestInterception(true)
- page.on('request', req => {
+ page.on('request', (req) => {
const url = req.url()
// `setContent()` uses about:blank internally; the logo is a data: URL.
if (url === 'about:blank' || url.startsWith('data:')) {
@@ -298,7 +298,7 @@ export class OgImageService implements OnModuleDestroy {
return image
} catch (error) {
if (attempt === 2) throw error
- await new Promise(r => setTimeout(r, attempt * 250))
+ await new Promise((r) => setTimeout(r, attempt * 250))
} finally {
try {
await page.close()
diff --git a/backend/apps/cloud/src/organisation/entity/organisation-member.entity.ts b/backend/apps/cloud/src/organisation/entity/organisation-member.entity.ts
index a25b5aa0f..8f348a87b 100644
--- a/backend/apps/cloud/src/organisation/entity/organisation-member.entity.ts
+++ b/backend/apps/cloud/src/organisation/entity/organisation-member.entity.ts
@@ -22,10 +22,10 @@ export class OrganisationMember {
id: string
@ApiProperty({ type: () => User })
- @ManyToOne(() => User, user => user.organisationMemberships)
+ @ManyToOne(() => User, (user) => user.organisationMemberships)
user: User
- @ManyToOne(() => Organisation, org => org.members)
+ @ManyToOne(() => Organisation, (org) => org.members)
organisation: Organisation
@Column({
diff --git a/backend/apps/cloud/src/organisation/entity/organisation.entity.ts b/backend/apps/cloud/src/organisation/entity/organisation.entity.ts
index c0b7fa61a..cb4c9ef4d 100644
--- a/backend/apps/cloud/src/organisation/entity/organisation.entity.ts
+++ b/backend/apps/cloud/src/organisation/entity/organisation.entity.ts
@@ -17,10 +17,10 @@ export class Organisation {
@Column('varchar', { length: 50 })
name: string
- @OneToMany(() => OrganisationMember, member => member.organisation)
+ @OneToMany(() => OrganisationMember, (member) => member.organisation)
members: OrganisationMember[]
- @OneToMany(() => Project, project => project.organisation)
+ @OneToMany(() => Project, (project) => project.organisation)
projects: Project[]
@Column({ type: 'timestamp', default: () => 'CURRENT_TIMESTAMP' })
diff --git a/backend/apps/cloud/src/organisation/organisation.controller.ts b/backend/apps/cloud/src/organisation/organisation.controller.ts
index 92f279a1f..a32943b4f 100644
--- a/backend/apps/cloud/src/organisation/organisation.controller.ts
+++ b/backend/apps/cloud/src/organisation/organisation.controller.ts
@@ -216,7 +216,7 @@ export class OrganisationController {
// }
const isAlreadyMember = !_isEmpty(
- _find(organisation.members, member => member.user?.id === invitee.id),
+ _find(organisation.members, (member) => member.user?.id === invitee.id),
)
if (isAlreadyMember) {
diff --git a/backend/apps/cloud/src/organisation/organisation.service.ts b/backend/apps/cloud/src/organisation/organisation.service.ts
index a6d82b7a1..e105d20d7 100644
--- a/backend/apps/cloud/src/organisation/organisation.service.ts
+++ b/backend/apps/cloud/src/organisation/organisation.service.ts
@@ -108,7 +108,7 @@ export class OrganisationService {
validateManageAccess(organisation: Organisation, userId: string) {
const membership = _find(
organisation.members,
- member => member.user?.id === userId,
+ (member) => member.user?.id === userId,
)
if (!membership || membership.role === OrganisationRole.viewer) {
diff --git a/backend/apps/cloud/src/project/dto/project-password.dto.ts b/backend/apps/cloud/src/project/dto/project-password.dto.ts
index d49e2d58b..833870670 100644
--- a/backend/apps/cloud/src/project/dto/project-password.dto.ts
+++ b/backend/apps/cloud/src/project/dto/project-password.dto.ts
@@ -18,6 +18,6 @@ export class ProjectPasswordDto {
password?: string | null
@IsOptional()
- @ValidateIf(o => o.isPasswordProtected !== null)
+ @ValidateIf((o) => o.isPasswordProtected !== null)
isPasswordProtected?: boolean | null
}
diff --git a/backend/apps/cloud/src/project/dto/project.dto.ts b/backend/apps/cloud/src/project/dto/project.dto.ts
index 56dc64d0a..49b1b4a02 100644
--- a/backend/apps/cloud/src/project/dto/project.dto.ts
+++ b/backend/apps/cloud/src/project/dto/project.dto.ts
@@ -83,7 +83,7 @@ export class ProjectDTO {
'Optional website URL. Used to display favicon and construct clickable page links.',
})
@IsOptional()
- @ValidateIf(o => o.websiteUrl !== null && o.websiteUrl !== undefined)
+ @ValidateIf((o) => o.websiteUrl !== null && o.websiteUrl !== undefined)
@IsUrl({}, { message: 'websiteUrl must be a valid URL' })
@MaxLength(512)
websiteUrl?: string | null
diff --git a/backend/apps/cloud/src/project/entity/annotation.entity.ts b/backend/apps/cloud/src/project/entity/annotation.entity.ts
index af71311b4..4ef620f4c 100644
--- a/backend/apps/cloud/src/project/entity/annotation.entity.ts
+++ b/backend/apps/cloud/src/project/entity/annotation.entity.ts
@@ -22,7 +22,7 @@ export class Annotation {
@CreateDateColumn()
created: Date
- @ManyToOne(() => Project, project => project.annotations)
+ @ManyToOne(() => Project, (project) => project.annotations)
@JoinColumn()
project: Project
}
diff --git a/backend/apps/cloud/src/project/entity/funnel.entity.ts b/backend/apps/cloud/src/project/entity/funnel.entity.ts
index ce71c71a2..9d4c8942a 100644
--- a/backend/apps/cloud/src/project/entity/funnel.entity.ts
+++ b/backend/apps/cloud/src/project/entity/funnel.entity.ts
@@ -24,7 +24,7 @@ export class Funnel {
@CreateDateColumn()
created: Date
- @ManyToOne(() => Project, project => project.funnels)
+ @ManyToOne(() => Project, (project) => project.funnels)
@JoinColumn()
project: Project
}
diff --git a/backend/apps/cloud/src/project/entity/project-share.entity.ts b/backend/apps/cloud/src/project/entity/project-share.entity.ts
index 2ae498969..2c81cae4c 100644
--- a/backend/apps/cloud/src/project/entity/project-share.entity.ts
+++ b/backend/apps/cloud/src/project/entity/project-share.entity.ts
@@ -26,13 +26,13 @@ export class ProjectShare {
* User whom with the project was shared
*/
@ApiProperty({ type: () => User })
- @ManyToOne(() => User, user => user.sharedProjects)
+ @ManyToOne(() => User, (user) => user.sharedProjects)
user: User
/**
* Project in question
*/
- @ManyToOne(() => Project, project => project.share)
+ @ManyToOne(() => Project, (project) => project.share)
project: Project
/**
diff --git a/backend/apps/cloud/src/project/entity/project-subscriber.entity.ts b/backend/apps/cloud/src/project/entity/project-subscriber.entity.ts
index 7e3238db2..9a8df6e09 100644
--- a/backend/apps/cloud/src/project/entity/project-subscriber.entity.ts
+++ b/backend/apps/cloud/src/project/entity/project-subscriber.entity.ts
@@ -33,7 +33,7 @@ export class ProjectSubscriber {
@UpdateDateColumn()
updatedAt: Date
- @ManyToOne(() => Project, project => project.subscribers)
+ @ManyToOne(() => Project, (project) => project.subscribers)
@JoinColumn()
project: Project
}
diff --git a/backend/apps/cloud/src/project/entity/project-view-custom-event.entity.ts b/backend/apps/cloud/src/project/entity/project-view-custom-event.entity.ts
index bf5d908d8..98091d8eb 100644
--- a/backend/apps/cloud/src/project/entity/project-view-custom-event.entity.ts
+++ b/backend/apps/cloud/src/project/entity/project-view-custom-event.entity.ts
@@ -60,6 +60,6 @@ export class ProjectViewCustomEventEntity {
@UpdateDateColumn()
updatedAt: Date
- @ManyToOne(() => ProjectViewEntity, projectView => projectView.customEvents)
+ @ManyToOne(() => ProjectViewEntity, (projectView) => projectView.customEvents)
view: ProjectViewEntity
}
diff --git a/backend/apps/cloud/src/project/entity/project-view.entity.ts b/backend/apps/cloud/src/project/entity/project-view.entity.ts
index 9ca3fd7cc..ae8f233e0 100644
--- a/backend/apps/cloud/src/project/entity/project-view.entity.ts
+++ b/backend/apps/cloud/src/project/entity/project-view.entity.ts
@@ -47,13 +47,13 @@ export class ProjectViewEntity {
@UpdateDateColumn()
updatedAt: Date
- @ManyToOne(() => Project, project => project.views, { onDelete: 'CASCADE' })
+ @ManyToOne(() => Project, (project) => project.views, { onDelete: 'CASCADE' })
project: Project
@ApiProperty({ type: ProjectViewCustomEventEntity, isArray: true })
@OneToMany(
() => ProjectViewCustomEventEntity,
- projectViewCustomEvent => projectViewCustomEvent.view,
+ (projectViewCustomEvent) => projectViewCustomEvent.view,
)
customEvents: ProjectViewCustomEventEntity[]
}
diff --git a/backend/apps/cloud/src/project/entity/project.entity.ts b/backend/apps/cloud/src/project/entity/project.entity.ts
index a8ff8cdd2..7f2758ed9 100644
--- a/backend/apps/cloud/src/project/entity/project.entity.ts
+++ b/backend/apps/cloud/src/project/entity/project.entity.ts
@@ -80,43 +80,43 @@ export class Project {
botsProtectionLevel: BotsProtectionLevel
@ApiProperty({ type: () => User })
- @ManyToOne(() => User, user => user.projects)
+ @ManyToOne(() => User, (user) => user.projects)
admin: User
@ApiProperty({ type: () => ProjectShare })
- @OneToMany(() => ProjectShare, share => share.project)
+ @OneToMany(() => ProjectShare, (share) => share.project)
share: ProjectShare[]
@ApiProperty({ type: () => Alert })
- @OneToMany(() => Alert, alert => alert.project)
+ @OneToMany(() => Alert, (alert) => alert.project)
alerts: Alert[]
@Column({ type: 'timestamp', default: () => 'CURRENT_TIMESTAMP' })
created: Date
- @OneToMany(() => ProjectSubscriber, subscriber => subscriber.project, {
+ @OneToMany(() => ProjectSubscriber, (subscriber) => subscriber.project, {
cascade: true,
})
subscribers: ProjectSubscriber[]
@ApiProperty({ type: () => Funnel })
- @OneToMany(() => Funnel, funnel => funnel.project)
+ @OneToMany(() => Funnel, (funnel) => funnel.project)
funnels: Funnel[]
@ApiProperty({ type: () => Annotation })
- @OneToMany(() => Annotation, annotation => annotation.project)
+ @OneToMany(() => Annotation, (annotation) => annotation.project)
annotations: Annotation[]
@ApiProperty({ type: () => Goal })
- @OneToMany(() => Goal, goal => goal.project)
+ @OneToMany(() => Goal, (goal) => goal.project)
goals: Goal[]
@ApiProperty({ type: () => FeatureFlag })
- @OneToMany(() => FeatureFlag, featureFlag => featureFlag.project)
+ @OneToMany(() => FeatureFlag, (featureFlag) => featureFlag.project)
featureFlags: FeatureFlag[]
@ApiProperty({ type: () => Experiment })
- @OneToMany(() => Experiment, experiment => experiment.project)
+ @OneToMany(() => Experiment, (experiment) => experiment.project)
experiments: Experiment[]
@Column('varchar', {
@@ -132,10 +132,10 @@ export class Project {
@Column('boolean', { default: false })
isArchived: boolean
- @OneToMany(() => ProjectViewEntity, projectView => projectView.id)
+ @OneToMany(() => ProjectViewEntity, (projectView) => projectView.id)
views: ProjectViewEntity[]
- @ManyToOne(() => Organisation, org => org.projects, { nullable: true })
+ @ManyToOne(() => Organisation, (org) => org.projects, { nullable: true })
organisation: Organisation | null
// Google Search Console integration
diff --git a/backend/apps/cloud/src/project/gsc.service.ts b/backend/apps/cloud/src/project/gsc.service.ts
index a1e8432a6..9e72864fe 100644
--- a/backend/apps/cloud/src/project/gsc.service.ts
+++ b/backend/apps/cloud/src/project/gsc.service.ts
@@ -317,7 +317,7 @@ export class GSCService {
position?: number
}>
return rows
- .map(row => ({
+ .map((row) => ({
name: row.keys?.[0] || '(not set)',
count: Math.round(row.clicks || 0),
impressions: Math.round(row.impressions || 0),
diff --git a/backend/apps/cloud/src/project/project.controller.ts b/backend/apps/cloud/src/project/project.controller.ts
index cfc676216..91ad3b602 100644
--- a/backend/apps/cloud/src/project/project.controller.ts
+++ b/backend/apps/cloud/src/project/project.controller.ts
@@ -781,7 +781,7 @@ export class ProjectController {
]
try {
- const promises = _map(queries, async query =>
+ const promises = _map(queries, async (query) =>
clickhouse.command({
query,
query_params: {
@@ -1052,7 +1052,7 @@ export class ProjectController {
}
const isSharingWithUser = !_isEmpty(
- _find(project.share, share => share.user?.id === invitee.id),
+ _find(project.share, (share) => share.user?.id === invitee.id),
)
if (isSharingWithUser) {
@@ -1083,9 +1083,7 @@ export class ProjectController {
ActionTokenType.PROJECT_SHARE,
share.id,
)
- const url = `${
- isDevelopment ? headers.origin : PRODUCTION_ORIGIN
- }/share/${actionToken.id}`
+ const url = `${isDevelopment ? headers.origin : PRODUCTION_ORIGIN}/share/${actionToken.id}`
await this.mailerService.sendEmail(
invitee.email,
LetterTemplate.ProjectInvitation,
@@ -1581,7 +1579,7 @@ export class ProjectController {
]
try {
- const promises = _map(queries, async query =>
+ const promises = _map(queries, async (query) =>
clickhouse.command({
query,
query_params: {
@@ -1941,9 +1939,11 @@ export class ProjectController {
let isAccessConfirmed = true
if (userId) {
- const userShare = project.share?.find(share => share.user?.id === userId)
+ const userShare = project.share?.find(
+ (share) => share.user?.id === userId,
+ )
const organisationMembership = project.organisation?.members?.find(
- member => member.user?.id === userId,
+ (member) => member.user?.id === userId,
)
if (project.admin?.id === userId) {
diff --git a/backend/apps/cloud/src/project/project.service.ts b/backend/apps/cloud/src/project/project.service.ts
index e0429b9da..0450ec722 100644
--- a/backend/apps/cloud/src/project/project.service.ts
+++ b/backend/apps/cloud/src/project/project.service.ts
@@ -118,7 +118,7 @@ export const processProjectUser = (
project: Project,
properties: Array<'share' | 'organisation.members'> = ['share'],
): Project => {
- _map(properties, property => {
+ _map(properties, (property) => {
const array =
property === 'share' ? project.share : project.organisation?.members
@@ -497,7 +497,7 @@ export class ProjectService implements OnModuleDestroy {
'pinnedProject.projectId = project.id AND pinnedProject.userId = :userId',
)
.where(
- new Brackets(qb => {
+ new Brackets((qb) => {
qb.where('project.adminId = :userId')
.orWhere(
'EXISTS (SELECT 1 FROM project_share ps WHERE ps.projectId = project.id AND ps.userId = :userId)',
@@ -562,7 +562,7 @@ export class ProjectService implements OnModuleDestroy {
.leftJoin('project.share', 'share')
.where('project.organisation IS NULL')
.andWhere(
- new Brackets(qb => {
+ new Brackets((qb) => {
qb.where('admin.id = :userId', { userId }).orWhere(
'share.user.id = :userId AND share.role = :adminRole',
{ userId, adminRole: Role.admin },
@@ -670,7 +670,7 @@ export class ProjectService implements OnModuleDestroy {
) !== -1 ||
_findIndex(
project.organisation?.members,
- member => member.user?.id === uid && member.confirmed === true,
+ (member) => member.user?.id === uid && member.confirmed === true,
) !== -1
) {
return null
@@ -703,14 +703,14 @@ export class ProjectService implements OnModuleDestroy {
uid === project.admin?.id ||
_findIndex(
project.share,
- share =>
+ (share) =>
share.user?.id === uid &&
share.role === Role.admin &&
share.confirmed === true,
) !== -1 ||
_findIndex(
project.organisation?.members,
- member =>
+ (member) =>
member.user?.id === uid &&
member.confirmed === true &&
(member.role === OrganisationRole.admin ||
@@ -799,7 +799,7 @@ export class ProjectService implements OnModuleDestroy {
}
await Promise.all(
- _map(queries, query =>
+ _map(queries, (query) =>
clickhouse.command({
query,
query_params: params,
@@ -816,7 +816,7 @@ export class ProjectService implements OnModuleDestroy {
'The list of allowed origins has to be smaller than 300 symbols',
)
- _map(projectDTO.origins, host => {
+ _map(projectDTO.origins, (host) => {
if (!ORIGINS_REGEX.test(_trim(host))) {
throw new ConflictException(`Host ${host} is not correct`)
}
@@ -830,7 +830,7 @@ export class ProjectService implements OnModuleDestroy {
throw new UnprocessableEntityException(
'The list of allowed blacklisted IP addresses must be less than 300 characters.',
)
- _map(projectDTO.ipBlacklist, ip => {
+ _map(projectDTO.ipBlacklist, (ip) => {
if (!net.isIP(_trim(ip)) && !IP_REGEX.test(_trim(ip))) {
throw new ConflictException(`IP address ${ip} is not correct`)
}
@@ -850,7 +850,7 @@ export class ProjectService implements OnModuleDestroy {
)
const countryCodeRegex = /^[A-Z]{2}$/
- _map(projectDTO.countryBlacklist, code => {
+ _map(projectDTO.countryBlacklist, (code) => {
const trimmedCode = _trim(code).toUpperCase()
if (!countryCodeRegex.test(trimmedCode)) {
throw new ConflictException(
@@ -942,25 +942,25 @@ export class ProjectService implements OnModuleDestroy {
query: countEVQuery,
query_params: params,
})
- .then(resultSet => resultSet.json()),
+ .then((resultSet) => resultSet.json()),
clickhouse
.query({
query: countCustomEVQuery,
query_params: params,
})
- .then(resultSet => resultSet.json()),
+ .then((resultSet) => resultSet.json()),
clickhouse
.query({
query: countCaptchaQuery,
query_params: params,
})
- .then(resultSet => resultSet.json()),
+ .then((resultSet) => resultSet.json()),
clickhouse
.query({
query: countErrorsQuery,
query_params: params,
})
- .then(resultSet => resultSet.json()),
+ .then((resultSet) => resultSet.json()),
])
totalPageviews += pageviews[0]['count()']
@@ -1040,25 +1040,25 @@ export class ProjectService implements OnModuleDestroy {
query: countEVQuery,
query_params: params,
})
- .then(resultSet => resultSet.json()),
+ .then((resultSet) => resultSet.json()),
clickhouse
.query({
query: countCustomEVQuery,
query_params: params,
})
- .then(resultSet => resultSet.json()),
+ .then((resultSet) => resultSet.json()),
clickhouse
.query({
query: countCaptchaQuery,
query_params: params,
})
- .then(resultSet => resultSet.json()),
+ .then((resultSet) => resultSet.json()),
clickhouse
.query({
query: countErrorsQuery,
query_params: params,
})
- .then(resultSet => resultSet.json()),
+ .then((resultSet) => resultSet.json()),
])
totalTraffic += rawTraffic[0]['count()']
@@ -1181,7 +1181,7 @@ export class ProjectService implements OnModuleDestroy {
query,
query_params: params,
})
- .then(resultSet => resultSet.json<{ pid: string }>())
+ .then((resultSet) => resultSet.json<{ pid: string }>())
return _map(data, ({ pid }) => pid)
}
@@ -1230,7 +1230,7 @@ export class ProjectService implements OnModuleDestroy {
query,
query_params: params,
})
- .then(resultSet => resultSet.json<{ pid: string }>())
+ .then((resultSet) => resultSet.json<{ pid: string }>())
return _map(data, ({ pid }) => pid)
}
@@ -1279,7 +1279,7 @@ export class ProjectService implements OnModuleDestroy {
query,
query_params: params,
})
- .then(resultSet => resultSet.json<{ pid: string }>())
+ .then((resultSet) => resultSet.json<{ pid: string }>())
return _map(data, ({ pid }) => pid)
}
@@ -1454,7 +1454,7 @@ export class ProjectService implements OnModuleDestroy {
relations: ['project'],
where: { id: subscriberId },
})
- return projects.map(project => project.project)
+ return projects.map((project) => project.project)
}
async getOwnProject(projectId: string, userId: string) {
@@ -1661,7 +1661,7 @@ export class ProjectService implements OnModuleDestroy {
query,
query_params: params,
})
- .then(resultSet => resultSet.json())
+ .then((resultSet) => resultSet.json())
count = data[0]['count']
} catch (reason) {
@@ -1744,10 +1744,12 @@ export class ProjectService implements OnModuleDestroy {
const pinnedProjectIds = await this.getPinnedProjectIds(userId)
- paginated.results = _map(paginated.results, project => {
- const userShare = project.share?.find(share => share.user?.id === userId)
+ paginated.results = _map(paginated.results, (project) => {
+ const userShare = project.share?.find(
+ (share) => share.user?.id === userId,
+ )
const organisationMembership = project.organisation?.members?.find(
- member => member.user?.id === userId,
+ (member) => member.user?.id === userId,
)
let role
@@ -1793,7 +1795,7 @@ export class ProjectService implements OnModuleDestroy {
},
})
- return _map(pinnedProjects, pp => pp.project?.id).filter(Boolean)
+ return _map(pinnedProjects, (pp) => pp.project?.id).filter(Boolean)
}
async pinProject(userId: string, projectId: string): Promise<void> {
diff --git a/backend/apps/cloud/src/project/repositories/projects-views.repository.ts b/backend/apps/cloud/src/project/repositories/projects-views.repository.ts
index 08a8b1a56..7a5914b35 100644
--- a/backend/apps/cloud/src/project/repositories/projects-views.repository.ts
+++ b/backend/apps/cloud/src/project/repositories/projects-views.repository.ts
@@ -38,7 +38,7 @@ export class ProjectsViewsRepository {
})
if (data.customEvents) {
- const customEventPromises = data.customEvents.map(customEvent => {
+ const customEventPromises = data.customEvents.map((customEvent) => {
return this.projectViewCustomEventsRepository.save({
viewId: view.id,
customEventName: customEvent.customEventName,
@@ -112,7 +112,7 @@ export class ProjectsViewsRepository {
await this.viewsRepository.save(entity)
if (!_isEmpty(entity.customEvents)) {
- const customEventPromises = entity.customEvents.map(customEvent => {
+ const customEventPromises = entity.customEvents.map((customEvent) => {
return this.projectViewCustomEventsRepository.save({
id: customEvent.id,
viewId: id,
diff --git a/backend/apps/cloud/src/revenue/adapters/paddle.adapter.ts b/backend/apps/cloud/src/revenue/adapters/paddle.adapter.ts
index b588a83b0..3a4e5e6ce 100644
--- a/backend/apps/cloud/src/revenue/adapters/paddle.adapter.ts
+++ b/backend/apps/cloud/src/revenue/adapters/paddle.adapter.ts
@@ -332,7 +332,7 @@ export class PaddleAdapter {
// Determine transaction type
let type = RevenueType.SALE
const lineItems = transaction.details.line_items || []
- if (lineItems.some(item => item?.price?.billing_cycle != null)) {
+ if (lineItems.some((item) => item?.price?.billing_cycle != null)) {
type = RevenueType.SUBSCRIPTION
}
diff --git a/backend/apps/cloud/src/revenue/revenue.service.ts b/backend/apps/cloud/src/revenue/revenue.service.ts
index cfb242ab9..4b946f947 100644
--- a/backend/apps/cloud/src/revenue/revenue.service.ts
+++ b/backend/apps/cloud/src/revenue/revenue.service.ts
@@ -223,7 +223,7 @@ export class RevenueService {
groupTo: groupToUTC,
},
})
- .then(resultSet =>
+ .then((resultSet) =>
resultSet.json<{
totalRevenue: number
salesCount: number
@@ -266,7 +266,7 @@ export class RevenueService {
groupTo: groupFromUTC,
},
})
- .then(resultSet => resultSet.json<{ totalRevenue: number }>())
+ .then((resultSet) => resultSet.json<{ totalRevenue: number }>())
const previousRevenue = previousData[0]?.totalRevenue || 0
const revenueChange =
@@ -336,7 +336,7 @@ export class RevenueService {
timezone,
},
})
- .then(resultSet =>
+ .then((resultSet) =>
resultSet.json<{
year: number
month?: number
@@ -431,7 +431,7 @@ export class RevenueService {
`
const { data: countData } = await clickhouse
.query({ query: countQuery, query_params: params })
- .then(resultSet => resultSet.json<{ total: number }>())
+ .then((resultSet) => resultSet.json<{ total: number }>())
// Get transactions
const transactionsQuery = `
@@ -479,7 +479,7 @@ export class RevenueService {
query: transactionsQuery,
query_params: { ...params, take, skip },
})
- .then(resultSet =>
+ .then((resultSet) =>
resultSet.json<{
transaction_id: string
provider: string
@@ -496,7 +496,7 @@ export class RevenueService {
}>(),
)
- const transactions: RevenueTransactionDto[] = data.map(row => ({
+ const transactions: RevenueTransactionDto[] = data.map((row) => ({
transactionId: row.transaction_id,
provider: row.provider,
type: row.type,
diff --git a/backend/apps/cloud/src/task-manager/task-manager.service.ts b/backend/apps/cloud/src/task-manager/task-manager.service.ts
index d78bc51d1..5cad17671 100644
--- a/backend/apps/cloud/src/task-manager/task-manager.service.ts
+++ b/backend/apps/cloud/src/task-manager/task-manager.service.ts
@@ -144,7 +144,7 @@ const executeChunkedQueries = async (
getFromDate: (user?: User) => string,
getToDate: (user?: User) => string,
): Promise<CHPlanUsage[]> => {
- return mapLimit(users, 5, async user => {
+ return mapLimit(users, 5, async (user) => {
if (_isEmpty(user.projects)) {
return {
id: user.id,
@@ -152,7 +152,7 @@ const executeChunkedQueries = async (
}
}
- const pids = _map(user.projects, p => p.id)
+ const pids = _map(user.projects, (p) => p.id)
let totalCount = 0
const from = getFromDate(user)
const to = getToDate(user)
@@ -167,7 +167,7 @@ const executeChunkedQueries = async (
query,
query_params: { pids: pidChunk, uid: user.id, from, to },
})
- .then(resultSet => resultSet.json<CHPlanUsage>())
+ .then((resultSet) => resultSet.json<CHPlanUsage>())
totalCount += data[0]?.count || 0
}
@@ -421,11 +421,11 @@ export class TaskManagerService {
const analyticsGoals = _filter(
projectGoals,
- g => g.type === GoalType.PAGEVIEW,
+ (g) => g.type === GoalType.PAGEVIEW,
)
const customEventGoals = _filter(
projectGoals,
- g => g.type === GoalType.CUSTOM_EVENT,
+ (g) => g.type === GoalType.CUSTOM_EVENT,
)
const analyticsQuery = buildUnionQuery('analytics', analyticsGoals)
@@ -438,7 +438,7 @@ export class TaskManagerService {
query: analyticsQuery.query,
query_params: analyticsQuery.params,
})
- .then(resultSet =>
+ .then((resultSet) =>
resultSet.json<{
goalId: string
conversions: any
@@ -452,7 +452,7 @@ export class TaskManagerService {
query: customEventQuery.query,
query_params: customEventQuery.params,
})
- .then(resultSet =>
+ .then((resultSet) =>
resultSet.json<{
goalId: string
conversions: any
@@ -494,15 +494,11 @@ export class TaskManagerService {
): string {
if (type === '3rdparty') {
const token = this.projectService.createUnsubscribeKey(id)
- return `${this.configService.get(
- 'CLIENT_URL',
- )}/3rd-party-unsubscribe/${token}`
+ return `${this.configService.get('CLIENT_URL')}/3rd-party-unsubscribe/${token}`
}
const token = this.userService.createUnsubscribeKey(id)
- return `${this.configService.get(
- 'CLIENT_URL',
- )}/reports-unsubscribe/${token}`
+ return `${this.configService.get('CLIENT_URL')}/reports-unsubscribe/${token}`
}
async handleUserReports(
@@ -538,12 +534,12 @@ export class TaskManagerService {
now,
)
- await mapLimit(users, REPORTS_USERS_CONCURRENCY, async user => {
+ await mapLimit(users, REPORTS_USERS_CONCURRENCY, async (user) => {
const { id, email, projects } = user
try {
const unsubscribeUrl = this.generateUnsubscribeUrl(id, 'user-reports')
- const ids = _map(projects, p => p.id)
+ const ids = _map(projects, (p) => p.id)
const [summary, topCountries, errorCounts, totalSessions] =
await Promise.all([
@@ -604,7 +600,7 @@ export class TaskManagerService {
{ goalId: string; conversions: number; conversionRate: number }
>
- const goalsWithConversions = _map(projectGoals, goal => {
+ const goalsWithConversions = _map(projectGoals, (goal) => {
const stats = conversionsById[goal.id]
return {
name: goal.name,
@@ -615,7 +611,7 @@ export class TaskManagerService {
const activeGoals = _filter(
goalsWithConversions,
- g => g.conversions > 0,
+ (g) => g.conversions > 0,
)
return {
@@ -688,122 +684,130 @@ export class TaskManagerService {
now,
)
- await mapLimit(subscribers, REPORTS_USERS_CONCURRENCY, async subscriber => {
- const { id, email } = subscriber
+ await mapLimit(
+ subscribers,
+ REPORTS_USERS_CONCURRENCY,
+ async (subscriber) => {
+ const { id, email } = subscriber
- try {
- const projects = await this.projectService.getSubscriberProjects(id)
- const unsubscribeUrl = this.generateUnsubscribeUrl(id, '3rdparty')
- const ids = projects.map(project => project.id)
-
- const [summary, topCountries, errorCounts, totalSessions] =
- await Promise.all([
- this.analyticsService.getAnalyticsSummary(
- ids,
- undefined,
- params.analyticsParam,
- undefined,
- undefined,
- undefined,
- undefined,
- undefined,
- now,
- ),
- this.analyticsService.getTopCountriesForReport(
- ids,
- groupFrom,
- groupTo,
- ),
- this.analyticsService.getErrorCountsForReport(
- ids,
- groupFrom,
- groupTo,
- ),
- this.analyticsService.getTotalSessionsForReport(
- ids,
- groupFrom,
- groupTo,
- ),
- ])
-
- const data = this.analyticsService.convertSummaryToReportFormat(summary)
-
- const projectsWithExtraData = await mapLimit(
- ids,
- REPORTS_PROJECTS_CONCURRENCY,
- async (pid, index) => {
- const projectData = data[pid] || {}
- const topCountry = topCountries[pid]?.cc || null
- const errorStats = errorCounts[pid] || { count: 0, uniqueErrors: 0 }
- const pidTotalSessions = totalSessions[pid] || 0
-
- const projectGoals = await this.goalService.findByProject(pid)
- const conversions = await this.getGoalsWithConversionsForReport(
- pid,
- projectGoals,
- groupFrom,
- groupTo,
- pidTotalSessions,
- )
+ try {
+ const projects = await this.projectService.getSubscriberProjects(id)
+ const unsubscribeUrl = this.generateUnsubscribeUrl(id, '3rdparty')
+ const ids = projects.map((project) => project.id)
+
+ const [summary, topCountries, errorCounts, totalSessions] =
+ await Promise.all([
+ this.analyticsService.getAnalyticsSummary(
+ ids,
+ undefined,
+ params.analyticsParam,
+ undefined,
+ undefined,
+ undefined,
+ undefined,
+ undefined,
+ now,
+ ),
+ this.analyticsService.getTopCountriesForReport(
+ ids,
+ groupFrom,
+ groupTo,
+ ),
+ this.analyticsService.getErrorCountsForReport(
+ ids,
+ groupFrom,
+ groupTo,
+ ),
+ this.analyticsService.getTotalSessionsForReport(
+ ids,
+ groupFrom,
+ groupTo,
+ ),
+ ])
+
+ const data =
+ this.analyticsService.convertSummaryToReportFormat(summary)
+
+ const projectsWithExtraData = await mapLimit(
+ ids,
+ REPORTS_PROJECTS_CONCURRENCY,
+ async (pid, index) => {
+ const projectData = data[pid] || {}
+ const topCountry = topCountries[pid]?.cc || null
+ const errorStats = errorCounts[pid] || {
+ count: 0,
+ uniqueErrors: 0,
+ }
+ const pidTotalSessions = totalSessions[pid] || 0
+
+ const projectGoals = await this.goalService.findByProject(pid)
+ const conversions = await this.getGoalsWithConversionsForReport(
+ pid,
+ projectGoals,
+ groupFrom,
+ groupTo,
+ pidTotalSessions,
+ )
- const conversionsById = _reduce(
- conversions,
- (acc, row) => ({ ...acc, [row.goalId]: row }),
- {},
- ) as Record<
- string,
- { goalId: string; conversions: number; conversionRate: number }
- >
+ const conversionsById = _reduce(
+ conversions,
+ (acc, row) => ({ ...acc, [row.goalId]: row }),
+ {},
+ ) as Record<
+ string,
+ { goalId: string; conversions: number; conversionRate: number }
+ >
+
+ const goalsWithConversions = _map(projectGoals, (goal) => {
+ const stats = conversionsById[goal.id]
+ return {
+ name: goal.name,
+ conversions: stats?.conversions || 0,
+ conversionRate: stats?.conversionRate || 0,
+ }
+ })
+
+ const activeGoals = _filter(
+ goalsWithConversions,
+ (g) => g.conversions > 0,
+ )
- const goalsWithConversions = _map(projectGoals, goal => {
- const stats = conversionsById[goal.id]
return {
- name: goal.name,
- conversions: stats?.conversions || 0,
- conversionRate: stats?.conversionRate || 0,
+ data: projectData,
+ name: projects[index].name,
+ topCountry,
+ errors:
+ errorStats.count > 0
+ ? {
+ count: errorStats.count,
+ uniqueErrors: errorStats.uniqueErrors,
+ }
+ : null,
+ goals: activeGoals.length > 0 ? activeGoals : null,
}
- })
-
- const activeGoals = _filter(
- goalsWithConversions,
- g => g.conversions > 0,
- )
+ },
+ )
- return {
- data: projectData,
- name: projects[index].name,
- topCountry,
- errors:
- errorStats.count > 0
- ? {
- count: errorStats.count,
- uniqueErrors: errorStats.uniqueErrors,
- }
- : null,
- goals: activeGoals.length > 0 ? activeGoals : null,
- }
- },
- )
+ const result = {
+ type: params.type,
+ date,
+ projects: projectsWithExtraData,
+ tip,
+ unsubscribeUrl,
+ }
- const result = {
- type: params.type,
- date,
- projects: projectsWithExtraData,
- tip,
- unsubscribeUrl,
+ await this.mailerService.sendEmail(
+ email,
+ LetterTemplate.ProjectReport,
+ result,
+ )
+ } catch (reason) {
+ this.logger.error(
+ `[CRON WORKER](handleSubscriberReports) Frequency: ${reportFrequency}; Error: ${reason}`,
+ )
}
-
- await this.mailerService.sendEmail(
- email,
- LetterTemplate.ProjectReport,
- result,
- )
- } catch (reason) {
- this.logger.error(
- `[CRON WORKER](handleSubscriberReports) Frequency: ${reportFrequency}; Error: ${reason}`,
- )
- }
- })
+ },
+ )
}
@Cron(CronExpression.EVERY_DAY_AT_5PM)
@@ -817,9 +821,9 @@ export class TaskManagerService {
// This stuff is used solely to calculate whether the user has exceeded their limit > 30% or continuously for 2 months
const monthlyUsage = await executeChunkedQueries(
users,
- user =>
+ (user) =>
dayjs.utc(user.planExceedContactedAt).format('YYYY-MM-01 00:00:00'),
- user =>
+ (user) =>
dayjs
.utc(user.planExceedContactedAt)
.endOf('month')
@@ -851,7 +855,7 @@ export class TaskManagerService {
dashboardBlockReason: DashboardBlockReason.exceeding_plan_limits,
})
}),
- ).catch(reason => {
+ ).catch((reason) => {
this.logger.error(
`[CRON WORKER](lockDashboards) Error occured: ${reason}`,
)
@@ -884,7 +888,7 @@ export class TaskManagerService {
// if there are exceeding users, contact them and let them know that their usage is > than 30% their tier allows
if (!_isEmpty(exceedingUsers)) {
- const percExceedingUsagePromises = _map(exceedingUsers, async user => {
+ const percExceedingUsagePromises = _map(exceedingUsers, async (user) => {
const { id, email, usage, planCode } = user
const suggestedPlanLimit = getNextPlan(planCode)
@@ -909,7 +913,7 @@ export class TaskManagerService {
})
})
- await Promise.allSettled(percExceedingUsagePromises).catch(reason => {
+ await Promise.allSettled(percExceedingUsagePromises).catch((reason) => {
this.logger.error(
`[CRON WORKER](checkPlanUsage - percExceedingUsagePromises) Error occured: ${reason}`,
)
@@ -918,8 +922,8 @@ export class TaskManagerService {
const filteredUsers = _filter(
users,
- user =>
- !_find(exceedingUsers, exceedingUser => exceedingUser.id === user.id),
+ (user) =>
+ !_find(exceedingUsers, (exceedingUser) => exceedingUser.id === user.id),
)
if (_isEmpty(filteredUsers)) {
@@ -952,7 +956,7 @@ export class TaskManagerService {
if (!_isEmpty(continuousExceedingUsers)) {
const continuousExceedingUsagePromises = _map(
continuousExceedingUsers,
- async user => {
+ async (user) => {
const { id, email, usage, planCode } = user
const [userThisMonthUsage, userLastMonthUsage] = usage || []
@@ -982,7 +986,7 @@ export class TaskManagerService {
)
await Promise.allSettled(continuousExceedingUsagePromises).catch(
- reason => {
+ (reason) => {
this.logger.error(
`[CRON WORKER](checkPlanUsage - continuousExceedingUsagePromises) Error occured: ${reason}`,
)
@@ -1017,7 +1021,7 @@ export class TaskManagerService {
url: 'https://swetrix.com/billing',
}
- const promises = _map(users, async user => {
+ const promises = _map(users, async (user) => {
const { id, email, planCode, projects } = user
if (_isEmpty(projects) || _isNull(projects)) {
@@ -1041,7 +1045,7 @@ export class TaskManagerService {
}
})
- await Promise.allSettled(promises).catch(reason => {
+ await Promise.allSettled(promises).catch((reason) => {
this.logger.error(
`[CRON WORKER](checkLeftEvents) Error occured: ${reason}`,
)
@@ -1094,7 +1098,7 @@ export class TaskManagerService {
return
}
- const promises = _map(projects, async project => {
+ const promises = _map(projects, async (project) => {
try {
if (project.paddleApiKeyEnc) {
const apiKey = this.revenueService.getPaddleApiKey(project)
@@ -1136,7 +1140,7 @@ export class TaskManagerService {
}
})
- await Promise.allSettled(promises).catch(reason => {
+ await Promise.allSettled(promises).catch((reason) => {
this.logger.error(
`[CRON WORKER](syncRevenueData) Error occured: ${reason}`,
)
@@ -1188,7 +1192,7 @@ export class TaskManagerService {
select: ['id', 'telegramChatId'],
})
- const promises = _map(users, async user => {
+ const promises = _map(users, async (user) => {
const { id } = user
await this.userService.update(id, {
@@ -1196,7 +1200,7 @@ export class TaskManagerService {
})
})
- await Promise.allSettled(promises).catch(reason => {
+ await Promise.allSettled(promises).catch((reason) => {
this.logger.error(
`[CRON WORKER](checkIsTelegramChatIdConfirmed) Error occured: ${reason}`,
)
@@ -1211,7 +1215,7 @@ export class TaskManagerService {
},
})
- const promises = _map(users, async user => {
+ const promises = _map(users, async (user) => {
const cancellationEffectiveDate = new Date(user.cancellationEffectiveDate)
const now = new Date()
@@ -1231,7 +1235,7 @@ export class TaskManagerService {
}
})
- await Promise.allSettled(promises).catch(reason => {
+ await Promise.allSettled(promises).catch((reason) => {
this.logger.error(
`[CRON WORKER](cleanUpUnpaidSubUsers) Error occured: ${reason}`,
)
@@ -1252,7 +1256,7 @@ export class TaskManagerService {
},
})
- const promises = _map(users, async user => {
+ const promises = _map(users, async (user) => {
const { id, email } = user
await this.userService.update(id, {
@@ -1267,7 +1271,7 @@ export class TaskManagerService {
)
})
- await Promise.allSettled(promises).catch(reason => {
+ await Promise.allSettled(promises).catch((reason) => {
this.logger.error(`[CRON WORKER](trialReminder) Error occured: ${reason}`)
})
}
@@ -1282,7 +1286,7 @@ export class TaskManagerService {
},
})
- const promises = _map(users, async user => {
+ const promises = _map(users, async (user) => {
const { id, created } = user
await this.userService.update(id, {
@@ -1292,7 +1296,7 @@ export class TaskManagerService {
})
})
- await Promise.allSettled(promises).catch(reason => {
+ await Promise.allSettled(promises).catch((reason) => {
this.logger.error(
`[CRON WORKER](fixAFuckingTrialEndDateNullBug) Error occured: ${reason}`,
)
@@ -1314,7 +1318,7 @@ export class TaskManagerService {
],
})
- const promises = _map(users, async user => {
+ const promises = _map(users, async (user) => {
const { id, email } = user
await this.userService.update(id, {
@@ -1328,7 +1332,7 @@ export class TaskManagerService {
await this.projectService.clearProjectsRedisCache(id)
})
- await Promise.allSettled(promises).catch(reason => {
+ await Promise.allSettled(promises).catch((reason) => {
this.logger.error(`[CRON WORKER](trialEnd) Error occured: ${reason}`)
})
}
@@ -1371,7 +1375,7 @@ export class TaskManagerService {
relations: ['project'],
})
- const promises = _map(alerts, async alert => {
+ const promises = _map(alerts, async (alert) => {
try {
const project = _find(projects, { id: alert.project.id })
@@ -1472,7 +1476,7 @@ export class TaskManagerService {
relations: ['project'],
})
- const promises = _map(alerts, async alert => {
+ const promises = _map(alerts, async (alert) => {
try {
const project = _find(projects, { id: alert.project.id })
@@ -1577,7 +1581,7 @@ export class TaskManagerService {
query,
query_params: queryParams,
})
- .then(resultSet => resultSet.json())
+ .then((resultSet) => resultSet.json())
const count = Number(queryResult[0]['count()']) || 0
@@ -1643,7 +1647,7 @@ export class TaskManagerService {
try {
const { data: errorDetailResult } = await clickhouse
.query({ query: detailQuery, query_params: detailQueryParams })
- .then(resultSet => resultSet.json())
+ .then((resultSet) => resultSet.json())
if (errorDetailResult && errorDetailResult.length > 0) {
errorDetails = errorDetailResult[0] as typeof errorDetails
}
@@ -1826,7 +1830,7 @@ export class TaskManagerService {
const messages = await this.telegramService.getMessages()
- const promises = messages.map(async message => {
+ const promises = messages.map(async (message) => {
try {
await this.telegramService.sendMessage(
message.id,
@@ -1867,7 +1871,7 @@ export class TaskManagerService {
// a bit more than 2 months ago
const nineWeeksAgo = dayjs.utc().subtract(9, 'w').format('YYYY-MM-DD')
- await mapLimit(users, REPORTS_USERS_CONCURRENCY, async user => {
+ await mapLimit(users, REPORTS_USERS_CONCURRENCY, async (user) => {
const { id, projects } = user
try {
@@ -1875,7 +1879,7 @@ export class TaskManagerService {
return
}
- const pids = _map(projects, p => p.id)
+ const pids = _map(projects, (p) => p.id)
// No need to check for performance activity because it's not tracked without tracking analytics
const queryAnalytics = `SELECT count() FROM analytics WHERE pid IN ({pids:Array(FixedString(12))}) AND created BETWEEN {nineWeeksAgo:String} AND {now:String}`
@@ -1900,7 +1904,7 @@ export class TaskManagerService {
query: queryAnalytics,
query_params: queryParams,
})
- .then(resultSet => resultSet.json<{ 'count()': number }>())
+ .then((resultSet) => resultSet.json<{ 'count()': number }>())
totalAnalytics += analyticsResult[0]['count()']
@@ -1923,7 +1927,7 @@ export class TaskManagerService {
query: queryCaptcha,
query_params: queryParams,
})
- .then(resultSet => resultSet.json<{ 'count()': number }>())
+ .then((resultSet) => resultSet.json<{ 'count()': number }>())
totalCaptcha += captchaResult[0]['count()']
@@ -1946,7 +1950,7 @@ export class TaskManagerService {
query: queryCustomEvents,
query_params: queryParams,
})
- .then(resultSet => resultSet.json<{ 'count()': number }>())
+ .then((resultSet) => resultSet.json<{ 'count()': number }>())
totalCustomEvents += customEventsResult[0]['count()']
diff --git a/backend/apps/cloud/src/user/entities/refresh-token.entity.ts b/backend/apps/cloud/src/user/entities/refresh-token.entity.ts
index 5347b2236..d03dcd52d 100644
--- a/backend/apps/cloud/src/user/entities/refresh-token.entity.ts
+++ b/backend/apps/cloud/src/user/entities/refresh-token.entity.ts
@@ -18,7 +18,7 @@ export class RefreshToken {
@Column('text')
refreshToken: string
- @ManyToOne(() => User, user => user.refreshTokens, {
+ @ManyToOne(() => User, (user) => user.refreshTokens, {
onDelete: 'CASCADE',
})
@JoinColumn()
diff --git a/backend/apps/cloud/src/user/entities/user.entity.ts b/backend/apps/cloud/src/user/entities/user.entity.ts
index 44ce93e76..26ae0b149 100644
--- a/backend/apps/cloud/src/user/entities/user.entity.ts
+++ b/backend/apps/cloud/src/user/entities/user.entity.ts
@@ -161,9 +161,10 @@ export const getNextPlan = (planCode: PlanCode): PlanSignature | undefined => {
Object.values(ACCOUNT_PLANS)
.filter(
- plan => ![PlanCode.free, PlanCode.trial, PlanCode.none].includes(plan.id),
+ (plan) =>
+ ![PlanCode.free, PlanCode.trial, PlanCode.none].includes(plan.id),
)
- .some(plan => {
+ .some((plan) => {
if (plan.monthlyUsageLimit > currentLimit) {
nextPlan = plan
return true
@@ -319,13 +320,13 @@ export class User {
/* Relations */
- @OneToMany(() => Project, project => project.admin)
+ @OneToMany(() => Project, (project) => project.admin)
projects: Project[]
- @OneToMany(() => ProjectShare, sharedProjects => sharedProjects.user)
+ @OneToMany(() => ProjectShare, (sharedProjects) => sharedProjects.user)
sharedProjects: ProjectShare[]
- @OneToMany(() => ActionToken, actionToken => actionToken.user)
+ @OneToMany(() => ActionToken, (actionToken) => actionToken.user)
actionTokens: ActionToken[]
@Column({
@@ -421,10 +422,10 @@ export class User {
@Column({ default: false })
registeredWithGithub: boolean
- @OneToMany(() => RefreshToken, refreshToken => refreshToken.user)
+ @OneToMany(() => RefreshToken, (refreshToken) => refreshToken.user)
@JoinTable()
refreshTokens: RefreshToken[]
- @OneToMany(() => OrganisationMember, membership => membership.user)
+ @OneToMany(() => OrganisationMember, (membership) => membership.user)
organisationMemberships: OrganisationMember[]
}
diff --git a/backend/apps/cloud/src/user/user.controller.ts b/backend/apps/cloud/src/user/user.controller.ts
index 558b904ce..21329fe68 100644
--- a/backend/apps/cloud/src/user/user.controller.ts
+++ b/backend/apps/cloud/src/user/user.controller.ts
@@ -515,9 +515,7 @@ export class UserController {
ActionTokenType.EMAIL_VERIFICATION,
user.email,
)
- const url = `${
- isDevelopment ? request.headers.origin : PRODUCTION_ORIGIN
- }/verify/${token.id}`
+ const url = `${isDevelopment ? request.headers.origin : PRODUCTION_ORIGIN}/verify/${token.id}`
await this.userService.update(id, { emailRequests: 1 + user.emailRequests })
await this.mailerService.sendEmail(user.email, LetterTemplate.SignUp, {
diff --git a/backend/apps/cloud/src/user/user.service.ts b/backend/apps/cloud/src/user/user.service.ts
index 3dac6039d..430824fc0 100644
--- a/backend/apps/cloud/src/user/user.service.ts
+++ b/backend/apps/cloud/src/user/user.service.ts
@@ -337,7 +337,7 @@ export class UserService {
const stringifiedPlanId = String(planId)
const plan = Object.values(ACCOUNT_PLANS).find(
- tier =>
+ (tier) =>
// @ts-ignore
tier.pid === stringifiedPlanId ||
// @ts-ignore
@@ -557,7 +557,7 @@ export class UserService {
.leftJoinAndSelect('user.projects', 'projects')
.select(['user.id', 'user.email', 'projects.id', 'projects.name'])
.where('user.id IN (:...userIds)', {
- userIds: userIds.map(u => u.id),
+ userIds: userIds.map((u) => u.id),
})
.getMany()
}
@@ -595,7 +595,7 @@ export class UserService {
.leftJoinAndSelect('user.projects', 'projects')
.select(['user.id', 'user.email', 'user.planCode', 'projects.id'])
.where('user.id IN (:...userIds)', {
- userIds: userIds.map(u => u.id),
+ userIds: userIds.map((u) => u.id),
})
.getMany()
}
@@ -628,7 +628,7 @@ export class UserService {
.leftJoinAndSelect('user.projects', 'projects')
.select(['user.id', 'user.email', 'user.planCode', 'projects.id'])
.where('user.id IN (:...userIds)', {
- userIds: userIds.map(u => u.id),
+ userIds: userIds.map((u) => u.id),
})
.getMany()
}
diff --git a/backend/apps/cloud/src/webhook/webhook.controller.ts b/backend/apps/cloud/src/webhook/webhook.controller.ts
index bbe95696e..8c14505c0 100644
--- a/backend/apps/cloud/src/webhook/webhook.controller.ts
+++ b/backend/apps/cloud/src/webhook/webhook.controller.ts
@@ -106,9 +106,7 @@ export class WebhookController {
uid = JSON.parse(passthrough)?.uid
} catch {
this.logger.error(
- `[${body.alert_name}] Cannot parse the uid: ${JSON.stringify(
- body,
- )}`,
+ `[${body.alert_name}] Cannot parse the uid: ${JSON.stringify(body)}`,
)
}
diff --git a/backend/apps/community/src/analytics/analytics.controller.ts b/backend/apps/community/src/analytics/analytics.controller.ts
index fc001a065..39c78af4d 100644
--- a/backend/apps/community/src/analytics/analytics.controller.ts
+++ b/backend/apps/community/src/analytics/analytics.controller.ts
@@ -776,7 +776,7 @@ export class AnalyticsController {
this.logger.log(`pidsArray: ${pidsArray}`, 'GET /analytics/birdseye')
- const validationPromises = _map(pidsArray, async currentPID => {
+ const validationPromises = _map(pidsArray, async (currentPID) => {
await this.analyticsService.checkProjectAccess(
currentPID,
uid,
@@ -823,7 +823,7 @@ export class AnalyticsController {
measure = DEFAULT_MEASURE
}
- const validationPromises = _map(pidsArray, async currentPID => {
+ const validationPromises = _map(pidsArray, async (currentPID) => {
await this.analyticsService.checkProjectAccess(
currentPID,
uid,
@@ -860,7 +860,7 @@ export class AnalyticsController {
this.logger.log(`pidsArray: ${pidsArray}`, 'GET /analytics/hb')
- const validationPromises = _map(pidsArray, async currentPID => {
+ const validationPromises = _map(pidsArray, async (currentPID) => {
await this.analyticsService.checkProjectAccess(
currentPID,
uid,
@@ -872,12 +872,12 @@ export class AnalyticsController {
const result = {}
- const keyCountPromises = _map(pidsArray, async currentPID => {
+ const keyCountPromises = _map(pidsArray, async (currentPID) => {
result[currentPID] =
await this.analyticsService.getOnlineUserCount(currentPID)
})
- await Promise.all(keyCountPromises).catch(reason => {
+ await Promise.all(keyCountPromises).catch((reason) => {
this.logger.error(`[GET /analytics/hb] ${reason}`)
throw new InternalServerErrorException(
'An error occured while calculating heartbeat statistics',
@@ -954,7 +954,7 @@ export class AnalyticsController {
since,
},
})
- .then(resultSet => resultSet.json())
+ .then((resultSet) => resultSet.json())
return data
}
diff --git a/backend/apps/community/src/analytics/analytics.service.ts b/backend/apps/community/src/analytics/analytics.service.ts
index ccac045f4..a732493fd 100644
--- a/backend/apps/community/src/analytics/analytics.service.ts
+++ b/backend/apps/community/src/analytics/analytics.service.ts
@@ -519,7 +519,7 @@ export class AnalyticsService {
pid,
},
})
- .then(resultSet => resultSet.json())
+ .then((resultSet) => resultSet.json())
return _map(data, type)
}
@@ -544,9 +544,9 @@ export class AnalyticsService {
query,
query_params: { pid },
})
- .then(resultSet => resultSet.json<Record<string, string>[]>())
+ .then((resultSet) => resultSet.json<Record<string, string>[]>())
- return data.map(row => ({
+ return data.map((row) => ({
name: row[column],
version: row[safeVersionCol],
}))
@@ -683,7 +683,7 @@ export class AnalyticsService {
removeCyclicDependencies(links: IUserFlowLink[]): IUserFlowLink[] {
const visited = new Set<string>()
- return links.filter(link => {
+ return links.filter((link) => {
const key = `${link.source}_${link.target}`
if (visited.has(key)) {
return false
@@ -741,7 +741,7 @@ export class AnalyticsService {
query,
query_params: params,
})
- .then(res => res.json<IUserFlowLink>())
+ .then((res) => res.json<IUserFlowLink>())
if (_isEmpty(data)) {
const empty = { nodes: [], links: [] }
@@ -815,7 +815,7 @@ export class AnalyticsService {
)
}
- if (_some(pages, page => !_isString(page))) {
+ if (_some(pages, (page) => !_isString(page))) {
throw new UnprocessableEntityException(
'Pages array must contain string values only',
)
@@ -841,7 +841,7 @@ export class AnalyticsService {
query: `SELECT min(created) AS firstCreated FROM ${table} WHERE pid = {pid:FixedString(12)}`,
query_params: { pid },
})
- .then(res => res.json<{ firstCreated?: string }>())
+ .then((res) => res.json<{ firstCreated?: string }>())
const firstCreated = fromData?.[0]?.firstCreated
@@ -881,7 +881,7 @@ export class AnalyticsService {
const { column, filter, isExclusive, isContains = false } = curr
if (_isArray(filter)) {
- const filterArray = _map(filter, f => ({
+ const filterArray = _map(filter, (f) => ({
column,
filter: f,
isExclusive,
@@ -1061,7 +1061,7 @@ export class AnalyticsService {
`(domain(ref) != '' AND (lower(domain(ref)) = {${dp}:String} OR endsWith(lower(domain(ref)), concat('.', {${dp}:String})))) OR (domain(ref) = '' AND (lower(ref) = {${dp}:String} OR endsWith(lower(ref), concat('.', {${dp}:String}))))`,
)
}
- const combined = parts.map(p => `(${p})`).join(' OR ')
+ const combined = parts.map((p) => `(${p})`).join(' OR ')
query += isExclusive ? `NOT (${combined})` : `(${combined})`
continue
}
@@ -1137,9 +1137,7 @@ export class AnalyticsService {
}
} else {
query += isArrayDataset
- ? `indexOf(${sqlColumn}, {${param}:String}) ${
- isExclusive ? '=' : '>'
- } 0`
+ ? `indexOf(${sqlColumn}, {${param}:String}) ${isExclusive ? '=' : '>'} 0`
: `${isExclusive ? 'NOT ' : ''}${sqlColumn} = {${param}:String}`
}
}
@@ -1279,7 +1277,7 @@ export class AnalyticsService {
query,
query_params: { psid, pid },
})
- .then(resultSet =>
+ .then((resultSet) =>
resultSet.json<{
firstSeen: string | null
}>(),
@@ -1384,7 +1382,7 @@ export class AnalyticsService {
}
generateEmptyFunnel(pages: string[]): IFunnel[] {
- return _map(pages, value => ({
+ return _map(pages, (value) => ({
value,
events: 0,
eventsPerc: 0,
@@ -1447,7 +1445,7 @@ export class AnalyticsService {
query,
query_params: { ...params, ...pageParams },
})
- .then(resultSet => resultSet.json<IFunnelCHResponse>())
+ .then((resultSet) => resultSet.json<IFunnelCHResponse>())
if (_isEmpty(data)) {
return this.generateEmptyFunnel(pages)
@@ -1473,7 +1471,7 @@ export class AnalyticsService {
query,
query_params: { pid, groupFrom, groupTo },
})
- .then(resultSet => resultSet.json<{ c: number }>())
+ .then((resultSet) => resultSet.json<{ c: number }>())
return data[0]?.c || 0
}
@@ -1513,7 +1511,7 @@ export class AnalyticsService {
const [filtersQuery, filtersParams, , customEVFilterApplied] =
this.getFiltersQuery(filters, DataType.ANALYTICS)
- const promises = pids.map(async pid => {
+ const promises = pids.map(async (pid) => {
try {
if (period === 'all') {
let queryAll = `
@@ -1582,7 +1580,7 @@ export class AnalyticsService {
...filtersParams,
},
})
- .then(resultSet => resultSet.json<BirdseyeCHResponse>())
+ .then((resultSet) => resultSet.json<BirdseyeCHResponse>())
let bounceRate = 0
@@ -1814,7 +1812,7 @@ export class AnalyticsService {
...filtersParams,
},
})
- .then(resultSet => resultSet.json<BirdseyeCHResponse>())
+ .then((resultSet) => resultSet.json<BirdseyeCHResponse>())
data = _sortBy(data, 'sortOrder')
@@ -1933,7 +1931,7 @@ export class AnalyticsService {
query,
query_params: { ...paramsData.params, timezone: safeTimezone },
})
- .then(resultSet => resultSet.json<TrafficCEFilterCHResponse>())
+ .then((resultSet) => resultSet.json<TrafficCEFilterCHResponse>())
const visits =
this.extractCustomEventsChartData(data, xShifted)?._unknown_event || []
@@ -1952,7 +1950,7 @@ export class AnalyticsService {
query,
query_params: { ...paramsData.params, timezone: safeTimezone },
})
- .then(resultSet => resultSet.json<TrafficCHResponse>())
+ .then((resultSet) => resultSet.json<TrafficCHResponse>())
const { visits } = this.extractChartData(data, xShifted)
@@ -1998,10 +1996,10 @@ export class AnalyticsService {
const cols = ['dns', 'tls', 'conn', 'response', 'render', 'domLoad', 'ttfb']
const columnSelectors = cols
- .map(col => `${MEASURES_MAP[measure]}(${col}) as ${col}`)
+ .map((col) => `${MEASURES_MAP[measure]}(${col}) as ${col}`)
.join(', ')
- const promises = pids.map(async pid => {
+ const promises = pids.map(async (pid) => {
try {
if (period === 'all') {
const queryAll = `SELECT ${columnSelectors} FROM performance WHERE pid = {pid:FixedString(12)} ${filtersQuery}`
@@ -2013,7 +2011,9 @@ export class AnalyticsService {
...filtersParams,
},
})
- .then(resultSet => resultSet.json<Partial<PerformanceCHResponse>>())
+ .then((resultSet) =>
+ resultSet.json<Partial<PerformanceCHResponse>>(),
+ )
result[pid] = {
current: {
@@ -2080,7 +2080,7 @@ export class AnalyticsService {
...filtersParams,
},
})
- .then(resultSet => resultSet.json<Partial<PerformanceCHResponse>>())
+ .then((resultSet) => resultSet.json<Partial<PerformanceCHResponse>>())
data = _sortBy(data, 'sortOrder')
@@ -2174,7 +2174,7 @@ export class AnalyticsService {
query,
query_params: { pid },
})
- .then(resultSet => resultSet.json<any>())
+ .then((resultSet) => resultSet.json<any>())
return _map(data, 'page')
}
@@ -2193,7 +2193,7 @@ export class AnalyticsService {
pid,
},
})
- .then(resultSet => resultSet.json())
+ .then((resultSet) => resultSet.json())
return _map(data, type)
}
@@ -2212,7 +2212,7 @@ export class AnalyticsService {
: !_isEmpty(
_find(
parsedFilters,
- filter =>
+ (filter) =>
(filter.column === 'pg' || filter.column === 'host') &&
!filter.isExclusive,
),
@@ -2233,7 +2233,7 @@ export class AnalyticsService {
}
// Build a single query combining all metrics
- const withClauses = columns.map(col => {
+ const withClauses = columns.map((col) => {
const baseQuery = generateParamsQuery(
col,
subQuery,
@@ -2261,7 +2261,7 @@ export class AnalyticsService {
extra_fields
FROM (
${columns
- .map(col => {
+ .map((col) => {
let extraField = `CAST([] AS Array(Nullable(String))) as extra_fields`
if (col === 'rg') {
@@ -2293,9 +2293,9 @@ export class AnalyticsService {
query,
query_params: paramsData.params,
})
- .then(resultSet => resultSet.json<any>())
+ .then((resultSet) => resultSet.json<any>())
- const params = Object.fromEntries(columns.map(col => [col, []]))
+ const params = Object.fromEntries(columns.map((col) => [col, []]))
const { length } = data
@@ -2728,7 +2728,7 @@ export class AnalyticsService {
const cols = ['dns', 'tls', 'conn', 'response', 'render', 'domLoad', 'ttfb']
const columnSelectors = cols
- .map(col => `${MEASURES_MAP[measure]}(${col}) as ${col}`)
+ .map((col) => `${MEASURES_MAP[measure]}(${col}) as ${col}`)
.join(', ')
return `
@@ -2761,7 +2761,9 @@ export class AnalyticsService {
const cols = ['dns', 'tls', 'conn', 'response', 'render', 'domLoad', 'ttfb']
const columnSelectors = cols
- .map(col => `quantilesExactInclusive(0.5, 0.75, 0.95)(${col}) as ${col}`)
+ .map(
+ (col) => `quantilesExactInclusive(0.5, 0.75, 0.95)(${col}) as ${col}`,
+ )
.join(', ')
return `
@@ -2931,7 +2933,7 @@ export class AnalyticsService {
query,
query_params: paramsData.params,
})
- .then(resultSet => resultSet.json<any>())
+ .then((resultSet) => resultSet.json<any>())
return data || []
}
@@ -2961,7 +2963,7 @@ export class AnalyticsService {
query,
query_params: paramsData.params,
})
- .then(resultSet => resultSet.json<any>())
+ .then((resultSet) => resultSet.json<any>())
return data || []
}
@@ -3019,7 +3021,7 @@ export class AnalyticsService {
query,
query_params: { ...paramsData.params, timezone: safeTimezone },
})
- .then(resultSet => resultSet.json<TrafficCEFilterCHResponse>())
+ .then((resultSet) => resultSet.json<TrafficCEFilterCHResponse>())
const uniques =
this.extractCustomEventsChartData(data, xShifted)?._unknown_event || []
@@ -3047,7 +3049,7 @@ export class AnalyticsService {
query,
query_params: { ...paramsData.params, timezone: safeTimezone },
})
- .then(resultSet => resultSet.json<TrafficCHResponse>())
+ .then((resultSet) => resultSet.json<TrafficCHResponse>())
const { visits, uniques, sdur } = this.extractChartData(data, xShifted)
@@ -3180,19 +3182,19 @@ export class AnalyticsService {
query: pageviewsQuery,
query_params: queryParams,
})
- .then(resultSet => resultSet.json<any>()),
+ .then((resultSet) => resultSet.json<any>()),
clickhouse
.query({
query: customEventsQuery,
query_params: queryParams,
})
- .then(resultSet => resultSet.json<any>()),
+ .then((resultSet) => resultSet.json<any>()),
clickhouse
.query({
query: errorsQuery,
query_params: queryParams,
})
- .then(resultSet => resultSet.json<any>()),
+ .then((resultSet) => resultSet.json<any>()),
])
const pageviews = this.extractCountsForSessionChart(
@@ -3220,15 +3222,15 @@ export class AnalyticsService {
x: xShifted,
}
- if (_some(pageviews, count => count > 0)) {
+ if (_some(pageviews, (count) => count > 0)) {
chartOutput.pageviews = pageviews
}
- if (_some(customEvents, count => count > 0)) {
+ if (_some(customEvents, (count) => count > 0)) {
chartOutput.customEvents = customEvents
}
- if (_some(errors, count => count > 0)) {
+ if (_some(errors, (count) => count > 0)) {
chartOutput.errors = errors
}
@@ -3297,7 +3299,7 @@ export class AnalyticsService {
'errors',
)
- if (!_some(_values(params), val => !_isEmpty(val))) {
+ if (!_some(_values(params), (val) => !_isEmpty(val))) {
throw new BadRequestException(
'There are no error details for specified time frame',
)
@@ -3319,7 +3321,7 @@ export class AnalyticsService {
query,
query_params: paramsData.params,
})
- .then(resultSet => resultSet.json<TrafficCEFilterCHResponse>())
+ .then((resultSet) => resultSet.json<TrafficCEFilterCHResponse>())
const { count, affectedUsers } = this.extractErrorsChartData(data, x)
chart = {
@@ -3419,7 +3421,7 @@ export class AnalyticsService {
'captcha',
)
- if (!_some(_values(params), val => !_isEmpty(val))) {
+ if (!_some(_values(params), (val) => !_isEmpty(val))) {
throw new BadRequestException(
'There are no parameters for the specified time frames',
)
@@ -3446,7 +3448,7 @@ export class AnalyticsService {
query,
query_params: { ...paramsData.params, timezone: safeTimezone },
})
- .then(resultSet => resultSet.json<TrafficCEFilterCHResponse>())
+ .then((resultSet) => resultSet.json<TrafficCEFilterCHResponse>())
const { count } = this.extractCaptchaChartData(data, xShifted)
chart = {
@@ -3522,7 +3524,7 @@ export class AnalyticsService {
query,
query_params: { ...paramsData.params, timezone: safeTimezone },
})
- .then(resultSet => resultSet.json())
+ .then((resultSet) => resultSet.json())
return {
x: xShifted,
@@ -3541,7 +3543,7 @@ export class AnalyticsService {
query,
query_params: { ...paramsData.params, timezone: safeTimezone },
})
- .then(resultSet => resultSet.json<PerformanceCHResponse>())
+ .then((resultSet) => resultSet.json<PerformanceCHResponse>())
return {
x: xShifted,
@@ -3574,7 +3576,7 @@ export class AnalyticsService {
measure,
)
- if (!_some(_values(params), val => !_isEmpty(val))) {
+ if (!_some(_values(params), (val) => !_isEmpty(val))) {
throw new BadRequestException(
'There are no parameters for the specified time frames',
)
@@ -3615,7 +3617,7 @@ export class AnalyticsService {
query,
query_params: params.params,
})
- .then(resultSet => resultSet.json<CustomsCHResponse>())
+ .then((resultSet) => resultSet.json<CustomsCHResponse>())
const size = _size(data)
for (let i = 0; i < size; ++i) {
@@ -3653,7 +3655,7 @@ export class AnalyticsService {
query,
query_params: params.params,
})
- .then(resultSet => resultSet.json<PropertiesCHResponse>())
+ .then((resultSet) => resultSet.json<PropertiesCHResponse>())
const size = _size(data)
for (let i = 0; i < size; ++i) {
@@ -3750,7 +3752,7 @@ export class AnalyticsService {
query,
query_params: paramsData.params,
})
- .then(resultSet => resultSet.json<IAggregatedMetadata>())
+ .then((resultSet) => resultSet.json<IAggregatedMetadata>())
return {
result,
@@ -3852,7 +3854,7 @@ export class AnalyticsService {
query,
query_params: paramsData.params,
})
- .then(resultSet => resultSet.json<IAggregatedMetadata>())
+ .then((resultSet) => resultSet.json<IAggregatedMetadata>())
return {
result,
@@ -3898,7 +3900,7 @@ export class AnalyticsService {
since,
},
})
- .then(resultSet => resultSet.json<{ count: string }>())
+ .then((resultSet) => resultSet.json<{ count: string }>())
return Number(data[0]?.count || 0)
} catch (error) {
@@ -3955,7 +3957,7 @@ export class AnalyticsService {
customEvents: customEvents || [],
},
})
- .then(resultSet => resultSet.json<CustomsCHAggregatedResponse>())
+ .then((resultSet) => resultSet.json<CustomsCHAggregatedResponse>())
const events = this.extractCustomEventsChartData(data, xShifted)
@@ -4110,7 +4112,7 @@ export class AnalyticsService {
query: queryPages,
query_params: paramsData.params,
})
- .then(resultSet => resultSet.json<IPageflow>())
+ .then((resultSet) => resultSet.json<IPageflow>())
let details = (
await clickhouse
@@ -4118,7 +4120,7 @@ export class AnalyticsService {
query: querySessionDetails,
query_params: paramsData.params,
})
- .then(resultSet => resultSet.json())
+ .then((resultSet) => resultSet.json())
.then(({ data }) => data)
)[0] as any
@@ -4129,7 +4131,7 @@ export class AnalyticsService {
query: querySessionDuration,
query_params: paramsData.params,
})
- .then(resultSet =>
+ .then((resultSet) =>
resultSet.json<{
duration: number | null
lastSeen: string | null
@@ -4178,7 +4180,7 @@ export class AnalyticsService {
query: querySessionDetailsFromCustomEV,
query_params: paramsData.params,
})
- .then(resultSet => resultSet.json())
+ .then((resultSet) => resultSet.json())
.then(({ data }) => data)
)[0]
}
@@ -4405,7 +4407,7 @@ export class AnalyticsService {
skip,
},
})
- .then(resultSet => resultSet.json())
+ .then((resultSet) => resultSet.json())
return data
}
@@ -4475,7 +4477,7 @@ export class AnalyticsService {
skip,
},
})
- .then(resultSet => resultSet.json())
+ .then((resultSet) => resultSet.json())
return data
}
@@ -4574,21 +4576,21 @@ export class AnalyticsService {
query: queryErrorDetails,
query_params: paramsData.params,
})
- .then(resultSet => resultSet.json<any>())
+ .then((resultSet) => resultSet.json<any>())
.then(({ data }) => data[0]),
clickhouse
.query({
query: queryFirstLastSeen,
query_params: paramsData.params,
})
- .then(resultSet => resultSet.json<any>())
+ .then((resultSet) => resultSet.json<any>())
.then(({ data }) => data[0]),
clickhouse
.query({
query: queryMetadata,
query_params: paramsData.params,
})
- .then(resultSet => resultSet.json<IAggregatedMetadata>())
+ .then((resultSet) => resultSet.json<IAggregatedMetadata>())
.then(({ data }) => data),
])
@@ -4729,28 +4731,28 @@ export class AnalyticsService {
query: queryTotalSessions,
query_params: paramsData.params,
})
- .then(resultSet => resultSet.json<any>())
+ .then((resultSet) => resultSet.json<any>())
.then(({ data }) => data[0]),
clickhouse
.query({
query: queryErrorStats,
query_params: paramsWithTimezone,
})
- .then(resultSet => resultSet.json<any>())
+ .then((resultSet) => resultSet.json<any>())
.then(({ data }) => data[0]),
clickhouse
.query({
query: queryMostFrequentError,
query_params: paramsWithTimezone,
})
- .then(resultSet => resultSet.json<any>())
+ .then((resultSet) => resultSet.json<any>())
.then(({ data }) => data[0] || null),
clickhouse
.query({
query: queryChart,
query_params: paramsWithTimezone,
})
- .then(resultSet => resultSet.json<any>())
+ .then((resultSet) => resultSet.json<any>())
.then(({ data }) => data),
])
@@ -4848,11 +4850,11 @@ export class AnalyticsService {
const [countResult, sessionsResult] = await Promise.all([
clickhouse
.query({ query: queryCount, query_params: params })
- .then(resultSet => resultSet.json<any>())
+ .then((resultSet) => resultSet.json<any>())
.then(({ data }) => data[0]),
clickhouse
.query({ query: querySessions, query_params: params })
- .then(resultSet => resultSet.json<any>())
+ .then((resultSet) => resultSet.json<any>())
.then(({ data }) => data),
])
@@ -4895,7 +4897,7 @@ export class AnalyticsService {
query,
query_params: { ...params, pid },
})
- .then(resultSet => resultSet.json())
+ .then((resultSet) => resultSet.json())
.then(({ data }) => data)
)[0]
} catch (reason) {
@@ -4988,7 +4990,7 @@ export class AnalyticsService {
const results = []
await Promise.all(
- customEvents.map(async event => {
+ customEvents.map(async (event) => {
const result = await this.getMetaResult(
pid,
event,
@@ -5002,7 +5004,7 @@ export class AnalyticsService {
}),
)
- return results.filter(r => !!r)
+ return results.filter((r) => !!r)
}
async getMetaResult(
@@ -5122,7 +5124,7 @@ export class AnalyticsService {
query: `${queryCurrent} UNION ALL ${queryPrevious}`,
query_params: params,
})
- .then(resultSet =>
+ .then((resultSet) =>
resultSet.json<{
sortOrder: 1 | 2
key: string
@@ -5262,7 +5264,7 @@ export class AnalyticsService {
query,
query_params: { pid, ...paramsData.params, take, skip },
})
- .then(resultSet => resultSet.json())
+ .then((resultSet) => resultSet.json())
return data
.filter((profile: any) => profile.profileId)
@@ -5349,19 +5351,19 @@ export class AnalyticsService {
] = await Promise.all([
clickhouse
.query({ query: querySessionCount, query_params: params })
- .then(resultSet => resultSet.json()),
+ .then((resultSet) => resultSet.json()),
clickhouse
.query({ query: queryAvgDuration, query_params: params })
- .then(resultSet => resultSet.json()),
+ .then((resultSet) => resultSet.json()),
clickhouse
.query({ query: queryPageviews, query_params: params })
- .then(resultSet => resultSet.json()),
+ .then((resultSet) => resultSet.json()),
clickhouse
.query({ query: queryEvents, query_params: params })
- .then(resultSet => resultSet.json()),
+ .then((resultSet) => resultSet.json()),
clickhouse
.query({ query: queryDetails, query_params: params })
- .then(resultSet => resultSet.json()),
+ .then((resultSet) => resultSet.json()),
])
const sessionCount = (sessionCountResult.data[0] || {}) as Record<
@@ -5408,7 +5410,7 @@ export class AnalyticsService {
query,
query_params: { pid, profileId, limit: Number(limit) },
})
- .then(resultSet => resultSet.json())
+ .then((resultSet) => resultSet.json())
return data as { page: string; count: number }[]
}
@@ -5441,7 +5443,7 @@ export class AnalyticsService {
query,
query_params: { pid, profileId, startDate },
})
- .then(resultSet => resultSet.json())
+ .then((resultSet) => resultSet.json())
return data as { date: string; count: number }[]
}
@@ -5503,13 +5505,13 @@ export class AnalyticsService {
const [pageviewsResult, eventsResult, errorsResult] = await Promise.all([
clickhouse
.query({ query: queryPageviews, query_params: params })
- .then(resultSet => resultSet.json()),
+ .then((resultSet) => resultSet.json()),
clickhouse
.query({ query: queryEvents, query_params: params })
- .then(resultSet => resultSet.json()),
+ .then((resultSet) => resultSet.json()),
clickhouse
.query({ query: queryErrors, query_params: params })
- .then(resultSet => resultSet.json()),
+ .then((resultSet) => resultSet.json()),
])
// Merge all timestamps and create aligned data
@@ -5546,9 +5548,9 @@ export class AnalyticsService {
return {
x: sortedTimes,
- pageviews: sortedTimes.map(t => pageviewsMap.get(t) || 0),
- customEvents: sortedTimes.map(t => eventsMap.get(t) || 0),
- errors: sortedTimes.map(t => errorsMap.get(t) || 0),
+ pageviews: sortedTimes.map((t) => pageviewsMap.get(t) || 0),
+ customEvents: sortedTimes.map((t) => eventsMap.get(t) || 0),
+ errors: sortedTimes.map((t) => errorsMap.get(t) || 0),
}
}
@@ -5661,7 +5663,7 @@ export class AnalyticsService {
skip,
},
})
- .then(resultSet => resultSet.json())
+ .then((resultSet) => resultSet.json())
return data as object[]
}
diff --git a/backend/apps/community/src/analytics/decorators/validate-project-ids.decorator.ts b/backend/apps/community/src/analytics/decorators/validate-project-ids.decorator.ts
index c7048ef44..29abc118b 100644
--- a/backend/apps/community/src/analytics/decorators/validate-project-ids.decorator.ts
+++ b/backend/apps/community/src/analytics/decorators/validate-project-ids.decorator.ts
@@ -26,7 +26,7 @@ export function ValidateProjectIds(validationOptions?: ValidationOptions) {
return false
}
- return value.every(pid => PID_REGEX.test(pid))
+ return value.every((pid) => PID_REGEX.test(pid))
},
defaultMessage() {
return 'One of the provided Project IDs (pids) is incorrect'
diff --git a/backend/apps/community/src/analytics/dto/events.dto.ts b/backend/apps/community/src/analytics/dto/events.dto.ts
index 92089a249..769d5d8e5 100644
--- a/backend/apps/community/src/analytics/dto/events.dto.ts
+++ b/backend/apps/community/src/analytics/dto/events.dto.ts
@@ -75,7 +75,7 @@ export class MetadataValueType implements ValidatorConstraintInterface {
validate(metadata: Record<string, string>) {
const values = _values(metadata)
- return !_some(values, value => typeof value !== 'string')
+ return !_some(values, (value) => typeof value !== 'string')
}
}
diff --git a/backend/apps/community/src/analytics/dto/get-heartbeat-stats.ts b/backend/apps/community/src/analytics/dto/get-heartbeat-stats.ts
index d073b574d..cedec1e31 100644
--- a/backend/apps/community/src/analytics/dto/get-heartbeat-stats.ts
+++ b/backend/apps/community/src/analytics/dto/get-heartbeat-stats.ts
@@ -5,13 +5,13 @@ import { ValidateProjectIds } from '../decorators/validate-project-ids.decorator
export class GetHeartbeatStatsDto {
@ApiProperty({ description: 'Array of project IDs', required: false })
- @ValidateIf(o => o.pids || !o.pid)
+ @ValidateIf((o) => o.pids || !o.pid)
@IsOptional()
@ValidateProjectIds()
pids?: string[]
@ApiProperty({ description: 'Single project ID', required: false })
- @ValidateIf(o => !o.pids || o.pid)
+ @ValidateIf((o) => !o.pids || o.pid)
@IsOptional()
@Matches(PID_REGEX, { message: 'The provided Project ID (pid) is incorrect' })
pid?: string
diff --git a/backend/apps/community/src/analytics/dto/get-overall-stats.dto.ts b/backend/apps/community/src/analytics/dto/get-overall-stats.dto.ts
index 92104b02d..d6730606c 100644
--- a/backend/apps/community/src/analytics/dto/get-overall-stats.dto.ts
+++ b/backend/apps/community/src/analytics/dto/get-overall-stats.dto.ts
@@ -14,13 +14,13 @@ import { ValidateProjectIds } from '../decorators/validate-project-ids.decorator
export class GetOverallStatsDto {
@ApiProperty({ description: 'Array of project IDs', required: false })
- @ValidateIf(o => o.pids || !o.pid)
+ @ValidateIf((o) => o.pids || !o.pid)
@IsOptional()
@ValidateProjectIds()
pids?: string[]
@ApiProperty({ description: 'Single project ID', required: false })
- @ValidateIf(o => !o.pids || o.pid)
+ @ValidateIf((o) => !o.pids || o.pid)
@IsOptional()
@Matches(PID_REGEX, { message: 'The provided Project ID (pid) is incorrect' })
pid?: string
diff --git a/backend/apps/community/src/analytics/dto/patch-status.dto.ts b/backend/apps/community/src/analytics/dto/patch-status.dto.ts
index 44a8dc921..94c0984fa 100644
--- a/backend/apps/community/src/analytics/dto/patch-status.dto.ts
+++ b/backend/apps/community/src/analytics/dto/patch-status.dto.ts
@@ -25,7 +25,7 @@ export class PatchStatusDto {
example: 'c138c2b1826d9fec65d230e471ab2c25',
description: 'Error id',
})
- @ValidateIf(o => !o.eids || o.eid)
+ @ValidateIf((o) => !o.eids || o.eid)
@IsNotEmpty()
@IsString()
eid: string
@@ -37,7 +37,7 @@ export class PatchStatusDto {
],
description: 'Error id list',
})
- @ValidateIf(o => o.eids || !o.eid)
+ @ValidateIf((o) => o.eids || !o.eid)
@IsNotEmpty()
@IsArray()
@IsString({ each: true })
diff --git a/backend/apps/community/src/analytics/utils/referrers.map.ts b/backend/apps/community/src/analytics/utils/referrers.map.ts
index d77afd773..ac8d4b40b 100644
--- a/backend/apps/community/src/analytics/utils/referrers.map.ts
+++ b/backend/apps/community/src/analytics/utils/referrers.map.ts
@@ -31,7 +31,7 @@ const loadMap = (): ReferrerJson[] => {
export const getDomainsForRefName = (name: string): string[] | null => {
const list = loadMap()
- const found = list.find(g => g.name.toLowerCase() === name.toLowerCase())
+ const found = list.find((g) => g.name.toLowerCase() === name.toLowerCase())
if (!found) return null
return found.patterns
}
diff --git a/backend/apps/community/src/auth/auth.controller.ts b/backend/apps/community/src/auth/auth.controller.ts
index 225418e84..20a164eb2 100644
--- a/backend/apps/community/src/auth/auth.controller.ts
+++ b/backend/apps/community/src/auth/auth.controller.ts
@@ -216,7 +216,9 @@ export class AuthController {
await this.mailerService.sendEmail(
user.email,
LetterTemplate.MailAddressChangeConfirmation,
- { url },
+ {
+ url,
+ },
)
}
@ApiOperation({ summary: 'Request a password reset' })
diff --git a/backend/apps/community/src/auth/auth.service.ts b/backend/apps/community/src/auth/auth.service.ts
index 5aa4bf487..8bf376f61 100644
--- a/backend/apps/community/src/auth/auth.service.ts
+++ b/backend/apps/community/src/auth/auth.service.ts
@@ -48,7 +48,7 @@ export class AuthService {
) {}
private async createSha1Hash(text: string): Promise<string> {
- return new Promise(resolve => {
+ return new Promise((resolve) => {
const sha1sum = createHash('sha1')
.update(text)
.digest('hex')
diff --git a/backend/apps/community/src/common/templates/en/customer_project-invitation.html b/backend/apps/community/src/common/templates/en/customer_project-invitation.html
index c5511765f..5d58b36ba 100644
--- a/backend/apps/community/src/common/templates/en/customer_project-invitation.html
+++ b/backend/apps/community/src/common/templates/en/customer_project-invitation.html
@@ -1,3 +1,5 @@
-<a href="mailto:{{email}}">{{email}}</a> has invited you to the {{name}} website analytics dashboard with the role {{role}} on their Swetrix Community Edition instance.
-<br/>
-You can accept or decline the invitation in your dashboard.
+<a href="mailto:{{email}}">{{email}}</a> has invited you to the {{name}} website
+analytics dashboard with the role {{role}} on their Swetrix Community Edition
+instance.
+<br />
+You can accept or decline the invitation in your dashboard.
diff --git a/backend/apps/community/src/common/templates/en/mailaddress-change_confirmation.html b/backend/apps/community/src/common/templates/en/mailaddress-change_confirmation.html
index f89051abb..3d81afae0 100644
--- a/backend/apps/community/src/common/templates/en/mailaddress-change_confirmation.html
+++ b/backend/apps/community/src/common/templates/en/mailaddress-change_confirmation.html
@@ -1,9 +1,11 @@
-You have requested a change of your email address at the Swetrix Community Edition instance.
-<br/>
-The new email will only be applied after you have confirmed this action by clicking the link below.
-<br/>
-<br/>
+You have requested a change of your email address at the Swetrix Community
+Edition instance.
+<br />
+The new email will only be applied after you have confirmed this action by
+clicking the link below.
+<br />
+<br />
<a href="{{url}}" target="_blank">Confirm email update.</a>
-<br/>
-<br/>
+<br />
+<br />
If you have not changed your email, please ignore this email.
diff --git a/backend/apps/community/src/common/templates/en/password-change_confirmation.html b/backend/apps/community/src/common/templates/en/password-change_confirmation.html
index bb40efcbf..e9bd220da 100644
--- a/backend/apps/community/src/common/templates/en/password-change_confirmation.html
+++ b/backend/apps/community/src/common/templates/en/password-change_confirmation.html
@@ -1,7 +1,8 @@
You have changed your password at the Swetrix Community Edition instance.
-<br/>
-The new password will only be applied after you have confirmed this action by clicking the link below.
+<br />
+The new password will only be applied after you have confirmed this action by
+clicking the link below.
<a href="{{url}}" target="_blank">Confirm password change</a>
-<br/>
-<br/>
+<br />
+<br />
If you have not changed your password, please ignore this email.
diff --git a/backend/apps/community/src/common/utils.ts b/backend/apps/community/src/common/utils.ts
index c6f9ba5f8..31d376416 100644
--- a/backend/apps/community/src/common/utils.ts
+++ b/backend/apps/community/src/common/utils.ts
@@ -181,7 +181,7 @@ const getFunnelClickhouse = async (
query,
query_params: queryParams,
})
- .then(resultSet => resultSet.json<ClickhouseFunnel>())
+ .then((resultSet) => resultSet.json<ClickhouseFunnel>())
if (_isEmpty(data)) {
throw new NotFoundException(
@@ -207,7 +207,7 @@ const getFunnelsClickhouse = async (
query,
query_params: queryParams,
})
- .then(resultSet => resultSet.json<ClickhouseFunnel>())
+ .then((resultSet) => resultSet.json<ClickhouseFunnel>())
return data
}
@@ -225,7 +225,7 @@ const deleteAllRefreshTokensClickhouse = async (userId: string) => {
const updateFunnelClickhouse = async (funnel: any) => {
const filtered = _reduce(
- _filter(_keys(funnel), key => ALLOWED_FUNNEL_KEYS.includes(key)),
+ _filter(_keys(funnel), (key) => ALLOWED_FUNNEL_KEYS.includes(key)),
(obj, key) => {
obj[key] = funnel[key]
return obj
@@ -240,7 +240,7 @@ const updateFunnelClickhouse = async (funnel: any) => {
const params: Record<string, string> = { id: funnel.id }
- const assignments = _map(columns, col => {
+ const assignments = _map(columns, (col) => {
params[col] = filtered[col]
return `${col}={${col}:String}`
}).join(', ')
@@ -292,7 +292,7 @@ const getProjectClickhouse = async (id: string): Promise<Project> => {
id,
},
})
- .then(resultSet => resultSet.json<Project>())
+ .then((resultSet) => resultSet.json<Project>())
if (_isEmpty(data)) {
throw new NotFoundException(`Project ${id} was not found in the database`)
@@ -343,7 +343,7 @@ const getProjectsClickhouse = async (
adminId,
},
})
- .then(resultSet => resultSet.json<Project>())
+ .then((resultSet) => resultSet.json<Project>())
return data
}
@@ -365,7 +365,7 @@ const getProjectsClickhouse = async (
adminId,
},
})
- .then(resultSet => resultSet.json<Project>())
+ .then((resultSet) => resultSet.json<Project>())
return data
}
@@ -379,7 +379,7 @@ const updateProjectClickhouse = async (
: ALLOWED_KEYS
const filtered = _reduce(
- _filter(_keys(project), key => updatableKeys.includes(key)),
+ _filter(_keys(project), (key) => updatableKeys.includes(key)),
(obj, key) => {
obj[key] = project[key]
return obj
@@ -396,7 +396,7 @@ const updateProjectClickhouse = async (
const UINT8_COLUMNS = ['captchaDifficulty']
const params: Record<string, any> = { id: project.id }
- const assignments = _map(columns, col => {
+ const assignments = _map(columns, (col) => {
params[col] = filtered[col]
let type = 'String'
if (INT8_COLUMNS.includes(col)) {
@@ -494,7 +494,7 @@ const findProjectShareClickhouse = async (
query: `SELECT * FROM project_share WHERE id = {id:FixedString(36)}`,
query_params: { id },
})
- .then(resultSet => resultSet.json<ClickhouseProjectShare>())
+ .then((resultSet) => resultSet.json<ClickhouseProjectShare>())
if (_isEmpty(data)) {
return null
@@ -527,7 +527,7 @@ const findProjectSharesByProjectClickhouse = async (
`,
query_params: { projectId },
})
- .then(resultSet => resultSet.json<ClickhouseProjectShareWithUser>())
+ .then((resultSet) => resultSet.json<ClickhouseProjectShareWithUser>())
return data
} catch {
@@ -568,7 +568,7 @@ const findProjectSharesByUserClickhouse = async (
`,
query_params: { userId, search: `%${search}%` },
})
- .then(resultSet => resultSet.json<ClickhouseProjectShareWithProject>())
+ .then((resultSet) => resultSet.json<ClickhouseProjectShareWithProject>())
return data
} catch {
@@ -590,7 +590,7 @@ const findProjectShareByUserAndProjectClickhouse = async (
`,
query_params: { userId, projectId },
})
- .then(resultSet => resultSet.json<ClickhouseProjectShare>())
+ .then((resultSet) => resultSet.json<ClickhouseProjectShare>())
if (_isEmpty(data)) {
return null
@@ -635,7 +635,7 @@ const updateProjectShareClickhouse = async (
update: Partial<{ role: string; confirmed: number }>,
) => {
const filtered = _reduce(
- _filter(_keys(update), key => ALLOWED_SHARE_KEYS.includes(key)),
+ _filter(_keys(update), (key) => ALLOWED_SHARE_KEYS.includes(key)),
(obj, key) => {
obj[key] = update[key]
return obj
@@ -713,7 +713,7 @@ const findRefreshTokenClickhouse = async (
refreshToken,
},
})
- .then(resultSet => resultSet.json())
+ .then((resultSet) => resultSet.json())
return data
}
@@ -743,7 +743,7 @@ const findProjectViewCustomEventsClickhouse = async (viewId: string) => {
viewId,
},
})
- .then(resultSet => resultSet.json())
+ .then((resultSet) => resultSet.json())
return data
} catch {
@@ -772,7 +772,7 @@ const doesProjectViewExistClickhouse = async (
projectId,
},
})
- .then(resultSet => resultSet.json<{ count: number }>())
+ .then((resultSet) => resultSet.json<{ count: number }>())
if (_isEmpty(data)) {
return false
@@ -802,7 +802,7 @@ const findProjectViewClickhouse = async (id: string, projectId: string) => {
projectId,
},
})
- .then(resultSet => resultSet.json())
+ .then((resultSet) => resultSet.json())
if (_isEmpty(data)) {
return null
@@ -836,7 +836,7 @@ const findProjectViewsClickhouse = async (projectId: string) => {
projectId,
},
})
- .then(resultSet => resultSet.json())
+ .then((resultSet) => resultSet.json())
if (_isEmpty(data)) {
return []
@@ -964,7 +964,7 @@ const getAnnotationsClickhouse = async (
query,
query_params: queryParams,
})
- .then(resultSet => resultSet.json<ClickhouseAnnotation>())
+ .then((resultSet) => resultSet.json<ClickhouseAnnotation>())
return data
}
@@ -991,7 +991,7 @@ const getAnnotationClickhouse = async (
query,
query_params: queryParams,
})
- .then(resultSet => resultSet.json<ClickhouseAnnotation>())
+ .then((resultSet) => resultSet.json<ClickhouseAnnotation>())
if (_isEmpty(data)) {
return null
@@ -1028,7 +1028,7 @@ const updateAnnotationClickhouse = async (annotation: {
const filtered = _reduce(
_filter(
_keys(annotation),
- key => ALLOWED_ANNOTATION_KEYS.includes(key) && annotation[key] != null,
+ (key) => ALLOWED_ANNOTATION_KEYS.includes(key) && annotation[key] != null,
),
(obj, key) => {
obj[key] = annotation[key]
@@ -1044,7 +1044,7 @@ const updateAnnotationClickhouse = async (annotation: {
const params: Record<string, string> = { id: annotation.id }
- const assignments = _map(columns, col => {
+ const assignments = _map(columns, (col) => {
params[col] = filtered[col]
const type = col === 'date' ? 'Date' : 'String'
return `${col}={${col}:${type}}`
@@ -1200,9 +1200,9 @@ const getPinnedProjectsClickhouse = async (
query,
query_params: { visitorId },
})
- .then(resultSet => resultSet.json<{ projectId: string }>())
+ .then((resultSet) => resultSet.json<{ projectId: string }>())
- return _map(data, row => row.projectId)
+ return _map(data, (row) => row.projectId)
}
const pinProjectClickhouse = async (
@@ -1250,7 +1250,7 @@ const getSaltClickhouse = async (
query,
query_params: { rotation },
})
- .then(resultSet => resultSet.json<ClickhouseSalt>())
+ .then((resultSet) => resultSet.json<ClickhouseSalt>())
return _head(data) || null
} catch {
diff --git a/backend/apps/community/src/feature-flag/feature-flag.controller.ts b/backend/apps/community/src/feature-flag/feature-flag.controller.ts
index a2ac4e062..f67911628 100644
--- a/backend/apps/community/src/feature-flag/feature-flag.controller.ts
+++ b/backend/apps/community/src/feature-flag/feature-flag.controller.ts
@@ -101,7 +101,7 @@ export class FeatureFlagController {
search,
)
- result.results = _map(result.results, flag => ({
+ result.results = _map(result.results, (flag) => ({
...flag,
pid: flag.projectId,
})) as any
@@ -284,7 +284,7 @@ export class FeatureFlagController {
flags,
evaluatedFlags,
profileId,
- ).catch(err => {
+ ).catch((err) => {
this.logger.error({ err }, 'Failed to track flag evaluations')
})
@@ -301,7 +301,7 @@ export class FeatureFlagController {
const now = new Date().toISOString().slice(0, 19).replace('T', ' ')
- const values = flags.map(flag => ({
+ const values = flags.map((flag) => ({
pid,
flagId: flag.id,
flagKey: flag.key,
@@ -474,7 +474,7 @@ export class FeatureFlagController {
try {
const { data } = await clickhouse
.query({ query: statsQuery, query_params: queryParams })
- .then(resultSet =>
+ .then((resultSet) =>
resultSet.json<{
evaluations: number
profileCount: number
@@ -617,7 +617,7 @@ export class FeatureFlagController {
const [profilesResult, countResult] = await Promise.all([
clickhouse
.query({ query: profilesQuery, query_params: queryParams })
- .then(resultSet =>
+ .then((resultSet) =>
resultSet.json<{
profileId: string
lastEvaluated: string
@@ -627,10 +627,10 @@ export class FeatureFlagController {
),
clickhouse
.query({ query: countQuery, query_params: queryParams })
- .then(resultSet => resultSet.json<{ total: number }>()),
+ .then((resultSet) => resultSet.json<{ total: number }>()),
])
- const profiles = profilesResult.data.map(row => ({
+ const profiles = profilesResult.data.map((row) => ({
profileId: row.profileId,
isIdentified: row.profileId.startsWith('usr_'),
lastResult: row.lastResult === 1,
diff --git a/backend/apps/community/src/feature-flag/feature-flag.service.ts b/backend/apps/community/src/feature-flag/feature-flag.service.ts
index a7432ea72..f68c05a8a 100644
--- a/backend/apps/community/src/feature-flag/feature-flag.service.ts
+++ b/backend/apps/community/src/feature-flag/feature-flag.service.ts
@@ -96,7 +96,7 @@ export class FeatureFlagService {
query,
query_params: { id },
})
- .then(resultSet => resultSet.json<ClickhouseFeatureFlag>())
+ .then((resultSet) => resultSet.json<ClickhouseFeatureFlag>())
if (_isEmpty(data)) {
return null
@@ -119,7 +119,7 @@ export class FeatureFlagService {
query,
query_params: { projectId, key },
})
- .then(resultSet => resultSet.json<ClickhouseFeatureFlag>())
+ .then((resultSet) => resultSet.json<ClickhouseFeatureFlag>())
if (_isEmpty(data)) {
return null
@@ -140,9 +140,9 @@ export class FeatureFlagService {
query,
query_params: { projectId },
})
- .then(resultSet => resultSet.json<ClickhouseFeatureFlag>())
+ .then((resultSet) => resultSet.json<ClickhouseFeatureFlag>())
- return _map(data, flag => this.formatFlagFromClickhouse(flag)).filter(
+ return _map(data, (flag) => this.formatFlagFromClickhouse(flag)).filter(
(flag): flag is FeatureFlag => flag !== null,
)
}
@@ -160,9 +160,9 @@ export class FeatureFlagService {
query,
query_params: { projectId },
})
- .then(resultSet => resultSet.json<ClickhouseFeatureFlag>())
+ .then((resultSet) => resultSet.json<ClickhouseFeatureFlag>())
- return _map(data, flag => this.formatFlagFromClickhouse(flag)).filter(
+ return _map(data, (flag) => this.formatFlagFromClickhouse(flag)).filter(
(flag): flag is FeatureFlag => flag !== null,
)
}
@@ -213,17 +213,17 @@ export class FeatureFlagService {
query: countQuery,
query_params: queryParams,
})
- .then(resultSet => resultSet.json<{ total: number }>()),
+ .then((resultSet) => resultSet.json<{ total: number }>()),
clickhouse
.query({
query: dataQuery,
query_params: queryParams,
})
- .then(resultSet => resultSet.json<ClickhouseFeatureFlag>()),
+ .then((resultSet) => resultSet.json<ClickhouseFeatureFlag>()),
])
const total = countResult.data[0]?.total || 0
- const results = _map(dataResult.data, flag =>
+ const results = _map(dataResult.data, (flag) =>
this.formatFlagFromClickhouse(flag),
).filter((flag): flag is FeatureFlag => flag !== null)
@@ -245,7 +245,7 @@ export class FeatureFlagService {
query,
query_params: { projectId },
})
- .then(resultSet => resultSet.json<{ total: number }>())
+ .then((resultSet) => resultSet.json<{ total: number }>())
return data[0]?.total || 0
}
@@ -314,7 +314,7 @@ export class FeatureFlagService {
const filtered = _reduce(
_filter(
_keys(flagData),
- key =>
+ (key) =>
ALLOWED_FLAG_KEYS.includes(key) &&
flagData[key as keyof FeatureFlag] !== undefined,
),
@@ -337,7 +337,7 @@ export class FeatureFlagService {
const params: Record<string, any> = { id }
- const assignments = _map(columns, col => {
+ const assignments = _map(columns, (col) => {
const value = formattedData[col as keyof ClickhouseFeatureFlag]
params[col] = value
diff --git a/backend/apps/community/src/goal/goal.controller.ts b/backend/apps/community/src/goal/goal.controller.ts
index 00d55317a..0d9e12b71 100644
--- a/backend/apps/community/src/goal/goal.controller.ts
+++ b/backend/apps/community/src/goal/goal.controller.ts
@@ -128,7 +128,7 @@ export class GoalController {
return {
...result,
- results: _map(result.results, goal => ({
+ results: _map(result.results, (goal) => ({
...goal,
pid: goal.projectId,
})),
@@ -376,7 +376,7 @@ export class GoalController {
const { data: conversionsData } = await clickhouse
.query({ query: conversionsQuery, query_params: queryParams })
- .then(resultSet =>
+ .then((resultSet) =>
resultSet.json<{ conversions: number; uniqueSessions: number }>(),
)
@@ -401,7 +401,7 @@ export class GoalController {
groupTo: groupToUTC,
},
})
- .then(resultSet => resultSet.json<{ totalSessions: number }>())
+ .then((resultSet) => resultSet.json<{ totalSessions: number }>())
const totalSessions = totalData[0]?.totalSessions || 1
const conversionRate = _round((uniqueSessions / totalSessions) * 100, 2)
@@ -423,7 +423,7 @@ export class GoalController {
const { data: previousData } = await clickhouse
.query({ query: conversionsQuery, query_params: previousQueryParams })
- .then(resultSet =>
+ .then((resultSet) =>
resultSet.json<{ conversions: number; uniqueSessions: number }>(),
)
@@ -610,7 +610,7 @@ export class GoalController {
const { data } = await clickhouse
.query({ query: chartQuery, query_params: queryParams })
- .then(resultSet =>
+ .then((resultSet) =>
resultSet.json<{
year: number
month?: number
diff --git a/backend/apps/community/src/goal/goal.service.ts b/backend/apps/community/src/goal/goal.service.ts
index 5269b463c..7c36aa063 100644
--- a/backend/apps/community/src/goal/goal.service.ts
+++ b/backend/apps/community/src/goal/goal.service.ts
@@ -83,7 +83,7 @@ export class GoalService {
query,
query_params: { id },
})
- .then(resultSet => resultSet.json<ClickhouseGoal>())
+ .then((resultSet) => resultSet.json<ClickhouseGoal>())
if (_isEmpty(data)) {
return null
@@ -109,9 +109,9 @@ export class GoalService {
query,
query_params: { projectId },
})
- .then(resultSet => resultSet.json<ClickhouseGoal>())
+ .then((resultSet) => resultSet.json<ClickhouseGoal>())
- return _map(data, goal => this.formatGoalFromClickhouse(goal))
+ return _map(data, (goal) => this.formatGoalFromClickhouse(goal))
}
async paginate(
@@ -157,17 +157,17 @@ export class GoalService {
query: countQuery,
query_params: queryParams,
})
- .then(resultSet => resultSet.json<{ total: number }>()),
+ .then((resultSet) => resultSet.json<{ total: number }>()),
clickhouse
.query({
query: dataQuery,
query_params: queryParams,
})
- .then(resultSet => resultSet.json<ClickhouseGoal>()),
+ .then((resultSet) => resultSet.json<ClickhouseGoal>()),
])
const total = countResult.data[0]?.total || 0
- const results = _map(dataResult.data, goal =>
+ const results = _map(dataResult.data, (goal) =>
this.formatGoalFromClickhouse(goal),
)
@@ -189,7 +189,7 @@ export class GoalService {
query,
query_params: { projectId },
})
- .then(resultSet => resultSet.json<{ total: number }>())
+ .then((resultSet) => resultSet.json<{ total: number }>())
return data[0]?.total || 0
}
@@ -228,7 +228,7 @@ export class GoalService {
const filtered = _reduce(
_filter(
_keys(goalData),
- key =>
+ (key) =>
ALLOWED_GOAL_KEYS.includes(key) &&
goalData[key as keyof Goal] !== undefined,
),
@@ -249,7 +249,7 @@ export class GoalService {
const params: Record<string, any> = { id }
- const assignments = _map(columns, col => {
+ const assignments = _map(columns, (col) => {
const value = formattedData[col as keyof ClickhouseGoal]
params[col] = value
diff --git a/backend/apps/community/src/mailer/mailer.service.ts b/backend/apps/community/src/mailer/mailer.service.ts
index 6a91bcf0f..ff8ccbb07 100644
--- a/backend/apps/community/src/mailer/mailer.service.ts
+++ b/backend/apps/community/src/mailer/mailer.service.ts
@@ -111,7 +111,7 @@ export class MailerService {
mxRecords.sort((a, b) => a.priority - b.priority)
const targets = mxRecords.length
- ? mxRecords.map(mx => mx.exchange)
+ ? mxRecords.map((mx) => mx.exchange)
: [domain]
for (const host of targets) {
diff --git a/backend/apps/community/src/project/dto/project-password.dto.ts b/backend/apps/community/src/project/dto/project-password.dto.ts
index d49e2d58b..833870670 100644
--- a/backend/apps/community/src/project/dto/project-password.dto.ts
+++ b/backend/apps/community/src/project/dto/project-password.dto.ts
@@ -18,6 +18,6 @@ export class ProjectPasswordDto {
password?: string | null
@IsOptional()
- @ValidateIf(o => o.isPasswordProtected !== null)
+ @ValidateIf((o) => o.isPasswordProtected !== null)
isPasswordProtected?: boolean | null
}
diff --git a/backend/apps/community/src/project/project.controller.ts b/backend/apps/community/src/project/project.controller.ts
index 4899d9a6c..5ddca3a6e 100644
--- a/backend/apps/community/src/project/project.controller.ts
+++ b/backend/apps/community/src/project/project.controller.ts
@@ -187,17 +187,17 @@ export class ProjectController {
// 3) Combine owned and shared projects, remove duplicates (prefer owned)
const combinedProjectsMap: Record<string, Project> = {}
- _map(ownedProjects, p => {
+ _map(ownedProjects, (p) => {
combinedProjectsMap[p.id] = p
})
- _map(sharedProjects, p => {
+ _map(sharedProjects, (p) => {
if (!combinedProjectsMap[p.id]) {
combinedProjectsMap[p.id] = p
}
})
- let combinedProjects = _map(combinedProjectsMap, p => p)
+ let combinedProjects = _map(combinedProjectsMap, (p) => p)
// Get pinned project IDs to mark shared projects as pinned too
const pinnedProjectIds = await getPinnedProjectsClickhouse(userId)
@@ -248,7 +248,7 @@ export class ProjectController {
await this.projectService.getPIDsWhereErrorsDataExists(paginatedPids)
const funnelsData = await Promise.allSettled(
- pidsWithData.map(async pid => {
+ pidsWithData.map(async (pid) => {
return {
pid,
data: await getFunnelsClickhouse(pid),
@@ -274,7 +274,7 @@ export class ProjectController {
{},
)
- const results = _map(paginatedProjects, project => {
+ const results = _map(paginatedProjects, (project) => {
const userShare = sharesByProjectId[project.id]
const isOwner = userId && project.adminId === userId
const role = isOwner
diff --git a/backend/apps/community/src/project/project.service.ts b/backend/apps/community/src/project/project.service.ts
index 05ee95729..1d04b3274 100644
--- a/backend/apps/community/src/project/project.service.ts
+++ b/backend/apps/community/src/project/project.service.ts
@@ -202,7 +202,7 @@ export class ProjectService {
uid === project.adminId ||
_findIndex(
project.share,
- share =>
+ (share) =>
share.user?.id === uid &&
share.role === Role.admin &&
share.confirmed === true,
@@ -285,7 +285,7 @@ export class ProjectService {
query,
query_params: params,
})
- .then(resultSet => resultSet.json<{ pid: string }>())
+ .then((resultSet) => resultSet.json<{ pid: string }>())
return _map(data, ({ pid }) => pid)
}
@@ -334,7 +334,7 @@ export class ProjectService {
query,
query_params: params,
})
- .then(resultSet => resultSet.json<{ pid: string }>())
+ .then((resultSet) => resultSet.json<{ pid: string }>())
return _map(data, ({ pid }) => pid)
}
@@ -383,7 +383,7 @@ export class ProjectService {
query,
query_params: params,
})
- .then(resultSet => resultSet.json<{ pid: string }>())
+ .then((resultSet) => resultSet.json<{ pid: string }>())
return _map(data, ({ pid }) => pid)
}
@@ -408,7 +408,7 @@ export class ProjectService {
}
await Promise.all(
- _map(queries, query =>
+ _map(queries, (query) =>
clickhouse.command({
query,
query_params: params,
@@ -513,7 +513,7 @@ export class ProjectService {
return []
}
- return _map(customEvents, customEvent =>
+ return _map(customEvents, (customEvent) =>
this.formatCustomEventToClickhose(viewId, customEvent),
)
}
@@ -563,7 +563,7 @@ export class ProjectService {
updView.filters = []
}
- updView.customEvents = _map(view.customEvents, customEvent => ({
+ updView.customEvents = _map(view.customEvents, (customEvent) => ({
...customEvent,
createdAt: '1970-01-01T00:00:00.000Z',
updatedAt: '1970-01-01T00:00:00.000Z',
@@ -606,7 +606,7 @@ export class ProjectService {
'The list of allowed origins has to be smaller than 300 symbols',
)
- _map(projectDTO.origins, host => {
+ _map(projectDTO.origins, (host) => {
if (!ORIGINS_REGEX.test(_trim(host))) {
throw new ConflictException(`Host ${host} is not correct`)
}
@@ -618,7 +618,7 @@ export class ProjectService {
throw new UnprocessableEntityException(
'The list of allowed blacklisted IP addresses must be less than 300 characters.',
)
- _map(projectDTO.ipBlacklist, ip => {
+ _map(projectDTO.ipBlacklist, (ip) => {
if (!net.isIP(_trim(ip)) && !IP_REGEX.test(_trim(ip))) {
throw new ConflictException(`IP address ${ip} is not correct`)
}
@@ -636,7 +636,7 @@ export class ProjectService {
)
const countryCodeRegex = /^[A-Z]{2}$/
- _map(projectDTO.countryBlacklist, code => {
+ _map(projectDTO.countryBlacklist, (code) => {
const trimmedCode = _trim(code).toUpperCase()
if (!countryCodeRegex.test(trimmedCode)) {
throw new ConflictException(
diff --git a/backend/apps/community/src/user/user.controller.ts b/backend/apps/community/src/user/user.controller.ts
index 6fcb2f47f..285055d21 100644
--- a/backend/apps/community/src/user/user.controller.ts
+++ b/backend/apps/community/src/user/user.controller.ts
@@ -163,7 +163,7 @@ export class UserController {
try {
if (!_isEmpty(projects)) {
- const pidArray = projects.map(el => el.id)
+ const pidArray = projects.map((el) => el.id)
const queries = [
'ALTER TABLE analytics DELETE WHERE pid IN ({pids:Array(FixedString(12))})',
'ALTER TABLE customEV DELETE WHERE pid IN ({pids:Array(FixedString(12))})',
@@ -172,7 +172,7 @@ export class UserController {
'ALTER TABLE error_statuses DELETE WHERE pid IN ({pids:Array(FixedString(12))})',
]
await deleteProjectsByUserIdClickhouse(id)
- const promises = _map(queries, async query =>
+ const promises = _map(queries, async (query) =>
clickhouse.command({
query,
query_params: { pids: pidArray },
diff --git a/backend/apps/community/src/user/user.service.ts b/backend/apps/community/src/user/user.service.ts
index 05f8ab896..3a9a6d13b 100644
--- a/backend/apps/community/src/user/user.service.ts
+++ b/backend/apps/community/src/user/user.service.ts
@@ -49,7 +49,7 @@ export class UserService {
query: `SELECT * FROM user WHERE ${where}`,
query_params: queryParams,
})
- .then(resultSet => resultSet.json<ClickhouseInputUser>())
+ .then((resultSet) => resultSet.json<ClickhouseInputUser>())
return this.formatUser(data[0])
}
@@ -156,7 +156,7 @@ export class UserService {
.query({
query: 'SELECT count() as total FROM user',
})
- .then(resultSet => resultSet.json<{ total: number }>())
+ .then((resultSet) => resultSet.json<{ total: number }>())
const total = Array.isArray(data) && data.length > 0 ? data[0].total : 0
return Number(total) || 0
diff --git a/backend/package-lock.json b/backend/package-lock.json
index 8336f7f59..27bbf9660 100644
--- a/backend/package-lock.json
+++ b/backend/package-lock.json
@@ -91,8 +91,8 @@
"@types/passport-jwt": "^4.0.1",
"@types/randomstring": "^1.3.0",
"knip": "^5.77.2",
+ "oxfmt": "^0.24.0",
"oxlint": "^0.16.10",
- "prettier": "^3.7.4",
"ts-prune": "^0.10.3",
"typescript": "^5.9.3"
},
@@ -3524,6 +3524,118 @@
"win32"
]
},
+ "node_modules/@oxfmt/darwin-arm64": {
+ "version": "0.24.0",
+ "resolved": "https://registry.npmjs.org/@oxfmt/darwin-arm64/-/darwin-arm64-0.24.0.tgz",
+ "integrity": "sha512-aYXuGf/yq8nsyEcHindGhiz9I+GEqLkVq8CfPbd+6VE259CpPEH+CaGHEO1j6vIOmNr8KHRq+IAjeRO2uJpb8A==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "darwin"
+ ]
+ },
+ "node_modules/@oxfmt/darwin-x64": {
+ "version": "0.24.0",
+ "resolved": "https://registry.npmjs.org/@oxfmt/darwin-x64/-/darwin-x64-0.24.0.tgz",
+ "integrity": "sha512-vs3b8Bs53hbiNvcNeBilzE/+IhDTWKjSBB3v/ztr664nZk65j0xr+5IHMBNz3CFppmX7o/aBta2PxY+t+4KoPg==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "darwin"
+ ]
+ },
+ "node_modules/@oxfmt/linux-arm64-gnu": {
+ "version": "0.24.0",
+ "resolved": "https://registry.npmjs.org/@oxfmt/linux-arm64-gnu/-/linux-arm64-gnu-0.24.0.tgz",
+ "integrity": "sha512-ItPDOPoQ0wLj/s8osc5ch57uUcA1Wk8r0YdO8vLRpXA3UNg7KPOm1vdbkIZRRiSUphZcuX5ioOEetEK8H7RlTw==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ]
+ },
+ "node_modules/@oxfmt/linux-arm64-musl": {
+ "version": "0.24.0",
+ "resolved": "https://registry.npmjs.org/@oxfmt/linux-arm64-musl/-/linux-arm64-musl-0.24.0.tgz",
+ "integrity": "sha512-JkQO3WnQjQTJONx8nxdgVBfl6BBFfpp9bKhChYhWeakwJdr7QPOAWJ/v3FGZfr0TbqINwnNR74aVZayDDRyXEA==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ]
+ },
+ "node_modules/@oxfmt/linux-x64-gnu": {
+ "version": "0.24.0",
+ "resolved": "https://registry.npmjs.org/@oxfmt/linux-x64-gnu/-/linux-x64-gnu-0.24.0.tgz",
+ "integrity": "sha512-N/SXlFO+2kak5gMt0oxApi0WXQDhwA0PShR0UbkY0PwtHjfSiDqJSOumyNqgQVoroKr1GNnoRmUqjZIz6DKIcw==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ]
+ },
+ "node_modules/@oxfmt/linux-x64-musl": {
+ "version": "0.24.0",
+ "resolved": "https://registry.npmjs.org/@oxfmt/linux-x64-musl/-/linux-x64-musl-0.24.0.tgz",
+ "integrity": "sha512-WM0pek5YDCQf50XQ7GLCE9sMBCMPW/NPAEPH/Hx6Qyir37lEsP4rUmSECo/QFNTU6KBc9NnsviAyJruWPpCMXw==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ]
+ },
+ "node_modules/@oxfmt/win32-arm64": {
+ "version": "0.24.0",
+ "resolved": "https://registry.npmjs.org/@oxfmt/win32-arm64/-/win32-arm64-0.24.0.tgz",
+ "integrity": "sha512-vFCseli1KWtwdHrVlT/jWfZ8jP8oYpnPPEjI23mPLW8K/6GEJmmvy0PZP5NpWUFNTzX0lqie58XnrATJYAe9Xw==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ]
+ },
+ "node_modules/@oxfmt/win32-x64": {
+ "version": "0.24.0",
+ "resolved": "https://registry.npmjs.org/@oxfmt/win32-x64/-/win32-x64-0.24.0.tgz",
+ "integrity": "sha512-0tmlNzcyewAnauNeBCq0xmAkmiKzl+H09p0IdHy+QKrTQdtixtf+AOjDAADbRfihkS+heF15Pjc4IyJMdAAJjw==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ]
+ },
"node_modules/@oxlint/darwin-arm64": {
"version": "0.16.12",
"resolved": "https://registry.npmjs.org/@oxlint/darwin-arm64/-/darwin-arm64-0.16.12.tgz",
@@ -11560,6 +11672,35 @@
"@oxc-resolver/binding-win32-x64-msvc": "11.16.2"
}
},
+ "node_modules/oxfmt": {
+ "version": "0.24.0",
+ "resolved": "https://registry.npmjs.org/oxfmt/-/oxfmt-0.24.0.tgz",
+ "integrity": "sha512-UjeM3Peez8Tl7IJ9s5UwAoZSiDRMww7BEc21gDYxLq3S3/KqJnM3mjNxsoSHgmBvSeX6RBhoVc2MfC/+96RdSw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "tinypool": "2.0.0"
+ },
+ "bin": {
+ "oxfmt": "bin/oxfmt"
+ },
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/Boshen"
+ },
+ "optionalDependencies": {
+ "@oxfmt/darwin-arm64": "0.24.0",
+ "@oxfmt/darwin-x64": "0.24.0",
+ "@oxfmt/linux-arm64-gnu": "0.24.0",
+ "@oxfmt/linux-arm64-musl": "0.24.0",
+ "@oxfmt/linux-x64-gnu": "0.24.0",
+ "@oxfmt/linux-x64-musl": "0.24.0",
+ "@oxfmt/win32-arm64": "0.24.0",
+ "@oxfmt/win32-x64": "0.24.0"
+ }
+ },
"node_modules/oxlint": {
"version": "0.16.12",
"resolved": "https://registry.npmjs.org/oxlint/-/oxlint-0.16.12.tgz",
@@ -12067,22 +12208,6 @@
"node": ">=0.10.0"
}
},
- "node_modules/prettier": {
- "version": "3.7.4",
- "resolved": "https://registry.npmjs.org/prettier/-/prettier-3.7.4.tgz",
- "integrity": "sha512-v6UNi1+3hSlVvv8fSaoUbggEM5VErKmmpGA7Pl3HF8V6uKY7rvClBOJlH6yNwQtfTueNkGVpOv/mtWL9L4bgRA==",
- "dev": true,
- "license": "MIT",
- "bin": {
- "prettier": "bin/prettier.cjs"
- },
- "engines": {
- "node": ">=14"
- },
- "funding": {
- "url": "https://github.com/prettier/prettier?sponsor=1"
- }
- },
"node_modules/preview-email": {
"version": "3.1.0",
"resolved": "https://registry.npmjs.org/preview-email/-/preview-email-3.1.0.tgz",
@@ -13929,6 +14054,16 @@
"node": ">=12"
}
},
+ "node_modules/tinypool": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/tinypool/-/tinypool-2.0.0.tgz",
+ "integrity": "sha512-/RX9RzeH2xU5ADE7n2Ykvmi9ED3FBGPAjw9u3zucrNNaEBIO0HPSYgL0NT7+3p147ojeSdaVu08F6hjpv31HJg==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": "^20.0.0 || >=22.0.0"
+ }
+ },
"node_modules/tlds": {
"version": "1.261.0",
"resolved": "https://registry.npmjs.org/tlds/-/tlds-1.261.0.tgz",
diff --git a/backend/package.json b/backend/package.json
index 72ede8267..f37b1defc 100644
--- a/backend/package.json
+++ b/backend/package.json
@@ -11,7 +11,8 @@
"build": "npm run refresh-submodules && node --max-old-space-size=4096 ./node_modules/@nestjs/cli/bin/nest.js build cloud && mv apps/cloud/dist dist && npm run sentry:sourcemaps",
"build:no-submodules-refresh": "node --max-old-space-size=4096 ./node_modules/@nestjs/cli/bin/nest.js build cloud && mv apps/cloud/dist dist && npm run sentry:sourcemaps",
"postbuild": "cp .env dist/.env",
- "format": "prettier --write \"apps/community/src/**/*.ts\" \"apps/cloud/src/**/*.ts\"",
+ "format": "oxfmt --write apps/community/src apps/cloud/src",
+ "format:check": "oxfmt --check apps/community/src apps/cloud/src",
"clickhouse:initialise": "node migrations/clickhouse/initialise_selfhosted.js",
"start": "cross-env NODE_ENV=development nest start",
"start:dev": "cross-env NODE_ENV=development nest start --watch",
@@ -29,6 +30,7 @@
"@ai-sdk/openai": "^3.0.1",
"@clickhouse/client": "^1.15.0",
"@faker-js/faker": "^10.1.0",
+ "@googleapis/searchconsole": "^6.0.1",
"@nestjs-modules/mailer": "^2.0.2",
"@nestjs/axios": "^4.0.1",
"@nestjs/common": "^11.1.10",
@@ -64,7 +66,6 @@
"dotenv": "^17.2.3",
"express": "^5.2.1",
"front-matter": "^4.0.2",
- "@googleapis/searchconsole": "^6.0.1",
"google-auth-library": "^10.5.0",
"handlebars": "^4.7.8",
"ioredis": "^5.8.2",
@@ -111,8 +112,8 @@
"@types/passport-jwt": "^4.0.1",
"@types/randomstring": "^1.3.0",
"knip": "^5.77.2",
+ "oxfmt": "^0.24.0",
"oxlint": "^0.16.10",
- "prettier": "^3.7.4",
"ts-prune": "^0.10.3",
"typescript": "^5.9.3"
},
diff --git a/docs/.oxfmtrc.json b/docs/.oxfmtrc.json
new file mode 100644
index 000000000..8d804152f
--- /dev/null
+++ b/docs/.oxfmtrc.json
@@ -0,0 +1,13 @@
+{
+ "printWidth": 80,
+ "useTabs": false,
+ "tabWidth": 2,
+ "trailingComma": "all",
+ "semi": false,
+ "singleQuote": true,
+ "bracketSpacing": true,
+ "arrowParens": "always",
+ "jsxSingleQuote": true,
+ "bracketSameLine": false,
+ "endOfLine": "lf"
+}
diff --git a/docs/.prettierrc.js b/docs/.prettierrc.js
deleted file mode 100644
index bd6302ddd..000000000
--- a/docs/.prettierrc.js
+++ /dev/null
@@ -1,13 +0,0 @@
-module.exports = {
- printWidth: 120, // max 120 chars in line, code is easy to read
- useTabs: false, // use spaces instead of tabs
- tabWidth: 2, // "visual width" of of the "tab"
- trailingComma: 'all', // add trailing commas in objects, arrays, etc.
- semi: false, // Only add semicolons at the beginning of lines that may introduce ASI failures
- singleQuote: true, // '' for stings instead of ""
- bracketSpacing: true, // import { some } ... instead of import {some} ...
- arrowParens: 'always', // braces even for single param in arrow functions (a) => { }
- jsxSingleQuote: true, // '' for react props
- bracketSameLine: false, // pretty JSX
- endOfLine: 'lf', // 'lf' for linux, 'crlf' for windows, we need to use 'lf' for git
-}
diff --git a/docs/package-lock.json b/docs/package-lock.json
index c406ae65e..86f9abff5 100644
--- a/docs/package-lock.json
+++ b/docs/package-lock.json
@@ -26,7 +26,7 @@
"devDependencies": {
"@docusaurus/module-type-aliases": "3.9.2",
"@docusaurus/types": "3.9.2",
- "prettier": "^3.6.2"
+ "oxfmt": "^0.24.0"
},
"engines": {
"node": ">=18.0"
@@ -4698,6 +4698,118 @@
"node": ">=8.0.0"
}
},
+ "node_modules/@oxfmt/darwin-arm64": {
+ "version": "0.24.0",
+ "resolved": "https://registry.npmjs.org/@oxfmt/darwin-arm64/-/darwin-arm64-0.24.0.tgz",
+ "integrity": "sha512-aYXuGf/yq8nsyEcHindGhiz9I+GEqLkVq8CfPbd+6VE259CpPEH+CaGHEO1j6vIOmNr8KHRq+IAjeRO2uJpb8A==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "darwin"
+ ]
+ },
+ "node_modules/@oxfmt/darwin-x64": {
+ "version": "0.24.0",
+ "resolved": "https://registry.npmjs.org/@oxfmt/darwin-x64/-/darwin-x64-0.24.0.tgz",
+ "integrity": "sha512-vs3b8Bs53hbiNvcNeBilzE/+IhDTWKjSBB3v/ztr664nZk65j0xr+5IHMBNz3CFppmX7o/aBta2PxY+t+4KoPg==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "darwin"
+ ]
+ },
+ "node_modules/@oxfmt/linux-arm64-gnu": {
+ "version": "0.24.0",
+ "resolved": "https://registry.npmjs.org/@oxfmt/linux-arm64-gnu/-/linux-arm64-gnu-0.24.0.tgz",
+ "integrity": "sha512-ItPDOPoQ0wLj/s8osc5ch57uUcA1Wk8r0YdO8vLRpXA3UNg7KPOm1vdbkIZRRiSUphZcuX5ioOEetEK8H7RlTw==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ]
+ },
+ "node_modules/@oxfmt/linux-arm64-musl": {
+ "version": "0.24.0",
+ "resolved": "https://registry.npmjs.org/@oxfmt/linux-arm64-musl/-/linux-arm64-musl-0.24.0.tgz",
+ "integrity": "sha512-JkQO3WnQjQTJONx8nxdgVBfl6BBFfpp9bKhChYhWeakwJdr7QPOAWJ/v3FGZfr0TbqINwnNR74aVZayDDRyXEA==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ]
+ },
+ "node_modules/@oxfmt/linux-x64-gnu": {
+ "version": "0.24.0",
+ "resolved": "https://registry.npmjs.org/@oxfmt/linux-x64-gnu/-/linux-x64-gnu-0.24.0.tgz",
+ "integrity": "sha512-N/SXlFO+2kak5gMt0oxApi0WXQDhwA0PShR0UbkY0PwtHjfSiDqJSOumyNqgQVoroKr1GNnoRmUqjZIz6DKIcw==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ]
+ },
+ "node_modules/@oxfmt/linux-x64-musl": {
+ "version": "0.24.0",
+ "resolved": "https://registry.npmjs.org/@oxfmt/linux-x64-musl/-/linux-x64-musl-0.24.0.tgz",
+ "integrity": "sha512-WM0pek5YDCQf50XQ7GLCE9sMBCMPW/NPAEPH/Hx6Qyir37lEsP4rUmSECo/QFNTU6KBc9NnsviAyJruWPpCMXw==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ]
+ },
+ "node_modules/@oxfmt/win32-arm64": {
+ "version": "0.24.0",
+ "resolved": "https://registry.npmjs.org/@oxfmt/win32-arm64/-/win32-arm64-0.24.0.tgz",
+ "integrity": "sha512-vFCseli1KWtwdHrVlT/jWfZ8jP8oYpnPPEjI23mPLW8K/6GEJmmvy0PZP5NpWUFNTzX0lqie58XnrATJYAe9Xw==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ]
+ },
+ "node_modules/@oxfmt/win32-x64": {
+ "version": "0.24.0",
+ "resolved": "https://registry.npmjs.org/@oxfmt/win32-x64/-/win32-x64-0.24.0.tgz",
+ "integrity": "sha512-0tmlNzcyewAnauNeBCq0xmAkmiKzl+H09p0IdHy+QKrTQdtixtf+AOjDAADbRfihkS+heF15Pjc4IyJMdAAJjw==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ]
+ },
"node_modules/@pnpm/config.env-replace": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/@pnpm/config.env-replace/-/config.env-replace-1.1.0.tgz",
@@ -13276,6 +13388,45 @@
"opener": "bin/opener-bin.js"
}
},
+ "node_modules/oxfmt": {
+ "version": "0.24.0",
+ "resolved": "https://registry.npmjs.org/oxfmt/-/oxfmt-0.24.0.tgz",
+ "integrity": "sha512-UjeM3Peez8Tl7IJ9s5UwAoZSiDRMww7BEc21gDYxLq3S3/KqJnM3mjNxsoSHgmBvSeX6RBhoVc2MfC/+96RdSw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "tinypool": "2.0.0"
+ },
+ "bin": {
+ "oxfmt": "bin/oxfmt"
+ },
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/Boshen"
+ },
+ "optionalDependencies": {
+ "@oxfmt/darwin-arm64": "0.24.0",
+ "@oxfmt/darwin-x64": "0.24.0",
+ "@oxfmt/linux-arm64-gnu": "0.24.0",
+ "@oxfmt/linux-arm64-musl": "0.24.0",
+ "@oxfmt/linux-x64-gnu": "0.24.0",
+ "@oxfmt/linux-x64-musl": "0.24.0",
+ "@oxfmt/win32-arm64": "0.24.0",
+ "@oxfmt/win32-x64": "0.24.0"
+ }
+ },
+ "node_modules/oxfmt/node_modules/tinypool": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/tinypool/-/tinypool-2.0.0.tgz",
+ "integrity": "sha512-/RX9RzeH2xU5ADE7n2Ykvmi9ED3FBGPAjw9u3zucrNNaEBIO0HPSYgL0NT7+3p147ojeSdaVu08F6hjpv31HJg==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": "^20.0.0 || >=22.0.0"
+ }
+ },
"node_modules/p-cancelable": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/p-cancelable/-/p-cancelable-3.0.0.tgz",
@@ -15198,22 +15349,6 @@
"postcss": "^8.4.31"
}
},
- "node_modules/prettier": {
- "version": "3.7.4",
- "resolved": "https://registry.npmjs.org/prettier/-/prettier-3.7.4.tgz",
- "integrity": "sha512-v6UNi1+3hSlVvv8fSaoUbggEM5VErKmmpGA7Pl3HF8V6uKY7rvClBOJlH6yNwQtfTueNkGVpOv/mtWL9L4bgRA==",
- "dev": true,
- "license": "MIT",
- "bin": {
- "prettier": "bin/prettier.cjs"
- },
- "engines": {
- "node": ">=14"
- },
- "funding": {
- "url": "https://github.com/prettier/prettier?sponsor=1"
- }
- },
"node_modules/pretty-error": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/pretty-error/-/pretty-error-4.0.0.tgz",
diff --git a/docs/package.json b/docs/package.json
index 1e309ba04..4190e6653 100644
--- a/docs/package.json
+++ b/docs/package.json
@@ -10,7 +10,8 @@
"deploy": "docusaurus deploy",
"clear": "docusaurus clear",
"serve": "docusaurus serve",
- "format": "prettier --write .",
+ "format": "oxfmt --write ./src ./*.js",
+ "format:check": "oxfmt --check ./src ./*.js",
"write-translations": "docusaurus write-translations",
"write-heading-ids": "docusaurus write-heading-ids"
},
@@ -33,7 +34,7 @@
"devDependencies": {
"@docusaurus/module-type-aliases": "3.9.2",
"@docusaurus/types": "3.9.2",
- "prettier": "^3.6.2"
+ "oxfmt": "^0.24.0"
},
"browserslist": {
"production": [
diff --git a/web/.oxfmtrc.json b/web/.oxfmtrc.json
new file mode 100644
index 000000000..8a0fc7139
--- /dev/null
+++ b/web/.oxfmtrc.json
@@ -0,0 +1,17 @@
+{
+ "printWidth": 80,
+ "useTabs": false,
+ "tabWidth": 2,
+ "trailingComma": "all",
+ "semi": false,
+ "singleQuote": true,
+ "bracketSpacing": true,
+ "arrowParens": "always",
+ "jsxSingleQuote": true,
+ "bracketSameLine": false,
+ "endOfLine": "lf",
+ "experimentalTailwindcss": {
+ "stylesheet": "app/styles/tailwind.css",
+ "functions": ["clsx", "cn", "cx"]
+ }
+}
diff --git a/web/.prettierignore b/web/.prettierignore
deleted file mode 100644
index 3548a93b4..000000000
--- a/web/.prettierignore
+++ /dev/null
@@ -1,6 +0,0 @@
-node_modules
-build
-dist
-public
-.cache
-deployment
\ No newline at end of file
diff --git a/web/.prettierrc.cjs b/web/.prettierrc.cjs
deleted file mode 100644
index 2020cf623..000000000
--- a/web/.prettierrc.cjs
+++ /dev/null
@@ -1,15 +0,0 @@
-module.exports = {
- printWidth: 120, // max 120 chars in line, code is easy to read
- useTabs: false, // use spaces instead of tabs
- tabWidth: 2, // "visual width" of of the "tab"
- trailingComma: 'all', // add trailing commas in objects, arrays, etc.
- semi: false, // Only add semicolons at the beginning of lines that may introduce ASI failures
- singleQuote: true, // '' for stings instead of ""
- bracketSpacing: true, // import { some } ... instead of import {some} ...
- arrowParens: 'always', // braces even for single param in arrow functions (a) => { }
- jsxSingleQuote: true, // '' for react props
- bracketSameLine: false, // pretty JSX
- endOfLine: 'lf', // 'lf' for linux, 'crlf' for windows, we need to use 'lf' for git
- plugins: ['prettier-plugin-tailwindcss'],
- tailwindStylesheet: './app/styles/tailwind.css',
-}
diff --git a/web/app/App.tsx b/web/app/App.tsx
index 2937a109b..2d474b9ae 100644
--- a/web/app/App.tsx
+++ b/web/app/App.tsx
@@ -67,7 +67,11 @@ const App = () => {
return (
<>
- {!_includes(routesWithOutHeader, pathname) && !isReferralPage && !isProjectViewPage ? <Header /> : null}
+ {!_includes(routesWithOutHeader, pathname) &&
+ !isReferralPage &&
+ !isProjectViewPage ? (
+ <Header />
+ ) : null}
<Outlet />
<Toaster
theme={theme}
diff --git a/web/app/api/api.server.ts b/web/app/api/api.server.ts
index 9ffac29a9..39e2c2f9a 100644
--- a/web/app/api/api.server.ts
+++ b/web/app/api/api.server.ts
@@ -58,7 +58,9 @@ async function fetchWithTimeout(
): Promise<Response> {
const controller = new AbortController()
const id = setTimeout(() => controller.abort(), timeoutMs)
- return fetch(input, { ...init, signal: controller.signal }).finally(() => clearTimeout(id))
+ return fetch(input, { ...init, signal: controller.signal }).finally(() =>
+ clearTimeout(id),
+ )
}
interface ServerFetchOptions {
@@ -82,7 +84,12 @@ export async function serverFetch<T = unknown>(
endpoint: string,
options: ServerFetchOptions = {},
): Promise<ServerFetchResult<T>> {
- const { method = 'GET', body, headers: customHeaders = {}, skipAuth = false } = options
+ const {
+ method = 'GET',
+ body,
+ headers: customHeaders = {},
+ skipAuth = false,
+ } = options
const apiUrl = getApiUrl()
const cleanEndpoint = endpoint.startsWith('/') ? endpoint.slice(1) : endpoint
@@ -121,7 +128,8 @@ export async function serverFetch<T = unknown>(
const refreshResult = await tryRefreshToken(request)
if (refreshResult.success && refreshResult.tokens) {
- fetchHeaders['Authorization'] = `Bearer ${refreshResult.tokens.accessToken}`
+ fetchHeaders['Authorization'] =
+ `Bearer ${refreshResult.tokens.accessToken}`
const retryResponse = await fetchWithTimeout(url, {
method,
@@ -209,7 +217,12 @@ export async function streamingServerFetch(
endpoint: string,
options: ServerFetchOptions = {},
): Promise<Response> {
- const { method = 'GET', body, headers: customHeaders = {}, skipAuth = false } = options
+ const {
+ method = 'GET',
+ body,
+ headers: customHeaders = {},
+ skipAuth = false,
+ } = options
const apiUrl = getApiUrl()
const cleanEndpoint = endpoint.startsWith('/') ? endpoint.slice(1) : endpoint
@@ -248,7 +261,8 @@ export async function streamingServerFetch(
const refreshResult = await tryRefreshToken(request)
if (refreshResult.success && refreshResult.tokens) {
- fetchHeaders['Authorization'] = `Bearer ${refreshResult.tokens.accessToken}`
+ fetchHeaders['Authorization'] =
+ `Bearer ${refreshResult.tokens.accessToken}`
const retryResponse = await fetch(url, {
method,
@@ -317,7 +331,9 @@ async function tryRefreshToken(
}
}
-async function parseErrorResponse(response: Response): Promise<string | string[]> {
+async function parseErrorResponse(
+ response: Response,
+): Promise<string | string[]> {
try {
const contentType = response.headers.get('content-type')
if (!contentType?.includes('application/json')) {
@@ -509,8 +525,12 @@ interface BlogPostContent {
}
}
-export async function getBlogPosts(request: Request): Promise<BlogPost[] | null> {
- const result = await serverFetch<BlogPost[]>(request, 'v1/blog', { skipAuth: true })
+export async function getBlogPosts(
+ request: Request,
+): Promise<BlogPost[] | null> {
+ const result = await serverFetch<BlogPost[]>(request, 'v1/blog', {
+ skipAuth: true,
+ })
if (result.error || !result.data) {
return null
@@ -519,8 +539,15 @@ export async function getBlogPosts(request: Request): Promise<BlogPost[] | null>
return result.data
}
-export async function getBlogPost(request: Request, slug: string): Promise<BlogPostContent | null> {
- const result = await serverFetch<BlogPostContent>(request, `v1/blog/${slug}`, { skipAuth: true })
+export async function getBlogPost(
+ request: Request,
+ slug: string,
+): Promise<BlogPostContent | null> {
+ const result = await serverFetch<BlogPostContent>(
+ request,
+ `v1/blog/${slug}`,
+ { skipAuth: true },
+ )
if (result.error || !result.data) {
return null
@@ -534,7 +561,11 @@ export async function getBlogPostWithCategory(
category: string,
slug: string,
): Promise<BlogPostContent | null> {
- const result = await serverFetch<BlogPostContent>(request, `v1/blog/${category}/${slug}`, { skipAuth: true })
+ const result = await serverFetch<BlogPostContent>(
+ request,
+ `v1/blog/${category}/${slug}`,
+ { skipAuth: true },
+ )
if (result.error || !result.data) {
return null
@@ -552,7 +583,9 @@ export interface AuthMeResponse {
totalMonthlyEvents: number
}
-export async function authMeServer(request: Request): Promise<ServerFetchResult<AuthMeResponse>> {
+export async function authMeServer(
+ request: Request,
+): Promise<ServerFetchResult<AuthMeResponse>> {
return serverFetch<AuthMeResponse>(request, 'user/me')
}
@@ -566,8 +599,12 @@ interface GeneralStats {
events: number
}
-export async function getGeneralStats(request: Request): Promise<GeneralStats | null> {
- const result = await serverFetch<GeneralStats>(request, 'log/generalStats', { skipAuth: true })
+export async function getGeneralStats(
+ request: Request,
+): Promise<GeneralStats | null> {
+ const result = await serverFetch<GeneralStats>(request, 'log/generalStats', {
+ skipAuth: true,
+ })
if (result.error || !result.data) {
return null
@@ -599,7 +636,11 @@ export interface TrafficLogResponse {
properties: Record<string, number>
appliedFilters?: AnalyticsFilter[]
timeBucket?: string[]
- meta?: { key: string; current: { sum: number; avg: number }; previous: { sum: number; avg: number } }[]
+ meta?: {
+ key: string
+ current: { sum: number; avg: number }
+ previous: { sum: number; avg: number }
+ }[]
}
interface OverallPeriodStats {
@@ -657,7 +698,11 @@ export async function getProjectDataServer(
headers['x-password'] = params.password
}
- return serverFetch<TrafficLogResponse>(request, `log?${queryParams.toString()}`, { headers })
+ return serverFetch<TrafficLogResponse>(
+ request,
+ `log?${queryParams.toString()}`,
+ { headers },
+ )
}
export async function getOverallStatsServer(
@@ -672,7 +717,10 @@ export async function getOverallStatsServer(
queryParams.append('timeBucket', params.timeBucket)
queryParams.append('period', params.period)
queryParams.append('filters', serializeFiltersForUrl(params.filters))
- queryParams.append('includeChart', params.includeChart !== false ? 'true' : 'false')
+ queryParams.append(
+ 'includeChart',
+ params.includeChart !== false ? 'true' : 'false',
+ )
if (params.from) queryParams.append('from', params.from)
if (params.to) queryParams.append('to', params.to)
if (params.timezone) queryParams.append('timezone', params.timezone)
@@ -682,7 +730,11 @@ export async function getOverallStatsServer(
headers['x-password'] = params.password
}
- return serverFetch<Record<string, OverallObject>>(request, `log/birdseye?${queryParams.toString()}`, { headers })
+ return serverFetch<Record<string, OverallObject>>(
+ request,
+ `log/birdseye?${queryParams.toString()}`,
+ { headers },
+ )
}
interface CustomEventsChartResponse {
@@ -712,7 +764,11 @@ export async function getCustomEventsDataServer(
headers['x-password'] = params.password
}
- return serverFetch<CustomEventsChartResponse>(request, `log/customEvents?${queryParams.toString()}`, { headers })
+ return serverFetch<CustomEventsChartResponse>(
+ request,
+ `log/customEvents?${queryParams.toString()}`,
+ { headers },
+ )
}
export interface PerformanceDataResponse {
@@ -752,7 +808,11 @@ export async function getPerfDataServer(
headers['x-password'] = params.password
}
- return serverFetch<PerformanceDataResponse>(request, `log/performance?${queryParams.toString()}`, { headers })
+ return serverFetch<PerformanceDataResponse>(
+ request,
+ `log/performance?${queryParams.toString()}`,
+ { headers },
+ )
}
export interface PerformanceOverallObject {
@@ -838,7 +898,11 @@ export async function getSessionsServer(
headers['x-password'] = params.password
}
- return serverFetch<SessionsResponse>(request, `log/sessions?${queryParams.toString()}`, { headers })
+ return serverFetch<SessionsResponse>(
+ request,
+ `log/sessions?${queryParams.toString()}`,
+ { headers },
+ )
}
interface PageflowItem {
@@ -894,7 +958,11 @@ export async function getSessionServer(
headers['x-password'] = password
}
- return serverFetch<SessionDetailsResponse>(request, `log/session?${queryParams.toString()}`, { headers })
+ return serverFetch<SessionDetailsResponse>(
+ request,
+ `log/session?${queryParams.toString()}`,
+ { headers },
+ )
}
interface SwetrixError {
@@ -916,7 +984,11 @@ export interface ErrorsResponse {
export async function getErrorsServer(
request: Request,
pid: string,
- params: AnalyticsParams & { take?: number; skip?: number; options?: Record<string, unknown> },
+ params: AnalyticsParams & {
+ take?: number
+ skip?: number
+ options?: Record<string, unknown>
+ },
): Promise<ServerFetchResult<ErrorsResponse>> {
const queryParams = new URLSearchParams()
queryParams.append('pid', pid)
@@ -935,7 +1007,11 @@ export async function getErrorsServer(
headers['x-password'] = params.password
}
- return serverFetch<ErrorsResponse>(request, `log/errors?${queryParams.toString()}`, { headers })
+ return serverFetch<ErrorsResponse>(
+ request,
+ `log/errors?${queryParams.toString()}`,
+ { headers },
+ )
}
export interface ErrorDetailsResponse {
@@ -986,7 +1062,11 @@ export async function getErrorServer(
headers['x-password'] = params.password
}
- return serverFetch<ErrorDetailsResponse>(request, `log/error?${queryParams.toString()}`, { headers })
+ return serverFetch<ErrorDetailsResponse>(
+ request,
+ `log/error?${queryParams.toString()}`,
+ { headers },
+ )
}
export interface ErrorOverviewResponse {
@@ -1025,7 +1105,11 @@ export async function getErrorOverviewServer(
headers['x-password'] = params.password
}
- return serverFetch<ErrorOverviewResponse>(request, `log/error-overview?${queryParams.toString()}`, { headers })
+ return serverFetch<ErrorOverviewResponse>(
+ request,
+ `log/error-overview?${queryParams.toString()}`,
+ { headers },
+ )
}
// ============================================================================
@@ -1071,7 +1155,10 @@ export async function getProjectFeatureFlagsServer(
params.append('search', search.trim())
}
- return serverFetch<FeatureFlagsResponse>(request, `feature-flag/project/${projectId}?${params.toString()}`)
+ return serverFetch<FeatureFlagsResponse>(
+ request,
+ `feature-flag/project/${projectId}?${params.toString()}`,
+ )
}
export interface FeatureFlagStats {
@@ -1095,7 +1182,10 @@ export async function getFeatureFlagStatsServer(
if (to) params.append('to', to)
if (timezone) params.append('timezone', timezone)
- return serverFetch<FeatureFlagStats>(request, `feature-flag/${flagId}/stats?${params.toString()}`)
+ return serverFetch<FeatureFlagStats>(
+ request,
+ `feature-flag/${flagId}/stats?${params.toString()}`,
+ )
}
export interface FeatureFlagProfile {
@@ -1130,9 +1220,13 @@ export async function getFeatureFlagProfilesServer(
if (from) params.append('from', from)
if (to) params.append('to', to)
if (timezone) params.append('timezone', timezone)
- if (resultFilter && resultFilter !== 'all') params.append('result', resultFilter)
+ if (resultFilter && resultFilter !== 'all')
+ params.append('result', resultFilter)
- return serverFetch<FeatureFlagProfilesResponse>(request, `feature-flag/${flagId}/profiles?${params.toString()}`)
+ return serverFetch<FeatureFlagProfilesResponse>(
+ request,
+ `feature-flag/${flagId}/profiles?${params.toString()}`,
+ )
}
// ============================================================================
@@ -1172,7 +1266,10 @@ export async function getProjectGoalsServer(
params.append('search', search.trim())
}
- return serverFetch<GoalsResponse>(request, `goal/project/${projectId}?${params.toString()}`)
+ return serverFetch<GoalsResponse>(
+ request,
+ `goal/project/${projectId}?${params.toString()}`,
+ )
}
export interface GoalStats {
@@ -1196,7 +1293,10 @@ export async function getGoalStatsServer(
if (to) params.append('to', to)
if (timezone) params.append('timezone', timezone)
- return serverFetch<GoalStats>(request, `goal/${goalId}/stats?${params.toString()}`)
+ return serverFetch<GoalStats>(
+ request,
+ `goal/${goalId}/stats?${params.toString()}`,
+ )
}
export interface GoalChartData {
@@ -1219,7 +1319,10 @@ export async function getGoalChartServer(
if (to) params.append('to', to)
if (timezone) params.append('timezone', timezone)
- return serverFetch<{ chart: GoalChartData }>(request, `goal/${goalId}/chart?${params.toString()}`)
+ return serverFetch<{ chart: GoalChartData }>(
+ request,
+ `goal/${goalId}/chart?${params.toString()}`,
+ )
}
// ============================================================================
@@ -1242,7 +1345,10 @@ export async function getProjectAlertsServer(
skip: String(skip),
})
- return serverFetch<AlertsResponse>(request, `alert/project/${projectId}?${params.toString()}`)
+ return serverFetch<AlertsResponse>(
+ request,
+ `alert/project/${projectId}?${params.toString()}`,
+ )
}
// ============================================================================
@@ -1285,7 +1391,11 @@ export async function getFunnelDataServer(
headers['x-password'] = password
}
- return serverFetch<FunnelDataResponse>(request, `log/funnel?${queryParams.toString()}`, { headers })
+ return serverFetch<FunnelDataResponse>(
+ request,
+ `log/funnel?${queryParams.toString()}`,
+ { headers },
+ )
}
// ============================================================================
@@ -1331,7 +1441,11 @@ export async function getCaptchaDataServer(
headers['x-password'] = password
}
- return serverFetch<CaptchaDataResponse>(request, `log/captcha?${queryParams.toString()}`, { headers })
+ return serverFetch<CaptchaDataResponse>(
+ request,
+ `log/captcha?${queryParams.toString()}`,
+ { headers },
+ )
}
// ============================================================================
@@ -1425,10 +1539,16 @@ export async function getExperimentResultsServer(
if (to) params.append('to', to)
if (timezone) params.append('timezone', timezone)
- return serverFetch<ExperimentResults>(request, `experiment/${experimentId}/results?${params.toString()}`)
+ return serverFetch<ExperimentResults>(
+ request,
+ `experiment/${experimentId}/results?${params.toString()}`,
+ )
}
-export async function getGoalServer(request: Request, goalId: string): Promise<ServerFetchResult<Goal>> {
+export async function getGoalServer(
+ request: Request,
+ goalId: string,
+): Promise<ServerFetchResult<Goal>> {
return serverFetch<Goal>(request, `goal/${goalId}`)
}
@@ -1484,7 +1604,11 @@ export async function getProfilesServer(
headers['x-password'] = password
}
- return serverFetch<ProfilesResponse>(request, `log/profiles?${params.toString()}`, { headers })
+ return serverFetch<ProfilesResponse>(
+ request,
+ `log/profiles?${params.toString()}`,
+ { headers },
+ )
}
interface ProfileDetails {
@@ -1539,7 +1663,11 @@ export async function getProfileServer(
headers['x-password'] = password
}
- return serverFetch<ProfileDetailsResponse>(request, `log/profile?${params.toString()}`, { headers })
+ return serverFetch<ProfileDetailsResponse>(
+ request,
+ `log/profile?${params.toString()}`,
+ { headers },
+ )
}
interface ProfileSession {
@@ -1592,7 +1720,11 @@ export async function getProfileSessionsServer(
headers['x-password'] = password
}
- return serverFetch<ProfileSessionsResponse>(request, `log/profile/sessions?${params.toString()}`, { headers })
+ return serverFetch<ProfileSessionsResponse>(
+ request,
+ `log/profile/sessions?${params.toString()}`,
+ { headers },
+ )
}
// ============================================================================
@@ -1678,7 +1810,11 @@ export async function getCustomEventsMetadataServer(
headers['x-password'] = params.password
}
- return serverFetch<CustomEventsMetadataResponse>(request, `log/meta?${queryParams.toString()}`, { headers })
+ return serverFetch<CustomEventsMetadataResponse>(
+ request,
+ `log/meta?${queryParams.toString()}`,
+ { headers },
+ )
}
// ============================================================================
@@ -1718,7 +1854,11 @@ export async function getPropertyMetadataServer(
headers['x-password'] = params.password
}
- return serverFetch<PropertyMetadataResponse>(request, `log/property?${queryParams.toString()}`, { headers })
+ return serverFetch<PropertyMetadataResponse>(
+ request,
+ `log/property?${queryParams.toString()}`,
+ { headers },
+ )
}
// ============================================================================
@@ -1770,7 +1910,11 @@ export async function getErrorSessionsServer(
headers['x-password'] = params.password
}
- return serverFetch<ErrorSessionsResponse>(request, `log/error-sessions?${queryParams.toString()}`, { headers })
+ return serverFetch<ErrorSessionsResponse>(
+ request,
+ `log/error-sessions?${queryParams.toString()}`,
+ { headers },
+ )
}
// ============================================================================
@@ -1793,7 +1937,9 @@ export async function getLiveVisitorsServer(
headers['x-password'] = password
}
- return serverFetch<LiveStats>(request, `log/hb?pids=${pidsParam}`, { headers })
+ return serverFetch<LiveStats>(request, `log/hb?pids=${pidsParam}`, {
+ headers,
+ })
}
export interface LiveVisitorInfo {
@@ -1814,7 +1960,11 @@ export async function getLiveVisitorsInfoServer(
headers['x-password'] = password
}
- return serverFetch<LiveVisitorInfo[]>(request, `log/live-visitors?pid=${pid}`, { headers })
+ return serverFetch<LiveVisitorInfo[]>(
+ request,
+ `log/live-visitors?pid=${pid}`,
+ { headers },
+ )
}
// ============================================================================
@@ -1857,9 +2007,13 @@ export async function getProjectDataCustomEventsServer(
headers['x-password'] = params.password
}
- return serverFetch<ProjectDataCustomEventsResponse>(request, `log/custom-events?${queryParams.toString()}`, {
- headers,
- })
+ return serverFetch<ProjectDataCustomEventsResponse>(
+ request,
+ `log/custom-events?${queryParams.toString()}`,
+ {
+ headers,
+ },
+ )
}
// ============================================================================
@@ -1884,7 +2038,10 @@ export async function generateSSOAuthURLServer(
payload.redirectUrl = redirectUrl
}
- const endpoint = provider === 'openid-connect' ? 'v1/auth/oidc/initiate' : 'v1/auth/sso/generate'
+ const endpoint =
+ provider === 'openid-connect'
+ ? 'v1/auth/oidc/initiate'
+ : 'v1/auth/sso/generate'
return serverFetch<SSOAuthURLResponse>(request, endpoint, {
method: 'POST',
@@ -1905,7 +2062,8 @@ export async function getJWTBySSOHashServer(
hash: string,
provider: SSOProvider,
): Promise<ServerFetchResult<SSOHashResponse>> {
- const endpoint = provider === 'openid-connect' ? 'v1/auth/oidc/hash' : 'v1/auth/sso/hash'
+ const endpoint =
+ provider === 'openid-connect' ? 'v1/auth/oidc/hash' : 'v1/auth/sso/hash'
const body = provider === 'openid-connect' ? { hash } : { hash, provider }
return serverFetch<SSOHashResponse>(request, endpoint, {
@@ -1999,7 +2157,11 @@ export async function getUserFlowServer(
headers['x-password'] = params.password
}
- return serverFetch<UserFlowResponse>(request, `log/user-flow?${queryParams.toString()}`, { headers })
+ return serverFetch<UserFlowResponse>(
+ request,
+ `log/user-flow?${queryParams.toString()}`,
+ { headers },
+ )
}
// ============================================================================
@@ -2017,7 +2179,9 @@ export async function getFiltersServer(
headers['x-password'] = password
}
- return serverFetch<string[]>(request, `log/filters?pid=${pid}&type=${type}`, { headers })
+ return serverFetch<string[]>(request, `log/filters?pid=${pid}&type=${type}`, {
+ headers,
+ })
}
export async function getErrorsFiltersServer(
@@ -2031,7 +2195,11 @@ export async function getErrorsFiltersServer(
headers['x-password'] = password
}
- return serverFetch<string[]>(request, `log/errors-filters?pid=${pid}&type=${type}`, { headers })
+ return serverFetch<string[]>(
+ request,
+ `log/errors-filters?pid=${pid}&type=${type}`,
+ { headers },
+ )
}
export interface VersionFilter {
@@ -2051,9 +2219,13 @@ export async function getVersionFiltersServer(
headers['x-password'] = password
}
- return serverFetch<VersionFilter[]>(request, `log/filters/versions?pid=${pid}&type=${type}&column=${column}`, {
- headers,
- })
+ return serverFetch<VersionFilter[]>(
+ request,
+ `log/filters/versions?pid=${pid}&type=${type}&column=${column}`,
+ {
+ headers,
+ },
+ )
}
// ============================================================================
@@ -2107,7 +2279,11 @@ export async function getGSCKeywordsServer(
headers['x-password'] = params.password
}
- return serverFetch<GSCKeywordsResponse>(request, `log/keywords?${queryParams.toString()}`, { headers })
+ return serverFetch<GSCKeywordsResponse>(
+ request,
+ `log/keywords?${queryParams.toString()}`,
+ { headers },
+ )
}
// ============================================================================
@@ -2121,7 +2297,10 @@ export interface RevenueStatus {
lastSyncAt?: string
}
-export async function getRevenueStatusServer(request: Request, pid: string): Promise<ServerFetchResult<RevenueStatus>> {
+export async function getRevenueStatusServer(
+ request: Request,
+ pid: string,
+): Promise<ServerFetchResult<RevenueStatus>> {
return serverFetch<RevenueStatus>(request, `project/${pid}/revenue/status`)
}
@@ -2168,5 +2347,8 @@ export async function getRevenueDataServer(
if (params.timezone) queryParams.append('timezone', params.timezone)
if (params.timeBucket) queryParams.append('timeBucket', params.timeBucket)
- return serverFetch<RevenueDataResponse>(request, `log/revenue?${queryParams.toString()}`)
+ return serverFetch<RevenueDataResponse>(
+ request,
+ `log/revenue?${queryParams.toString()}`,
+ )
}
diff --git a/web/app/api/index.ts b/web/app/api/index.ts
index a36b72395..0216dd770 100644
--- a/web/app/api/index.ts
+++ b/web/app/api/index.ts
@@ -31,7 +31,11 @@ export const askAI = async (
if (!response.ok) {
const errorData = await response.json().catch(() => ({}))
- throw new Error(errorData.message || errorData.error || `HTTP error! status: ${response.status}`)
+ throw new Error(
+ errorData.message ||
+ errorData.error ||
+ `HTTP error! status: ${response.status}`,
+ )
}
const reader = response.body?.getReader()
diff --git a/web/app/components/DashboardLockedBanner.tsx b/web/app/components/DashboardLockedBanner.tsx
index fb00fd40e..1c0267691 100644
--- a/web/app/components/DashboardLockedBanner.tsx
+++ b/web/app/components/DashboardLockedBanner.tsx
@@ -39,9 +39,14 @@ const DashboardLockedBanner = () => {
<div className='flex flex-wrap items-center justify-between'>
<div className='flex flex-1 items-center'>
<span className='flex rounded-lg bg-yellow-600 p-2'>
- <LockClosedIcon className='h-6 w-6 text-white' aria-hidden='true' />
+ <LockClosedIcon
+ className='h-6 w-6 text-white'
+ aria-hidden='true'
+ />
</span>
- <p className='ml-3 font-medium text-black'>{t('dashboard.accountLocked')}</p>
+ <p className='ml-3 font-medium text-black'>
+ {t('dashboard.accountLocked')}
+ </p>
</div>
<div className='order-3 mt-2 w-full shrink-0 sm:order-2 sm:mt-0 sm:w-auto'>
<span
diff --git a/web/app/components/EventsRunningOutBanner.tsx b/web/app/components/EventsRunningOutBanner.tsx
index 2a018e300..9c6705445 100644
--- a/web/app/components/EventsRunningOutBanner.tsx
+++ b/web/app/components/EventsRunningOutBanner.tsx
@@ -48,10 +48,15 @@ const EventsRunningOutBanner = () => {
<div className='flex flex-wrap items-center justify-between'>
<div className='flex flex-1 items-center'>
<span className='flex rounded-lg bg-yellow-600 p-2'>
- <ExclamationTriangleIcon className='h-6 w-6 text-white' aria-hidden='true' />
+ <ExclamationTriangleIcon
+ className='h-6 w-6 text-white'
+ aria-hidden='true'
+ />
</span>
<p className='ml-3 truncate font-medium text-black'>
- <span className='md:hidden'>{t('dashboard.lowEventsTitle')}</span>
+ <span className='md:hidden'>
+ {t('dashboard.lowEventsTitle')}
+ </span>
<span className='hidden md:inline'>
{t('dashboard.eventsXPercUsed', {
amount: SHOW_BANNER_AT_PERC,
diff --git a/web/app/components/ExitIntentPopup.tsx b/web/app/components/ExitIntentPopup.tsx
index 59a2d7a8d..eade24577 100644
--- a/web/app/components/ExitIntentPopup.tsx
+++ b/web/app/components/ExitIntentPopup.tsx
@@ -14,12 +14,16 @@ interface ExitIntentPopupProps {
const COOKIE_NAME = 'exit-intent-dismissed'
const COOKIE_EXPIRATION = 7 * 24 * 60 * 60
-export default function ExitIntentPopup({ isStandalone = false }: ExitIntentPopupProps) {
+export default function ExitIntentPopup({
+ isStandalone = false,
+}: ExitIntentPopupProps) {
const { t } = useTranslation('common')
const [isVisible, setIsVisible] = useState(false)
const [isDismissed, setIsDismissed] = useState(false)
const contextMenuActiveRef = useRef(false)
- const contextMenuTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null)
+ const contextMenuTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(
+ null,
+ )
useEffect(() => {
if (isStandalone) {
@@ -105,14 +109,20 @@ export default function ExitIntentPopup({ isStandalone = false }: ExitIntentPopu
</button>
<div className='mb-6'>
- <Badge className='text-base' label={t('exitIntentPopup.freeTrial')} colour='green' />
+ <Badge
+ className='text-base'
+ label={t('exitIntentPopup.freeTrial')}
+ colour='green'
+ />
</div>
<h2 className='mb-4 max-w-3xl text-[2.5rem]/10 font-semibold tracking-tight text-pretty text-gray-950 lg:text-5xl dark:text-gray-200'>
{t('exitIntentPopup.title')}
</h2>
- <p className='mb-8 text-xl leading-relaxed text-gray-950 dark:text-gray-200'>{t('exitIntentPopup.desc')}</p>
+ <p className='mb-8 text-xl leading-relaxed text-gray-950 dark:text-gray-200'>
+ {t('exitIntentPopup.desc')}
+ </p>
<Link
to='/'
diff --git a/web/app/components/Footer/index.tsx b/web/app/components/Footer/index.tsx
index 63401b7ea..964973be6 100644
--- a/web/app/components/Footer/index.tsx
+++ b/web/app/components/Footer/index.tsx
@@ -29,10 +29,26 @@ import routesPath from '~/utils/routes'
export const CONTACT_US_URL = `https://swetrix.com${routesPath.contact}`
const products = [
- { key: 'header.solutions.analytics.title', href: routesPath.main, internal: true },
- { key: 'header.solutions.performance.title', href: routesPath.performance, internal: true },
- { key: 'header.solutions.errors.title', href: routesPath.errorTracking, internal: true },
- { key: 'header.solutions.captcha.title', href: routesPath.captchaLanding, internal: true },
+ {
+ key: 'header.solutions.analytics.title',
+ href: routesPath.main,
+ internal: true,
+ },
+ {
+ key: 'header.solutions.performance.title',
+ href: routesPath.performance,
+ internal: true,
+ },
+ {
+ key: 'header.solutions.errors.title',
+ href: routesPath.errorTracking,
+ internal: true,
+ },
+ {
+ key: 'header.solutions.captcha.title',
+ href: routesPath.captchaLanding,
+ internal: true,
+ },
]
const productionNavigation = {
@@ -84,14 +100,34 @@ const communityEditionNavigation = {
resources: [
{ key: 'docs', href: DOCS_URL, internal: false },
{ key: 'pricing', href: `https://swetrix.com/#pricing`, internal: false },
- { key: 'tools', href: `https://swetrix.com${routesPath.tools}`, internal: false },
- { key: 'utm', href: `https://swetrix.com${routesPath.utm_generator}`, internal: false },
- { key: 'ctr', href: `https://swetrix.com${routesPath.ctr_calculator}`, internal: false },
- { key: 'roi', href: `https://swetrix.com${routesPath.roi_calculator}`, internal: false },
+ {
+ key: 'tools',
+ href: `https://swetrix.com${routesPath.tools}`,
+ internal: false,
+ },
+ {
+ key: 'utm',
+ href: `https://swetrix.com${routesPath.utm_generator}`,
+ internal: false,
+ },
+ {
+ key: 'ctr',
+ href: `https://swetrix.com${routesPath.ctr_calculator}`,
+ internal: false,
+ },
+ {
+ key: 'roi',
+ href: `https://swetrix.com${routesPath.roi_calculator}`,
+ internal: false,
+ },
],
company: [
{ key: 'cloudEdition', href: 'https://swetrix.com', internal: false },
- { key: 'blog', href: `https://swetrix.com${routesPath.blog}`, internal: false },
+ {
+ key: 'blog',
+ href: `https://swetrix.com${routesPath.blog}`,
+ internal: false,
+ },
{ key: 'supportUs', href: DONATE_URL, internal: false },
],
community: [
@@ -101,12 +137,27 @@ const communityEditionNavigation = {
{ name: 'LinkedIn', href: LINKEDIN_URL },
],
comparisons: [
- { name: 'Google Analytics', href: 'https://swetrix.com/comparison/google-analytics' },
+ {
+ name: 'Google Analytics',
+ href: 'https://swetrix.com/comparison/google-analytics',
+ },
{ name: 'Plausible', href: 'https://swetrix.com/comparison/plausible' },
- { name: 'Cloudflare Analytics', href: 'https://swetrix.com/comparison/cloudflare-analytics' },
- { name: 'Fathom Analytics', href: 'https://swetrix.com/comparison/fathom-analytics' },
- { name: 'Simple Analytics', href: 'https://swetrix.com/comparison/simple-analytics' },
- { name: 'Vercel Web Analytics', href: 'https://swetrix.com/comparison/vercel-web-analytics' },
+ {
+ name: 'Cloudflare Analytics',
+ href: 'https://swetrix.com/comparison/cloudflare-analytics',
+ },
+ {
+ name: 'Fathom Analytics',
+ href: 'https://swetrix.com/comparison/fathom-analytics',
+ },
+ {
+ name: 'Simple Analytics',
+ href: 'https://swetrix.com/comparison/simple-analytics',
+ },
+ {
+ name: 'Vercel Web Analytics',
+ href: 'https://swetrix.com/comparison/vercel-web-analytics',
+ },
{ name: 'Rybbit', href: 'https://swetrix.com/comparison/rybbit' },
{ name: 'Pirsch', href: 'https://swetrix.com/comparison/pirsch' },
{ name: 'Umami', href: 'https://swetrix.com/comparison/umami' },
@@ -114,12 +165,22 @@ const communityEditionNavigation = {
{ name: 'PostHog', href: 'https://swetrix.com/comparison/posthog' },
],
legal: [
- { key: 'contact', href: `https://swetrix.com${routesPath.contact}`, internal: false },
- { key: 'imprint', href: `https://swetrix.com${routesPath.imprint}`, internal: false },
+ {
+ key: 'contact',
+ href: `https://swetrix.com${routesPath.contact}`,
+ internal: false,
+ },
+ {
+ key: 'imprint',
+ href: `https://swetrix.com${routesPath.imprint}`,
+ internal: false,
+ },
],
}
-const navigation = isSelfhosted ? communityEditionNavigation : productionNavigation
+const navigation = isSelfhosted
+ ? communityEditionNavigation
+ : productionNavigation
const LanguageSelector = () => {
const {
@@ -133,13 +194,23 @@ const LanguageSelector = () => {
buttonClassName='!py-2 !px-3 inline-flex items-center rounded-md bg-transparent hover:bg-white/10 [&>svg]:w-4 [&>svg]:h-4 [&>svg]:mr-0 [&>svg]:ml-1 font-medium !text-sm text-white border border-white/20'
title={
<span className='inline-flex items-center'>
- <Flag className='mr-2 rounded-xs' country={languageFlag[language]} size={16} alt={languages[language]} />
+ <Flag
+ className='mr-2 rounded-xs'
+ country={languageFlag[language]}
+ size={16}
+ alt={languages[language]}
+ />
{languages[language]}
</span>
}
labelExtractor={(lng: string) => (
<div className='flex items-center'>
- <Flag className='mr-2 rounded-xs' country={languageFlag[lng]} size={16} alt={languageFlag[lng]} />
+ <Flag
+ className='mr-2 rounded-xs'
+ country={languageFlag[lng]}
+ size={16}
+ alt={languageFlag[lng]}
+ />
{languages[lng]}
</div>
)}
@@ -162,9 +233,15 @@ const ThemeSelector = () => {
title={
<span className='flex items-center'>
{theme === 'dark' ? (
- <MoonIcon className='mr-2 h-4 w-4 text-gray-300' aria-hidden='true' />
+ <MoonIcon
+ className='mr-2 h-4 w-4 text-gray-300'
+ aria-hidden='true'
+ />
) : (
- <SunIcon className='mr-2 h-4 w-4 text-gray-300' aria-hidden='true' />
+ <SunIcon
+ className='mr-2 h-4 w-4 text-gray-300'
+ aria-hidden='true'
+ />
)}
{theme === 'dark' ? t('header.dark') : t('header.light')}
</span>
@@ -203,10 +280,21 @@ interface FooterProps {
showDBIPMessage?: boolean
}
-const FooterLink = ({ href, internal, children }: { href: string; internal: boolean; children: React.ReactNode }) => {
+const FooterLink = ({
+ href,
+ internal,
+ children,
+}: {
+ href: string
+ internal: boolean
+ children: React.ReactNode
+}) => {
if (internal) {
return (
- <Link to={href} className='underline-animate text-sm text-white transition-colors'>
+ <Link
+ to={href}
+ className='underline-animate text-sm text-white transition-colors'
+ >
{children}
</Link>
)
@@ -246,7 +334,9 @@ const Footer = ({ showDBIPMessage }: FooterProps) => {
<ul className='-mx-3 flex flex-row flex-wrap gap-y-8 lg:flex-nowrap'>
<li className='flex w-1/2 flex-col px-3 lg:w-1/5'>
<ul>
- <li className='mb-4 text-sm font-bold text-white uppercase'>{t('footer.products')}</li>
+ <li className='mb-4 text-sm font-bold text-white uppercase'>
+ {t('footer.products')}
+ </li>
{_map(navigation.products, ({ key, href, internal }) => (
<li key={key} className='mb-2'>
<FooterLink href={href} internal={internal}>
@@ -259,7 +349,9 @@ const Footer = ({ showDBIPMessage }: FooterProps) => {
<li className='flex w-1/2 flex-col px-3 lg:w-1/5'>
<ul>
- <li className='mb-4 text-sm font-bold text-white uppercase'>{t('footer.resources')}</li>
+ <li className='mb-4 text-sm font-bold text-white uppercase'>
+ {t('footer.resources')}
+ </li>
{_map(navigation.resources, ({ key, href, internal }) => (
<li key={key} className='mb-2'>
<FooterLink href={href} internal={internal}>
@@ -272,7 +364,9 @@ const Footer = ({ showDBIPMessage }: FooterProps) => {
<li className='flex w-1/2 flex-col px-3 lg:w-1/5'>
<ul>
- <li className='mb-4 text-sm font-bold text-white uppercase'>{t('footer.company')}</li>
+ <li className='mb-4 text-sm font-bold text-white uppercase'>
+ {t('footer.company')}
+ </li>
{_map(navigation.company, ({ key, href, internal }) => (
<li key={key} className='mb-2'>
<FooterLink href={href} internal={internal}>
@@ -285,7 +379,9 @@ const Footer = ({ showDBIPMessage }: FooterProps) => {
<li className='flex w-1/2 flex-col px-3 lg:w-1/5'>
<ul>
- <li className='mb-4 text-sm font-bold text-white uppercase'>{t('footer.community')}</li>
+ <li className='mb-4 text-sm font-bold text-white uppercase'>
+ {t('footer.community')}
+ </li>
{_map(navigation.community, ({ name, href }) => (
<li key={name} className='mb-2'>
<FooterLink href={href} internal={false}>
@@ -298,7 +394,9 @@ const Footer = ({ showDBIPMessage }: FooterProps) => {
<li className='flex w-1/2 flex-col px-3 lg:w-1/5'>
<ul>
- <li className='mb-4 text-sm font-bold text-white uppercase'>{t('footer.comparisons')}</li>
+ <li className='mb-4 text-sm font-bold text-white uppercase'>
+ {t('footer.comparisons')}
+ </li>
{_map(navigation.comparisons, ({ name, href }) => (
<li key={name} className='mb-2'>
<FooterLink href={href} internal={!isSelfhosted}>
@@ -338,9 +436,27 @@ const Footer = ({ showDBIPMessage }: FooterProps) => {
{isSelfhosted ? null : (
<div className='mt-2 flex text-sm text-white'>
<Trans t={t} i18nKey='footer.madeInHostedIn'>
- <Flag className='mx-[1ch]' country='GB' size={16} alt='GB' aria-hidden='true' />
- <Flag className='mx-[1ch]' country='UA' size={16} alt='UA' aria-hidden='true' />
- <Flag className='mx-[1ch]' country='EU' size={16} alt='EU' aria-hidden='true' />
+ <Flag
+ className='mx-[1ch]'
+ country='GB'
+ size={16}
+ alt='GB'
+ aria-hidden='true'
+ />
+ <Flag
+ className='mx-[1ch]'
+ country='UA'
+ size={16}
+ alt='UA'
+ aria-hidden='true'
+ />
+ <Flag
+ className='mx-[1ch]'
+ country='EU'
+ size={16}
+ alt='EU'
+ aria-hidden='true'
+ />
</Trans>
</div>
)}
@@ -371,7 +487,12 @@ const Footer = ({ showDBIPMessage }: FooterProps) => {
{showDBIPMessage && isSelfhosted ? (
<>
{' · '}
- <a href='https://db-ip.com' target='_blank' rel='noopener noreferrer' className='underline-animate'>
+ <a
+ href='https://db-ip.com'
+ target='_blank'
+ rel='noopener noreferrer'
+ className='underline-animate'
+ >
IP Geolocation by DB-IP
</a>
</>
diff --git a/web/app/components/GithubAuth.tsx b/web/app/components/GithubAuth.tsx
index f3c7e50ad..b929c574a 100644
--- a/web/app/components/GithubAuth.tsx
+++ b/web/app/components/GithubAuth.tsx
@@ -13,7 +13,12 @@ interface GoogleAuthProps {
disabled?: boolean
}
-const GithubAuth = ({ isMiniButton, className, onClick, disabled }: GoogleAuthProps) => {
+const GithubAuth = ({
+ isMiniButton,
+ className,
+ onClick,
+ disabled,
+}: GoogleAuthProps) => {
const { t } = useTranslation()
const { theme } = useTheme()
@@ -30,7 +35,11 @@ const GithubAuth = ({ isMiniButton, className, onClick, disabled }: GoogleAuthPr
regular
disabled={disabled}
>
- {theme === 'dark' ? <GithubLightSVG className='size-5' /> : <GithubDarkSVG className='size-5' />}
+ {theme === 'dark' ? (
+ <GithubLightSVG className='size-5' />
+ ) : (
+ <GithubDarkSVG className='size-5' />
+ )}
</Button>
)
}
@@ -47,7 +56,11 @@ const GithubAuth = ({ isMiniButton, className, onClick, disabled }: GoogleAuthPr
disabled={disabled}
>
<>
- {theme === 'dark' ? <GithubLightSVG className='mr-2 size-5' /> : <GithubDarkSVG className='mr-2 size-5' />}
+ {theme === 'dark' ? (
+ <GithubLightSVG className='mr-2 size-5' />
+ ) : (
+ <GithubDarkSVG className='mr-2 size-5' />
+ )}
{t('auth.common.github')}
</>
</Button>
diff --git a/web/app/components/GoogleAuth.tsx b/web/app/components/GoogleAuth.tsx
index 8656dbedf..712905140 100644
--- a/web/app/components/GoogleAuth.tsx
+++ b/web/app/components/GoogleAuth.tsx
@@ -11,7 +11,12 @@ interface GoogleAuthProps {
disabled?: boolean
}
-const GoogleAuth = ({ onClick, isMiniButton, className, disabled }: GoogleAuthProps) => {
+const GoogleAuth = ({
+ onClick,
+ isMiniButton,
+ className,
+ disabled,
+}: GoogleAuthProps) => {
const { t } = useTranslation()
if (isMiniButton) {
diff --git a/web/app/components/Header/index.tsx b/web/app/components/Header/index.tsx
index 0f7395c58..ea7258b63 100644
--- a/web/app/components/Header/index.tsx
+++ b/web/app/components/Header/index.tsx
@@ -15,7 +15,11 @@ import {
PopoverBackdrop,
} from '@headlessui/react'
import { ArrowRightIcon } from '@heroicons/react/20/solid'
-import { Bars3Icon, XMarkIcon, ChevronDownIcon } from '@heroicons/react/24/outline'
+import {
+ Bars3Icon,
+ XMarkIcon,
+ ChevronDownIcon,
+} from '@heroicons/react/24/outline'
import { MoonIcon, SunIcon } from '@heroicons/react/24/solid'
import { SiYoutube } from '@icons-pack/react-simple-icons'
import cx from 'clsx'
@@ -25,13 +29,26 @@ import utc from 'dayjs/plugin/utc'
import { type t as i18nextT } from 'i18next'
import _map from 'lodash/map'
import _startsWith from 'lodash/startsWith'
-import { GaugeIcon, ChartPieIcon, BugIcon, PuzzleIcon, PhoneIcon } from 'lucide-react'
+import {
+ GaugeIcon,
+ ChartPieIcon,
+ BugIcon,
+ PuzzleIcon,
+ PhoneIcon,
+} from 'lucide-react'
import { memo, Fragment, useMemo, useState, useEffect } from 'react'
import { useTranslation } from 'react-i18next'
import { Link } from 'react-router'
import { changeLanguage } from '~/i18n'
-import { whitelist, languages, languageFlag, isSelfhosted, DOCS_URL, isDisableMarketingPages } from '~/lib/constants'
+import {
+ whitelist,
+ languages,
+ languageFlag,
+ isSelfhosted,
+ DOCS_URL,
+ isDisableMarketingPages,
+} from '~/lib/constants'
import { useAuth } from '~/providers/AuthProvider'
import { useTheme } from '~/providers/ThemeProvider'
import Flag from '~/ui/Flag'
@@ -78,7 +95,11 @@ const getSolutions = (t: typeof i18nextT) => [
]
const getCallsToAction = (t: typeof i18nextT) => [
- { name: t('header.watchDemo'), link: 'https://www.youtube.com/watch?v=XBp38fZREIE', icon: SiYoutube },
+ {
+ name: t('header.watchDemo'),
+ link: 'https://www.youtube.com/watch?v=XBp38fZREIE',
+ icon: SiYoutube,
+ },
{ name: t('header.contactSales'), link: routes.contact, icon: PhoneIcon },
]
@@ -126,7 +147,10 @@ const SolutionsMenu = () => {
/>
<div>
{_startsWith(item.link, '/') ? (
- <Link to={item.link} className='text-sm font-semibold text-gray-900 dark:text-gray-50'>
+ <Link
+ to={item.link}
+ className='text-sm font-semibold text-gray-900 dark:text-gray-50'
+ >
{item.name}
<span className='absolute inset-0' />
</Link>
@@ -142,7 +166,9 @@ const SolutionsMenu = () => {
</a>
)}
- <p className='mt-1 text-xs text-gray-600 dark:text-neutral-100'>{item.description}</p>
+ <p className='mt-1 text-xs text-gray-600 dark:text-neutral-100'>
+ {item.description}
+ </p>
</div>
</div>
))}
@@ -208,9 +234,12 @@ const ProfileMenu = ({ logoutHandler }: { logoutHandler: () => void }) => {
<MenuButton className='underline-animate flex items-center justify-center text-base leading-6 font-semibold text-slate-800 focus:outline-hidden dark:text-white'>
<span>{t('common.account')}</span>
<ChevronDownIcon
- className={cx('ml-1 h-4 w-4 transform-gpu stroke-2 transition-transform', {
- 'rotate-180': open,
- })}
+ className={cx(
+ 'ml-1 h-4 w-4 transform-gpu stroke-2 transition-transform',
+ {
+ 'rotate-180': open,
+ },
+ )}
aria-hidden='true'
/>
</MenuButton>
@@ -221,10 +250,16 @@ const ProfileMenu = ({ logoutHandler }: { logoutHandler: () => void }) => {
modal={false}
>
<p className='truncate p-2' role='none'>
- <span className='block text-xs text-gray-500 dark:text-gray-300' role='none'>
+ <span
+ className='block text-xs text-gray-500 dark:text-gray-300'
+ role='none'
+ >
{t('header.signedInAs')}
</span>
- <span className='mt-0.5 text-sm font-semibold text-gray-700 dark:text-gray-50' role='none'>
+ <span
+ className='mt-0.5 text-sm font-semibold text-gray-700 dark:text-gray-50'
+ role='none'
+ >
{user?.email}
</span>
</p>
@@ -394,16 +429,25 @@ const TrialBanner = () => {
const isTomorrow = future.isSame(now.add(1, 'day'), 'day')
if (isToday) {
- return [TRIAL_STATUS_MAPPING.ENDS_TODAY, t('header.trialBanner.endsToday')]
+ return [
+ TRIAL_STATUS_MAPPING.ENDS_TODAY,
+ t('header.trialBanner.endsToday'),
+ ]
}
if (isTomorrow) {
- return [TRIAL_STATUS_MAPPING.ENDS_TOMORROW, t('header.trialBanner.endsTomorrow')]
+ return [
+ TRIAL_STATUS_MAPPING.ENDS_TOMORROW,
+ t('header.trialBanner.endsTomorrow'),
+ ]
}
}
// trial ends in more than 1 day
const amount = Math.round(dayjs.duration(diff).asDays())
- return [TRIAL_STATUS_MAPPING.ENDS_IN_X_DAYS, t('header.trialBanner.youHaveXDaysLeft', { amount })]
+ return [
+ TRIAL_STATUS_MAPPING.ENDS_IN_X_DAYS,
+ t('header.trialBanner.youHaveXDaysLeft', { amount }),
+ ]
}, [user, t])
const blackFridayBannerVisible = useMemo(() => {
@@ -504,17 +548,23 @@ const BlackFridayBanner = () => {
{/* Mobile layout - compact, wraps if needed */}
<div className='relative flex flex-wrap items-center justify-center gap-x-2 gap-y-1 px-3 py-1.5 sm:hidden'>
- <span className='flex items-center gap-2 text-sm text-white/90'>Get</span>
+ <span className='flex items-center gap-2 text-sm text-white/90'>
+ Get
+ </span>
<span className='rounded bg-gradient-to-r from-amber-500 to-orange-500 px-1.5 py-0.5 text-xs font-bold text-white'>
50% OFF
</span>
- <div className='flex items-center gap-2 text-sm text-white/90'>with the code:</div>
+ <div className='flex items-center gap-2 text-sm text-white/90'>
+ with the code:
+ </div>
<code className='rounded bg-black/40 px-1.5 py-0.5 font-mono text-xs font-bold text-amber-400'>
BLACKFRIDAY
</code>
<span className='font-mono text-xs text-white/80'>
- {String(timeLeft.days).padStart(2, '0')}:{String(timeLeft.hours).padStart(2, '0')}:
- {String(timeLeft.minutes).padStart(2, '0')}:{String(timeLeft.seconds).padStart(2, '0')}
+ {String(timeLeft.days).padStart(2, '0')}:
+ {String(timeLeft.hours).padStart(2, '0')}:
+ {String(timeLeft.minutes).padStart(2, '0')}:
+ {String(timeLeft.seconds).padStart(2, '0')}
</span>
</div>
@@ -590,7 +640,8 @@ const AuthedHeader = ({
return (
<header
className={cx('relative overflow-x-clip', {
- 'border-b border-gray-200 bg-gray-50 dark:border-slate-600/40 dark:bg-slate-900': colourBackground,
+ 'border-b border-gray-200 bg-gray-50 dark:border-slate-600/40 dark:bg-slate-900':
+ colourBackground,
})}
>
<nav className='mx-auto max-w-7xl px-4 sm:px-6 lg:px-8' aria-label='Top'>
@@ -611,7 +662,9 @@ const AuthedHeader = ({
{t('billing.inactive')}
</Link>
) : null}
- {!isSelfhosted && !isDisableMarketingPages ? <SolutionsMenu /> : null}
+ {!isSelfhosted && !isDisableMarketingPages ? (
+ <SolutionsMenu />
+ ) : null}
{!isSelfhosted && !isDisableMarketingPages ? (
<Link
to={routes.blog}
@@ -669,7 +722,8 @@ const NotAuthedHeader = ({
return (
<header
className={cx('relative overflow-x-clip', {
- 'border-b border-gray-200 bg-gray-50 dark:border-slate-600/40 dark:bg-slate-900': colourBackground,
+ 'border-b border-gray-200 bg-gray-50 dark:border-slate-600/40 dark:bg-slate-900':
+ colourBackground,
})}
>
<nav className='mx-auto max-w-7xl px-4 sm:px-6 lg:px-8' aria-label='Top'>
@@ -686,7 +740,9 @@ const NotAuthedHeader = ({
{!refPage ? (
<div className='ml-10 hidden items-center gap-4 space-x-1 lg:flex'>
- {!isSelfhosted && !isDisableMarketingPages ? <SolutionsMenu /> : null}
+ {!isSelfhosted && !isDisableMarketingPages ? (
+ <SolutionsMenu />
+ ) : null}
{!isSelfhosted && !isDisableMarketingPages ? (
<Link
to={routes.blog}
@@ -780,13 +836,25 @@ const Header = ({ refPage, transparent }: HeaderProps) => {
{/* Computer / Laptop / Tablet layout header */}
{isAuthenticated ? (
- <AuthedHeader logoutHandler={logoutHandler} colourBackground={!transparent} openMenu={openMenu} />
+ <AuthedHeader
+ logoutHandler={logoutHandler}
+ colourBackground={!transparent}
+ openMenu={openMenu}
+ />
) : (
- <NotAuthedHeader colourBackground={!transparent} refPage={refPage} openMenu={openMenu} />
+ <NotAuthedHeader
+ colourBackground={!transparent}
+ refPage={refPage}
+ openMenu={openMenu}
+ />
)}
{/* Mobile header popup */}
- <Dialog className='lg:hidden' open={mobileMenuOpen} onClose={setMobileMenuOpen}>
+ <Dialog
+ className='lg:hidden'
+ open={mobileMenuOpen}
+ onClose={setMobileMenuOpen}
+ >
<div className='fixed inset-0 z-10' />
<DialogPanel className='fixed inset-y-0 top-0 right-0 z-30 w-full overflow-y-auto border-gray-300/80 bg-gray-100/80 p-4 backdrop-blur-2xl sm:max-w-sm sm:border dark:border-slate-900/80 dark:bg-slate-800/80'>
<div className='flex items-center justify-between'>
@@ -832,7 +900,10 @@ const Header = ({ refPage, transparent }: HeaderProps) => {
<DisclosureButton className='flex w-full items-center justify-between rounded-lg py-2 pr-3.5 pl-3 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'>
{t('header.solutions.title')}
<ChevronDownIcon
- className={cx(open ? 'rotate-180' : '', 'h-5 w-5 flex-none')}
+ className={cx(
+ open ? 'rotate-180' : '',
+ 'h-5 w-5 flex-none',
+ )}
aria-hidden='true'
/>
</DisclosureButton>
@@ -880,7 +951,9 @@ const Header = ({ refPage, transparent }: HeaderProps) => {
</a>
)}
- <p className='mt-1 text-xs text-gray-600 dark:text-neutral-100'>{item.description}</p>
+ <p className='mt-1 text-xs text-gray-600 dark:text-neutral-100'>
+ {item.description}
+ </p>
</div>
</DisclosureButton>
))}
@@ -890,7 +963,9 @@ const Header = ({ refPage, transparent }: HeaderProps) => {
)}
</Disclosure>
) : null}
- {!isSelfhosted && isAuthenticated && user?.planCode === 'none' ? (
+ {!isSelfhosted &&
+ isAuthenticated &&
+ user?.planCode === 'none' ? (
<Link
to={routes.billing}
onClick={() => setMobileMenuOpen(false)}
@@ -900,7 +975,10 @@ const Header = ({ refPage, transparent }: HeaderProps) => {
{t('billing.inactive')}
</Link>
) : null}
- {!isSelfhosted && isAuthenticated && user?.planCode !== 'none' && user?.planCode !== 'trial' ? (
+ {!isSelfhosted &&
+ isAuthenticated &&
+ user?.planCode !== 'none' &&
+ user?.planCode !== 'trial' ? (
<Link
to={routes.billing}
onClick={() => setMobileMenuOpen(false)}
@@ -910,7 +988,9 @@ const Header = ({ refPage, transparent }: HeaderProps) => {
{t('common.billing')}
</Link>
) : null}
- {!isSelfhosted && !isDisableMarketingPages && !isAuthenticated ? (
+ {!isSelfhosted &&
+ !isDisableMarketingPages &&
+ !isAuthenticated ? (
<Link
to={`${routes.main}#pricing`}
onClick={() => setMobileMenuOpen(false)}
@@ -989,7 +1069,9 @@ const Header = ({ refPage, transparent }: HeaderProps) => {
className='-mx-3 block 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'
aria-label={t('titles.signup')}
>
- {isSelfhosted ? t('header.signUp') : t('header.startForFree')}
+ {isSelfhosted
+ ? t('header.signUp')
+ : t('header.startForFree')}
</Link>
</>
)}
diff --git a/web/app/components/LocaleLinks.tsx b/web/app/components/LocaleLinks.tsx
index 769b2e68c..b2eba561b 100644
--- a/web/app/components/LocaleLinks.tsx
+++ b/web/app/components/LocaleLinks.tsx
@@ -3,7 +3,12 @@ import _some from 'lodash/some'
import { useMemo } from 'react'
import { useLocation, Location } from 'react-router'
-import { whitelist, whitelistWithCC, MAIN_URL, defaultLanguage } from '~/lib/constants'
+import {
+ whitelist,
+ whitelistWithCC,
+ MAIN_URL,
+ defaultLanguage,
+} from '~/lib/constants'
const getUrlFromLocation = (location: Location) => {
const { pathname, hash, search } = location
@@ -69,7 +74,10 @@ const getShouldBeIgnored = (location: Location) => {
export const LocaleLinks = () => {
const location = useLocation()
- const shouldBeIgnored = useMemo(() => getShouldBeIgnored(location), [location])
+ const shouldBeIgnored = useMemo(
+ () => getShouldBeIgnored(location),
+ [location],
+ )
const altLinks = useMemo(() => getAlternateLinks(location), [location])
if (shouldBeIgnored) {
diff --git a/web/app/components/SEO.tsx b/web/app/components/SEO.tsx
index a18bf8f7a..0d640a54a 100644
--- a/web/app/components/SEO.tsx
+++ b/web/app/components/SEO.tsx
@@ -45,7 +45,10 @@ export const SEO = () => {
<>
<title>{title}</title>
<meta property='og:title' content='Swetrix' />
- <meta name='twitter:title' content='Swetrix | Turn traffic into insights' />
+ <meta
+ name='twitter:title'
+ content='Swetrix | Turn traffic into insights'
+ />
<meta
name='description'
content='Swetrix is a cookieless, privacy-first and GDPR-compliant Google Analytics alternative'
@@ -60,14 +63,26 @@ export const SEO = () => {
/>
{isMainPage ? (
<>
- <meta name='twitter:image' content='https://swetrix.com/assets/og_image.png?v=1' />
- <meta property='og:image' content='https://swetrix.com/assets/og_image.png?v=1' />
+ <meta
+ name='twitter:image'
+ content='https://swetrix.com/assets/og_image.png?v=1'
+ />
+ <meta
+ property='og:image'
+ content='https://swetrix.com/assets/og_image.png?v=1'
+ />
</>
) : null}
{isErrorsPage ? (
<>
- <meta name='twitter:image' content='https://swetrix.com/assets/og_image_errors.png?v=1' />
- <meta property='og:image' content='https://swetrix.com/assets/og_image_errors.png?v=1' />
+ <meta
+ name='twitter:image'
+ content='https://swetrix.com/assets/og_image_errors.png?v=1'
+ />
+ <meta
+ property='og:image'
+ content='https://swetrix.com/assets/og_image_errors.png?v=1'
+ />
</>
) : null}
{!isProjectViewPage && !isMainPage && !isErrorsPage ? (
diff --git a/web/app/components/SelfhostedApiUrlBanner.tsx b/web/app/components/SelfhostedApiUrlBanner.tsx
index c74ad18a2..5a02d8a9b 100644
--- a/web/app/components/SelfhostedApiUrlBanner.tsx
+++ b/web/app/components/SelfhostedApiUrlBanner.tsx
@@ -20,9 +20,14 @@ const SelfhostedApiUrlBanner = () => {
<div className='flex flex-wrap items-center justify-between'>
<div className='flex flex-1 items-center'>
<span className='flex rounded-lg bg-yellow-600 p-2'>
- <ExclamationTriangleIcon className='h-6 w-6 text-white' aria-hidden='true' />
+ <ExclamationTriangleIcon
+ className='h-6 w-6 text-white'
+ aria-hidden='true'
+ />
</span>
- <p className='ml-3 truncate font-medium text-black'>{t('ce.noApiUrl.banner')}</p>
+ <p className='ml-3 truncate font-medium text-black'>
+ {t('ce.noApiUrl.banner')}
+ </p>
</div>
<div className='order-3 mt-2 w-full shrink-0 sm:order-2 sm:mt-0 sm:w-auto'>
<span
@@ -51,10 +56,12 @@ const SelfhostedApiUrlBanner = () => {
<p className='mb-2 font-medium'>{t('ce.noApiUrl.examplesTitle')}</p>
<ul className='mb-3 list-disc pl-6'>
<li>
- {t('ce.noApiUrl.exampleLocal.label')} <code>{t('ce.noApiUrl.exampleLocal.value')}</code>
+ {t('ce.noApiUrl.exampleLocal.label')}{' '}
+ <code>{t('ce.noApiUrl.exampleLocal.value')}</code>
</li>
<li>
- {t('ce.noApiUrl.exampleSubdomain.label')} <code>{t('ce.noApiUrl.exampleSubdomain.value')}</code>
+ {t('ce.noApiUrl.exampleSubdomain.label')}{' '}
+ <code>{t('ce.noApiUrl.exampleSubdomain.value')}</code>
</li>
</ul>
<p>{t('ce.noApiUrl.finalNote')}</p>
diff --git a/web/app/components/marketing/ComparisonTable.tsx b/web/app/components/marketing/ComparisonTable.tsx
index 02d16db00..bc1454e94 100644
--- a/web/app/components/marketing/ComparisonTable.tsx
+++ b/web/app/components/marketing/ComparisonTable.tsx
@@ -3,7 +3,12 @@ import cx from 'clsx'
import _map from 'lodash/map'
import { useTranslation } from 'react-i18next'
-const COMPETITORS_LIST = ['Google Analytics', 'Fathom', 'Plausible', 'Simple Analytics']
+const COMPETITORS_LIST = [
+ 'Google Analytics',
+ 'Fathom',
+ 'Plausible',
+ 'Simple Analytics',
+]
const SWETRIX_AND_COMPETITORS_LIST = ['Swetrix', ...COMPETITORS_LIST]
// The order in the table is defined by the Swetrix object
@@ -111,9 +116,14 @@ export const ComparisonTable = ({ className }: ComparisonTableProps) => {
<tbody className='divide-y divide-slate-300 bg-gray-50 dark:divide-slate-700 dark:bg-slate-800'>
{_map(COMPETITOR_FEATURE_TABLE.Swetrix, (_, key) => (
<tr key={key}>
- <td className='w-1/6 px-3 py-4 text-sm text-slate-700 sm:pl-6 dark:text-gray-50'>{t(key)}</td>
+ <td className='w-1/6 px-3 py-4 text-sm text-slate-700 sm:pl-6 dark:text-gray-50'>
+ {t(key)}
+ </td>
{_map(SWETRIX_AND_COMPETITORS_LIST, (service) => (
- <td key={`${key}-${service}`} className='w-1/6 px-3 py-4 text-sm text-gray-50 sm:pl-6'>
+ <td
+ key={`${key}-${service}`}
+ className='w-1/6 px-3 py-4 text-sm text-gray-50 sm:pl-6'
+ >
{COMPETITOR_FEATURE_TABLE[service][key] ? (
<CheckIcon
className='h-5 w-5 shrink-0 text-green-600 dark:text-green-500'
diff --git a/web/app/components/marketing/FAQ.tsx b/web/app/components/marketing/FAQ.tsx
index 70fabe7b7..7e5422fa4 100644
--- a/web/app/components/marketing/FAQ.tsx
+++ b/web/app/components/marketing/FAQ.tsx
@@ -16,8 +16,10 @@ const FAQ = () => {
}
const values = {
- lowestPlanEventsAmount: PLAN_LIMITS['100k'].monthlyUsageLimit.toLocaleString('en-US'),
- moderatePlanEventsAmount: PLAN_LIMITS['500k'].monthlyUsageLimit.toLocaleString('en-US'),
+ lowestPlanEventsAmount:
+ PLAN_LIMITS['100k'].monthlyUsageLimit.toLocaleString('en-US'),
+ moderatePlanEventsAmount:
+ PLAN_LIMITS['500k'].monthlyUsageLimit.toLocaleString('en-US'),
freeTrialDays: TRIAL_DAYS,
}
const stripTags = (html: string) =>
@@ -25,7 +27,10 @@ const FAQ = () => {
allowedTags: [],
allowedAttributes: {},
})
- const items = t('main.faq.items', { returnObjects: true }) as { q: string; a: string }[]
+ const items = t('main.faq.items', { returnObjects: true }) as {
+ q: string
+ a: string
+ }[]
const structuredData = {
'@context': 'https://schema.org',
'@type': 'FAQPage',
@@ -55,7 +60,11 @@ const FAQ = () => {
return (
<details
key={item.q}
- className={cn('group w-full text-left', showTopBorder && 'border-t border-gray-200 dark:border-white/10')}
+ className={cn(
+ 'group w-full text-left',
+ showTopBorder &&
+ 'border-t border-gray-200 dark:border-white/10',
+ )}
>
<summary className='flex w-full cursor-pointer items-center justify-between px-4 py-4'>
<span className='text-base font-medium text-slate-900 group-hover:underline dark:text-white'>
diff --git a/web/app/components/pricing/BillingPricing.tsx b/web/app/components/pricing/BillingPricing.tsx
index f47f59ab2..86073915c 100644
--- a/web/app/components/pricing/BillingPricing.tsx
+++ b/web/app/components/pricing/BillingPricing.tsx
@@ -36,9 +36,13 @@ interface BillingPricingProps {
metainfo?: Metainfo
}
-const formatEventsLong = (value: number): string => value.toLocaleString('en-US')
+const formatEventsLong = (value: number): string =>
+ value.toLocaleString('en-US')
-const BillingPricing = ({ lastEvent, metainfo = DEFAULT_METAINFO }: BillingPricingProps) => {
+const BillingPricing = ({
+ lastEvent,
+ metainfo = DEFAULT_METAINFO,
+}: BillingPricingProps) => {
const {
t,
i18n: { language },
@@ -50,7 +54,10 @@ const BillingPricing = ({ lastEvent, metainfo = DEFAULT_METAINFO }: BillingPrici
const changePlanFetcher = useFetcher<BillingActionData>()
const [planCodeLoading, setPlanCodeLoading] = useState<string | null>(null)
- const [isNewPlanConfirmationModalOpened, setIsNewPlanConfirmationModalOpened] = useState(false)
+ const [
+ isNewPlanConfirmationModalOpened,
+ setIsNewPlanConfirmationModalOpened,
+ ] = useState(false)
const [newPlanId, setNewPlanId] = useState<number | null>(null)
const [downgradeTo, setDowngradeTo] = useState<{
planCode: string
@@ -59,11 +66,16 @@ const BillingPricing = ({ lastEvent, metainfo = DEFAULT_METAINFO }: BillingPrici
ypid: string
} | null>(null)
const [showDowngradeModal, setShowDowngradeModal] = useState(false)
- const [billingFrequency, setBillingFrequency] = useState(user?.billingFrequency || BillingFrequency.monthly)
+ const [billingFrequency, setBillingFrequency] = useState(
+ user?.billingFrequency || BillingFrequency.monthly,
+ )
const [enableLegacyPlans, setEnableLegacyPlans] = useState(false)
const subUpdatePreview = useMemo(() => {
- if (previewFetcher.state === 'loading' || previewFetcher.state === 'submitting') {
+ if (
+ previewFetcher.state === 'loading' ||
+ previewFetcher.state === 'submitting'
+ ) {
return null
}
if (previewFetcher.data?.success && previewFetcher.data.data) {
@@ -75,7 +87,9 @@ const BillingPricing = ({ lastEvent, metainfo = DEFAULT_METAINFO }: BillingPrici
return null
}, [previewFetcher.data, previewFetcher.state])
- const isSubUpdating = changePlanFetcher.state === 'submitting' || changePlanFetcher.state === 'loading'
+ const isSubUpdating =
+ changePlanFetcher.state === 'submitting' ||
+ changePlanFetcher.state === 'loading'
useEffect(() => {
const urlParams = new URLSearchParams(window.location.search)
@@ -92,7 +106,10 @@ const BillingPricing = ({ lastEvent, metainfo = DEFAULT_METAINFO }: BillingPrici
toast.success(t('apiNotifications.subscriptionUpdated'))
closeUpdateModal(true)
} else if (changePlanFetcher.data?.error) {
- console.error('[ERROR] An error occured while updating subscription:', changePlanFetcher.data.error)
+ console.error(
+ '[ERROR] An error occured while updating subscription:',
+ changePlanFetcher.data.error,
+ )
toast.error('An error occured while updating subscription')
closeUpdateModal(true)
}
@@ -106,7 +123,9 @@ const BillingPricing = ({ lastEvent, metainfo = DEFAULT_METAINFO }: BillingPrici
'[ERROR] An error occured while loading subscription update pricing preview:',
previewFetcher.data.error,
)
- toast.error('An error occured while loading subscription update pricing preview')
+ toast.error(
+ 'An error occured while loading subscription update pricing preview',
+ )
}
}, [previewFetcher.data?.error])
@@ -169,8 +188,14 @@ const BillingPricing = ({ lastEvent, metainfo = DEFAULT_METAINFO }: BillingPrici
if (planCodeLoading || !isSelectingDifferentPlan) return
- if (user.subID && !user.cancellationEffectiveDate && user.planCode !== 'none') {
- const planId = Number(billingFrequency === BillingFrequency.monthly ? tier.pid : tier.ypid)
+ if (
+ user.subID &&
+ !user.cancellationEffectiveDate &&
+ user.planCode !== 'none'
+ ) {
+ const planId = Number(
+ billingFrequency === BillingFrequency.monthly ? tier.pid : tier.ypid,
+ )
setNewPlanId(planId)
loadSubUpdatePreview(planId)
return
@@ -185,7 +210,8 @@ const BillingPricing = ({ lastEvent, metainfo = DEFAULT_METAINFO }: BillingPrici
}
window.Paddle.Checkout.open({
- product: billingFrequency === BillingFrequency.monthly ? tier.pid : tier.ypid,
+ product:
+ billingFrequency === BillingFrequency.monthly ? tier.pid : tier.ypid,
email: user.email,
passthrough: JSON.stringify({ uid: user.id }),
locale: paddleLanguageMapping[language] || language,
@@ -224,8 +250,12 @@ const BillingPricing = ({ lastEvent, metainfo = DEFAULT_METAINFO }: BillingPrici
const getActionLabel = (tier: any): string => {
const planCodeID = tier.index
- const downgrade = !user?.cancellationEffectiveDate && planCodeID < userPlancodeID
- if (user?.cancellationEffectiveDate || isUnselectablePlanCode(user?.planCode)) {
+ const downgrade =
+ !user?.cancellationEffectiveDate && planCodeID < userPlancodeID
+ if (
+ user?.cancellationEffectiveDate ||
+ isUnselectablePlanCode(user?.planCode)
+ ) {
return t('pricing.subscribe')
}
if (planCodeID > userPlancodeID) {
@@ -234,23 +264,30 @@ const BillingPricing = ({ lastEvent, metainfo = DEFAULT_METAINFO }: BillingPrici
if (downgrade) {
return t('pricing.downgrade')
}
- if (user?.billingFrequency === billingFrequency && user?.planCode === tier.planCode) {
+ if (
+ user?.billingFrequency === billingFrequency &&
+ user?.planCode === tier.planCode
+ ) {
return t('pricing.yourPlan')
}
- return billingFrequency === BillingFrequency.monthly ? t('pricing.switchToMonthly') : t('pricing.switchToYearly')
+ return billingFrequency === BillingFrequency.monthly
+ ? t('pricing.switchToMonthly')
+ : t('pricing.switchToYearly')
}
const isDisabledForTier = (tier: any): boolean => {
return (
planCodeLoading !== null ||
(tier.planCode === user?.planCode &&
- (user?.billingFrequency === billingFrequency || isUnselectablePlanCode(user?.planCode)))
+ (user?.billingFrequency === billingFrequency ||
+ isUnselectablePlanCode(user?.planCode)))
)
}
const tiers = useMemo(() => {
const validCodes = PLAN_CODES_ARRAY.filter(
- (code): code is keyof typeof PLAN_LIMITS => typeof code === 'string' && code in PLAN_LIMITS,
+ (code): code is keyof typeof PLAN_LIMITS =>
+ typeof code === 'string' && code in PLAN_LIMITS,
)
return validCodes.map((code) => PLAN_LIMITS[code])
}, [PLAN_CODES_ARRAY])
@@ -259,7 +296,9 @@ const BillingPricing = ({ lastEvent, metainfo = DEFAULT_METAINFO }: BillingPrici
<>
<div className='rounded-xl border border-gray-200 p-4 sm:p-6 dark:border-white/10'>
<div className='mb-3 flex justify-between'>
- <h2 className='text-2xl font-bold text-black dark:text-gray-50'>{t('common.billing')}</h2>
+ <h2 className='text-2xl font-bold text-black dark:text-gray-50'>
+ {t('common.billing')}
+ </h2>
<RadioGroup
value={billingFrequency}
onChange={setBillingFrequency}
@@ -305,15 +344,22 @@ const BillingPricing = ({ lastEvent, metainfo = DEFAULT_METAINFO }: BillingPrici
'flex items-center justify-between rounded-xl border px-4 py-3 text-black backdrop-blur-sm dark:bg-white/2 dark:text-white',
{
'border-gray-200 dark:border-white/10':
- user?.planCode !== tier.planCode || isUnselectablePlanCode(tier.planCode),
- 'border-indigo-500': user?.planCode === tier.planCode && !isUnselectablePlanCode(tier.planCode),
+ user?.planCode !== tier.planCode ||
+ isUnselectablePlanCode(tier.planCode),
+ 'border-indigo-500':
+ user?.planCode === tier.planCode &&
+ !isUnselectablePlanCode(tier.planCode),
},
)}
>
<div>
- <span className='text-base font-medium'>{formatEventsLong(tier.monthlyUsageLimit)}</span>
+ <span className='text-base font-medium'>
+ {formatEventsLong(tier.monthlyUsageLimit)}
+ </span>
&nbsp;
- <span className='text-sm text-gray-500 dark:text-gray-400'>{t('pricing.eventsPerMonth')}</span>
+ <span className='text-sm text-gray-500 dark:text-gray-400'>
+ {t('pricing.eventsPerMonth')}
+ </span>
</div>
<div className='flex items-center gap-3 text-sm'>
{tier.legacy ? (
@@ -346,7 +392,12 @@ const BillingPricing = ({ lastEvent, metainfo = DEFAULT_METAINFO }: BillingPrici
</span>
&nbsp;
<span className='text-sm'>
- /{t(billingFrequency === BillingFrequency.monthly ? 'pricing.perMonth' : 'pricing.perYear')}
+ /
+ {t(
+ billingFrequency === BillingFrequency.monthly
+ ? 'pricing.perMonth'
+ : 'pricing.perYear',
+ )}
</span>
</div>
<Button
@@ -380,7 +431,9 @@ const BillingPricing = ({ lastEvent, metainfo = DEFAULT_METAINFO }: BillingPrici
<span className='text-base font-medium'>
{t('pricing.overXEvents', { amount: formatEventsLong(20000000) })}
</span>
- <p className='text-sm group-hover:underline'>{t('pricing.contactUs')}</p>
+ <p className='text-sm group-hover:underline'>
+ {t('pricing.contactUs')}
+ </p>
</a>
</div>
</div>
@@ -400,7 +453,13 @@ const BillingPricing = ({ lastEvent, metainfo = DEFAULT_METAINFO }: BillingPrici
closeText={t('common.no')}
title={t('pricing.downgradeTitle')}
type='warning'
- message={<Trans t={t} i18nKey='pricing.downgradeDesc' values={{ email: CONTACT_EMAIL }} />}
+ message={
+ <Trans
+ t={t}
+ i18nKey='pricing.downgradeDesc'
+ values={{ email: CONTACT_EMAIL }}
+ />
+ }
isOpened={showDowngradeModal}
/>
@@ -463,10 +522,14 @@ const BillingPricing = ({ lastEvent, metainfo = DEFAULT_METAINFO }: BillingPrici
</td>
<td className='px-3 py-4 text-sm whitespace-nowrap text-gray-900 dark:text-gray-50'>
{language === 'en'
- ? dayjs((subUpdatePreview as any).immediatePayment.date)
+ ? dayjs(
+ (subUpdatePreview as any).immediatePayment.date,
+ )
.locale(language)
.format('MMMM D, YYYY')
- : dayjs((subUpdatePreview as any).immediatePayment.date)
+ : dayjs(
+ (subUpdatePreview as any).immediatePayment.date,
+ )
.locale(language)
.format('D MMMM, YYYY')}
</td>
@@ -477,21 +540,30 @@ const BillingPricing = ({ lastEvent, metainfo = DEFAULT_METAINFO }: BillingPrici
{(subUpdatePreview as any).immediatePayment.amount < 0 ? (
<p className='mt-2 italic'>
{t('billing.negativePayment', {
- currency: (subUpdatePreview as any).immediatePayment.symbol,
- dueNowAmount: -(subUpdatePreview as any).immediatePayment.amount,
+ currency: (subUpdatePreview as any).immediatePayment
+ .symbol,
+ dueNowAmount: -(subUpdatePreview as any).immediatePayment
+ .amount,
dueNowDate:
language === 'en'
- ? dayjs((subUpdatePreview as any).immediatePayment.date)
+ ? dayjs(
+ (subUpdatePreview as any).immediatePayment.date,
+ )
.locale(language)
.format('MMMM D, YYYY')
- : dayjs((subUpdatePreview as any).immediatePayment.date)
+ : dayjs(
+ (subUpdatePreview as any).immediatePayment.date,
+ )
.locale(language)
.format('D MMMM, YYYY'),
- nextPaymentAmount: (subUpdatePreview as any).nextPayment.amount,
+ nextPaymentAmount: (subUpdatePreview as any).nextPayment
+ .amount,
})}
</p>
) : null}
- <h2 className='mt-5 text-base font-bold'>{t('billing.nextPayment')}</h2>
+ <h2 className='mt-5 text-base font-bold'>
+ {t('billing.nextPayment')}
+ </h2>
<div className='mt-2 overflow-hidden ring-1 ring-black/5 md:rounded-lg'>
<table className='200 min-w-full divide-y divide-gray-300 dark:divide-gray-500'>
<thead className='bg-gray-50 dark:bg-slate-800'>
diff --git a/web/app/components/pricing/MarketingPricing.tsx b/web/app/components/pricing/MarketingPricing.tsx
index e8dc44b0e..98a10a95e 100644
--- a/web/app/components/pricing/MarketingPricing.tsx
+++ b/web/app/components/pricing/MarketingPricing.tsx
@@ -7,7 +7,13 @@ import { useState } from 'react'
import { useTranslation } from 'react-i18next'
import { Link } from 'react-router'
-import { CURRENCIES, PLAN_LIMITS, STANDARD_PLANS, BillingFrequency, TRIAL_DAYS } from '~/lib/constants'
+import {
+ CURRENCIES,
+ PLAN_LIMITS,
+ STANDARD_PLANS,
+ BillingFrequency,
+ TRIAL_DAYS,
+} from '~/lib/constants'
import { DEFAULT_METAINFO, Metainfo } from '~/lib/models/Metainfo'
import { useAuth } from '~/providers/AuthProvider'
import Tooltip from '~/ui/Tooltip'
@@ -19,22 +25,30 @@ interface MarketingPricingProps {
metainfo?: Metainfo
}
-const MarketingPricing = ({ metainfo = DEFAULT_METAINFO }: MarketingPricingProps) => {
+const MarketingPricing = ({
+ metainfo = DEFAULT_METAINFO,
+}: MarketingPricingProps) => {
const { isAuthenticated } = useAuth()
const { t } = useTranslation('common')
- const [billingFrequency, setBillingFrequency] = useState(BillingFrequency.monthly)
+ const [billingFrequency, setBillingFrequency] = useState(
+ BillingFrequency.monthly,
+ )
const currencyCode = metainfo.code
const currency = CURRENCIES[currencyCode]
- const plans = STANDARD_PLANS.map((code) => PLAN_LIMITS[code as keyof typeof PLAN_LIMITS])
+ const plans = STANDARD_PLANS.map(
+ (code) => PLAN_LIMITS[code as keyof typeof PLAN_LIMITS],
+ )
return (
<section id='pricing' className='relative p-2'>
<div className='rounded-xl bg-slate-900 py-16 sm:py-20'>
<div className='mx-auto grid max-w-7xl grid-cols-1 gap-6 px-4 sm:px-6 lg:grid-cols-12 lg:gap-10 lg:px-8'>
<div className='col-span-12 lg:col-span-5'>
- <h2 className='text-3xl font-extrabold tracking-tight text-white sm:text-4xl'>{t('pricing.title')}</h2>
+ <h2 className='text-3xl font-extrabold tracking-tight text-white sm:text-4xl'>
+ {t('pricing.title')}
+ </h2>
<p className='mt-2 max-w-md text-sm text-gray-100'>
{t('pricing.adv', {
amount: TRIAL_DAYS,
@@ -46,10 +60,19 @@ const MarketingPricing = ({ metainfo = DEFAULT_METAINFO }: MarketingPricingProps
{
label: (
<div className='flex items-center gap-2'>
- <span>{t('pricing.tiers.upToXWebsites', { amount: 50 })}</span>
+ <span>
+ {t('pricing.tiers.upToXWebsites', { amount: 50 })}
+ </span>
<Tooltip
- text={t('pricing.tiers.moreWebsitesForFee', { amount: 50 })}
- tooltipNode={<CircleHelpIcon className='size-4 stroke-gray-50' strokeWidth={1.5} />}
+ text={t('pricing.tiers.moreWebsitesForFee', {
+ amount: 50,
+ })}
+ tooltipNode={
+ <CircleHelpIcon
+ className='size-4 stroke-gray-50'
+ strokeWidth={1.5}
+ />
+ }
/>
</div>
),
@@ -107,11 +130,15 @@ const MarketingPricing = ({ metainfo = DEFAULT_METAINFO }: MarketingPricingProps
to={isAuthenticated ? routes.billing : routes.signup}
className='mt-8 flex max-w-max items-center justify-center rounded-md border-2 border-slate-50 bg-gray-50 px-8 py-4 text-slate-900 transition-all hover:bg-transparent hover:text-gray-50'
aria-label={
- isAuthenticated ? t('main.goToBilling') : t('main.startAXDayFreeTrial', { amount: TRIAL_DAYS })
+ isAuthenticated
+ ? t('main.goToBilling')
+ : t('main.startAXDayFreeTrial', { amount: TRIAL_DAYS })
}
>
<span className='mr-1 text-center text-base font-semibold'>
- {isAuthenticated ? t('main.goToBilling') : t('main.startAXDayFreeTrial', { amount: TRIAL_DAYS })}
+ {isAuthenticated
+ ? t('main.goToBilling')
+ : t('main.startAXDayFreeTrial', { amount: TRIAL_DAYS })}
</span>
<ArrowRightIcon className='mt-[1px] h-4 w-5' />
</Link>
@@ -130,7 +157,9 @@ const MarketingPricing = ({ metainfo = DEFAULT_METAINFO }: MarketingPricingProps
value={BillingFrequency.monthly}
className={({ checked }) =>
cx(
- checked ? 'bg-white/90 text-slate-900' : 'text-gray-200 hover:bg-white/30 hover:text-white',
+ checked
+ ? 'bg-white/90 text-slate-900'
+ : 'text-gray-200 hover:bg-white/30 hover:text-white',
'flex cursor-pointer items-center justify-center rounded-md px-2.5 py-1 transition-all',
)
}
@@ -142,7 +171,9 @@ const MarketingPricing = ({ metainfo = DEFAULT_METAINFO }: MarketingPricingProps
value={BillingFrequency.yearly}
className={({ checked }) =>
cx(
- checked ? 'bg-white/90 text-slate-900' : 'text-gray-200 hover:bg-white/30 hover:text-white',
+ checked
+ ? 'bg-white/90 text-slate-900'
+ : 'text-gray-200 hover:bg-white/30 hover:text-white',
'flex cursor-pointer items-center justify-center rounded-md px-2.5 py-1 transition-all',
)
}
@@ -158,9 +189,13 @@ const MarketingPricing = ({ metainfo = DEFAULT_METAINFO }: MarketingPricingProps
className='flex items-center justify-between rounded-xl border border-white/10 bg-white/2 px-4 py-3 text-white backdrop-blur-sm transition-all hover:bg-white/10'
>
<div>
- <span className='text-base font-medium'>{formatEventsLong(tier.monthlyUsageLimit)}</span>
+ <span className='text-base font-medium'>
+ {formatEventsLong(tier.monthlyUsageLimit)}
+ </span>
&nbsp;
- <span className='text-sm text-gray-400'>{t('pricing.eventsPerMonth')}</span>
+ <span className='text-sm text-gray-400'>
+ {t('pricing.eventsPerMonth')}
+ </span>
</div>
<div className='text-sm'>
<span className='font-semibold text-white'>
@@ -172,7 +207,12 @@ const MarketingPricing = ({ metainfo = DEFAULT_METAINFO }: MarketingPricingProps
</span>
&nbsp;
<span className='text-sm text-gray-400'>
- /{t(billingFrequency === BillingFrequency.monthly ? 'pricing.perMonth' : 'pricing.perYear')}
+ /
+ {t(
+ billingFrequency === BillingFrequency.monthly
+ ? 'pricing.perMonth'
+ : 'pricing.perYear',
+ )}
</span>
</div>
</div>
@@ -186,9 +226,13 @@ const MarketingPricing = ({ metainfo = DEFAULT_METAINFO }: MarketingPricingProps
className='group flex items-center justify-between rounded-xl border border-white/10 bg-white/2 px-4 py-3 text-white backdrop-blur-sm transition-all hover:bg-white/10'
>
<span className='text-base font-medium'>
- {t('pricing.overXEvents', { amount: formatEventsLong(20000000) })}
+ {t('pricing.overXEvents', {
+ amount: formatEventsLong(20000000),
+ })}
</span>
- <p className='text-sm group-hover:underline'>{t('pricing.contactUs')}</p>
+ <p className='text-sm group-hover:underline'>
+ {t('pricing.contactUs')}
+ </p>
</a>
</div>
</div>
diff --git a/web/app/entry.server.tsx b/web/app/entry.server.tsx
index 9df808ce5..2b117d3f6 100644
--- a/web/app/entry.server.tsx
+++ b/web/app/entry.server.tsx
@@ -52,7 +52,9 @@ export default async function handleRequest(
},
})
- const callbackName = isbot(request.headers.get('user-agent')) ? 'onAllReady' : 'onShellReady'
+ const callbackName = isbot(request.headers.get('user-agent'))
+ ? 'onAllReady'
+ : 'onShellReady'
return new Promise((resolve, reject) => {
let didError = false
@@ -68,7 +70,10 @@ export default async function handleRequest(
responseHeaders.set('Content-Type', 'text/html')
// Prevent HTML from being cached so users always get fresh chunk references after deployments
- responseHeaders.set('Cache-Control', 'no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0')
+ responseHeaders.set(
+ 'Cache-Control',
+ 'no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0',
+ )
responseHeaders.set('Pragma', 'no-cache')
responseHeaders.set('Expires', '0')
responseHeaders.append('Vary', 'Cookie')
diff --git a/web/app/hooks/useAnalyticsProxy.ts b/web/app/hooks/useAnalyticsProxy.ts
index 52957cc9d..a1f0a85be 100644
--- a/web/app/hooks/useAnalyticsProxy.ts
+++ b/web/app/hooks/useAnalyticsProxy.ts
@@ -31,7 +31,9 @@ import type {
AnalyticsParams as ServerAnalyticsParams,
} from '~/api/api.server'
-type ClientAnalyticsParams = Partial<Omit<ServerAnalyticsParams, 'password'>> & {
+type ClientAnalyticsParams = Partial<
+ Omit<ServerAnalyticsParams, 'password'>
+> & {
take?: number
skip?: number
options?: Record<string, unknown>
@@ -55,11 +57,15 @@ async function postAnalytics<T>(payload: unknown): Promise<ProxyResponse<T>> {
try {
result = (await response.json()) as ProxyResponse<T>
} catch {
- throw new Error(`Invalid JSON from /api/analytics (status ${response.status})`)
+ throw new Error(
+ `Invalid JSON from /api/analytics (status ${response.status})`,
+ )
}
if (!response.ok) {
- throw new Error(result.error || `Request failed (status ${response.status})`)
+ throw new Error(
+ result.error || `Request failed (status ${response.status})`,
+ )
}
return result
}
@@ -69,20 +75,27 @@ export function useSessionsProxy() {
const [error, setError] = useState<string | null>(null)
const [isLoading, setIsLoading] = useState(false)
- const fetchSessions = useCallback(async (projectId: string, params: ClientAnalyticsParams) => {
- setIsLoading(true)
- setError(null)
+ const fetchSessions = useCallback(
+ async (projectId: string, params: ClientAnalyticsParams) => {
+ setIsLoading(true)
+ setError(null)
- try {
- const result = await postAnalytics<SessionsResponse>({ action: 'getSessions', projectId, params })
- setData(result.data)
- setError(result.error)
- } catch (err) {
- setError(err instanceof Error ? err.message : 'Unknown error')
- } finally {
- setIsLoading(false)
- }
- }, [])
+ try {
+ const result = await postAnalytics<SessionsResponse>({
+ action: 'getSessions',
+ projectId,
+ params,
+ })
+ setData(result.data)
+ setError(result.error)
+ } catch (err) {
+ setError(err instanceof Error ? err.message : 'Unknown error')
+ } finally {
+ setIsLoading(false)
+ }
+ },
+ [],
+ )
return { fetchSessions, data, error, isLoading }
}
@@ -92,20 +105,27 @@ export function useErrorsProxy() {
const [error, setError] = useState<string | null>(null)
const [isLoading, setIsLoading] = useState(false)
- const fetchErrors = useCallback(async (projectId: string, params: ClientAnalyticsParams) => {
- setIsLoading(true)
- setError(null)
+ const fetchErrors = useCallback(
+ async (projectId: string, params: ClientAnalyticsParams) => {
+ setIsLoading(true)
+ setError(null)
- try {
- const result = await postAnalytics<ErrorsResponse>({ action: 'getErrors', projectId, params })
- setData(result.data)
- setError(result.error)
- } catch (err) {
- setError(err instanceof Error ? err.message : 'Unknown error')
- } finally {
- setIsLoading(false)
- }
- }, [])
+ try {
+ const result = await postAnalytics<ErrorsResponse>({
+ action: 'getErrors',
+ projectId,
+ params,
+ })
+ setData(result.data)
+ setError(result.error)
+ } catch (err) {
+ setError(err instanceof Error ? err.message : 'Unknown error')
+ } finally {
+ setIsLoading(false)
+ }
+ },
+ [],
+ )
return { fetchErrors, data, error, isLoading }
}
@@ -115,22 +135,29 @@ export function useFeatureFlagStatsProxy() {
const [error, setError] = useState<string | null>(null)
const [isLoading, setIsLoading] = useState(false)
- const fetchStats = useCallback(async (flagId: string, params: ClientAnalyticsParams) => {
- setIsLoading(true)
- setError(null)
+ const fetchStats = useCallback(
+ async (flagId: string, params: ClientAnalyticsParams) => {
+ setIsLoading(true)
+ setError(null)
- try {
- const result = await postAnalytics<FeatureFlagStats>({ action: 'getFeatureFlagStats', flagId, params })
- setData(result.data)
- setError(result.error)
- return result.data
- } catch (err) {
- setError(err instanceof Error ? err.message : 'Unknown error')
- return null
- } finally {
- setIsLoading(false)
- }
- }, [])
+ try {
+ const result = await postAnalytics<FeatureFlagStats>({
+ action: 'getFeatureFlagStats',
+ flagId,
+ params,
+ })
+ setData(result.data)
+ setError(result.error)
+ return result.data
+ } catch (err) {
+ setError(err instanceof Error ? err.message : 'Unknown error')
+ return null
+ } finally {
+ setIsLoading(false)
+ }
+ },
+ [],
+ )
return { fetchStats, data, error, isLoading }
}
@@ -140,26 +167,29 @@ export function useFeatureFlagProfilesProxy() {
const [error, setError] = useState<string | null>(null)
const [isLoading, setIsLoading] = useState(false)
- const fetchProfiles = useCallback(async (flagId: string, params: ClientAnalyticsParams) => {
- setIsLoading(true)
- setError(null)
+ const fetchProfiles = useCallback(
+ async (flagId: string, params: ClientAnalyticsParams) => {
+ setIsLoading(true)
+ setError(null)
- try {
- const result = await postAnalytics<FeatureFlagProfilesResponse>({
- action: 'getFeatureFlagProfiles',
- flagId,
- params,
- })
- setData(result.data)
- setError(result.error)
- return result.data
- } catch (err) {
- setError(err instanceof Error ? err.message : 'Unknown error')
- return null
- } finally {
- setIsLoading(false)
- }
- }, [])
+ try {
+ const result = await postAnalytics<FeatureFlagProfilesResponse>({
+ action: 'getFeatureFlagProfiles',
+ flagId,
+ params,
+ })
+ setData(result.data)
+ setError(result.error)
+ return result.data
+ } catch (err) {
+ setError(err instanceof Error ? err.message : 'Unknown error')
+ return null
+ } finally {
+ setIsLoading(false)
+ }
+ },
+ [],
+ )
return { fetchProfiles, data, error, isLoading }
}
@@ -169,22 +199,29 @@ export function useGoalStatsProxy() {
const [error, setError] = useState<string | null>(null)
const [isLoading, setIsLoading] = useState(false)
- const fetchStats = useCallback(async (goalId: string, params: ClientAnalyticsParams) => {
- setIsLoading(true)
- setError(null)
+ const fetchStats = useCallback(
+ async (goalId: string, params: ClientAnalyticsParams) => {
+ setIsLoading(true)
+ setError(null)
- try {
- const result = await postAnalytics<GoalStats>({ action: 'getGoalStats', goalId, params })
- setData(result.data)
- setError(result.error)
- return result.data
- } catch (err) {
- setError(err instanceof Error ? err.message : 'Unknown error')
- return null
- } finally {
- setIsLoading(false)
- }
- }, [])
+ try {
+ const result = await postAnalytics<GoalStats>({
+ action: 'getGoalStats',
+ goalId,
+ params,
+ })
+ setData(result.data)
+ setError(result.error)
+ return result.data
+ } catch (err) {
+ setError(err instanceof Error ? err.message : 'Unknown error')
+ return null
+ } finally {
+ setIsLoading(false)
+ }
+ },
+ [],
+ )
return { fetchStats, data, error, isLoading }
}
@@ -194,22 +231,29 @@ export function useGoalChartProxy() {
const [error, setError] = useState<string | null>(null)
const [isLoading, setIsLoading] = useState(false)
- const fetchChart = useCallback(async (goalId: string, params: ClientAnalyticsParams) => {
- setIsLoading(true)
- setError(null)
+ const fetchChart = useCallback(
+ async (goalId: string, params: ClientAnalyticsParams) => {
+ setIsLoading(true)
+ setError(null)
- try {
- const result = await postAnalytics<{ chart: GoalChartData }>({ action: 'getGoalChart', goalId, params })
- setData(result.data)
- setError(result.error)
- return result.data
- } catch (err) {
- setError(err instanceof Error ? err.message : 'Unknown error')
- return null
- } finally {
- setIsLoading(false)
- }
- }, [])
+ try {
+ const result = await postAnalytics<{ chart: GoalChartData }>({
+ action: 'getGoalChart',
+ goalId,
+ params,
+ })
+ setData(result.data)
+ setError(result.error)
+ return result.data
+ } catch (err) {
+ setError(err instanceof Error ? err.message : 'Unknown error')
+ return null
+ } finally {
+ setIsLoading(false)
+ }
+ },
+ [],
+ )
return { fetchChart, data, error, isLoading }
}
@@ -219,22 +263,29 @@ export function useCaptchaProxy() {
const [error, setError] = useState<string | null>(null)
const [isLoading, setIsLoading] = useState(false)
- const fetchCaptcha = useCallback(async (projectId: string, params: ClientAnalyticsParams) => {
- setIsLoading(true)
- setError(null)
+ const fetchCaptcha = useCallback(
+ async (projectId: string, params: ClientAnalyticsParams) => {
+ setIsLoading(true)
+ setError(null)
- try {
- const result = await postAnalytics<CaptchaDataResponse>({ action: 'getCaptchaData', projectId, params })
- setData(result.data)
- setError(result.error)
- return result.data
- } catch (err) {
- setError(err instanceof Error ? err.message : 'Unknown error')
- return null
- } finally {
- setIsLoading(false)
- }
- }, [])
+ try {
+ const result = await postAnalytics<CaptchaDataResponse>({
+ action: 'getCaptchaData',
+ projectId,
+ params,
+ })
+ setData(result.data)
+ setError(result.error)
+ return result.data
+ } catch (err) {
+ setError(err instanceof Error ? err.message : 'Unknown error')
+ return null
+ } finally {
+ setIsLoading(false)
+ }
+ },
+ [],
+ )
return { fetchCaptcha, data, error, isLoading }
}
@@ -244,22 +295,29 @@ export function useExperimentResultsProxy() {
const [error, setError] = useState<string | null>(null)
const [isLoading, setIsLoading] = useState(false)
- const fetchResults = useCallback(async (experimentId: string, params: ClientAnalyticsParams) => {
- setIsLoading(true)
- setError(null)
+ const fetchResults = useCallback(
+ async (experimentId: string, params: ClientAnalyticsParams) => {
+ setIsLoading(true)
+ setError(null)
- try {
- const result = await postAnalytics<ExperimentResults>({ action: 'getExperimentResults', experimentId, params })
- setData(result.data)
- setError(result.error)
- return result.data
- } catch (err) {
- setError(err instanceof Error ? err.message : 'Unknown error')
- return null
- } finally {
- setIsLoading(false)
- }
- }, [])
+ try {
+ const result = await postAnalytics<ExperimentResults>({
+ action: 'getExperimentResults',
+ experimentId,
+ params,
+ })
+ setData(result.data)
+ setError(result.error)
+ return result.data
+ } catch (err) {
+ setError(err instanceof Error ? err.message : 'Unknown error')
+ return null
+ } finally {
+ setIsLoading(false)
+ }
+ },
+ [],
+ )
return { fetchResults, data, error, isLoading }
}
@@ -274,7 +332,11 @@ export function useExperimentProxy() {
setError(null)
try {
- const result = await postAnalytics<Experiment>({ action: 'getExperiment', experimentId, params: {} })
+ const result = await postAnalytics<Experiment>({
+ action: 'getExperiment',
+ experimentId,
+ params: {},
+ })
setData(result.data)
setError(result.error)
return result.data
@@ -299,7 +361,11 @@ export function useGoalProxy() {
setError(null)
try {
- const result = await postAnalytics<Goal>({ action: 'getGoal', goalId, params: {} })
+ const result = await postAnalytics<Goal>({
+ action: 'getGoal',
+ goalId,
+ params: {},
+ })
setData(result.data)
setError(result.error)
return result.data
@@ -319,22 +385,29 @@ export function useProjectGoalsProxy() {
const [error, setError] = useState<string | null>(null)
const [isLoading, setIsLoading] = useState(false)
- const fetchGoals = useCallback(async (projectId: string, params: ClientAnalyticsParams = {}) => {
- setIsLoading(true)
- setError(null)
+ const fetchGoals = useCallback(
+ async (projectId: string, params: ClientAnalyticsParams = {}) => {
+ setIsLoading(true)
+ setError(null)
- try {
- const result = await postAnalytics<GoalsResponse>({ action: 'getProjectGoals', projectId, params })
- setData(result.data)
- setError(result.error)
- return result.data
- } catch (err) {
- setError(err instanceof Error ? err.message : 'Unknown error')
- return null
- } finally {
- setIsLoading(false)
- }
- }, [])
+ try {
+ const result = await postAnalytics<GoalsResponse>({
+ action: 'getProjectGoals',
+ projectId,
+ params,
+ })
+ setData(result.data)
+ setError(result.error)
+ return result.data
+ } catch (err) {
+ setError(err instanceof Error ? err.message : 'Unknown error')
+ return null
+ } finally {
+ setIsLoading(false)
+ }
+ },
+ [],
+ )
return { fetchGoals, data, error, isLoading }
}
@@ -344,22 +417,29 @@ export function useProjectFeatureFlagsProxy() {
const [error, setError] = useState<string | null>(null)
const [isLoading, setIsLoading] = useState(false)
- const fetchFeatureFlags = useCallback(async (projectId: string, params: ClientAnalyticsParams = {}) => {
- setIsLoading(true)
- setError(null)
+ const fetchFeatureFlags = useCallback(
+ async (projectId: string, params: ClientAnalyticsParams = {}) => {
+ setIsLoading(true)
+ setError(null)
- try {
- const result = await postAnalytics<FeatureFlagsResponse>({ action: 'getProjectFeatureFlags', projectId, params })
- setData(result.data)
- setError(result.error)
- return result.data
- } catch (err) {
- setError(err instanceof Error ? err.message : 'Unknown error')
- return null
- } finally {
- setIsLoading(false)
- }
- }, [])
+ try {
+ const result = await postAnalytics<FeatureFlagsResponse>({
+ action: 'getProjectFeatureFlags',
+ projectId,
+ params,
+ })
+ setData(result.data)
+ setError(result.error)
+ return result.data
+ } catch (err) {
+ setError(err instanceof Error ? err.message : 'Unknown error')
+ return null
+ } finally {
+ setIsLoading(false)
+ }
+ },
+ [],
+ )
return { fetchFeatureFlags, data, error, isLoading }
}
@@ -372,13 +452,19 @@ export function useProfilesProxy() {
const fetchProfiles = useCallback(
async (
projectId: string,
- params: ClientAnalyticsParams & { profileType?: 'all' | 'anonymous' | 'identified' } = {},
+ params: ClientAnalyticsParams & {
+ profileType?: 'all' | 'anonymous' | 'identified'
+ } = {},
) => {
setIsLoading(true)
setError(null)
try {
- const result = await postAnalytics<ProfilesResponse>({ action: 'getProfiles', projectId, params })
+ const result = await postAnalytics<ProfilesResponse>({
+ action: 'getProfiles',
+ projectId,
+ params,
+ })
setData(result.data)
setError(result.error)
return result.data
@@ -400,22 +486,34 @@ export function useProfileProxy() {
const [error, setError] = useState<string | null>(null)
const [isLoading, setIsLoading] = useState(false)
- const fetchProfile = useCallback(async (projectId: string, profileId: string, params: ClientAnalyticsParams = {}) => {
- setIsLoading(true)
- setError(null)
+ const fetchProfile = useCallback(
+ async (
+ projectId: string,
+ profileId: string,
+ params: ClientAnalyticsParams = {},
+ ) => {
+ setIsLoading(true)
+ setError(null)
- try {
- const result = await postAnalytics<ProfileDetailsResponse>({ action: 'getProfile', projectId, profileId, params })
- setData(result.data)
- setError(result.error)
- return result.data
- } catch (err) {
- setError(err instanceof Error ? err.message : 'Unknown error')
- return null
- } finally {
- setIsLoading(false)
- }
- }, [])
+ try {
+ const result = await postAnalytics<ProfileDetailsResponse>({
+ action: 'getProfile',
+ projectId,
+ profileId,
+ params,
+ })
+ setData(result.data)
+ setError(result.error)
+ return result.data
+ } catch (err) {
+ setError(err instanceof Error ? err.message : 'Unknown error')
+ return null
+ } finally {
+ setIsLoading(false)
+ }
+ },
+ [],
+ )
return { fetchProfile, data, error, isLoading }
}
@@ -426,7 +524,11 @@ export function useProfileSessionsProxy() {
const [isLoading, setIsLoading] = useState(false)
const fetchProfileSessions = useCallback(
- async (projectId: string, profileId: string, params: ClientAnalyticsParams = {}) => {
+ async (
+ projectId: string,
+ profileId: string,
+ params: ClientAnalyticsParams = {},
+ ) => {
setIsLoading(true)
setError(null)
@@ -454,25 +556,41 @@ export function useProfileSessionsProxy() {
}
export function useFiltersProxy() {
- const fetchFilters = useCallback(async (projectId: string, filterType: string): Promise<string[] | null> => {
- try {
- const result = await postAnalytics<string[]>({ action: 'getFilters', projectId, filterType, params: {} })
- return result.data
- } catch (err) {
- console.error('[useFiltersProxy] Error:', err)
- throw err
- }
- }, [])
+ const fetchFilters = useCallback(
+ async (projectId: string, filterType: string): Promise<string[] | null> => {
+ try {
+ const result = await postAnalytics<string[]>({
+ action: 'getFilters',
+ projectId,
+ filterType,
+ params: {},
+ })
+ return result.data
+ } catch (err) {
+ console.error('[useFiltersProxy] Error:', err)
+ throw err
+ }
+ },
+ [],
+ )
- const fetchErrorsFilters = useCallback(async (projectId: string, filterType: string): Promise<string[] | null> => {
- try {
- const result = await postAnalytics<string[]>({ action: 'getErrorsFilters', projectId, filterType, params: {} })
- return result.data
- } catch (err) {
- console.error('[useFiltersProxy] Error:', err)
- throw err
- }
- }, [])
+ const fetchErrorsFilters = useCallback(
+ async (projectId: string, filterType: string): Promise<string[] | null> => {
+ try {
+ const result = await postAnalytics<string[]>({
+ action: 'getErrorsFilters',
+ projectId,
+ filterType,
+ params: {},
+ })
+ return result.data
+ } catch (err) {
+ console.error('[useFiltersProxy] Error:', err)
+ throw err
+ }
+ },
+ [],
+ )
const fetchVersionFilters = useCallback(
async (
@@ -558,7 +676,11 @@ export function useErrorSessionsProxy() {
const [isLoading, setIsLoading] = useState(false)
const fetchErrorSessions = useCallback(
- async (projectId: string, errorId: string, params: ClientAnalyticsParams = {}) => {
+ async (
+ projectId: string,
+ errorId: string,
+ params: ClientAnalyticsParams = {},
+ ) => {
setIsLoading(true)
setError(null)
@@ -586,29 +708,43 @@ export function useErrorSessionsProxy() {
}
export function useLiveVisitorsProxy() {
- const fetchLiveVisitors = useCallback(async (pids: string[]): Promise<LiveStats | null> => {
- if (!pids || pids.length === 0) {
- return null
- }
+ const fetchLiveVisitors = useCallback(
+ async (pids: string[]): Promise<LiveStats | null> => {
+ if (!pids || pids.length === 0) {
+ return null
+ }
- try {
- const result = await postAnalytics<LiveStats>({ action: 'getLiveVisitors', pids, params: {} })
- return result.data
- } catch (err) {
- console.error('[useLiveVisitorsProxy] Error:', err)
- throw err
- }
- }, [])
+ try {
+ const result = await postAnalytics<LiveStats>({
+ action: 'getLiveVisitors',
+ pids,
+ params: {},
+ })
+ return result.data
+ } catch (err) {
+ console.error('[useLiveVisitorsProxy] Error:', err)
+ throw err
+ }
+ },
+ [],
+ )
- const fetchLiveVisitorsInfo = useCallback(async (projectId: string): Promise<LiveVisitorInfo[] | null> => {
- try {
- const result = await postAnalytics<LiveVisitorInfo[]>({ action: 'getLiveVisitorsInfo', projectId, params: {} })
- return result.data
- } catch (err) {
- console.error('[useLiveVisitorsProxy] Error:', err)
- throw err
- }
- }, [])
+ const fetchLiveVisitorsInfo = useCallback(
+ async (projectId: string): Promise<LiveVisitorInfo[] | null> => {
+ try {
+ const result = await postAnalytics<LiveVisitorInfo[]>({
+ action: 'getLiveVisitorsInfo',
+ projectId,
+ params: {},
+ })
+ return result.data
+ } catch (err) {
+ console.error('[useLiveVisitorsProxy] Error:', err)
+ throw err
+ }
+ },
+ [],
+ )
return { fetchLiveVisitors, fetchLiveVisitorsInfo }
}
@@ -644,22 +780,29 @@ export function useUserFlowProxy() {
const [error, setError] = useState<string | null>(null)
const [isLoading, setIsLoading] = useState(false)
- const fetchUserFlow = useCallback(async (projectId: string, params: ClientAnalyticsParams = {}) => {
- setIsLoading(true)
- setError(null)
+ const fetchUserFlow = useCallback(
+ async (projectId: string, params: ClientAnalyticsParams = {}) => {
+ setIsLoading(true)
+ setError(null)
- try {
- const result = await postAnalytics<UserFlowResponse>({ action: 'getUserFlow', projectId, params })
- setData(result.data)
- setError(result.error)
- return result.data
- } catch (err) {
- setError(err instanceof Error ? err.message : 'Unknown error')
- return null
- } finally {
- setIsLoading(false)
- }
- }, [])
+ try {
+ const result = await postAnalytics<UserFlowResponse>({
+ action: 'getUserFlow',
+ projectId,
+ params,
+ })
+ setData(result.data)
+ setError(result.error)
+ return result.data
+ } catch (err) {
+ setError(err instanceof Error ? err.message : 'Unknown error')
+ return null
+ } finally {
+ setIsLoading(false)
+ }
+ },
+ [],
+ )
return { fetchUserFlow, data, error, isLoading }
}
@@ -669,66 +812,99 @@ export function useGSCKeywordsProxy() {
const [error, setError] = useState<string | null>(null)
const [isLoading, setIsLoading] = useState(false)
- const fetchKeywords = useCallback(async (projectId: string, params: ClientAnalyticsParams = {}) => {
- setIsLoading(true)
- setError(null)
+ const fetchKeywords = useCallback(
+ async (projectId: string, params: ClientAnalyticsParams = {}) => {
+ setIsLoading(true)
+ setError(null)
- try {
- const result = await postAnalytics<GSCKeywordsResponse>({ action: 'getGSCKeywords', projectId, params })
- setData(result.data)
- setError(result.error)
- return result.data
- } catch (err) {
- setError(err instanceof Error ? err.message : 'Unknown error')
- return null
- } finally {
- setIsLoading(false)
- }
- }, [])
+ try {
+ const result = await postAnalytics<GSCKeywordsResponse>({
+ action: 'getGSCKeywords',
+ projectId,
+ params,
+ })
+ setData(result.data)
+ setError(result.error)
+ return result.data
+ } catch (err) {
+ setError(err instanceof Error ? err.message : 'Unknown error')
+ return null
+ } finally {
+ setIsLoading(false)
+ }
+ },
+ [],
+ )
return { fetchKeywords, data, error, isLoading }
}
export function useRevenueProxy() {
const [statusData, setStatusData] = useState<RevenueStatus | null>(null)
- const [revenueData, setRevenueData] = useState<RevenueDataResponse | null>(null)
+ const [revenueData, setRevenueData] = useState<RevenueDataResponse | null>(
+ null,
+ )
const [error, setError] = useState<string | null>(null)
const [isLoading, setIsLoading] = useState(false)
- const fetchRevenueStatus = useCallback(async (projectId: string): Promise<RevenueStatus | null> => {
- try {
- const result = await postAnalytics<RevenueStatus>({ action: 'getRevenueStatus', projectId, params: {} })
- setStatusData(result.data)
- return result.data
- } catch (err) {
- console.error('[useRevenueProxy] Error:', err)
- throw err
- }
- }, [])
+ const fetchRevenueStatus = useCallback(
+ async (projectId: string): Promise<RevenueStatus | null> => {
+ try {
+ const result = await postAnalytics<RevenueStatus>({
+ action: 'getRevenueStatus',
+ projectId,
+ params: {},
+ })
+ setStatusData(result.data)
+ return result.data
+ } catch (err) {
+ console.error('[useRevenueProxy] Error:', err)
+ throw err
+ }
+ },
+ [],
+ )
- const fetchRevenueData = useCallback(async (projectId: string, params: ClientAnalyticsParams = {}) => {
- setIsLoading(true)
- setError(null)
+ const fetchRevenueData = useCallback(
+ async (projectId: string, params: ClientAnalyticsParams = {}) => {
+ setIsLoading(true)
+ setError(null)
- try {
- const result = await postAnalytics<RevenueDataResponse>({ action: 'getRevenueData', projectId, params })
- setRevenueData(result.data)
- setError(result.error)
- return result.data
- } catch (err) {
- setError(err instanceof Error ? err.message : 'Unknown error')
- return null
- } finally {
- setIsLoading(false)
- }
- }, [])
+ try {
+ const result = await postAnalytics<RevenueDataResponse>({
+ action: 'getRevenueData',
+ projectId,
+ params,
+ })
+ setRevenueData(result.data)
+ setError(result.error)
+ return result.data
+ } catch (err) {
+ setError(err instanceof Error ? err.message : 'Unknown error')
+ return null
+ } finally {
+ setIsLoading(false)
+ }
+ },
+ [],
+ )
- return { fetchRevenueStatus, fetchRevenueData, statusData, revenueData, error, isLoading }
+ return {
+ fetchRevenueStatus,
+ fetchRevenueData,
+ statusData,
+ revenueData,
+ error,
+ isLoading,
+ }
}
export function useOverallStatsProxy() {
const fetchOverallStats = useCallback(
- async (pids: string[], params: ClientAnalyticsParams = {}): Promise<Record<string, OverallObject> | null> => {
+ async (
+ pids: string[],
+ params: ClientAnalyticsParams = {},
+ ): Promise<Record<string, OverallObject> | null> => {
try {
const result = await postAnalytics<Record<string, OverallObject>>({
action: 'getOverallStats',
diff --git a/web/app/hooks/useAnnotations.ts b/web/app/hooks/useAnnotations.ts
index edffe8fb4..d9905271e 100644
--- a/web/app/hooks/useAnnotations.ts
+++ b/web/app/hooks/useAnnotations.ts
@@ -5,7 +5,10 @@ import { useFetcher } from 'react-router'
import { toast } from 'sonner'
import { Annotation } from '~/lib/models/Project'
-import { useCurrentProject, useProjectPassword } from '~/providers/CurrentProjectProvider'
+import {
+ useCurrentProject,
+ useProjectPassword,
+} from '~/providers/CurrentProjectProvider'
import { ProjectViewActionData } from '~/routes/projects.$id'
const ANNOTATION_CLICK_THRESHOLD_PX = 30
@@ -15,7 +18,10 @@ interface ChartMetrics {
chartAreaWidth: number
}
-const findAnnotationLineElement = (target: Element, boundary: Element): Element | null => {
+const findAnnotationLineElement = (
+ target: Element,
+ boundary: Element,
+): Element | null => {
let element: Element | null = target
while (element && element !== boundary) {
@@ -38,13 +44,18 @@ const getAnnotationIdFromElement = (element: Element): string | null => {
return null
}
-const calculateChartMetrics = (svg: SVGSVGElement, chartContainer: HTMLElement): ChartMetrics => {
+const calculateChartMetrics = (
+ svg: SVGSVGElement,
+ chartContainer: HTMLElement,
+): ChartMetrics => {
const svgRect = svg.getBoundingClientRect()
let chartAreaStart = 50
let chartAreaWidth = svgRect.width - 70
- const xAxisPath = chartContainer.querySelector('.bb-axis-x path.domain') as SVGPathElement | null
+ const xAxisPath = chartContainer.querySelector(
+ '.bb-axis-x path.domain',
+ ) as SVGPathElement | null
if (xAxisPath) {
const pathBBox = xAxisPath.getBBox()
chartAreaStart = pathBBox.x
@@ -87,7 +98,9 @@ const findClosestAnnotation = (
for (const annotation of annotations) {
const annotationDate = dayjs(annotation.date).format('YYYY-MM-DD')
- const annotationIndex = xAxisData.findIndex((xDate) => dayjs(xDate).format('YYYY-MM-DD') === annotationDate)
+ const annotationIndex = xAxisData.findIndex(
+ (xDate) => dayjs(xDate).format('YYYY-MM-DD') === annotationDate,
+ )
if (annotationIndex !== -1) {
const annotationPercentage = annotationIndex / (xAxisData.length - 1)
@@ -125,7 +138,10 @@ interface UseAnnotationsReturn {
onAnnotationDelete: (annotation?: Annotation) => void
openAnnotationModal: (date?: string, annotation?: Annotation) => void
closeAnnotationModal: () => void
- handleChartContextMenu: (event: React.MouseEvent, xAxisData: string[] | undefined) => void
+ handleChartContextMenu: (
+ event: React.MouseEvent,
+ xAxisData: string[] | undefined,
+ ) => void
closeContextMenu: () => void
}
@@ -140,9 +156,15 @@ export const useAnnotations = (): UseAnnotationsReturn => {
const [annotations, setAnnotations] = useState<Annotation[]>([])
const [annotationsLoading, setAnnotationsLoading] = useState(false)
const [isAnnotationModalOpen, setIsAnnotationModalOpen] = useState(false)
- const [annotationToEdit, setAnnotationToEdit] = useState<Annotation | undefined>()
- const [annotationModalDate, setAnnotationModalDate] = useState<string | undefined>()
- const [pendingAction, setPendingAction] = useState<'create' | 'update' | 'delete' | null>(null)
+ const [annotationToEdit, setAnnotationToEdit] = useState<
+ Annotation | undefined
+ >()
+ const [annotationModalDate, setAnnotationModalDate] = useState<
+ string | undefined
+ >()
+ const [pendingAction, setPendingAction] = useState<
+ 'create' | 'update' | 'delete' | null
+ >(null)
const [contextMenu, setContextMenu] = useState<{
isOpen: boolean
@@ -212,7 +234,14 @@ export const useAnnotations = (): UseAnnotationsReturn => {
setPendingAction(null)
setAnnotationToEdit(undefined)
}
- }, [fetcher.state, fetcher.data, pendingAction, loadAnnotations, t, closeAnnotationModal])
+ }, [
+ fetcher.state,
+ fetcher.data,
+ pendingAction,
+ loadAnnotations,
+ t,
+ closeAnnotationModal,
+ ])
const onAnnotationCreate = useCallback(
(date: string, text: string) => {
@@ -267,11 +296,14 @@ export const useAnnotations = (): UseAnnotationsReturn => {
[fetcher, annotationToEdit],
)
- const openAnnotationModal = useCallback((date?: string, annotation?: Annotation) => {
- setAnnotationModalDate(date)
- setAnnotationToEdit(annotation)
- setIsAnnotationModalOpen(true)
- }, [])
+ const openAnnotationModal = useCallback(
+ (date?: string, annotation?: Annotation) => {
+ setAnnotationModalDate(date)
+ setAnnotationToEdit(annotation)
+ setIsAnnotationModalOpen(true)
+ },
+ [],
+ )
const handleChartContextMenu = useCallback(
(event: React.MouseEvent, xAxisData: string[] | undefined) => {
@@ -280,12 +312,16 @@ export const useAnnotations = (): UseAnnotationsReturn => {
let existingAnnotation: Annotation | null = null
let date: string | null = null
- const annotationLineElement = findAnnotationLineElement(event.target as Element, event.currentTarget as Element)
+ const annotationLineElement = findAnnotationLineElement(
+ event.target as Element,
+ event.currentTarget as Element,
+ )
if (annotationLineElement) {
const annotationId = getAnnotationIdFromElement(annotationLineElement)
if (annotationId) {
- existingAnnotation = annotations.find((a) => a.id === annotationId) || null
+ existingAnnotation =
+ annotations.find((a) => a.id === annotationId) || null
if (existingAnnotation) {
date = dayjs(existingAnnotation.date).format('YYYY-MM-DD')
}
@@ -293,7 +329,9 @@ export const useAnnotations = (): UseAnnotationsReturn => {
}
if (!existingAnnotation && xAxisData && xAxisData.length > 0) {
- const chartContainer = (event.currentTarget as HTMLElement).querySelector('.bb') as HTMLElement
+ const chartContainer = (
+ event.currentTarget as HTMLElement
+ ).querySelector('.bb') as HTMLElement
const svg = chartContainer?.querySelector('svg') as SVGSVGElement | null
if (svg) {
@@ -301,9 +339,17 @@ export const useAnnotations = (): UseAnnotationsReturn => {
const chartMetrics = calculateChartMetrics(svg, chartContainer)
const clickX = event.clientX - svgRect.left
- date = calculateDateFromPosition(event.clientX, svgRect, xAxisData, chartMetrics)
-
- existingAnnotation = annotations.find((a) => dayjs(a.date).format('YYYY-MM-DD') === date) || null
+ date = calculateDateFromPosition(
+ event.clientX,
+ svgRect,
+ xAxisData,
+ chartMetrics,
+ )
+
+ existingAnnotation =
+ annotations.find(
+ (a) => dayjs(a.date).format('YYYY-MM-DD') === date,
+ ) || null
if (!existingAnnotation && annotations.length > 0) {
const closestAnnotation = findClosestAnnotation(
diff --git a/web/app/hooks/useAuthProxy.ts b/web/app/hooks/useAuthProxy.ts
index afb976c9b..6ac972d6d 100644
--- a/web/app/hooks/useAuthProxy.ts
+++ b/web/app/hooks/useAuthProxy.ts
@@ -1,6 +1,11 @@
import { useCallback } from 'react'
-import type { SSOProvider, SSOAuthURLResponse, SSOHashResponse, AuthMeResponse } from '~/api/api.server'
+import type {
+ SSOProvider,
+ SSOAuthURLResponse,
+ SSOHashResponse,
+ AuthMeResponse,
+} from '~/api/api.server'
interface ProxyResponse<T> {
data: T | null
@@ -9,13 +14,21 @@ interface ProxyResponse<T> {
export function useAuthProxy() {
const generateSSOAuthURL = useCallback(
- async (provider: SSOProvider, redirectUrl?: string): Promise<SSOAuthURLResponse> => {
+ async (
+ provider: SSOProvider,
+ redirectUrl?: string,
+ ): Promise<SSOAuthURLResponse> => {
const response = await fetch('/api/auth', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ action: 'generateSSOAuthURL', provider, redirectUrl }),
+ body: JSON.stringify({
+ action: 'generateSSOAuthURL',
+ provider,
+ redirectUrl,
+ }),
})
- const result = (await response.json()) as ProxyResponse<SSOAuthURLResponse>
+ const result =
+ (await response.json()) as ProxyResponse<SSOAuthURLResponse>
if (result.error || !result.data) {
throw new Error(result.error || 'Failed to generate SSO URL')
}
@@ -25,11 +38,20 @@ export function useAuthProxy() {
)
const getJWTBySSOHash = useCallback(
- async (hash: string, provider: SSOProvider, remember = false): Promise<SSOHashResponse> => {
+ async (
+ hash: string,
+ provider: SSOProvider,
+ remember = false,
+ ): Promise<SSOHashResponse> => {
const response = await fetch('/api/auth', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ action: 'getJWTBySSOHash', hash, provider, remember }),
+ body: JSON.stringify({
+ action: 'getJWTBySSOHash',
+ hash,
+ provider,
+ remember,
+ }),
})
const result = (await response.json()) as ProxyResponse<SSOHashResponse>
if (result.error || !result.data) {
@@ -41,11 +63,20 @@ export function useAuthProxy() {
)
const processSSOTokenCommunityEdition = useCallback(
- async (code: string, hash: string, redirectUrl: string): Promise<unknown> => {
+ async (
+ code: string,
+ hash: string,
+ redirectUrl: string,
+ ): Promise<unknown> => {
const response = await fetch('/api/auth', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ action: 'processSSOTokenCommunityEdition', code, hash, redirectUrl }),
+ body: JSON.stringify({
+ action: 'processSSOTokenCommunityEdition',
+ code,
+ hash,
+ redirectUrl,
+ }),
})
const result = (await response.json()) as ProxyResponse<unknown>
if (result.error) {
@@ -56,58 +87,70 @@ export function useAuthProxy() {
[],
)
- const linkBySSOHash = useCallback(async (hash: string, provider: SSOProvider): Promise<unknown> => {
- const response = await fetch('/api/auth', {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ action: 'linkBySSOHash', hash, provider }),
- })
- const result = (await response.json()) as ProxyResponse<unknown>
- if (result.error) {
- throw new Error(result.error)
- }
- return result.data
- }, [])
+ const linkBySSOHash = useCallback(
+ async (hash: string, provider: SSOProvider): Promise<unknown> => {
+ const response = await fetch('/api/auth', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ action: 'linkBySSOHash', hash, provider }),
+ })
+ const result = (await response.json()) as ProxyResponse<unknown>
+ if (result.error) {
+ throw new Error(result.error)
+ }
+ return result.data
+ },
+ [],
+ )
- const processSSOToken = useCallback(async (token: string, hash: string): Promise<unknown> => {
- const response = await fetch('/api/auth', {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ action: 'processSSOToken', token, hash }),
- })
- const result = (await response.json()) as ProxyResponse<unknown>
- if (result.error) {
- throw new Error(result.error)
- }
- return result.data
- }, [])
+ const processSSOToken = useCallback(
+ async (token: string, hash: string): Promise<unknown> => {
+ const response = await fetch('/api/auth', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ action: 'processSSOToken', token, hash }),
+ })
+ const result = (await response.json()) as ProxyResponse<unknown>
+ if (result.error) {
+ throw new Error(result.error)
+ }
+ return result.data
+ },
+ [],
+ )
- const processGSCToken = useCallback(async (code: string, state: string): Promise<{ pid: string }> => {
- const response = await fetch('/api/auth', {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ action: 'processGSCToken', code, state }),
- })
- const result = (await response.json()) as ProxyResponse<{ pid: string }>
- if (result.error || !result.data) {
- throw new Error(result.error || 'Failed to process GSC token')
- }
- return result.data
- }, [])
+ const processGSCToken = useCallback(
+ async (code: string, state: string): Promise<{ pid: string }> => {
+ const response = await fetch('/api/auth', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ action: 'processGSCToken', code, state }),
+ })
+ const result = (await response.json()) as ProxyResponse<{ pid: string }>
+ if (result.error || !result.data) {
+ throw new Error(result.error || 'Failed to process GSC token')
+ }
+ return result.data
+ },
+ [],
+ )
- const authMe = useCallback(async (signal?: AbortSignal): Promise<AuthMeResponse> => {
- const response = await fetch('/api/auth', {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ action: 'authMe' }),
- signal,
- })
- const result = (await response.json()) as ProxyResponse<AuthMeResponse>
- if (result.error || !result.data) {
- throw new Error(result.error || 'Failed to fetch user')
- }
- return result.data
- }, [])
+ const authMe = useCallback(
+ async (signal?: AbortSignal): Promise<AuthMeResponse> => {
+ const response = await fetch('/api/auth', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ action: 'authMe' }),
+ signal,
+ })
+ const result = (await response.json()) as ProxyResponse<AuthMeResponse>
+ if (result.error || !result.data) {
+ throw new Error(result.error || 'Failed to fetch user')
+ }
+ return result.data
+ },
+ [],
+ )
return {
generateSSOAuthURL,
diff --git a/web/app/hooks/usePagination.tsx b/web/app/hooks/usePagination.tsx
index 0c9e37f15..1a6281eec 100644
--- a/web/app/hooks/usePagination.tsx
+++ b/web/app/hooks/usePagination.tsx
@@ -30,7 +30,10 @@ export const usePagination = (
}
const leftSiblingIndex = Math.max(currentPage - siblingCount, 1)
- const rightSiblingIndex = Math.min(currentPage + siblingCount, totalPageCount)
+ const rightSiblingIndex = Math.min(
+ currentPage + siblingCount,
+ totalPageCount,
+ )
/*
We do not want to show dots if there is only one position left
@@ -52,7 +55,10 @@ export const usePagination = (
if (shouldShowLeftDots && !shouldShowRightDots) {
const rightItemCount = 3 + 2 * siblingCount
- const rightRange = range(totalPageCount - rightItemCount + 1, totalPageCount)
+ const rightRange = range(
+ totalPageCount - rightItemCount + 1,
+ totalPageCount,
+ )
return [firstPageIndex, DOTS, ...rightRange]
}
diff --git a/web/app/hooks/useRequiredParams.ts b/web/app/hooks/useRequiredParams.ts
index 1603a5352..065de2cbd 100644
--- a/web/app/hooks/useRequiredParams.ts
+++ b/web/app/hooks/useRequiredParams.ts
@@ -1,3 +1,4 @@
import { useParams } from 'react-router'
-export const useRequiredParams = <T extends Record<string, unknown>>() => useParams() as T
+export const useRequiredParams = <T extends Record<string, unknown>>() =>
+ useParams() as T
diff --git a/web/app/hooks/useScript.ts b/web/app/hooks/useScript.ts
index cd5bfe0a2..cce0604db 100644
--- a/web/app/hooks/useScript.ts
+++ b/web/app/hooks/useScript.ts
@@ -31,7 +31,9 @@ const useScript = (src: string) => {
return
}
- let script = document.querySelector(`script[src="${src}"]`) as HTMLScriptElement | null
+ let script = document.querySelector(
+ `script[src="${src}"]`,
+ ) as HTMLScriptElement | null
if (!script) {
script = document.createElement('script')
diff --git a/web/app/hooks/useSize.ts b/web/app/hooks/useSize.ts
index 3e4400fb3..8c77e2f2c 100644
--- a/web/app/hooks/useSize.ts
+++ b/web/app/hooks/useSize.ts
@@ -2,7 +2,10 @@ import _get from 'lodash/get'
import type { MutableRefObject } from 'react'
import { useEffect, useRef, useState } from 'react'
-const useSize = (): [MutableRefObject<null>, { width: number; height: number }] => {
+const useSize = (): [
+ MutableRefObject<null>,
+ { width: number; height: number },
+] => {
const [size, setSize] = useState({
width: 0,
height: 0,
diff --git a/web/app/i18n.ts b/web/app/i18n.ts
index ae3c7849f..6d5c48ca1 100644
--- a/web/app/i18n.ts
+++ b/web/app/i18n.ts
@@ -21,7 +21,10 @@ export function detectLanguage(request: Request): string {
// Stage 1: Getting the language from the query ?lng= parameter
const url = new URL(request.url)
- if (url.searchParams.has('lng') && _includes(whitelist, url.searchParams.get('lng'))) {
+ if (
+ url.searchParams.has('lng') &&
+ _includes(whitelist, url.searchParams.get('lng'))
+ ) {
return url.searchParams.get('lng') as string
}
@@ -34,7 +37,10 @@ export function detectLanguage(request: Request): string {
}
// Stage 3: Getting the language from the Accept-Language header or fallback to default
- if (request.headers.has('accept-language') && _includes(whitelist, request.headers.get('accept-language'))) {
+ if (
+ request.headers.has('accept-language') &&
+ _includes(whitelist, request.headers.get('accept-language'))
+ ) {
return request.headers.get('accept-language') as string
}
diff --git a/web/app/lib/constants/index.ts b/web/app/lib/constants/index.ts
index b9c1bdec2..8e13e62d5 100644
--- a/web/app/lib/constants/index.ts
+++ b/web/app/lib/constants/index.ts
@@ -9,7 +9,11 @@ const displayDateOptions: Intl.DateTimeFormatOptions = {
day: 'numeric',
}
-const getCustomLabel = (dates: Date[], t: typeof i18nextT, language?: string): string => {
+const getCustomLabel = (
+ dates: Date[],
+ t: typeof i18nextT,
+ language?: string,
+): string => {
if (dates) {
let from: string
let to: string
@@ -58,7 +62,13 @@ export const VALID_PERIODS = [
'compare',
] as const
-export const VALID_TIME_BUCKETS = ['minute', 'hour', 'day', 'month', 'year'] as const
+export const VALID_TIME_BUCKETS = [
+ 'minute',
+ 'hour',
+ 'day',
+ 'month',
+ 'year',
+] as const
export type Period = (typeof VALID_PERIODS)[number]
@@ -169,7 +179,12 @@ export const PERIOD_PAIRS_COMPARE = {
} as const
// the order of panels in the project view
-export const TRAFFIC_PANELS_ORDER = ['location', 'pg', 'devices', 'traffic-sources']
+export const TRAFFIC_PANELS_ORDER = [
+ 'location',
+ 'pg',
+ 'devices',
+ 'traffic-sources',
+]
export const PERFORMANCE_PANELS_ORDER = ['location', 'pg', 'devices']
export const ERROR_PANELS_ORDER = ['location', 'pg', 'devices']
export const FILTERS_PANELS_ORDER = [
@@ -193,7 +208,18 @@ export const FILTERS_PANELS_ORDER = [
'te',
'co',
]
-export const ERRORS_FILTERS_PANELS_ORDER = ['cc', 'rg', 'ct', 'pg', 'br', 'brv', 'os', 'osv', 'lc', 'dv']
+export const ERRORS_FILTERS_PANELS_ORDER = [
+ 'cc',
+ 'rg',
+ 'ct',
+ 'pg',
+ 'br',
+ 'brv',
+ 'os',
+ 'osv',
+ 'lc',
+ 'dv',
+]
// the maximum amount of months user can go back when picking a date in flat picker (project view)
export const MAX_MONTHS_IN_PAST = 24
@@ -281,13 +307,15 @@ export const STATUSPAGE_URL = 'https://stats.uptimerobot.com/33rvmiXXEz'
export const MAIN_URL = 'https://swetrix.com'
export const LIVE_DEMO_URL = '/projects/STEzHcB1rALV'
export const BOOK_A_CALL_URL = 'https://cal.com/swetrix'
-export const PERFORMANCE_LIVE_DEMO_URL = '/projects/STEzHcB1rALV?tab=performance'
+export const PERFORMANCE_LIVE_DEMO_URL =
+ '/projects/STEzHcB1rALV?tab=performance'
export const ERROR_TRACKING_LIVE_DEMO_URL = '/projects/STEzHcB1rALV?tab=errors'
export const DOCS_URL = 'https://docs.swetrix.com'
export const INTEGRATIONS_URL = 'https://docs.swetrix.com/integrations'
export const ERROR_TRACKING_DOCS_URL = 'https://docs.swetrix.com/error-tracking'
-export const isBrowser = typeof window !== 'undefined' && typeof document !== 'undefined'
+export const isBrowser =
+ typeof window !== 'undefined' && typeof document !== 'undefined'
export const isIframe = isBrowser && window.self !== window.top
@@ -301,21 +329,36 @@ export const LIVE_VISITORS_UPDATE_INTERVAL = 40000
// Environment variables
// Using optional chaining for REMIX_ENV?. to avoid errors when running some unit tests
const isStaging = isBrowser ? window.REMIX_ENV?.STAGING : process.env.STAGING
-const STAGING_API_URL = isBrowser ? window.REMIX_ENV?.API_STAGING_URL : process.env.API_STAGING_URL
-const PRODUCTION_API_URL = isBrowser ? window.REMIX_ENV?.API_URL : process.env.API_URL
+const STAGING_API_URL = isBrowser
+ ? window.REMIX_ENV?.API_STAGING_URL
+ : process.env.API_STAGING_URL
+const PRODUCTION_API_URL = isBrowser
+ ? window.REMIX_ENV?.API_URL
+ : process.env.API_URL
-export const COOKIE_DOMAIN = (isBrowser ? window.REMIX_ENV?.COOKIE_DOMAIN : process.env.COOKIE_DOMAIN) || 'swetrix.com'
+export const COOKIE_DOMAIN =
+ (isBrowser ? window.REMIX_ENV?.COOKIE_DOMAIN : process.env.COOKIE_DOMAIN) ||
+ 'swetrix.com'
-export const isSelfhosted = Boolean(isBrowser ? window.REMIX_ENV?.SELFHOSTED : process.env.__SELFHOSTED)
+export const isSelfhosted = Boolean(
+ isBrowser ? window.REMIX_ENV?.SELFHOSTED : process.env.__SELFHOSTED,
+)
export const isDisableMarketingPages =
- (isBrowser ? window.REMIX_ENV?.DISABLE_MARKETING_PAGES : process.env.DISABLE_MARKETING_PAGES) === 'true'
+ (isBrowser
+ ? window.REMIX_ENV?.DISABLE_MARKETING_PAGES
+ : process.env.DISABLE_MARKETING_PAGES) === 'true'
-export const apiUrlUnprocessed = isSelfhosted || !isStaging ? PRODUCTION_API_URL : STAGING_API_URL
+export const apiUrlUnprocessed =
+ isSelfhosted || !isStaging ? PRODUCTION_API_URL : STAGING_API_URL
-export const TITLE_SUFFIX = isSelfhosted ? '| Swetrix Community Edition' : '| Swetrix'
+export const TITLE_SUFFIX = isSelfhosted
+ ? '| Swetrix Community Edition'
+ : '| Swetrix'
-export const API_URL = _endsWith(apiUrlUnprocessed, '/') ? apiUrlUnprocessed : `${apiUrlUnprocessed}/`
+export const API_URL = _endsWith(apiUrlUnprocessed, '/')
+ ? apiUrlUnprocessed
+ : `${apiUrlUnprocessed}/`
const NODE_ENV = isBrowser ? window.REMIX_ENV?.NODE_ENV : process.env.NODE_ENV
export const isDevelopment = !NODE_ENV || NODE_ENV === 'development'
@@ -374,7 +417,16 @@ export const I18N_CACHE_BREAKER = 28
export const roles: Role[] = ['admin', 'viewer']
-export const FUNNELS_PERIOD_PAIRS = ['1h', '1d', '7d', '4w', '3M', '12M', 'all', 'custom']
+export const FUNNELS_PERIOD_PAIRS = [
+ '1h',
+ '1d',
+ '7d',
+ '4w',
+ '3M',
+ '12M',
+ 'all',
+ 'custom',
+]
const SELFHOSTED_PROJECT_TABS = {
traffic: 'traffic',
@@ -813,7 +865,17 @@ export const PLAN_LIMITS = {
},
}
-export const STANDARD_PLANS = ['100k', '200k', '500k', 'startup', '2m', 'enterprise', '10m', '15m', '20m']
+export const STANDARD_PLANS = [
+ '100k',
+ '200k',
+ '500k',
+ 'startup',
+ '2m',
+ 'enterprise',
+ '10m',
+ '15m',
+ '20m',
+]
export const PURCHASABLE_LEGACY_PLANS = ['hobby', '50k']
diff --git a/web/app/modals/AnnotationModal.tsx b/web/app/modals/AnnotationModal.tsx
index 11c69a335..198d736eb 100644
--- a/web/app/modals/AnnotationModal.tsx
+++ b/web/app/modals/AnnotationModal.tsx
@@ -38,7 +38,10 @@ const AnnotationModal = ({
() => (isOpened ? annotation?.date || defaultDate || '' : ''),
[isOpened, annotation?.date, defaultDate],
)
- const initialText = useMemo(() => (isOpened ? annotation?.text || '' : ''), [isOpened, annotation?.text])
+ const initialText = useMemo(
+ () => (isOpened ? annotation?.text || '' : ''),
+ [isOpened, annotation?.text],
+ )
const [date, setDate] = useState(initialDate)
const [text, setText] = useState(initialText)
@@ -134,7 +137,7 @@ const AnnotationModal = ({
}}
options={{
altInputClass: cn(
- 'w-full rounded-md border-0 ring-1 ring-gray-300 bg-white px-3 py-2 text-sm text-gray-900 focus:ring-indigo-500 dark:ring-slate-800/50 dark:bg-slate-800 dark:text-gray-100',
+ 'w-full rounded-md border-0 bg-white px-3 py-2 text-sm text-gray-900 ring-1 ring-gray-300 focus:ring-indigo-500 dark:bg-slate-800 dark:text-gray-100 dark:ring-slate-800/50',
{
'cursor-not-allowed opacity-50': !allowedToManage,
},
@@ -161,11 +164,17 @@ const AnnotationModal = ({
</div>
<div className='flex items-start gap-2 rounded-md bg-blue-50 p-3 dark:bg-blue-900/20'>
<InfoIcon className='mt-0.5 h-4 w-4 shrink-0 text-blue-600 dark:text-blue-400' />
- <p className='text-xs text-blue-700 dark:text-blue-300'>{t('modals.annotation.warning')}</p>
+ <p className='text-xs text-blue-700 dark:text-blue-300'>
+ {t('modals.annotation.warning')}
+ </p>
</div>
</div>
}
- title={isEditMode ? t('modals.annotation.editTitle') : t('modals.annotation.addTitle')}
+ title={
+ isEditMode
+ ? t('modals.annotation.editTitle')
+ : t('modals.annotation.addTitle')
+ }
isOpened={isOpened}
overflowVisible
/>
diff --git a/web/app/modals/NewFunnel.tsx b/web/app/modals/NewFunnel.tsx
index bdf0a8208..164cfe4cb 100644
--- a/web/app/modals/NewFunnel.tsx
+++ b/web/app/modals/NewFunnel.tsx
@@ -27,19 +27,37 @@ interface FunnelStep {
value: string
}
-const createEmptyStep = (type: FunnelStepType = 'page'): FunnelStep => ({ type, value: '' })
-const INITIAL_FUNNEL_STEPS: FunnelStep[] = [createEmptyStep(), createEmptyStep()]
+const createEmptyStep = (type: FunnelStepType = 'page'): FunnelStep => ({
+ type,
+ value: '',
+})
+const INITIAL_FUNNEL_STEPS: FunnelStep[] = [
+ createEmptyStep(),
+ createEmptyStep(),
+]
-const NewFunnel = ({ onClose, onSubmit, isOpened, funnel, loading }: NewFunnelProps) => {
+const NewFunnel = ({
+ onClose,
+ onSubmit,
+ isOpened,
+ funnel,
+ loading,
+}: NewFunnelProps) => {
const { allowedToManage } = useCurrentProject()
const { t } = useTranslation('common')
const [name, setName] = useState(funnel?.name || '')
const [steps, setSteps] = useState<FunnelStep[]>(
funnel?.steps
- ? funnel.steps.map((s) => ({ type: s?.startsWith('/') ? 'page' : 'event', value: s }))
+ ? funnel.steps.map((s) => ({
+ type: s?.startsWith('/') ? 'page' : 'event',
+ value: s,
+ }))
: INITIAL_FUNNEL_STEPS,
)
- const allStepsFulfilled = useMemo(() => _every(steps, (step) => step.value && step.value.trim()), [steps])
+ const allStepsFulfilled = useMemo(
+ () => _every(steps, (step) => step.value && step.value.trim()),
+ [steps],
+ )
useEffect(() => {
if (!isOpened) {
@@ -49,7 +67,10 @@ const NewFunnel = ({ onClose, onSubmit, isOpened, funnel, loading }: NewFunnelPr
setName(funnel?.name || '') // eslint-disable-line react-hooks/set-state-in-effect -- Resetting form state when modal opens
setSteps(
funnel?.steps
- ? funnel.steps.map((s) => ({ type: s?.startsWith('/') ? 'page' : 'event', value: s }))
+ ? funnel.steps.map((s) => ({
+ type: s?.startsWith('/') ? 'page' : 'event',
+ value: s,
+ }))
: INITIAL_FUNNEL_STEPS,
)
}, [isOpened, funnel])
@@ -89,7 +110,13 @@ const NewFunnel = ({ onClose, onSubmit, isOpened, funnel, loading }: NewFunnelPr
onChange={(e) => setName(e.target.value)}
disabled={!allowedToManage}
/>
- <Text as='p' size='sm' weight='medium' colour='secondary' className='mt-5'>
+ <Text
+ as='p'
+ size='sm'
+ weight='medium'
+ colour='secondary'
+ className='mt-5'
+ >
{t('modals.funnels.steps')}
</Text>
{_map(steps, (step, index) => (
@@ -104,10 +131,17 @@ const NewFunnel = ({ onClose, onSubmit, isOpened, funnel, loading }: NewFunnelPr
labelExtractor={(item) => item.label}
onSelect={(item) => {
const newSteps = [...steps]
- newSteps[index] = { ...newSteps[index], type: item.key as FunnelStepType }
+ newSteps[index] = {
+ ...newSteps[index],
+ type: item.key as FunnelStepType,
+ }
setSteps(newSteps)
}}
- title={step.type === 'page' ? t('dashboard.page') : t('dashboard.event')}
+ title={
+ step.type === 'page'
+ ? t('dashboard.page')
+ : t('dashboard.event')
+ }
selectedItem={
step.type === 'page'
? { key: 'page', label: t('dashboard.page') }
@@ -120,7 +154,10 @@ const NewFunnel = ({ onClose, onSubmit, isOpened, funnel, loading }: NewFunnelPr
placeholder={step.type === 'page' ? '/pricing' : 'Registration'}
onChange={(e) => {
const newSteps = [...steps]
- newSteps[index] = { ...newSteps[index], value: e.target.value }
+ newSteps[index] = {
+ ...newSteps[index],
+ value: e.target.value,
+ }
setSteps(newSteps)
}}
disabled={!allowedToManage}
@@ -154,7 +191,9 @@ const NewFunnel = ({ onClose, onSubmit, isOpened, funnel, loading }: NewFunnelPr
) : null}
</div>
}
- title={funnel ? t('modals.funnels.editTitle') : t('modals.funnels.addTitle')}
+ title={
+ funnel ? t('modals.funnels.editTitle') : t('modals.funnels.addTitle')
+ }
isOpened={isOpened}
submitDisabled={!name || !allStepsFulfilled || !allowedToManage}
overflowVisible
diff --git a/web/app/modals/TrackingSnippet.tsx b/web/app/modals/TrackingSnippet.tsx
index 865cd26f8..8b5eed5d2 100644
--- a/web/app/modals/TrackingSnippet.tsx
+++ b/web/app/modals/TrackingSnippet.tsx
@@ -6,7 +6,9 @@ import { Badge } from '~/ui/Badge'
import Modal from '~/ui/Modal'
import Textarea from '~/ui/Textarea'
-const API_URL_WITHOUT_TRAILING_SLASH = API_URL.endsWith('/') ? API_URL.slice(0, -1) : API_URL
+const API_URL_WITHOUT_TRAILING_SLASH = API_URL.endsWith('/')
+ ? API_URL.slice(0, -1)
+ : API_URL
interface TrackingSnippetProps {
onClose: () => void
diff --git a/web/app/modals/ViewProjectHotkeys.tsx b/web/app/modals/ViewProjectHotkeys.tsx
index e1a3e3d65..8bac9874a 100644
--- a/web/app/modals/ViewProjectHotkeys.tsx
+++ b/web/app/modals/ViewProjectHotkeys.tsx
@@ -69,7 +69,9 @@ const HotkeysList = ({ title, hotkeys }: HotkeysListProps) => (
<table className='min-w-full divide-y divide-gray-300 dark:divide-gray-700'>
<thead>
<tr>
- <th className='pb-2 text-left text-base font-semibold text-gray-900 dark:text-gray-50'>{title}</th>
+ <th className='pb-2 text-left text-base font-semibold text-gray-900 dark:text-gray-50'>
+ {title}
+ </th>
<th />
</tr>
</thead>
diff --git a/web/app/pages/Auth/CreateNewPassword/CreateNewPassword.tsx b/web/app/pages/Auth/CreateNewPassword/CreateNewPassword.tsx
index a54318e4f..98a4e2156 100644
--- a/web/app/pages/Auth/CreateNewPassword/CreateNewPassword.tsx
+++ b/web/app/pages/Auth/CreateNewPassword/CreateNewPassword.tsx
@@ -48,7 +48,13 @@ const CreateNewPassword = () => {
error={actionData?.fieldErrors?.repeat}
disabled={isSubmitting}
/>
- <Button className='w-full justify-center' type='submit' loading={isSubmitting} primary giant>
+ <Button
+ className='w-full justify-center'
+ type='submit'
+ loading={isSubmitting}
+ primary
+ giant
+ >
{t('auth.recovery.save')}
</Button>
</Form>
diff --git a/web/app/pages/Auth/ForgotPassword/ForgotPassword.tsx b/web/app/pages/Auth/ForgotPassword/ForgotPassword.tsx
index da5813ddf..5084edf3d 100644
--- a/web/app/pages/Auth/ForgotPassword/ForgotPassword.tsx
+++ b/web/app/pages/Auth/ForgotPassword/ForgotPassword.tsx
@@ -1,6 +1,12 @@
import React, { useEffect } from 'react'
import { useTranslation, Trans } from 'react-i18next'
-import { Link, Form, useActionData, useNavigation, useSearchParams } from 'react-router'
+import {
+ Link,
+ Form,
+ useActionData,
+ useNavigation,
+ useSearchParams,
+} from 'react-router'
import { toast } from 'sonner'
import { isSelfhosted, TRIAL_DAYS } from '~/lib/constants'
@@ -48,7 +54,13 @@ const ForgotPassword = () => {
placeholder='[email protected]'
disabled={isSubmitting}
/>
- <Button className='w-full justify-center' type='submit' loading={isSubmitting} primary giant>
+ <Button
+ className='w-full justify-center'
+ type='submit'
+ loading={isSubmitting}
+ primary
+ giant
+ >
{t('auth.forgot.reset')}
</Button>
</Form>
diff --git a/web/app/pages/Auth/Signin/Signin.tsx b/web/app/pages/Auth/Signin/Signin.tsx
index 7bf4d11cd..2fc1e2cc5 100644
--- a/web/app/pages/Auth/Signin/Signin.tsx
+++ b/web/app/pages/Auth/Signin/Signin.tsx
@@ -1,6 +1,14 @@
import React, { useState, memo, useEffect } from 'react'
import { useTranslation, Trans } from 'react-i18next'
-import { Link, useNavigate, useSearchParams, Form, useActionData, useNavigation, useFetcher } from 'react-router'
+import {
+ Link,
+ useNavigate,
+ useSearchParams,
+ Form,
+ useActionData,
+ useNavigation,
+ useFetcher,
+} from 'react-router'
import { toast } from 'sonner'
import GithubAuth from '~/components/GithubAuth'
@@ -51,20 +59,28 @@ const Signin = () => {
// 2FA is required from URL params, action data, or SSO flow
const isTwoFARequired =
- searchParams.get('show_2fa_screen') === 'true' || actionData?.requires2FA === true || sso2FARequired
+ searchParams.get('show_2fa_screen') === 'true' ||
+ actionData?.requires2FA === true ||
+ sso2FARequired
// Derive 2FA error from fetcher data
const twoFACodeError = twoFAFetcher.data?.fieldErrors?.twoFACode || null
useEffect(() => {
if (actionData?.error && !actionData?.fieldErrors) {
- const errorMessage = Array.isArray(actionData.error) ? actionData.error[0] : actionData.error
+ const errorMessage = Array.isArray(actionData.error)
+ ? actionData.error[0]
+ : actionData.error
toast.error(errorMessage)
}
}, [actionData?.error, actionData?.fieldErrors, actionData?.timestamp])
const clearFieldError = (fieldName: string) => {
- if (actionData?.fieldErrors?.[fieldName as keyof typeof actionData.fieldErrors]) {
+ if (
+ actionData?.fieldErrors?.[
+ fieldName as keyof typeof actionData.fieldErrors
+ ]
+ ) {
setClearedErrors((prev) => new Set(prev).add(fieldName))
}
}
@@ -73,7 +89,9 @@ const Signin = () => {
if (clearedErrors.has(fieldName)) {
return undefined
}
- return actionData?.fieldErrors?.[fieldName as keyof typeof actionData.fieldErrors]
+ return actionData?.fieldErrors?.[
+ fieldName as keyof typeof actionData.fieldErrors
+ ]
}
const handleFormSubmit = () => {
@@ -103,7 +121,10 @@ const Signin = () => {
uuid,
auth_url: authUrl,
expires_in: expiresIn,
- } = await generateSSOAuthURL(provider, `${window.location.origin}${routes.socialised}`)
+ } = await generateSSOAuthURL(
+ provider,
+ `${window.location.origin}${routes.socialised}`,
+ )
const safeAuthUrl = (() => {
try {
@@ -116,14 +137,21 @@ const Signin = () => {
!(
provider === 'openid-connect' &&
parsed.protocol === 'http:' &&
- (parsed.hostname === 'localhost' || parsed.hostname === '127.0.0.1' || parsed.hostname === '::1')
+ (parsed.hostname === 'localhost' ||
+ parsed.hostname === '127.0.0.1' ||
+ parsed.hostname === '::1')
)
) {
return null
}
- if (provider === 'google' && parsed.hostname !== 'accounts.google.com') return null
- if (provider === 'github' && parsed.hostname !== 'github.com') return null
+ if (
+ provider === 'google' &&
+ parsed.hostname !== 'accounts.google.com'
+ )
+ return null
+ if (provider === 'github' && parsed.hostname !== 'github.com')
+ return null
return parsed.toString()
} catch {
@@ -147,7 +175,11 @@ const Signin = () => {
await delay(HASH_CHECK_FREQUENCY)
try {
- const { user, totalMonthlyEvents } = await getJWTBySSOHash(uuid, provider, !dontRemember)
+ const { user, totalMonthlyEvents } = await getJWTBySSOHash(
+ uuid,
+ provider,
+ !dontRemember,
+ )
authWindow.close()
if (user.isTwoFactorAuthenticationEnabled) {
@@ -179,7 +211,11 @@ const Signin = () => {
}
}
} catch (reason) {
- toast.error(typeof reason === 'string' ? reason : t('apiNotifications.socialisationGenericError'))
+ toast.error(
+ typeof reason === 'string'
+ ? reason
+ : t('apiNotifications.socialisationGenericError'),
+ )
setIsSsoLoading(false)
return
}
@@ -208,10 +244,19 @@ const Signin = () => {
{isTwoFARequired ? (
<>
<div className='mb-8'>
- <Text as='h1' size='3xl' weight='bold' className='tracking-tight'>
+ <Text
+ as='h1'
+ size='3xl'
+ weight='bold'
+ className='tracking-tight'
+ >
{t('auth.signin.2fa')}
</Text>
- <Text as='p' colour='muted' className='mt-2 whitespace-pre-line'>
+ <Text
+ as='p'
+ colour='muted'
+ className='mt-2 whitespace-pre-line'
+ >
{t('auth.signin.2faDesc')}
</Text>
</div>
@@ -226,7 +271,12 @@ const Signin = () => {
error={twoFACodeError}
/>
<div className='mt-6 flex items-center justify-between'>
- <Text as='div' size='sm' colour='muted' className='whitespace-pre-line'>
+ <Text
+ as='div'
+ size='sm'
+ colour='muted'
+ className='whitespace-pre-line'
+ >
{!isSelfhosted ? (
<Trans
t={t}
@@ -251,7 +301,12 @@ const Signin = () => {
) : (
<>
<div className='mb-8'>
- <Text as='h1' size='3xl' weight='bold' className='tracking-tight'>
+ <Text
+ as='h1'
+ size='3xl'
+ weight='bold'
+ className='tracking-tight'
+ >
{t('auth.signin.title')}
</Text>
<Text as='p' colour='muted' className='mt-2'>
@@ -259,29 +314,56 @@ const Signin = () => {
</Text>
</div>
- <div className={cn('grid gap-3', isSelfhosted ? 'grid-cols-1' : 'grid-cols-2')}>
+ <div
+ className={cn(
+ 'grid gap-3',
+ isSelfhosted ? 'grid-cols-1' : 'grid-cols-2',
+ )}
+ >
{isSelfhosted ? (
- <OIDCAuth onClick={() => onSsoLogin('openid-connect')} disabled={isLoading} className='w-full' />
+ <OIDCAuth
+ onClick={() => onSsoLogin('openid-connect')}
+ disabled={isLoading}
+ className='w-full'
+ />
) : (
<>
- <GoogleAuth onClick={() => onSsoLogin('google')} disabled={isLoading} />
- <GithubAuth onClick={() => onSsoLogin('github')} disabled={isLoading} />
+ <GoogleAuth
+ onClick={() => onSsoLogin('google')}
+ disabled={isLoading}
+ />
+ <GithubAuth
+ onClick={() => onSsoLogin('github')}
+ disabled={isLoading}
+ />
</>
)}
</div>
<div className='relative my-6'>
- <div className='absolute inset-0 flex items-center' aria-hidden='true'>
+ <div
+ className='absolute inset-0 flex items-center'
+ aria-hidden='true'
+ >
<div className='w-full border-t border-gray-200 dark:border-gray-700' />
</div>
<div className='relative flex justify-center text-sm'>
- <Text as='span' colour='muted' size='sm' className='bg-gray-50 px-4 dark:bg-slate-900'>
+ <Text
+ as='span'
+ colour='muted'
+ size='sm'
+ className='bg-gray-50 px-4 dark:bg-slate-900'
+ >
{t('auth.common.orContinueWith')} email
</Text>
</div>
</div>
- <Form method='post' className='space-y-4' onSubmit={handleFormSubmit}>
+ <Form
+ method='post'
+ className='space-y-4'
+ onSubmit={handleFormSubmit}
+ >
<Input
name='email'
type='email'
@@ -311,7 +393,11 @@ const Signin = () => {
/>
{/* Hidden input for form submission since Headless UI Checkbox doesn't submit natively */}
- <input type='hidden' name='dontRemember' value={dontRemember ? 'true' : 'false'} />
+ <input
+ type='hidden'
+ name='dontRemember'
+ value={dontRemember ? 'true' : 'false'}
+ />
<div className='flex items-center justify-between'>
<Checkbox
@@ -321,20 +407,34 @@ const Signin = () => {
label={
<span className='flex items-center gap-1'>
<Text size='sm'>{t('auth.common.noRemember')}</Text>
- <Tooltip text={t('auth.common.noRememberHint')} className='relative' />
+ <Tooltip
+ text={t('auth.common.noRememberHint')}
+ className='relative'
+ />
</span>
}
/>
</div>
- <Button className='mt-6 w-full justify-center' type='submit' loading={isFormSubmitting} primary giant>
+ <Button
+ className='mt-6 w-full justify-center'
+ type='submit'
+ loading={isFormSubmitting}
+ primary
+ giant
+ >
{t('auth.signin.button')}
</Button>
</Form>
{/* Sign up link */}
{!isSelfhosted ? (
- <Text as='p' size='sm' colour='muted' className='mt-6 text-center'>
+ <Text
+ as='p'
+ size='sm'
+ colour='muted'
+ className='mt-6 text-center'
+ >
<Trans
t={t}
i18nKey='auth.signin.notAMember'
@@ -375,7 +475,11 @@ const Signin = () => {
<div className='relative'>
<div className='overflow-hidden rounded-xl shadow-2xl ring-1 ring-white/10'>
<img
- src={theme === 'dark' ? '/assets/screenshot_dark.png' : '/assets/screenshot_light.png'}
+ src={
+ theme === 'dark'
+ ? '/assets/screenshot_dark.png'
+ : '/assets/screenshot_light.png'
+ }
alt='Swetrix Dashboard'
className='w-full'
/>
diff --git a/web/app/pages/Auth/Signup/Signup.tsx b/web/app/pages/Auth/Signup/Signup.tsx
index 8a266e9e0..025a02f00 100644
--- a/web/app/pages/Auth/Signup/Signup.tsx
+++ b/web/app/pages/Auth/Signup/Signup.tsx
@@ -1,14 +1,29 @@
-import { BarChart3Icon, MousePointerClickIcon, ShieldCheckIcon, SparklesIcon } from 'lucide-react'
+import {
+ BarChart3Icon,
+ MousePointerClickIcon,
+ ShieldCheckIcon,
+ SparklesIcon,
+} from 'lucide-react'
import React, { useState, useEffect, memo } from 'react'
import { useTranslation, Trans } from 'react-i18next'
-import { Link, useNavigate, Form, useActionData, useNavigation } from 'react-router'
+import {
+ Link,
+ useNavigate,
+ Form,
+ useActionData,
+ useNavigation,
+} from 'react-router'
import { toast } from 'sonner'
import GithubAuth from '~/components/GithubAuth'
import GoogleAuth from '~/components/GoogleAuth'
import OIDCAuth from '~/components/OIDCAuth'
import { useAuthProxy } from '~/hooks/useAuthProxy'
-import { HAVE_I_BEEN_PWNED_URL, isSelfhosted, TRIAL_DAYS } from '~/lib/constants'
+import {
+ HAVE_I_BEEN_PWNED_URL,
+ isSelfhosted,
+ TRIAL_DAYS,
+} from '~/lib/constants'
import { SSOProvider } from '~/lib/models/Auth'
import { useAuth } from '~/providers/AuthProvider'
import { useTheme } from '~/providers/ThemeProvider'
@@ -24,9 +39,19 @@ import { MIN_PASSWORD_CHARS } from '~/utils/validator'
const HASH_CHECK_FREQUENCY = 1000
-const featureIcons = [BarChart3Icon, MousePointerClickIcon, ShieldCheckIcon, SparklesIcon]
+const featureIcons = [
+ BarChart3Icon,
+ MousePointerClickIcon,
+ ShieldCheckIcon,
+ SparklesIcon,
+]
-const featureKeys = ['realTimeAnalytics', 'eventTracking', 'privacyFirst', 'intuitive'] as const
+const featureKeys = [
+ 'realTimeAnalytics',
+ 'eventTracking',
+ 'privacyFirst',
+ 'intuitive',
+] as const
const Signup = () => {
const { t } = useTranslation('common')
@@ -50,13 +75,19 @@ const Signup = () => {
useEffect(() => {
if (actionData?.error && !actionData?.fieldErrors) {
- const errorMessage = Array.isArray(actionData.error) ? actionData.error[0] : actionData.error
+ const errorMessage = Array.isArray(actionData.error)
+ ? actionData.error[0]
+ : actionData.error
toast.error(errorMessage)
}
}, [actionData?.error, actionData?.fieldErrors, actionData?.timestamp])
const clearFieldError = (fieldName: string) => {
- if (actionData?.fieldErrors?.[fieldName as keyof typeof actionData.fieldErrors]) {
+ if (
+ actionData?.fieldErrors?.[
+ fieldName as keyof typeof actionData.fieldErrors
+ ]
+ ) {
setClearedErrors((prev) => new Set(prev).add(fieldName))
}
}
@@ -65,7 +96,9 @@ const Signup = () => {
if (clearedErrors.has(fieldName)) {
return undefined
}
- return actionData?.fieldErrors?.[fieldName as keyof typeof actionData.fieldErrors]
+ return actionData?.fieldErrors?.[
+ fieldName as keyof typeof actionData.fieldErrors
+ ]
}
const handleFormSubmit = () => {
@@ -84,7 +117,11 @@ const Signup = () => {
setIsSsoLoading(true)
try {
- const { uuid, auth_url: authUrl, expires_in: expiresIn } = await generateSSOAuthURL(provider)
+ const {
+ uuid,
+ auth_url: authUrl,
+ expires_in: expiresIn,
+ } = await generateSSOAuthURL(provider)
const safeAuthUrl = (() => {
try {
@@ -97,14 +134,21 @@ const Signup = () => {
!(
provider === 'openid-connect' &&
parsed.protocol === 'http:' &&
- (parsed.hostname === 'localhost' || parsed.hostname === '127.0.0.1' || parsed.hostname === '::1')
+ (parsed.hostname === 'localhost' ||
+ parsed.hostname === '127.0.0.1' ||
+ parsed.hostname === '::1')
)
) {
return null
}
- if (provider === 'google' && parsed.hostname !== 'accounts.google.com') return null
- if (provider === 'github' && parsed.hostname !== 'github.com') return null
+ if (
+ provider === 'google' &&
+ parsed.hostname !== 'accounts.google.com'
+ )
+ return null
+ if (provider === 'github' && parsed.hostname !== 'github.com')
+ return null
return parsed.toString()
} catch {
@@ -128,7 +172,11 @@ const Signup = () => {
await delay(HASH_CHECK_FREQUENCY)
try {
- const { user, totalMonthlyEvents } = await getJWTBySSOHash(uuid, provider, true)
+ const { user, totalMonthlyEvents } = await getJWTBySSOHash(
+ uuid,
+ provider,
+ true,
+ )
authWindow.close()
if (user.isTwoFactorAuthenticationEnabled) {
@@ -160,7 +208,10 @@ const Signup = () => {
}
}
} catch (reason) {
- toast.error((reason as { message?: string })?.message || t('apiNotifications.socialisationGenericError'))
+ toast.error(
+ (reason as { message?: string })?.message ||
+ t('apiNotifications.socialisationGenericError'),
+ )
setIsSsoLoading(false)
return
}
@@ -185,23 +236,46 @@ const Signup = () => {
)}
</div>
- <div className={cn('grid gap-3', isSelfhosted ? 'grid-cols-1' : 'grid-cols-2')}>
+ <div
+ className={cn(
+ 'grid gap-3',
+ isSelfhosted ? 'grid-cols-1' : 'grid-cols-2',
+ )}
+ >
{isSelfhosted ? (
- <OIDCAuth onClick={() => onSsoLogin('openid-connect')} disabled={isLoading} className='w-full' />
+ <OIDCAuth
+ onClick={() => onSsoLogin('openid-connect')}
+ disabled={isLoading}
+ className='w-full'
+ />
) : (
<>
- <GoogleAuth onClick={() => onSsoLogin('google')} disabled={isLoading} />
- <GithubAuth onClick={() => onSsoLogin('github')} disabled={isLoading} />
+ <GoogleAuth
+ onClick={() => onSsoLogin('google')}
+ disabled={isLoading}
+ />
+ <GithubAuth
+ onClick={() => onSsoLogin('github')}
+ disabled={isLoading}
+ />
</>
)}
</div>
<div className='relative my-6'>
- <div className='absolute inset-0 flex items-center' aria-hidden='true'>
+ <div
+ className='absolute inset-0 flex items-center'
+ aria-hidden='true'
+ >
<div className='w-full border-t border-gray-200 dark:border-gray-700' />
</div>
<div className='relative flex justify-center text-sm'>
- <Text as='span' colour='muted' size='sm' className='bg-gray-50 px-4 dark:bg-slate-900'>
+ <Text
+ as='span'
+ colour='muted'
+ size='sm'
+ className='bg-gray-50 px-4 dark:bg-slate-900'
+ >
{t('auth.common.orContinueWith')} email
</Text>
</div>
@@ -237,7 +311,11 @@ const Signup = () => {
{/* Hidden fields for checkbox values since Headless UI Checkbox doesn't submit natively */}
<input type='hidden' name='tos' value={tos ? 'true' : 'false'} />
- <input type='hidden' name='checkIfLeaked' value={checkIfLeaked ? 'true' : 'false'} />
+ <input
+ type='hidden'
+ name='checkIfLeaked'
+ value={checkIfLeaked ? 'true' : 'false'}
+ />
{isSelfhosted ? null : (
<Checkbox
@@ -284,7 +362,9 @@ const Signup = () => {
checked={checkIfLeaked}
onChange={setCheckIfLeaked}
disabled={isLoading}
- label={<Text size='sm'>{t('auth.common.checkLeakedPassword')}</Text>}
+ label={
+ <Text size='sm'>{t('auth.common.checkLeakedPassword')}</Text>
+ }
/>
<Tooltip
className='ml-2'
@@ -310,7 +390,13 @@ const Signup = () => {
/>
</div>
- <Button className='mt-6 w-full justify-center' type='submit' loading={isFormSubmitting} primary giant>
+ <Button
+ className='mt-6 w-full justify-center'
+ type='submit'
+ loading={isFormSubmitting}
+ primary
+ giant
+ >
{t('auth.signup.button')}
</Button>
</Form>
@@ -351,7 +437,12 @@ const Signup = () => {
<Icon className='size-4 text-white' />
</div>
<div>
- <Text as='span' size='sm' weight='semibold' className='text-white'>
+ <Text
+ as='span'
+ size='sm'
+ weight='semibold'
+ className='text-white'
+ >
{t(`auth.signup.features.${key}`)}
</Text>
<Text as='span' size='sm' className='ml-1 text-slate-400'>
@@ -367,7 +458,11 @@ const Signup = () => {
<div className='relative'>
<div className='overflow-hidden rounded-xl shadow-2xl ring-1 ring-white/10'>
<img
- src={theme === 'dark' ? '/assets/screenshot_dark.png' : '/assets/screenshot_light.png'}
+ src={
+ theme === 'dark'
+ ? '/assets/screenshot_dark.png'
+ : '/assets/screenshot_light.png'
+ }
alt='Swetrix Dashboard'
className='w-full'
/>
diff --git a/web/app/pages/Auth/Socialised/index.tsx b/web/app/pages/Auth/Socialised/index.tsx
index fc8a8df49..21debc971 100644
--- a/web/app/pages/Auth/Socialised/index.tsx
+++ b/web/app/pages/Auth/Socialised/index.tsx
@@ -16,7 +16,11 @@ const Socialised = () => {
useEffect(() => {
// For some reason, Google redirects to a hash URL, let's fix it
- const _location = _replace(window.location.href, `${routes.socialised}#`, `${routes.socialised}?`)
+ const _location = _replace(
+ window.location.href,
+ `${routes.socialised}#`,
+ `${routes.socialised}?`,
+ )
const { searchParams } = new URL(_location)
const state = searchParams.get('state')
@@ -75,7 +79,11 @@ const Socialised = () => {
if (processedKey) {
sessionStorage.setItem(processedKey, '1')
}
- await processSSOTokenCommunityEdition(code, state, `${window.location.origin}${routes.socialised}`)
+ await processSSOTokenCommunityEdition(
+ code,
+ state,
+ `${window.location.origin}${routes.socialised}`,
+ )
} catch (reason) {
setIsError(true)
setLoading(false)
diff --git a/web/app/pages/Billing/index.tsx b/web/app/pages/Billing/index.tsx
index 7f186b9dc..478992ac4 100644
--- a/web/app/pages/Billing/index.tsx
+++ b/web/app/pages/Billing/index.tsx
@@ -1,4 +1,7 @@
-import { ExclamationTriangleIcon, InformationCircleIcon } from '@heroicons/react/24/outline'
+import {
+ ExclamationTriangleIcon,
+ InformationCircleIcon,
+} from '@heroicons/react/24/outline'
import dayjs from 'dayjs'
import duration from 'dayjs/plugin/duration'
import utc from 'dayjs/plugin/utc'
@@ -11,7 +14,12 @@ import { toast } from 'sonner'
import DashboardLockedBanner from '~/components/DashboardLockedBanner'
import FAQ from '~/components/marketing/FAQ'
import BillingPricing from '~/components/pricing/BillingPricing'
-import { PADDLE_JS_URL, PADDLE_VENDOR_ID, CONTACT_EMAIL, paddleLanguageMapping } from '~/lib/constants'
+import {
+ PADDLE_JS_URL,
+ PADDLE_VENDOR_ID,
+ CONTACT_EMAIL,
+ paddleLanguageMapping,
+} from '~/lib/constants'
import { DEFAULT_METAINFO } from '~/lib/models/Metainfo'
import { UsageInfo } from '~/lib/models/Usageinfo'
import { useAuth } from '~/providers/AuthProvider'
@@ -55,7 +63,10 @@ const Billing = () => {
return loaderData?.metainfo ?? DEFAULT_METAINFO
}, [loaderData?.metainfo, metainfoFetcher.data])
- const usageInfo = useMemo(() => loaderData?.usageInfo ?? DEFAULT_USAGE_INFO, [loaderData?.usageInfo])
+ const usageInfo = useMemo(
+ () => loaderData?.usageInfo ?? DEFAULT_USAGE_INFO,
+ [loaderData?.usageInfo],
+ )
const isLoading = !loaderData
const {
@@ -78,7 +89,9 @@ const Billing = () => {
const isTrial = planCode === 'trial'
const isNoSub = planCode === 'none'
- const totalUsage = maxEventsCount ? _round((usageInfo.total / maxEventsCount) * 100, 2) : 0
+ const totalUsage = maxEventsCount
+ ? _round((usageInfo.total / maxEventsCount) * 100, 2)
+ : 0
const remainingUsage = _round(100 - totalUsage, 2)
// Paddle (payment processor) set-up
@@ -197,30 +210,44 @@ const Billing = () => {
<DashboardLockedBanner />
<div className='mx-auto px-4 pt-12 whitespace-pre-line sm:px-6 md:w-11/12'>
- <h1 className='text-4xl font-extrabold text-gray-900 dark:text-gray-50'>{t('billing.title')}</h1>
+ <h1 className='text-4xl font-extrabold text-gray-900 dark:text-gray-50'>
+ {t('billing.title')}
+ </h1>
</div>
<div className='mx-auto mt-5 grid gap-x-10 gap-y-8 px-4 pb-4 whitespace-pre-line sm:px-6 md:w-11/12 lg:grid-cols-3'>
<div className='lg:col-span-2'>
- <h2 id='billing' className='mb-2 text-2xl font-medium text-gray-900 dark:text-gray-50'>
+ <h2
+ id='billing'
+ className='mb-2 text-2xl font-medium text-gray-900 dark:text-gray-50'
+ >
{t('billing.subscription')}
</h2>
<p className='mt-1 text-base text-gray-900 dark:text-gray-50'>
{isSubscriber ? t('billing.selectPlan') : t('billing.changePlan')}
</p>
- <p className='max-w-prose text-base text-gray-900 dark:text-gray-50'>{t('billing.membersNotification')}</p>
+ <p className='max-w-prose text-base text-gray-900 dark:text-gray-50'>
+ {t('billing.membersNotification')}
+ </p>
{isSubscriber && nextBillDate ? (
<div className='mt-5 max-w-prose rounded-md bg-blue-50 p-4 dark:bg-blue-600/30'>
<div className='flex'>
<div className='shrink-0'>
- <InformationCircleIcon aria-hidden='true' className='h-5 w-5 text-blue-400 dark:text-blue-100' />
+ <InformationCircleIcon
+ aria-hidden='true'
+ className='h-5 w-5 text-blue-400 dark:text-blue-100'
+ />
</div>
<p className='ml-3 text-sm font-medium text-blue-700 dark:text-blue-100'>
{t('billing.nextBillDateIs', {
date:
language === 'en'
- ? dayjs(nextBillDate).locale(language).format('MMMM D, YYYY')
- : dayjs(nextBillDate).locale(language).format('D MMMM, YYYY'),
+ ? dayjs(nextBillDate)
+ .locale(language)
+ .format('MMMM D, YYYY')
+ : dayjs(nextBillDate)
+ .locale(language)
+ .format('D MMMM, YYYY'),
})}
</p>
</div>
@@ -230,7 +257,10 @@ const Billing = () => {
<div className='mt-5 max-w-prose rounded-md bg-blue-50 p-4 dark:bg-blue-600/30'>
<div className='flex'>
<div className='shrink-0'>
- <InformationCircleIcon aria-hidden='true' className='h-5 w-5 text-blue-400 dark:text-blue-100' />
+ <InformationCircleIcon
+ aria-hidden='true'
+ className='h-5 w-5 text-blue-400 dark:text-blue-100'
+ />
</div>
<div className='ml-3'>
<h3 className='text-sm font-medium text-blue-700 dark:text-blue-100'>
@@ -240,8 +270,12 @@ const Billing = () => {
{t('billing.subscriptionCancelledDescription', {
date:
language === 'en'
- ? dayjs(cancellationEffectiveDate).locale(language).format('MMMM D, YYYY')
- : dayjs(cancellationEffectiveDate).locale(language).format('D MMMM, YYYY'),
+ ? dayjs(cancellationEffectiveDate)
+ .locale(language)
+ .format('MMMM D, YYYY')
+ : dayjs(cancellationEffectiveDate)
+ .locale(language)
+ .format('D MMMM, YYYY'),
})}
</p>
</div>
@@ -252,11 +286,18 @@ const Billing = () => {
<div className='mt-5 max-w-prose rounded-md bg-amber-400/10 p-4 dark:bg-amber-600/20'>
<div className='flex'>
<div className='shrink-0'>
- <InformationCircleIcon aria-hidden='true' className='h-5 w-5 text-amber-400 dark:text-amber-50' />
+ <InformationCircleIcon
+ aria-hidden='true'
+ className='h-5 w-5 text-amber-400 dark:text-amber-50'
+ />
</div>
<div className='ml-3'>
- <h3 className='text-sm font-medium text-amber-700 dark:text-amber-50'>{trialEndsOnMessage}</h3>
- <p className='mt-1 text-sm text-amber-700 dark:text-amber-50'>{t('billing.trialDescription')}</p>
+ <h3 className='text-sm font-medium text-amber-700 dark:text-amber-50'>
+ {trialEndsOnMessage}
+ </h3>
+ <p className='mt-1 text-sm text-amber-700 dark:text-amber-50'>
+ {t('billing.trialDescription')}
+ </p>
</div>
</div>
</div>
@@ -265,7 +306,10 @@ const Billing = () => {
<div className='mt-5 max-w-prose rounded-md bg-red-50 p-4 dark:bg-red-600/20'>
<div className='flex'>
<div className='shrink-0'>
- <ExclamationTriangleIcon aria-hidden='true' className='h-5 w-5 text-red-400 dark:text-red-100' />
+ <ExclamationTriangleIcon
+ aria-hidden='true'
+ className='h-5 w-5 text-red-400 dark:text-red-100'
+ />
</div>
<div className='ml-3'>
<h3 className='text-sm font-medium text-red-800 dark:text-red-100'>
@@ -286,12 +330,23 @@ const Billing = () => {
<BillingPricing lastEvent={lastEvent} metainfo={metainfo} />
<div className='mt-2 space-y-2'>
{subUpdateURL && !cancellationEffectiveDate ? (
- <Button className='mr-2' onClick={onUpdatePaymentDetails} type='button' primary large>
+ <Button
+ className='mr-2'
+ onClick={onUpdatePaymentDetails}
+ type='button'
+ primary
+ large
+ >
{t('billing.update')}
</Button>
) : null}
{subCancelURL && !cancellationEffectiveDate ? (
- <Button onClick={() => setIsCancelSubModalOpened(true)} type='button' semiDanger large>
+ <Button
+ onClick={() => setIsCancelSubModalOpened(true)}
+ type='button'
+ semiDanger
+ large
+ >
{t('billing.cancelSub')}
</Button>
) : null}
@@ -301,10 +356,15 @@ const Billing = () => {
</div>
<div className='lg:col-span-1'>
- <h2 id='usage' className='mb-2 text-2xl font-medium text-gray-900 dark:text-gray-50'>
+ <h2
+ id='usage'
+ className='mb-2 text-2xl font-medium text-gray-900 dark:text-gray-50'
+ >
{t('billing.planUsage')}
</h2>
- <p className='mt-1 max-w-prose text-base text-gray-900 dark:text-gray-50'>{t('billing.planUsageDesc')}</p>
+ <p className='mt-1 max-w-prose text-base text-gray-900 dark:text-gray-50'>
+ {t('billing.planUsageDesc')}
+ </p>
{isLoading || authLoading ? (
<Loader />
@@ -322,8 +382,12 @@ const Billing = () => {
<div className='ml-3'>
<p className='text-sm text-amber-800 dark:text-amber-100'>
{totalUsage >= 90
- ? t('billing.usageWarningCritical', { percentage: totalUsage })
- : t('billing.usageWarningHigh', { percentage: totalUsage })}
+ ? t('billing.usageWarningCritical', {
+ percentage: totalUsage,
+ })
+ : t('billing.usageWarningHigh', {
+ percentage: totalUsage,
+ })}
</p>
</div>
</div>
@@ -399,22 +463,34 @@ const Billing = () => {
className='w-full'
progress={[
{
- value: usageInfo.traffic === 0 ? 0 : (usageInfo.traffic / maxEventsCount) * 100,
+ value:
+ usageInfo.traffic === 0
+ ? 0
+ : (usageInfo.traffic / maxEventsCount) * 100,
lightColour: '#2563eb',
darkColour: '#1d4ed8',
},
{
- value: usageInfo.customEvents === 0 ? 0 : (usageInfo.customEvents / maxEventsCount) * 100,
+ value:
+ usageInfo.customEvents === 0
+ ? 0
+ : (usageInfo.customEvents / maxEventsCount) * 100,
lightColour: '#c026d3',
darkColour: '#a21caf',
},
{
- value: usageInfo.captcha === 0 ? 0 : (usageInfo.captcha / maxEventsCount) * 100,
+ value:
+ usageInfo.captcha === 0
+ ? 0
+ : (usageInfo.captcha / maxEventsCount) * 100,
lightColour: '#65a30d',
darkColour: '#4d7c0f',
},
{
- value: usageInfo.errors === 0 ? 0 : (usageInfo.errors / maxEventsCount) * 100,
+ value:
+ usageInfo.errors === 0
+ ? 0
+ : (usageInfo.errors / maxEventsCount) * 100,
lightColour: '#dc2626',
darkColour: '#b91c1c',
},
@@ -426,14 +502,20 @@ const Billing = () => {
{t('billing.xPercentUsed', { percentage: totalUsage })}
</p>
<p className='text-sm text-gray-600 dark:text-gray-400'>
- {t('billing.xPercentRemaining', { percentage: remainingUsage })}
+ {t('billing.xPercentRemaining', {
+ percentage: remainingUsage,
+ })}
</p>
</div>
<p className='mt-4 text-sm text-gray-600 dark:text-gray-400'>
{t('billing.resetDate', {
days: Math.ceil(
- (new Date(new Date().getFullYear(), new Date().getMonth() + 1, 1).getTime() -
+ (new Date(
+ new Date().getFullYear(),
+ new Date().getMonth() + 1,
+ 1,
+ ).getTime() -
new Date().getTime()) /
(1000 * 60 * 60 * 24),
),
diff --git a/web/app/pages/Blog/Post.tsx b/web/app/pages/Blog/Post.tsx
index 8b008ae22..ce6b756d7 100644
--- a/web/app/pages/Blog/Post.tsx
+++ b/web/app/pages/Blog/Post.tsx
@@ -85,7 +85,9 @@ export default function PostSlug() {
) : null}
<div className='flex flex-col gap-0.5 text-sm leading-4'>
{post?.author ? (
- <div className='font-semibold text-slate-900 dark:text-slate-200'>{post.author}</div>
+ <div className='font-semibold text-slate-900 dark:text-slate-200'>
+ {post.author}
+ </div>
) : null}
{post?.twitter_handle ? (
<div className='mt-1'>
diff --git a/web/app/pages/Captcha/CaptchaDemo.tsx b/web/app/pages/Captcha/CaptchaDemo.tsx
index 379468c79..f328c9f00 100644
--- a/web/app/pages/Captcha/CaptchaDemo.tsx
+++ b/web/app/pages/Captcha/CaptchaDemo.tsx
@@ -27,9 +27,18 @@ const PROJECT_OPTIONS = [
]
const TOKEN_OPTIONS = [
- { value: 'PASS000000000000000000', label: 'captchaPage.demoPage.tokenAlwaysPass' },
- { value: 'FAIL000000000000000000', label: 'captchaPage.demoPage.tokenAlwaysFail' },
- { value: 'USED000000000000000000', label: 'captchaPage.demoPage.tokenAlreadyUsed' },
+ {
+ value: 'PASS000000000000000000',
+ label: 'captchaPage.demoPage.tokenAlwaysPass',
+ },
+ {
+ value: 'FAIL000000000000000000',
+ label: 'captchaPage.demoPage.tokenAlwaysFail',
+ },
+ {
+ value: 'USED000000000000000000',
+ label: 'captchaPage.demoPage.tokenAlreadyUsed',
+ },
]
const THEME_OPTIONS = [
@@ -47,7 +56,9 @@ const CaptchaDemo = () => {
})
const [validationResult, setValidationResult] = useState<string | null>(null)
const [captchaInitialised, setCaptchaInitialised] = useState(false)
- const captchaScriptStatus = useScript('https://cdn.swetrixcaptcha.com/captcha-loader.js')
+ const captchaScriptStatus = useScript(
+ 'https://cdn.swetrixcaptcha.com/captcha-loader.js',
+ )
// Initialise captcha when script is loaded
useEffect(() => {
@@ -83,9 +94,12 @@ const CaptchaDemo = () => {
}
}, [config.theme, config.projectId, captchaInitialised])
- const updateConfig = useCallback((key: keyof CaptchaConfig, value: string) => {
- setConfig((prev) => ({ ...prev, [key]: value }))
- }, [])
+ const updateConfig = useCallback(
+ (key: keyof CaptchaConfig, value: string) => {
+ setConfig((prev) => ({ ...prev, [key]: value }))
+ },
+ [],
+ )
const handleValidateToken = async () => {
try {
@@ -103,11 +117,16 @@ const CaptchaDemo = () => {
const data = await response.json()
setValidationResult(JSON.stringify(data, null, 2))
} catch {
- setValidationResult(JSON.stringify({ error: 'Failed to validate token' }, null, 2))
+ setValidationResult(
+ JSON.stringify({ error: 'Failed to validate token' }, null, 2),
+ )
}
}
- const findSelectedOption = <T extends { value: string }>(options: T[], value: string) => {
+ const findSelectedOption = <T extends { value: string }>(
+ options: T[],
+ value: string,
+ ) => {
return options.find((opt) => opt.value === value) || options[0]
}
@@ -116,7 +135,13 @@ const CaptchaDemo = () => {
<main className='mx-auto max-w-7xl px-4 py-8 sm:px-6 md:py-12 lg:px-8'>
{/* Header Section */}
<div className='mb-8 md:mb-12'>
- <Text as='h1' size='3xl' weight='bold' tracking='tight' className='md:text-4xl lg:text-5xl'>
+ <Text
+ as='h1'
+ size='3xl'
+ weight='bold'
+ tracking='tight'
+ className='md:text-4xl lg:text-5xl'
+ >
{t('captchaPage.demoPage.title')}
</Text>
<Text as='p' size='lg' colour='muted' className='mt-2'>
@@ -133,7 +158,11 @@ const CaptchaDemo = () => {
className='rounded-lg border border-gray-200 bg-white p-6 dark:border-slate-800/60 dark:bg-slate-800/25'
key={`${config.theme}-${config.projectId}`}
>
- <div className='swecaptcha' data-project-id={config.projectId} data-theme={config.theme} />
+ <div
+ className='swecaptcha'
+ data-project-id={config.projectId}
+ data-theme={config.theme}
+ />
{captchaScriptStatus === 'error' ? (
<Text as='div' size='sm' colour='error'>
Failed to load CAPTCHA. Please refresh the page.
@@ -151,27 +180,37 @@ const CaptchaDemo = () => {
<div>
<Select
label={t('captchaPage.demoPage.theme')}
- items={THEME_OPTIONS.map((opt) => ({ ...opt, label: t(opt.label) }))}
+ items={THEME_OPTIONS.map((opt) => ({
+ ...opt,
+ label: t(opt.label),
+ }))}
labelExtractor={(item) => item.label}
keyExtractor={(item) => item.value}
onSelect={(item) => updateConfig('theme', item.value)}
title={t(findSelectedOption(THEME_OPTIONS, config.theme).label)}
- selectedItem={THEME_OPTIONS.map((opt) => ({ ...opt, label: t(opt.label) })).find(
- (opt) => opt.value === config.theme,
- )}
+ selectedItem={THEME_OPTIONS.map((opt) => ({
+ ...opt,
+ label: t(opt.label),
+ })).find((opt) => opt.value === config.theme)}
/>
</div>
<div>
<Select
label={t('captchaPage.demoPage.mode')}
- items={PROJECT_OPTIONS.map((opt) => ({ ...opt, label: t(opt.label) }))}
+ items={PROJECT_OPTIONS.map((opt) => ({
+ ...opt,
+ label: t(opt.label),
+ }))}
labelExtractor={(item) => item.label}
keyExtractor={(item) => item.value}
onSelect={(item) => updateConfig('projectId', item.value)}
- title={t(findSelectedOption(PROJECT_OPTIONS, config.projectId).label)}
- selectedItem={PROJECT_OPTIONS.map((opt) => ({ ...opt, label: t(opt.label) })).find(
- (opt) => opt.value === config.projectId,
+ title={t(
+ findSelectedOption(PROJECT_OPTIONS, config.projectId).label,
)}
+ selectedItem={PROJECT_OPTIONS.map((opt) => ({
+ ...opt,
+ label: t(opt.label),
+ })).find((opt) => opt.value === config.projectId)}
/>
</div>
</div>
@@ -187,17 +226,28 @@ const CaptchaDemo = () => {
<div className='flex-1'>
<Select
label={t('captchaPage.demoPage.tokenType')}
- items={TOKEN_OPTIONS.map((opt) => ({ ...opt, label: t(opt.label) }))}
+ items={TOKEN_OPTIONS.map((opt) => ({
+ ...opt,
+ label: t(opt.label),
+ }))}
labelExtractor={(item) => item.label}
keyExtractor={(item) => item.value}
onSelect={(item) => updateConfig('dummySecret', item.value)}
- title={t(findSelectedOption(TOKEN_OPTIONS, config.dummySecret).label)}
- selectedItem={TOKEN_OPTIONS.map((opt) => ({ ...opt, label: t(opt.label) })).find(
- (opt) => opt.value === config.dummySecret,
+ title={t(
+ findSelectedOption(TOKEN_OPTIONS, config.dummySecret).label,
)}
+ selectedItem={TOKEN_OPTIONS.map((opt) => ({
+ ...opt,
+ label: t(opt.label),
+ })).find((opt) => opt.value === config.dummySecret)}
/>
</div>
- <Button type='button' primary regular onClick={handleValidateToken}>
+ <Button
+ type='button'
+ primary
+ regular
+ onClick={handleValidateToken}
+ >
{t('captchaPage.demoPage.validateButton')}
</Button>
</div>
diff --git a/web/app/pages/Captcha/index.tsx b/web/app/pages/Captcha/index.tsx
index 417418d64..590cfb667 100644
--- a/web/app/pages/Captcha/index.tsx
+++ b/web/app/pages/Captcha/index.tsx
@@ -1,5 +1,10 @@
import { ArrowRightIcon } from '@heroicons/react/20/solid'
-import { CodeBracketIcon, PuzzlePieceIcon, CursorArrowRaysIcon, EyeSlashIcon } from '@heroicons/react/24/outline'
+import {
+ CodeBracketIcon,
+ PuzzlePieceIcon,
+ CursorArrowRaysIcon,
+ EyeSlashIcon,
+} from '@heroicons/react/24/outline'
import _map from 'lodash/map'
import { useEffect, useState } from 'react'
import { useTranslation, Trans } from 'react-i18next'
@@ -51,9 +56,13 @@ const Captcha = () => {
const { t } = useTranslation('common')
const [demoName, setDemoName] = useState('')
const [demoMessage, setDemoMessage] = useState('')
- const [demoStatus, setDemoStatus] = useState<'idle' | 'success' | 'error'>('idle')
+ const [demoStatus, setDemoStatus] = useState<'idle' | 'success' | 'error'>(
+ 'idle',
+ )
const [demoError, setDemoError] = useState('')
- const captchaScriptStatus = useScript('https://cdn.swetrixcaptcha.com/captcha-loader.js')
+ const captchaScriptStatus = useScript(
+ 'https://cdn.swetrixcaptcha.com/captcha-loader.js',
+ )
const [captchaInitialised, setCaptchaInitialised] = useState(false)
const { theme } = useTheme()
@@ -78,7 +87,9 @@ const Captcha = () => {
const handleDemoSubmit = (e: React.FormEvent) => {
e.preventDefault()
- const captchaInput = document.querySelector('input[name="swetrix-captcha-response"]') as HTMLInputElement | null
+ const captchaInput = document.querySelector(
+ 'input[name="swetrix-captcha-response"]',
+ ) as HTMLInputElement | null
const token = captchaInput?.value
if (!token) {
@@ -106,7 +117,10 @@ const Captcha = () => {
<main className='bg-gray-50 dark:bg-slate-900'>
<div className='relative isolate bg-gray-100/80 pt-2 dark:bg-slate-800/50'>
<div className='relative mx-2 overflow-hidden rounded-4xl'>
- <div aria-hidden className='pointer-events-none absolute inset-0 -z-10'>
+ <div
+ aria-hidden
+ className='pointer-events-none absolute inset-0 -z-10'
+ >
<div className='absolute inset-0 rounded-4xl bg-linear-115 from-indigo-200 from-15% via-purple-400 via-70% to-indigo-700 opacity-50 ring-1 ring-black/5 ring-inset sm:bg-linear-145 dark:from-slate-600 dark:opacity-60' />
</div>
<Header transparent />
@@ -154,7 +168,12 @@ const Captcha = () => {
<Text as='h2' size='3xl' weight='bold' className='sm:text-4xl'>
{t('captchaPage.whySwetrix')}
</Text>
- <Text as='p' size='lg' colour='muted' className='mx-auto mt-4 max-w-2xl'>
+ <Text
+ as='p'
+ size='lg'
+ colour='muted'
+ className='mx-auto mt-4 max-w-2xl'
+ >
{t('captchaPage.whySwetrixDesc')}
</Text>
</div>
@@ -163,7 +182,10 @@ const Captcha = () => {
{_map(features, (feature) => (
<div key={feature.titleKey} className='relative flex gap-4'>
<div className='flex h-14 w-14 shrink-0 items-center justify-center rounded-xl bg-indigo-100 dark:bg-indigo-900/30'>
- <feature.icon className='h-7 w-7 text-indigo-600 dark:text-indigo-400' aria-hidden='true' />
+ <feature.icon
+ className='h-7 w-7 text-indigo-600 dark:text-indigo-400'
+ aria-hidden='true'
+ />
</div>
<div>
<Text as='h3' size='xl' weight='semibold'>
@@ -179,10 +201,20 @@ const Captcha = () => {
</div>
<div className='mx-auto max-w-7xl px-4 py-20'>
- <Text as='h2' size='3xl' weight='bold' className='text-center sm:text-4xl'>
+ <Text
+ as='h2'
+ size='3xl'
+ weight='bold'
+ className='text-center sm:text-4xl'
+ >
{t('captchaPage.howItWorks.title')}
</Text>
- <Text as='p' size='lg' colour='muted' className='mx-auto mt-4 max-w-2xl text-center'>
+ <Text
+ as='p'
+ size='lg'
+ colour='muted'
+ className='mx-auto mt-4 max-w-2xl text-center'
+ >
{t('captchaPage.howItWorks.desc')}
</Text>
@@ -248,7 +280,12 @@ const Captcha = () => {
>
{t('captchaPage.demo.tagline')}
</Text>
- <Text as='h2' size='3xl' weight='bold' className='mt-2 sm:text-4xl'>
+ <Text
+ as='h2'
+ size='3xl'
+ weight='bold'
+ className='mt-2 sm:text-4xl'
+ >
{t('captchaPage.demo.title')}
</Text>
<Text as='p' size='lg' colour='muted' className='mt-4'>
@@ -272,7 +309,9 @@ const Captcha = () => {
to='/captcha/demo'
className='flex h-12 items-center justify-center rounded-md border-2 border-slate-900 bg-transparent px-6 text-slate-900 transition-all hover:bg-slate-900 hover:text-white dark:border-slate-50 dark:text-slate-50 dark:hover:bg-gray-50 dark:hover:text-slate-900'
>
- <span className='text-center text-base font-semibold'>{t('captchaPage.demo.seeDevDemo')}</span>
+ <span className='text-center text-base font-semibold'>
+ {t('captchaPage.demo.seeDevDemo')}
+ </span>
</Link>
</div>
</div>
@@ -305,7 +344,8 @@ const Captcha = () => {
<Input
label={
<>
- {t('captchaPage.demo.nameLabel')} <span className='text-red-500'>*</span>
+ {t('captchaPage.demo.nameLabel')}{' '}
+ <span className='text-red-500'>*</span>
</>
}
value={demoName}
@@ -322,14 +362,23 @@ const Captcha = () => {
rows={3}
/>
- <div className='swecaptcha' data-project-id={SWETRIX_PID} data-theme={theme} />
+ <div
+ className='swecaptcha'
+ data-project-id={SWETRIX_PID}
+ data-theme={theme}
+ />
{captchaScriptStatus === 'error' ? (
<Text as='div' size='sm' colour='error'>
Failed to load CAPTCHA. Please refresh the page.
</Text>
) : null}
- <Button type='submit' primary giant className='w-full justify-center'>
+ <Button
+ type='submit'
+ primary
+ giant
+ className='w-full justify-center'
+ >
{t('captchaPage.demo.submit')}
</Button>
</form>
diff --git a/web/app/pages/Contact/index.tsx b/web/app/pages/Contact/index.tsx
index 67fcbdb80..65ebe4ff9 100644
--- a/web/app/pages/Contact/index.tsx
+++ b/web/app/pages/Contact/index.tsx
@@ -1,7 +1,14 @@
import { SquareArrowOutUpRightIcon } from 'lucide-react'
import { useTranslation, Trans } from 'react-i18next'
-import { CONTACT_EMAIL, TWITTER_URL, TWITTER_USERNAME, DISCORD_URL, DOCS_URL, BOOK_A_CALL_URL } from '~/lib/constants'
+import {
+ CONTACT_EMAIL,
+ TWITTER_URL,
+ TWITTER_USERNAME,
+ DISCORD_URL,
+ DOCS_URL,
+ BOOK_A_CALL_URL,
+} from '~/lib/constants'
interface PanelProps {
href: string
@@ -20,8 +27,12 @@ const Panel = ({ href, title, description }: PanelProps) => (
className='absolute top-5 right-5 h-5 w-5 text-gray-900 dark:text-gray-100'
strokeWidth={1.5}
/>
- <h3 className='text-lg leading-7 font-semibold text-gray-900 dark:text-gray-100'>{title}</h3>
- <p className='mt-3 text-sm leading-6 text-gray-600 dark:text-gray-200'>{description}</p>
+ <h3 className='text-lg leading-7 font-semibold text-gray-900 dark:text-gray-100'>
+ {title}
+ </h3>
+ <p className='mt-3 text-sm leading-6 text-gray-600 dark:text-gray-200'>
+ {description}
+ </p>
</a>
)
@@ -31,7 +42,9 @@ const Contact = () => {
return (
<div className='min-h-min-footer bg-gray-50 dark:bg-slate-900'>
<div className='mx-auto px-4 pt-12 pb-16 whitespace-pre-line sm:px-6 md:w-4/5 lg:px-8'>
- <h1 className='text-4xl font-bold text-gray-900 dark:text-gray-50'>{t('titles.contact')}</h1>
+ <h1 className='text-4xl font-bold text-gray-900 dark:text-gray-50'>
+ {t('titles.contact')}
+ </h1>
<div className='mt-2 text-lg text-gray-900 dark:text-gray-50'>
<Trans
t={t}
@@ -45,17 +58,31 @@ const Contact = () => {
/>
),
twitter: (
- <a href={TWITTER_URL} className='font-medium text-indigo-600 hover:underline dark:text-indigo-400' />
+ <a
+ href={TWITTER_URL}
+ className='font-medium text-indigo-600 hover:underline dark:text-indigo-400'
+ />
),
discord: (
- <a href={DISCORD_URL} className='font-medium text-indigo-600 hover:underline dark:text-indigo-400' />
+ <a
+ href={DISCORD_URL}
+ className='font-medium text-indigo-600 hover:underline dark:text-indigo-400'
+ />
),
}}
/>
</div>
<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} title={t('contact.docs.title')} description={t('contact.docs.desc')} />
- <Panel href={BOOK_A_CALL_URL} title={t('contact.demo.title')} description={t('contact.demo.desc')} />
+ <Panel
+ href={DOCS_URL}
+ title={t('contact.docs.title')}
+ description={t('contact.docs.desc')}
+ />
+ <Panel
+ href={BOOK_A_CALL_URL}
+ title={t('contact.demo.title')}
+ description={t('contact.demo.desc')}
+ />
</div>
</div>
</div>
diff --git a/web/app/pages/Dashboard/AddProject.tsx b/web/app/pages/Dashboard/AddProject.tsx
index c55b83972..12fb67014 100644
--- a/web/app/pages/Dashboard/AddProject.tsx
+++ b/web/app/pages/Dashboard/AddProject.tsx
@@ -9,7 +9,11 @@ interface AddProjectProps {
viewMode: 'grid' | 'list'
}
-export const AddProject = ({ onClick, sitesCount, viewMode }: AddProjectProps) => {
+export const AddProject = ({
+ onClick,
+ sitesCount,
+ viewMode,
+}: AddProjectProps) => {
const { t } = useTranslation('common')
return (
@@ -20,9 +24,12 @@ export const AddProject = ({ onClick, sitesCount, viewMode }: AddProjectProps) =
'group cursor-pointer border-2 border-dashed border-gray-300 hover:border-gray-400',
viewMode === 'list'
? 'flex h-[72px] items-center justify-center rounded-lg'
- : cx('flex h-auto min-h-[153.1px] items-center justify-center rounded-lg', {
- 'lg:min-h-auto': sitesCount % 3 !== 0,
- }),
+ : cx(
+ 'flex h-auto min-h-[153.1px] items-center justify-center rounded-lg',
+ {
+ 'lg:min-h-auto': sitesCount % 3 !== 0,
+ },
+ ),
)}
>
<div className={cx(viewMode === 'list' && 'flex items-center')}>
diff --git a/web/app/pages/Dashboard/Dashboard.tsx b/web/app/pages/Dashboard/Dashboard.tsx
index 5534487cf..97d43fe73 100644
--- a/web/app/pages/Dashboard/Dashboard.tsx
+++ b/web/app/pages/Dashboard/Dashboard.tsx
@@ -3,21 +3,40 @@ import _isEmpty from 'lodash/isEmpty'
import _keys from 'lodash/keys'
import _map from 'lodash/map'
import _size from 'lodash/size'
-import { StretchHorizontalIcon, LayoutGridIcon, SearchIcon, XIcon, FolderPlusIcon } from 'lucide-react'
+import {
+ StretchHorizontalIcon,
+ LayoutGridIcon,
+ SearchIcon,
+ XIcon,
+ FolderPlusIcon,
+} from 'lucide-react'
import React, { useState, useEffect, useRef, useMemo, memo } from 'react'
import { useTranslation } from 'react-i18next'
-import { useLoaderData, useNavigate, useSearchParams, useFetcher, useNavigation, useRevalidator } from 'react-router'
+import {
+ useLoaderData,
+ useNavigate,
+ useSearchParams,
+ useFetcher,
+ useNavigation,
+ useRevalidator,
+} from 'react-router'
import { toast } from 'sonner'
import DashboardLockedBanner from '~/components/DashboardLockedBanner'
import EventsRunningOutBanner from '~/components/EventsRunningOutBanner'
-import { useLiveVisitorsProxy, useOverallStatsProxy } from '~/hooks/useAnalyticsProxy'
+import {
+ useLiveVisitorsProxy,
+ useOverallStatsProxy,
+} from '~/hooks/useAnalyticsProxy'
import useBreakpoint from '~/hooks/useBreakpoint'
import useDebounce from '~/hooks/useDebounce'
import { isSelfhosted, LIVE_VISITORS_UPDATE_INTERVAL } from '~/lib/constants'
import { Overall } from '~/lib/models/Project'
import { useAuth } from '~/providers/AuthProvider'
-import type { DashboardLoaderData, DashboardActionData } from '~/routes/dashboard'
+import type {
+ DashboardLoaderData,
+ DashboardActionData,
+} from '~/routes/dashboard'
import Input from '~/ui/Input'
import LoadingBar from '~/ui/LoadingBar'
import Modal from '~/ui/Modal'
@@ -60,7 +79,10 @@ const Dashboard = () => {
const [viewMode, setViewMode] = useState(loaderData.viewMode)
const isAboveLgBreakpoint = useBreakpoint('lg')
- const projects = useMemo(() => loaderData.projects?.results || [], [loaderData.projects?.results])
+ const projects = useMemo(
+ () => loaderData.projects?.results || [],
+ [loaderData.projects?.results],
+ )
const paginationTotal = loaderData.projects?.total || 0
const page = useMemo(() => {
@@ -81,12 +103,14 @@ const Dashboard = () => {
const pageSize = useMemo(() => {
const pageSizeParam = searchParams.get('pageSize')
- return pageSizeParam && PAGE_SIZE_OPTIONS.includes(parseInt(pageSizeParam, 10))
+ return pageSizeParam &&
+ PAGE_SIZE_OPTIONS.includes(parseInt(pageSizeParam, 10))
? parseInt(pageSizeParam, 10)
: PAGE_SIZE_OPTIONS[0]
}, [searchParams])
- const isLoading = navigation.state === 'loading' || revalidator.state === 'loading'
+ const isLoading =
+ navigation.state === 'loading' || revalidator.state === 'loading'
const [liveStats, setLiveStats] = useState<Record<string, number>>({})
const [overallStats, setOverallStats] = useState<Overall>({})
const { fetchLiveVisitors } = useLiveVisitorsProxy()
@@ -98,13 +122,17 @@ const Dashboard = () => {
const sortBy = useMemo(() => {
const sortParam = searchParams.get('sort')
- return sortParam && Object.values(SORT_OPTIONS).includes(sortParam as any) ? sortParam : SORT_OPTIONS.ALPHA_ASC
+ return sortParam && Object.values(SORT_OPTIONS).includes(sortParam as any)
+ ? sortParam
+ : SORT_OPTIONS.ALPHA_ASC
}, [searchParams])
// New project modal state
const [newProjectModalOpen, setNewProjectModalOpen] = useState(false)
const [newProjectName, setNewProjectName] = useState('')
- const [newProjectOrganisationId, setNewProjectOrganisationId] = useState<string | undefined>(undefined)
+ const [newProjectOrganisationId, setNewProjectOrganisationId] = useState<
+ string | undefined
+ >(undefined)
const [newProjectError, setNewProjectError] = useState<string | null>(null)
const [newProjectBeenSubmitted, setNewProjectBeenSubmitted] = useState(false)
@@ -115,7 +143,9 @@ const Dashboard = () => {
name: t('common.notSet'),
},
...(user?.organisationMemberships || [])
- .filter((om) => om.confirmed && (om.role === 'admin' || om.role === 'owner'))
+ .filter(
+ (om) => om.confirmed && (om.role === 'admin' || om.role === 'owner'),
+ )
.map((om) => om.organisation),
],
[user?.organisationMemberships, t],
@@ -179,7 +209,9 @@ const Dashboard = () => {
}
if (_size(newProjectName) > MAX_PROJECT_NAME_LENGTH) {
- errors.name = t('project.settings.pxCharsError', { amount: MAX_PROJECT_NAME_LENGTH })
+ errors.name = t('project.settings.pxCharsError', {
+ amount: MAX_PROJECT_NAME_LENGTH,
+ })
}
return { errors, valid: _isEmpty(_keys(errors)) }
@@ -191,10 +223,16 @@ const Dashboard = () => {
refetchProjects()
toast.success(t('project.settings.created'))
closeNewProjectModal()
- } else if (fetcher.data?.error && fetcher.data?.intent === 'create-project') {
+ } else if (
+ fetcher.data?.error &&
+ fetcher.data?.intent === 'create-project'
+ ) {
setNewProjectError(fetcher.data.error)
toast.error(fetcher.data.error)
- } else if (fetcher.data?.fieldErrors?.name && fetcher.data?.intent === 'create-project') {
+ } else if (
+ fetcher.data?.fieldErrors?.name &&
+ fetcher.data?.intent === 'create-project'
+ ) {
setNewProjectError(fetcher.data.fieldErrors.name)
}
}, [fetcher.data, t]) // eslint-disable-line react-hooks/exhaustive-deps
@@ -270,7 +308,10 @@ const Dashboard = () => {
updateLiveVisitors()
- const interval = setInterval(updateLiveVisitors, LIVE_VISITORS_UPDATE_INTERVAL)
+ const interval = setInterval(
+ updateLiveVisitors,
+ LIVE_VISITORS_UPDATE_INTERVAL,
+ )
return () => clearInterval(interval)
}, [projects, fetchLiveVisitors]) // Reset interval when projects change
@@ -310,7 +351,12 @@ const Dashboard = () => {
<div className='mx-auto w-full max-w-7xl px-4 py-6 sm:px-6 lg:px-8'>
<div className='mb-4 flex flex-wrap justify-between gap-2'>
<div className='flex items-end justify-between'>
- <Text as='h2' size='3xl' weight='bold' className='mt-2 flex items-baseline gap-2'>
+ <Text
+ as='h2'
+ size='3xl'
+ weight='bold'
+ className='mt-2 flex items-baseline gap-2'
+ >
<span>{t('titles.dashboard')}</span>
{isSearchActive ? (
<button
@@ -377,7 +423,11 @@ const Dashboard = () => {
setActivePeriod={handlePeriodChange}
isLoading={isLoading}
/>
- <SortSelector activeSort={sortBy} setActiveSort={handleSortChange} isLoading={isLoading} />
+ <SortSelector
+ activeSort={sortBy}
+ setActiveSort={handleSortChange}
+ isLoading={isLoading}
+ />
<div className='hidden lg:block'>
{viewMode === DASHBOARD_VIEW.GRID ? (
<button
@@ -442,14 +492,19 @@ const Dashboard = () => {
<div
className={cx(
'grid gap-3',
- _viewMode === DASHBOARD_VIEW.GRID ? 'grid-cols-1 lg:grid-cols-3' : 'grid-cols-1',
+ _viewMode === DASHBOARD_VIEW.GRID
+ ? 'grid-cols-1 lg:grid-cols-3'
+ : 'grid-cols-1',
)}
>
{_map(projects, (project) => (
<ProjectCard
key={`${project.id}-${project.name}`}
project={project}
- live={liveStats[project.id] ?? (_isEmpty(liveStats) ? null : 'N/A')}
+ live={
+ liveStats[project.id] ??
+ (_isEmpty(liveStats) ? null : 'N/A')
+ }
overallStats={overallStats[project.id]}
activePeriod={activePeriod}
viewMode={_viewMode}
@@ -457,7 +512,11 @@ const Dashboard = () => {
/>
))}
{_size(projects) % 12 !== 0 ? (
- <AddProject sitesCount={_size(projects)} onClick={onNewProject} viewMode={_viewMode} />
+ <AddProject
+ sitesCount={_size(projects)}
+ onClick={onNewProject}
+ viewMode={_viewMode}
+ />
) : null}
</div>
)}
@@ -508,7 +567,9 @@ const Dashboard = () => {
keyExtractor={(item) => item.id || 'not-set'}
labelExtractor={(item) => {
if (item.id === undefined) {
- return <span className='italic'>{t('common.notSet')}</span>
+ return (
+ <span className='italic'>{t('common.notSet')}</span>
+ )
}
return item.name
@@ -517,8 +578,14 @@ const Dashboard = () => {
setNewProjectOrganisationId(item.id)
}}
label={t('project.settings.organisation')}
- title={organisations.find((org) => org.id === newProjectOrganisationId)?.name}
- selectedItem={organisations.find((org) => org.id === newProjectOrganisationId)}
+ title={
+ organisations.find(
+ (org) => org.id === newProjectOrganisationId,
+ )?.name
+ }
+ selectedItem={organisations.find(
+ (org) => org.id === newProjectOrganisationId,
+ )}
/>
</div>
) : null}
diff --git a/web/app/pages/Dashboard/NoProjects.tsx b/web/app/pages/Dashboard/NoProjects.tsx
index e055e3070..264197900 100644
--- a/web/app/pages/Dashboard/NoProjects.tsx
+++ b/web/app/pages/Dashboard/NoProjects.tsx
@@ -27,12 +27,20 @@ export const NoProjects = ({ onClick, search }: NoProjectsProps) => {
return (
<div className='mx-auto w-full max-w-2xl py-16 text-center'>
<div className='mx-auto mb-6 flex size-14 items-center justify-center rounded-xl bg-gray-100 dark:bg-slate-800'>
- <FolderInputIcon className='size-7 text-gray-700 dark:text-gray-200' strokeWidth={1.5} />
+ <FolderInputIcon
+ className='size-7 text-gray-700 dark:text-gray-200'
+ strokeWidth={1.5}
+ />
</div>
<Text as='h3' size='xl' weight='medium' className='tracking-tight'>
{t('dashboard.noProjects')}
</Text>
- <Text as='p' size='sm' colour='secondary' className='mx-auto mt-2 max-w-md'>
+ <Text
+ as='p'
+ size='sm'
+ colour='secondary'
+ className='mx-auto mt-2 max-w-md'
+ >
{t('dashboard.createProject')}
</Text>
<div className='mt-6'>
diff --git a/web/app/pages/Dashboard/PeriodSelector.tsx b/web/app/pages/Dashboard/PeriodSelector.tsx
index 122348ce0..2bf7901bb 100644
--- a/web/app/pages/Dashboard/PeriodSelector.tsx
+++ b/web/app/pages/Dashboard/PeriodSelector.tsx
@@ -1,4 +1,9 @@
-import { Popover, PopoverButton, PopoverPanel, Transition } from '@headlessui/react'
+import {
+ Popover,
+ PopoverButton,
+ PopoverPanel,
+ Transition,
+} from '@headlessui/react'
import { ChevronDownIcon } from '@heroicons/react/20/solid'
import cx from 'clsx'
import _map from 'lodash/map'
@@ -12,7 +17,11 @@ interface PeriodSelectorProps {
isLoading: boolean
}
-export const PeriodSelector = ({ activePeriod, setActivePeriod, isLoading }: PeriodSelectorProps) => {
+export const PeriodSelector = ({
+ activePeriod,
+ setActivePeriod,
+ isLoading,
+}: PeriodSelectorProps) => {
const { t } = useTranslation('common')
const periods = useMemo(() => {
diff --git a/web/app/pages/Dashboard/ProjectCard.tsx b/web/app/pages/Dashboard/ProjectCard.tsx
index 4efe8c80e..48e34572a 100644
--- a/web/app/pages/Dashboard/ProjectCard.tsx
+++ b/web/app/pages/Dashboard/ProjectCard.tsx
@@ -3,7 +3,12 @@ import _find from 'lodash/find'
import _isNumber from 'lodash/isNumber'
import _replace from 'lodash/replace'
import _size from 'lodash/size'
-import { Settings2Icon, PinIcon, ChevronUpIcon, ChevronDownIcon } from 'lucide-react'
+import {
+ Settings2Icon,
+ PinIcon,
+ ChevronUpIcon,
+ ChevronDownIcon,
+} from 'lucide-react'
import React, { useState, useMemo, useCallback, useEffect } from 'react'
import { useTranslation } from 'react-i18next'
import { Link, useFetcher, useNavigate } from 'react-router'
@@ -150,12 +155,16 @@ export const ProjectCard = ({
websiteUrl,
} = project
- const faviconHost = useMemo(() => getFaviconHost(websiteUrl || null), [websiteUrl])
+ const faviconHost = useMemo(
+ () => getFaviconHost(websiteUrl || null),
+ [websiteUrl],
+ )
const [localIsPinned, setLocalIsPinned] = useState(isPinned)
const isPinning =
(fetcher.state === 'submitting' || fetcher.state === 'loading') &&
- (fetcher.formData?.get('intent') === 'pin-project' || fetcher.formData?.get('intent') === 'unpin-project')
+ (fetcher.formData?.get('intent') === 'pin-project' ||
+ fetcher.formData?.get('intent') === 'unpin-project')
const isAccepting =
(fetcher.state === 'submitting' || fetcher.state === 'loading') &&
@@ -173,7 +182,8 @@ export const ProjectCard = ({
// Guard: only process responses for this specific project card
const submittedProjectId = fetcher.formData?.get('projectId')
const submittedShareId = fetcher.formData?.get('shareId')
- const isForThisCard = submittedProjectId === id || submittedShareId === shareId
+ const isForThisCard =
+ submittedProjectId === id || submittedShareId === shareId
if (!isForThisCard) return
if (fetcher.data.success) {
@@ -199,12 +209,25 @@ export const ProjectCard = ({
}
} else if (fetcher.data.error) {
// Revert optimistic update on error
- if (fetcher.data.intent === 'pin-project' || fetcher.data.intent === 'unpin-project') {
+ if (
+ fetcher.data.intent === 'pin-project' ||
+ fetcher.data.intent === 'unpin-project'
+ ) {
setLocalIsPinned(isPinned)
}
toast.error(fetcher.data.error)
}
- }, [fetcher.data, fetcher.formData, isPinned, shareId, user, mergeUser, refetchProjects, t, id])
+ }, [
+ fetcher.data,
+ fetcher.formData,
+ isPinned,
+ shareId,
+ user,
+ mergeUser,
+ refetchProjects,
+ t,
+ id,
+ ])
const handlePinToggle = useCallback(
(e: React.MouseEvent) => {
@@ -255,11 +278,24 @@ export const ProjectCard = ({
const members = _size(share)
if (members > 0) {
- list.push({ colour: 'slate', label: t('common.xMembers', { number: members + 1 }) })
+ list.push({
+ colour: 'slate',
+ label: t('common.xMembers', { number: members + 1 }),
+ })
}
return list
- }, [t, active, isTransferring, isPublic, organisation, share, project.isAccessConfirmed, project.role, shareId])
+ }, [
+ t,
+ active,
+ isTransferring,
+ isPublic,
+ organisation,
+ share,
+ project.isAccessConfirmed,
+ project.role,
+ shareId,
+ ])
const onAccept = () => {
if (fetcher.state !== 'idle') {
@@ -307,7 +343,9 @@ export const ProjectCard = ({
onClick={onElementClick}
className={cx(
'group relative cursor-pointer overflow-hidden rounded-xl border border-gray-200 bg-gray-50 transition-colors hover:bg-gray-200/70 dark:border-slate-800/25 dark:bg-slate-800/70 dark:hover:bg-slate-700/60',
- viewMode === 'list' ? 'flex items-center justify-between px-6 py-4' : 'min-h-[153.1px]',
+ viewMode === 'list'
+ ? 'flex items-center justify-between px-6 py-4'
+ : 'min-h-[153.1px]',
)}
>
{/* Background sparkline chart */}
@@ -316,8 +354,18 @@ export const ProjectCard = ({
<Sparkline chart={overallStats.chart} className='w-full' />
</div>
) : null}
- <div className={cx('relative z-10 flex flex-col', viewMode === 'list' ? 'flex-1' : 'px-4 py-4')}>
- <div className={cx('flex items-center', viewMode === 'grid' ? 'justify-between' : 'justify-start gap-1')}>
+ <div
+ className={cx(
+ 'relative z-10 flex flex-col',
+ viewMode === 'list' ? 'flex-1' : 'px-4 py-4',
+ )}
+ >
+ <div
+ className={cx(
+ 'flex items-center',
+ viewMode === 'grid' ? 'justify-between' : 'justify-start gap-1',
+ )}
+ >
<div className='flex min-w-0 items-center gap-1'>
{faviconHost ? (
<img
@@ -336,7 +384,9 @@ export const ProjectCard = ({
<div
className={cx(
'flex shrink-0 items-center transition-opacity',
- alwaysShowActions ? 'opacity-100' : 'opacity-0 group-hover:opacity-100',
+ alwaysShowActions
+ ? 'opacity-100'
+ : 'opacity-0 group-hover:opacity-100',
)}
>
<button
@@ -344,9 +394,17 @@ export const ProjectCard = ({
className='rounded-md border border-transparent p-1.5 text-gray-800 transition-colors hover:border-gray-300 hover:bg-gray-50 hover:text-gray-900 dark:text-slate-400 dark:hover:border-slate-700/80 dark:hover:bg-slate-800 dark:hover:text-slate-300'
onClick={handlePinToggle}
disabled={isPinning}
- aria-label={localIsPinned ? t('dashboard.unpin') : t('dashboard.pin')}
+ aria-label={
+ localIsPinned ? t('dashboard.unpin') : t('dashboard.pin')
+ }
>
- <PinIcon className={cx('size-5 transition-transform', localIsPinned && 'rotate-30')} strokeWidth={1.5} />
+ <PinIcon
+ className={cx(
+ 'size-5 transition-transform',
+ localIsPinned && 'rotate-30',
+ )}
+ strokeWidth={1.5}
+ />
</button>
{project.isAccessConfirmed && role !== 'viewer' ? (
<button
@@ -366,27 +424,45 @@ export const ProjectCard = ({
</div>
<div className='mt-1 flex shrink-0 flex-wrap gap-2'>
{badges.length > 0 ? (
- badges.map((badge) => <Badge key={badge.label as string} {...badge} />)
+ badges.map((badge) => (
+ <Badge key={badge.label as string} {...badge} />
+ ))
) : (
<Badge label='I' colour='slate' className='invisible' />
)}
</div>
</div>
- <div className={cx('relative z-10 flex shrink-0 gap-5', viewMode === 'list' ? 'ml-4' : 'mt-4 px-4 pb-4')}>
+ <div
+ className={cx(
+ 'relative z-10 flex shrink-0 gap-5',
+ viewMode === 'list' ? 'ml-4' : 'mt-4 px-4 pb-4',
+ )}
+ >
<MiniCard
labelTKey='dashboard.pageviews'
total={live === 'N/A' ? 'N/A' : (overallStats?.current.all ?? null)}
percChange={
live === 'N/A'
? 0
- : calculateRelativePercentage(overallStats?.previous.all ?? 0, overallStats?.current.all ?? 0)
+ : calculateRelativePercentage(
+ overallStats?.previous.all ?? 0,
+ overallStats?.current.all ?? 0,
+ )
+ }
+ hasData={
+ project?.isDataExists ||
+ project?.isErrorDataExists ||
+ project?.isCaptchaDataExists
}
- hasData={project?.isDataExists || project?.isErrorDataExists || project?.isCaptchaDataExists}
/>
<MiniCard
labelTKey='dashboard.liveVisitors'
total={live}
- hasData={project?.isDataExists || project?.isErrorDataExists || project?.isCaptchaDataExists}
+ hasData={
+ project?.isDataExists ||
+ project?.isErrorDataExists ||
+ project?.isCaptchaDataExists
+ }
/>
</div>
{project.role !== 'owner' && !project.isAccessConfirmed ? (
diff --git a/web/app/pages/Dashboard/SortSelector.tsx b/web/app/pages/Dashboard/SortSelector.tsx
index 32dfee492..7ded298a6 100644
--- a/web/app/pages/Dashboard/SortSelector.tsx
+++ b/web/app/pages/Dashboard/SortSelector.tsx
@@ -1,4 +1,9 @@
-import { Popover, PopoverButton, PopoverPanel, Transition } from '@headlessui/react'
+import {
+ Popover,
+ PopoverButton,
+ PopoverPanel,
+ Transition,
+} from '@headlessui/react'
import { ChevronDownIcon } from '@heroicons/react/20/solid'
import cx from 'clsx'
import _map from 'lodash/map'
@@ -21,7 +26,11 @@ export const SORT_OPTIONS = {
DATE_DESC: 'date_desc',
} as const
-export const SortSelector = ({ activeSort, setActiveSort, isLoading }: SortSelectorProps) => {
+export const SortSelector = ({
+ activeSort,
+ setActiveSort,
+ isLoading,
+}: SortSelectorProps) => {
const { t } = useTranslation('common')
const { isLoading: authLoading } = useAuth()
diff --git a/web/app/pages/Dashboard/Sparkline.tsx b/web/app/pages/Dashboard/Sparkline.tsx
index 5f9c66108..14b7fc7ab 100644
--- a/web/app/pages/Dashboard/Sparkline.tsx
+++ b/web/app/pages/Dashboard/Sparkline.tsx
@@ -81,7 +81,9 @@ const Sparkline = memo(({ chart, className }: SparklineProps) => {
return null
}
- return <BillboardChart options={options} className={className} deps={[chart]} />
+ return (
+ <BillboardChart options={options} className={className} deps={[chart]} />
+ )
})
Sparkline.displayName = 'Sparkline'
diff --git a/web/app/pages/ErrorTracking/index.tsx b/web/app/pages/ErrorTracking/index.tsx
index 64bacc5a6..a78ae964f 100644
--- a/web/app/pages/ErrorTracking/index.tsx
+++ b/web/app/pages/ErrorTracking/index.tsx
@@ -19,7 +19,10 @@ const ErrorTracking = () => {
<main className='bg-gray-50 dark:bg-slate-900'>
<div className='relative isolate bg-gray-100/80 pt-2 dark:bg-slate-800/50'>
<div className='relative mx-2 overflow-hidden rounded-4xl'>
- <div aria-hidden className='pointer-events-none absolute inset-0 -z-10'>
+ <div
+ aria-hidden
+ className='pointer-events-none absolute inset-0 -z-10'
+ >
<div className='absolute inset-0 rounded-4xl bg-linear-115 from-rose-200 from-15% via-red-400 via-70% to-red-700 opacity-50 ring-1 ring-black/5 ring-inset sm:bg-linear-145 dark:from-slate-600 dark:opacity-60' />
</div>
<Header transparent />
@@ -55,7 +58,11 @@ const ErrorTracking = () => {
<div className='col-span-6 mt-10 overflow-visible lg:mt-0 lg:mr-0 lg:ml-4'>
<div className='relative z-20 mx-auto mt-10 overflow-hidden rounded-xl ring-2 ring-gray-900/10 lg:hidden dark:ring-white/10'>
<img
- src={theme === 'dark' ? '/assets/screenshot_dark.png' : '/assets/screenshot_light.png'}
+ src={
+ theme === 'dark'
+ ? '/assets/screenshot_dark.png'
+ : '/assets/screenshot_light.png'
+ }
className='relative w-full'
width='100%'
height='auto'
@@ -78,7 +85,9 @@ const ErrorTracking = () => {
<div className='relative h-[580px] lg:h-[640px] xl:h-[700px]'>
<img
src={
- theme === 'dark' ? '/assets/screenshot_errors_dark.png' : '/assets/screenshot_errors_light.png'
+ theme === 'dark'
+ ? '/assets/screenshot_errors_dark.png'
+ : '/assets/screenshot_errors_light.png'
}
className='size-full object-cover object-left'
alt='Swetrix Error Tracking'
@@ -103,14 +112,19 @@ const ErrorTracking = () => {
</div>
<div className='mx-auto mt-12 max-w-7xl bg-white px-4 pb-16 whitespace-pre-line dark:bg-slate-900'>
- <h2 className='text-4xl font-extrabold text-slate-900 dark:text-white'>{t('errors.fast.title')}</h2>
+ <h2 className='text-4xl font-extrabold text-slate-900 dark:text-white'>
+ {t('errors.fast.title')}
+ </h2>
<p className='mt-6 text-lg text-gray-900 dark:text-gray-50'>
<Trans
t={t}
i18nKey='errors.fast.desc'
components={{
indexUrl: (
- <Link to={routesPath.main} className='font-medium text-red-600 hover:underline dark:text-red-400' />
+ <Link
+ to={routesPath.main}
+ className='font-medium text-red-600 hover:underline dark:text-red-400'
+ />
),
perfUrl: (
@@ -138,13 +152,19 @@ const ErrorTracking = () => {
))}
</ul>
- <h2 className='mt-10 text-4xl font-extrabold text-slate-900 dark:text-white'>{t('errors.track.title')}</h2>
- <p className='mt-6 text-lg text-gray-900 dark:text-gray-50'>{t('errors.track.desc')}</p>
+ <h2 className='mt-10 text-4xl font-extrabold text-slate-900 dark:text-white'>
+ {t('errors.track.title')}
+ </h2>
+ <p className='mt-6 text-lg text-gray-900 dark:text-gray-50'>
+ {t('errors.track.desc')}
+ </p>
<h2 className='mt-10 text-4xl font-extrabold text-slate-900 dark:text-white'>
{t('performance.privacy.title')}
</h2>
- <p className='mt-6 text-lg text-gray-900 dark:text-gray-50'>{t('performance.privacy.desc')}</p>
+ <p className='mt-6 text-lg text-gray-900 dark:text-gray-50'>
+ {t('performance.privacy.desc')}
+ </p>
</div>
<MarketingPricing />
diff --git a/web/app/pages/Landings/Marketers.tsx b/web/app/pages/Landings/Marketers.tsx
index c7a3abfee..97b7bb1d6 100644
--- a/web/app/pages/Landings/Marketers.tsx
+++ b/web/app/pages/Landings/Marketers.tsx
@@ -6,7 +6,12 @@ import { Link } from 'react-router'
import Header from '~/components/Header'
import { ComparisonTable } from '~/components/marketing/ComparisonTable'
import { DitchGoogle } from '~/components/marketing/DitchGoogle'
-import { BOOK_A_CALL_URL, DISCORD_URL, INTEGRATIONS_URL, LIVE_DEMO_URL } from '~/lib/constants'
+import {
+ BOOK_A_CALL_URL,
+ DISCORD_URL,
+ INTEGRATIONS_URL,
+ LIVE_DEMO_URL,
+} from '~/lib/constants'
import { useTheme } from '~/providers/ThemeProvider'
import routesPath from '~/utils/routes'
@@ -22,17 +27,33 @@ const Marketers = () => {
aria-hidden='true'
>
<defs>
- <pattern id='rect-pattern' width={200} height={200} x='50%' y={-1} patternUnits='userSpaceOnUse'>
+ <pattern
+ id='rect-pattern'
+ width={200}
+ height={200}
+ x='50%'
+ y={-1}
+ patternUnits='userSpaceOnUse'
+ >
<path d='M.5 200V.5H200' fill='none' />
</pattern>
</defs>
- <svg x='50%' y={-1} className='overflow-visible fill-white dark:fill-gray-800/20'>
+ <svg
+ x='50%'
+ y={-1}
+ className='overflow-visible fill-white dark:fill-gray-800/20'
+ >
<path
d='M-200 0h201v201h-201Z M600 0h201v201h-201Z M-400 600h201v201h-201Z M200 800h201v201h-201Z'
strokeWidth={0}
/>
</svg>
- <rect width='100%' height='100%' strokeWidth={0} fill='url(#rect-pattern)' />
+ <rect
+ width='100%'
+ height='100%'
+ strokeWidth={0}
+ fill='url(#rect-pattern)'
+ />
</svg>
<div
className='absolute top-10 left-[calc(50%-4rem)] -z-10 transform-gpu blur-3xl sm:left-[calc(50%-18rem)] lg:top-[calc(50%-30rem)] lg:left-48 xl:left-[calc(50%-24rem)]'
@@ -82,7 +103,9 @@ const Marketers = () => {
rel='noopener noreferrer'
aria-label={`${t('common.liveDemo')} (opens in a new tab)`}
>
- <span className='text-base font-semibold'>{t('common.liveDemo')}</span>
+ <span className='text-base font-semibold'>
+ {t('common.liveDemo')}
+ </span>
</a>
</div>
<a
@@ -92,14 +115,20 @@ const Marketers = () => {
rel='noopener noreferrer'
aria-label={`${t('common.bookACall')} (opens in a new tab)`}
>
- <span className='text-base font-semibold'>{t('common.bookACall')}</span>
+ <span className='text-base font-semibold'>
+ {t('common.bookACall')}
+ </span>
<ArrowRightIcon className='mt-[1px] h-4 w-5' />
</a>
</div>
</div>
<div className='relative z-20 mx-auto mt-10 block max-w-[1300px] px-4 md:px-0'>
<img
- src={theme === 'dark' ? '/assets/screenshot_dark.png' : '/assets/screenshot_light.png'}
+ src={
+ theme === 'dark'
+ ? '/assets/screenshot_dark.png'
+ : '/assets/screenshot_light.png'
+ }
className='relative w-full rounded-xl ring-2 ring-gray-900/10 dark:ring-white/10'
width='100%'
height='auto'
@@ -110,39 +139,45 @@ const Marketers = () => {
</div>
<div className='mx-auto mt-12 mb-6 max-w-5xl px-5'>
- {_map(t('marketers.whyUs', { returnObjects: true }), (item: { name: string; desc: string[] }) => (
- <div key={item.name} className='mb-10 text-slate-900 last:mb-0 dark:text-white'>
- <h2 className='mb-5 text-4xl font-extrabold'>{item.name}</h2>
- {_map(item.desc, (descText) => (
- <p key={descText} className='mb-5 text-lg'>
- <Trans
- t={t}
- components={{
- span: <span className='font-bold' />,
- integrationLink: (
- <a
- href={INTEGRATIONS_URL}
- target='_blank'
- rel='noopener noreferrer'
- className='text-blue-600 hover:underline dark:text-blue-500'
- />
- ),
- discordUrl: (
- <a
- href={DISCORD_URL}
- target='_blank'
- rel='noopener noreferrer'
- className='text-blue-600 hover:underline dark:text-blue-500'
- />
- ),
- }}
- >
- {descText}
- </Trans>
- </p>
- ))}
- </div>
- ))}
+ {_map(
+ t('marketers.whyUs', { returnObjects: true }),
+ (item: { name: string; desc: string[] }) => (
+ <div
+ key={item.name}
+ className='mb-10 text-slate-900 last:mb-0 dark:text-white'
+ >
+ <h2 className='mb-5 text-4xl font-extrabold'>{item.name}</h2>
+ {_map(item.desc, (descText) => (
+ <p key={descText} className='mb-5 text-lg'>
+ <Trans
+ t={t}
+ components={{
+ span: <span className='font-bold' />,
+ integrationLink: (
+ <a
+ href={INTEGRATIONS_URL}
+ target='_blank'
+ rel='noopener noreferrer'
+ className='text-blue-600 hover:underline dark:text-blue-500'
+ />
+ ),
+ discordUrl: (
+ <a
+ href={DISCORD_URL}
+ target='_blank'
+ rel='noopener noreferrer'
+ className='text-blue-600 hover:underline dark:text-blue-500'
+ />
+ ),
+ }}
+ >
+ {descText}
+ </Trans>
+ </p>
+ ))}
+ </div>
+ ),
+ )}
<ComparisonTable className='py-5' />
</div>
diff --git a/web/app/pages/Landings/SmallBusinesses.tsx b/web/app/pages/Landings/SmallBusinesses.tsx
index f0a50aadc..81359014e 100644
--- a/web/app/pages/Landings/SmallBusinesses.tsx
+++ b/web/app/pages/Landings/SmallBusinesses.tsx
@@ -6,7 +6,13 @@ import { Link } from 'react-router'
import Header from '~/components/Header'
import { ComparisonTable } from '~/components/marketing/ComparisonTable'
import { DitchGoogle } from '~/components/marketing/DitchGoogle'
-import { BOOK_A_CALL_URL, DISCORD_URL, LIVE_DEMO_URL, TWITTER_URL, INTEGRATIONS_URL } from '~/lib/constants'
+import {
+ BOOK_A_CALL_URL,
+ DISCORD_URL,
+ LIVE_DEMO_URL,
+ TWITTER_URL,
+ INTEGRATIONS_URL,
+} from '~/lib/constants'
import { useTheme } from '~/providers/ThemeProvider'
import routesPath from '~/utils/routes'
@@ -22,17 +28,33 @@ const SmallBusinesses = () => {
aria-hidden='true'
>
<defs>
- <pattern id='rect-pattern' width={200} height={200} x='50%' y={-1} patternUnits='userSpaceOnUse'>
+ <pattern
+ id='rect-pattern'
+ width={200}
+ height={200}
+ x='50%'
+ y={-1}
+ patternUnits='userSpaceOnUse'
+ >
<path d='M.5 200V.5H200' fill='none' />
</pattern>
</defs>
- <svg x='50%' y={-1} className='overflow-visible fill-white dark:fill-gray-800/20'>
+ <svg
+ x='50%'
+ y={-1}
+ className='overflow-visible fill-white dark:fill-gray-800/20'
+ >
<path
d='M-200 0h201v201h-201Z M600 0h201v201h-201Z M-400 600h201v201h-201Z M200 800h201v201h-201Z'
strokeWidth={0}
/>
</svg>
- <rect width='100%' height='100%' strokeWidth={0} fill='url(#rect-pattern)' />
+ <rect
+ width='100%'
+ height='100%'
+ strokeWidth={0}
+ fill='url(#rect-pattern)'
+ />
</svg>
<div
className='absolute top-10 left-[calc(50%-4rem)] -z-10 transform-gpu blur-3xl sm:left-[calc(50%-18rem)] lg:top-[calc(50%-30rem)] lg:left-48 xl:left-[calc(50%-24rem)]'
@@ -82,7 +104,9 @@ const SmallBusinesses = () => {
rel='noopener noreferrer'
aria-label={`${t('common.liveDemo')} (opens in a new tab)`}
>
- <span className='text-base font-semibold'>{t('common.liveDemo')}</span>
+ <span className='text-base font-semibold'>
+ {t('common.liveDemo')}
+ </span>
</a>
</div>
<a
@@ -92,14 +116,20 @@ const SmallBusinesses = () => {
rel='noopener noreferrer'
aria-label={`${t('common.bookACall')} (opens in a new tab)`}
>
- <span className='text-base font-semibold'>{t('common.bookACall')}</span>
+ <span className='text-base font-semibold'>
+ {t('common.bookACall')}
+ </span>
<ArrowRightIcon className='mt-[1px] h-4 w-5' />
</a>
</div>
</div>
<div className='relative z-20 mx-auto mt-10 block max-w-[1300px] px-4 md:px-0'>
<img
- src={theme === 'dark' ? '/assets/screenshot_dark.png' : '/assets/screenshot_light.png'}
+ src={
+ theme === 'dark'
+ ? '/assets/screenshot_dark.png'
+ : '/assets/screenshot_light.png'
+ }
className='relative w-full rounded-xl ring-2 ring-gray-900/10 dark:ring-white/10'
width='100%'
height='auto'
@@ -110,47 +140,53 @@ const SmallBusinesses = () => {
</div>
<div className='mx-auto mt-12 mb-6 max-w-5xl px-5'>
- {_map(t('smbs.whyUs', { returnObjects: true }), (item: { name: string; desc: string[] }) => (
- <div key={item.name} className='mb-10 text-slate-900 last:mb-0 dark:text-white'>
- <h2 className='mb-5 text-4xl font-extrabold'>{item.name}</h2>
- {_map(item.desc, (descText) => (
- <p key={descText} className='mb-5 text-lg'>
- <Trans
- t={t}
- components={{
- span: <span className='font-bold' />,
- integrationLink: (
- <a
- href={INTEGRATIONS_URL}
- target='_blank'
- rel='noopener noreferrer'
- className='text-blue-600 hover:underline dark:text-blue-500'
- />
- ),
- discordUrl: (
- <a
- href={DISCORD_URL}
- target='_blank'
- rel='noopener noreferrer'
- className='text-blue-600 hover:underline dark:text-blue-500'
- />
- ),
- twitterUrl: (
- <a
- href={TWITTER_URL}
- target='_blank'
- rel='noopener noreferrer'
- className='text-blue-600 hover:underline dark:text-blue-500'
- />
- ),
- }}
- >
- {descText}
- </Trans>
- </p>
- ))}
- </div>
- ))}
+ {_map(
+ t('smbs.whyUs', { returnObjects: true }),
+ (item: { name: string; desc: string[] }) => (
+ <div
+ key={item.name}
+ className='mb-10 text-slate-900 last:mb-0 dark:text-white'
+ >
+ <h2 className='mb-5 text-4xl font-extrabold'>{item.name}</h2>
+ {_map(item.desc, (descText) => (
+ <p key={descText} className='mb-5 text-lg'>
+ <Trans
+ t={t}
+ components={{
+ span: <span className='font-bold' />,
+ integrationLink: (
+ <a
+ href={INTEGRATIONS_URL}
+ target='_blank'
+ rel='noopener noreferrer'
+ className='text-blue-600 hover:underline dark:text-blue-500'
+ />
+ ),
+ discordUrl: (
+ <a
+ href={DISCORD_URL}
+ target='_blank'
+ rel='noopener noreferrer'
+ className='text-blue-600 hover:underline dark:text-blue-500'
+ />
+ ),
+ twitterUrl: (
+ <a
+ href={TWITTER_URL}
+ target='_blank'
+ rel='noopener noreferrer'
+ className='text-blue-600 hover:underline dark:text-blue-500'
+ />
+ ),
+ }}
+ >
+ {descText}
+ </Trans>
+ </p>
+ ))}
+ </div>
+ ),
+ )}
<ComparisonTable className='py-5' />
</div>
diff --git a/web/app/pages/Landings/Startups.tsx b/web/app/pages/Landings/Startups.tsx
index 7018f5885..c2fb7b55f 100644
--- a/web/app/pages/Landings/Startups.tsx
+++ b/web/app/pages/Landings/Startups.tsx
@@ -6,7 +6,12 @@ import { Link } from 'react-router'
import Header from '~/components/Header'
import { ComparisonTable } from '~/components/marketing/ComparisonTable'
import { DitchGoogle } from '~/components/marketing/DitchGoogle'
-import { BOOK_A_CALL_URL, DISCORD_URL, LIVE_DEMO_URL, INTEGRATIONS_URL } from '~/lib/constants'
+import {
+ BOOK_A_CALL_URL,
+ DISCORD_URL,
+ LIVE_DEMO_URL,
+ INTEGRATIONS_URL,
+} from '~/lib/constants'
import { useTheme } from '~/providers/ThemeProvider'
import routesPath from '~/utils/routes'
@@ -22,17 +27,33 @@ const Startups = () => {
aria-hidden='true'
>
<defs>
- <pattern id='rect-pattern' width={200} height={200} x='50%' y={-1} patternUnits='userSpaceOnUse'>
+ <pattern
+ id='rect-pattern'
+ width={200}
+ height={200}
+ x='50%'
+ y={-1}
+ patternUnits='userSpaceOnUse'
+ >
<path d='M.5 200V.5H200' fill='none' />
</pattern>
</defs>
- <svg x='50%' y={-1} className='overflow-visible fill-white dark:fill-gray-800/20'>
+ <svg
+ x='50%'
+ y={-1}
+ className='overflow-visible fill-white dark:fill-gray-800/20'
+ >
<path
d='M-200 0h201v201h-201Z M600 0h201v201h-201Z M-400 600h201v201h-201Z M200 800h201v201h-201Z'
strokeWidth={0}
/>
</svg>
- <rect width='100%' height='100%' strokeWidth={0} fill='url(#rect-pattern)' />
+ <rect
+ width='100%'
+ height='100%'
+ strokeWidth={0}
+ fill='url(#rect-pattern)'
+ />
</svg>
<div
className='absolute top-10 left-[calc(50%-4rem)] -z-10 transform-gpu blur-3xl sm:left-[calc(50%-18rem)] lg:top-[calc(50%-30rem)] lg:left-48 xl:left-[calc(50%-24rem)]'
@@ -82,7 +103,9 @@ const Startups = () => {
rel='noopener noreferrer'
aria-label={`${t('common.liveDemo')} (opens in a new tab)`}
>
- <span className='text-base font-semibold'>{t('common.liveDemo')}</span>
+ <span className='text-base font-semibold'>
+ {t('common.liveDemo')}
+ </span>
</a>
</div>
<a
@@ -92,14 +115,20 @@ const Startups = () => {
rel='noopener noreferrer'
aria-label={`${t('common.bookACall')} (opens in a new tab)`}
>
- <span className='text-base font-semibold'>{t('common.bookACall')}</span>
+ <span className='text-base font-semibold'>
+ {t('common.bookACall')}
+ </span>
<ArrowRightIcon className='mt-[1px] h-4 w-5' />
</a>
</div>
</div>
<div className='relative z-20 mx-auto mt-10 block max-w-[1300px] px-4 md:px-0'>
<img
- src={theme === 'dark' ? '/assets/screenshot_dark.png' : '/assets/screenshot_light.png'}
+ src={
+ theme === 'dark'
+ ? '/assets/screenshot_dark.png'
+ : '/assets/screenshot_light.png'
+ }
className='relative w-full rounded-xl ring-2 ring-gray-900/10 dark:ring-white/10'
width='100%'
height='auto'
@@ -110,39 +139,45 @@ const Startups = () => {
</div>
<div className='mx-auto mt-12 mb-6 max-w-5xl px-5'>
- {_map(t('startups.whyUs', { returnObjects: true }), (item: { name: string; desc: string[] }) => (
- <div key={item.name} className='mb-10 text-slate-900 last:mb-0 dark:text-white'>
- <h2 className='mb-5 text-4xl font-extrabold'>{item.name}</h2>
- {_map(item.desc, (descText) => (
- <p key={descText} className='mb-5 text-lg'>
- <Trans
- t={t}
- components={{
- span: <span className='font-bold' />,
- integrationLink: (
- <a
- href={INTEGRATIONS_URL}
- target='_blank'
- rel='noopener noreferrer'
- className='text-blue-600 hover:underline dark:text-blue-500'
- />
- ),
- discordUrl: (
- <a
- href={DISCORD_URL}
- target='_blank'
- rel='noopener noreferrer'
- className='text-blue-600 hover:underline dark:text-blue-500'
- />
- ),
- }}
- >
- {descText}
- </Trans>
- </p>
- ))}
- </div>
- ))}
+ {_map(
+ t('startups.whyUs', { returnObjects: true }),
+ (item: { name: string; desc: string[] }) => (
+ <div
+ key={item.name}
+ className='mb-10 text-slate-900 last:mb-0 dark:text-white'
+ >
+ <h2 className='mb-5 text-4xl font-extrabold'>{item.name}</h2>
+ {_map(item.desc, (descText) => (
+ <p key={descText} className='mb-5 text-lg'>
+ <Trans
+ t={t}
+ components={{
+ span: <span className='font-bold' />,
+ integrationLink: (
+ <a
+ href={INTEGRATIONS_URL}
+ target='_blank'
+ rel='noopener noreferrer'
+ className='text-blue-600 hover:underline dark:text-blue-500'
+ />
+ ),
+ discordUrl: (
+ <a
+ href={DISCORD_URL}
+ target='_blank'
+ rel='noopener noreferrer'
+ className='text-blue-600 hover:underline dark:text-blue-500'
+ />
+ ),
+ }}
+ >
+ {descText}
+ </Trans>
+ </p>
+ ))}
+ </div>
+ ),
+ )}
<ComparisonTable className='py-5' />
</div>
diff --git a/web/app/pages/NotFound/index.tsx b/web/app/pages/NotFound/index.tsx
index 9a1730e01..f4db425fd 100644
--- a/web/app/pages/NotFound/index.tsx
+++ b/web/app/pages/NotFound/index.tsx
@@ -14,7 +14,12 @@ const NotFound = () => {
<div className='min-h-min-footer bg-gray-50 px-4 py-16 sm:px-6 sm:py-24 md:grid md:place-items-center lg:px-8 dark:bg-slate-900'>
<div className='mx-auto max-w-max'>
<main className='sm:flex'>
- <Text as='p' size='4xl' weight='bold' className='text-indigo-600 sm:text-5xl dark:text-indigo-500'>
+ <Text
+ as='p'
+ size='4xl'
+ weight='bold'
+ className='text-indigo-600 sm:text-5xl dark:text-indigo-500'
+ >
404
</Text>
<div className='sm:ml-6'>
@@ -22,7 +27,12 @@ const NotFound = () => {
<Text as='h1' size='4xl' weight='bold' className='sm:text-5xl'>
{t('notFoundPage.title')}
</Text>
- <Text as='p' size='base' colour='muted' className='mt-1 whitespace-pre-line'>
+ <Text
+ as='p'
+ size='base'
+ colour='muted'
+ className='mt-1 whitespace-pre-line'
+ >
{t('notFoundPage.description')}
</Text>
</div>
diff --git a/web/app/pages/Onboarding/Onboarding.tsx b/web/app/pages/Onboarding/Onboarding.tsx
index df9dfee9f..77abf74cb 100644
--- a/web/app/pages/Onboarding/Onboarding.tsx
+++ b/web/app/pages/Onboarding/Onboarding.tsx
@@ -1,7 +1,14 @@
import { EnvelopeIcon } from '@heroicons/react/24/outline'
import { CheckCircleIcon as CheckCircleIconSolid } from '@heroicons/react/24/solid'
import type { TFunction } from 'i18next'
-import { ChevronRightIcon, LaptopMinimalIcon, RocketIcon, CodeIcon, MailCheckIcon, SparklesIcon } from 'lucide-react'
+import {
+ ChevronRightIcon,
+ LaptopMinimalIcon,
+ RocketIcon,
+ CodeIcon,
+ MailCheckIcon,
+ SparklesIcon,
+} from 'lucide-react'
import { useState, useEffect, useMemo, useRef } from 'react'
import { Trans, useTranslation } from 'react-i18next'
import { Link, useNavigate, useFetcher, useLoaderData } from 'react-router'
@@ -12,7 +19,10 @@ import { useAuthProxy } from '~/hooks/useAuthProxy'
import { DOCS_URL, INTEGRATIONS_URL, isSelfhosted } from '~/lib/constants'
import { getSnippet } from '~/modals/TrackingSnippet'
import { useAuth } from '~/providers/AuthProvider'
-import type { OnboardingActionData, OnboardingLoaderData } from '~/routes/onboarding'
+import type {
+ OnboardingActionData,
+ OnboardingLoaderData,
+} from '~/routes/onboarding'
import { Badge } from '~/ui/Badge'
import Button from '~/ui/Button'
import PulsatingCircle from '~/ui/icons/PulsatingCircle'
@@ -85,7 +95,8 @@ const Onboarding = () => {
name?: string
}>({})
- const isLoading = fetcher.state === 'submitting' || fetcher.state === 'loading'
+ const isLoading =
+ fetcher.state === 'submitting' || fetcher.state === 'loading'
useEffect(() => {
if (!fetcher.data) return
@@ -115,7 +126,10 @@ const Onboarding = () => {
} else if (fetcher.data?.error) {
toast.error(fetcher.data.error)
} else if (fetcher.data?.fieldErrors?.name) {
- setTimeout(() => setNewProjectErrors({ name: fetcher.data!.fieldErrors!.name }), 0)
+ setTimeout(
+ () => setNewProjectErrors({ name: fetcher.data!.fieldErrors!.name }),
+ 0,
+ )
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [fetcher.data, fetcher.submit, loadUser, logout, navigate])
@@ -196,7 +210,11 @@ const Onboarding = () => {
}
if (trimmedName.length > MAX_PROJECT_NAME_LENGTH) {
- setNewProjectErrors({ name: t('project.settings.pxCharsError', { amount: MAX_PROJECT_NAME_LENGTH }) })
+ setNewProjectErrors({
+ name: t('project.settings.pxCharsError', {
+ amount: MAX_PROJECT_NAME_LENGTH,
+ }),
+ })
return
}
@@ -254,10 +272,22 @@ const Onboarding = () => {
{/* Sidebar - Desktop */}
<aside className='sticky top-6 hidden h-fit w-72 shrink-0 self-start overflow-hidden rounded-lg border border-gray-200 bg-white md:block dark:border-slate-800/60 dark:bg-slate-800/25'>
<div className='border-b border-gray-200 p-5 dark:border-slate-800/60'>
- <Text as='span' size='xs' weight='medium' colour='muted' className='tracking-wide uppercase'>
+ <Text
+ as='span'
+ size='xs'
+ weight='medium'
+ colour='muted'
+ className='tracking-wide uppercase'
+ >
{t('onboarding.welcome')}
</Text>
- <Text as='h1' size='xl' weight='semibold' tracking='tight' className='mt-1'>
+ <Text
+ as='h1'
+ size='xl'
+ weight='semibold'
+ tracking='tight'
+ className='mt-1'
+ >
{t('onboarding.title')}
</Text>
</div>
@@ -267,7 +297,11 @@ const Onboarding = () => {
{steps.map((step) => {
if (step.uiHidden) return null
- const status = step.completed ? 'complete' : step.current ? 'current' : 'upcoming'
+ const status = step.completed
+ ? 'complete'
+ : step.current
+ ? 'current'
+ : 'upcoming'
const StepIcon = STEP_ICONS[step.id as keyof typeof STEP_ICONS]
return (
@@ -277,16 +311,20 @@ const Onboarding = () => {
'group flex items-center gap-3 rounded-lg px-3 py-2.5 transition-colors',
status === 'current' &&
'bg-gradient-to-r from-indigo-500/10 to-purple-500/10 dark:from-indigo-500/20 dark:to-purple-500/20',
- status === 'complete' && 'bg-green-50/50 dark:bg-green-500/10',
+ status === 'complete' &&
+ 'bg-green-50/50 dark:bg-green-500/10',
status === 'upcoming' && 'opacity-60',
)}
>
<div
className={cn(
'flex size-9 shrink-0 items-center justify-center rounded-lg transition-colors',
- status === 'complete' && 'bg-green-100 dark:bg-green-500/20',
- status === 'current' && 'bg-indigo-100 dark:bg-indigo-500/20',
- status === 'upcoming' && 'bg-gray-100 dark:bg-slate-700',
+ status === 'complete' &&
+ 'bg-green-100 dark:bg-green-500/20',
+ status === 'current' &&
+ 'bg-indigo-100 dark:bg-indigo-500/20',
+ status === 'upcoming' &&
+ 'bg-gray-100 dark:bg-slate-700',
)}
>
{status === 'complete' ? (
@@ -295,8 +333,10 @@ const Onboarding = () => {
<StepIcon
className={cn(
'size-4',
- status === 'current' && 'text-indigo-600 dark:text-indigo-400',
- status === 'upcoming' && 'text-gray-400 dark:text-gray-500',
+ status === 'current' &&
+ 'text-indigo-600 dark:text-indigo-400',
+ status === 'upcoming' &&
+ 'text-gray-400 dark:text-gray-500',
)}
strokeWidth={1.5}
/>
@@ -309,13 +349,20 @@ const Onboarding = () => {
weight='medium'
className={cn(
'block',
- status === 'current' && 'text-indigo-700 dark:text-indigo-300',
- status === 'complete' && 'text-green-700 dark:text-green-300',
+ status === 'current' &&
+ 'text-indigo-700 dark:text-indigo-300',
+ status === 'complete' &&
+ 'text-green-700 dark:text-green-300',
)}
>
{step.title}
</Text>
- <Text as='span' size='xs' colour='muted' className='block'>
+ <Text
+ as='span'
+ size='xs'
+ colour='muted'
+ className='block'
+ >
{step.description}
</Text>
</div>
@@ -350,7 +397,10 @@ const Onboarding = () => {
{steps[currentStep]?.title}
</Text>
<Text as='span' size='xs' colour='muted'>
- {visibleSteps.findIndex((s) => s.id === steps[currentStep]?.id) + 1} / {visibleSteps.length}
+ {visibleSteps.findIndex(
+ (s) => s.id === steps[currentStep]?.id,
+ ) + 1}{' '}
+ / {visibleSteps.length}
</Text>
</div>
<div className='mt-3 overflow-hidden rounded-full bg-gray-200 dark:bg-slate-700'>
@@ -379,17 +429,37 @@ const Onboarding = () => {
<div className='mx-auto mb-6 flex size-16 items-center justify-center rounded-2xl bg-gradient-to-br from-indigo-100 to-purple-100 dark:from-indigo-500/20 dark:to-purple-500/20'>
<EnvelopeIcon className='size-8 text-indigo-600 dark:text-indigo-400' />
</div>
- <Text as='h1' size='3xl' weight='semibold' tracking='tight' className='text-center'>
+ <Text
+ as='h1'
+ size='3xl'
+ weight='semibold'
+ tracking='tight'
+ className='text-center'
+ >
{t('onboarding.confirm.title')}
</Text>
- <Text as='p' colour='secondary' className='mx-auto mt-4 max-w-md text-center whitespace-pre-line'>
+ <Text
+ as='p'
+ colour='secondary'
+ className='mx-auto mt-4 max-w-md text-center whitespace-pre-line'
+ >
{t('onboarding.confirm.linkSent', { email: user?.email })}
</Text>
- <Text as='p' size='sm' colour='muted' className='mx-auto mt-8 max-w-md text-center'>
+ <Text
+ as='p'
+ size='sm'
+ colour='muted'
+ className='mx-auto mt-8 max-w-md text-center'
+ >
{t('onboarding.confirm.spam')}
</Text>
- <Text as='p' size='sm' colour='muted' className='mt-2 text-center'>
+ <Text
+ as='p'
+ size='sm'
+ colour='muted'
+ className='mt-2 text-center'
+ >
<Trans
t={t}
i18nKey='onboarding.confirm.wrongEmail'
@@ -412,12 +482,25 @@ const Onboarding = () => {
{currentStep === 1 ? (
<form onSubmit={handleCreateProject} className='p-6 md:p-8'>
<div className='mx-auto mb-6 flex size-16 items-center justify-center rounded-2xl bg-gradient-to-br from-indigo-100 to-purple-100 dark:from-indigo-500/20 dark:to-purple-500/20'>
- <RocketIcon className='size-8 text-indigo-600 dark:text-indigo-400' strokeWidth={1.5} />
+ <RocketIcon
+ className='size-8 text-indigo-600 dark:text-indigo-400'
+ strokeWidth={1.5}
+ />
</div>
- <Text as='h1' size='3xl' weight='semibold' tracking='tight' className='text-center'>
+ <Text
+ as='h1'
+ size='3xl'
+ weight='semibold'
+ tracking='tight'
+ className='text-center'
+ >
{t('onboarding.createProject.title')}
</Text>
- <Text as='p' colour='secondary' className='mx-auto mt-4 max-w-md text-center whitespace-pre-line'>
+ <Text
+ as='p'
+ colour='secondary'
+ className='mx-auto mt-4 max-w-md text-center whitespace-pre-line'
+ >
{t('onboarding.createProject.desc')}
</Text>
@@ -447,12 +530,25 @@ const Onboarding = () => {
{currentStep === 2 && project ? (
<div className='p-6 md:p-8'>
<div className='mx-auto mb-6 flex size-16 items-center justify-center rounded-2xl bg-gradient-to-br from-indigo-100 to-purple-100 dark:from-indigo-500/20 dark:to-purple-500/20'>
- <CodeIcon className='size-8 text-indigo-600 dark:text-indigo-400' strokeWidth={1.5} />
+ <CodeIcon
+ className='size-8 text-indigo-600 dark:text-indigo-400'
+ strokeWidth={1.5}
+ />
</div>
- <Text as='h1' size='3xl' weight='semibold' tracking='tight' className='text-center'>
+ <Text
+ as='h1'
+ size='3xl'
+ weight='semibold'
+ tracking='tight'
+ className='text-center'
+ >
{t('onboarding.installTracking.title')}
</Text>
- <Text as='p' colour='secondary' className='mx-auto mt-4 max-w-lg text-center whitespace-pre-line'>
+ <Text
+ as='p'
+ colour='secondary'
+ className='mx-auto mt-4 max-w-lg text-center whitespace-pre-line'
+ >
<Trans
t={t}
i18nKey='onboarding.installTracking.desc'
@@ -472,7 +568,10 @@ const Onboarding = () => {
<div className='mt-8 rounded-lg border border-gray-200 bg-gray-50 p-5 dark:border-slate-700/60 dark:bg-slate-800/50'>
<div className='flex items-center gap-3'>
<div className='flex size-11 items-center justify-center rounded-lg bg-white dark:bg-slate-700'>
- <LaptopMinimalIcon className='size-5 text-gray-700 dark:text-gray-200' strokeWidth={1.5} />
+ <LaptopMinimalIcon
+ className='size-5 text-gray-700 dark:text-gray-200'
+ strokeWidth={1.5}
+ />
</div>
<div>
<Text as='h3' size='sm' weight='semibold'>
@@ -497,7 +596,8 @@ const Onboarding = () => {
<Textarea
classes={{
container: 'mt-3 font-mono text-sm',
- textarea: 'bg-white dark:bg-slate-900 ring-1 ring-gray-200 dark:ring-slate-700',
+ textarea:
+ 'bg-white dark:bg-slate-900 ring-1 ring-gray-200 dark:ring-slate-700',
}}
value={getSnippet(project.id)}
rows={15}
@@ -555,10 +655,22 @@ const Onboarding = () => {
<PulsatingCircle type='giant' />
)}
</div>
- <Text as='h1' size='3xl' weight='semibold' tracking='tight' className='text-center'>
- {hasEvents ? t('onboarding.verifyInstallation.perfect') : t('onboarding.verifyInstallation.navTitle')}
+ <Text
+ as='h1'
+ size='3xl'
+ weight='semibold'
+ tracking='tight'
+ className='text-center'
+ >
+ {hasEvents
+ ? t('onboarding.verifyInstallation.perfect')
+ : t('onboarding.verifyInstallation.navTitle')}
</Text>
- <Text as='p' colour='secondary' className='mx-auto mt-4 max-w-md text-center whitespace-pre-line'>
+ <Text
+ as='p'
+ colour='secondary'
+ className='mx-auto mt-4 max-w-md text-center whitespace-pre-line'
+ >
{hasEvents
? t('onboarding.verifyInstallation.eventReceived')
: t('onboarding.verifyInstallation.desc')}
@@ -566,7 +678,11 @@ const Onboarding = () => {
{hasEvents ? (
<div className='mx-auto mt-8 max-w-sm rounded-lg bg-green-50 p-4 dark:bg-green-500/10'>
- <Text as='p' size='sm' className='text-center text-green-700 dark:text-green-300'>
+ <Text
+ as='p'
+ size='sm'
+ className='text-center text-green-700 dark:text-green-300'
+ >
{t('onboarding.verifyInstallation.perfectDesc')}
</Text>
</div>
@@ -582,7 +698,9 @@ const Onboarding = () => {
</Text>
<Text as='p' size='xs' colour='muted'>
{project?.name
- ? t('onboarding.verifyInstallation.onTheXProject', { project: project.name })
+ ? t('onboarding.verifyInstallation.onTheXProject', {
+ project: project.name,
+ })
: t('onboarding.verifyInstallation.onYourProject')}
</Text>
</div>
@@ -617,7 +735,9 @@ const Onboarding = () => {
components={{
url: (
<Link
- to={isSelfhosted ? CONTACT_US_URL : routes.contact}
+ to={
+ isSelfhosted ? CONTACT_US_URL : routes.contact
+ }
target='_blank'
rel='noopener noreferrer'
className='font-medium text-indigo-600 hover:underline dark:text-indigo-400'
@@ -644,7 +764,11 @@ const Onboarding = () => {
{t('common.goBack')}
</Button>
) : null}
- <Button onClick={() => handleCompleteOnboarding(false)} primary large>
+ <Button
+ onClick={() => handleCompleteOnboarding(false)}
+ primary
+ large
+ >
{t('onboarding.finishOnboarding')}
</Button>
</div>
diff --git a/web/app/pages/OpenStartup/index.tsx b/web/app/pages/OpenStartup/index.tsx
index 06c71e57d..91d4d1009 100644
--- a/web/app/pages/OpenStartup/index.tsx
+++ b/web/app/pages/OpenStartup/index.tsx
@@ -274,14 +274,23 @@ const financeData = {
const financeDataToColumns = (financeData: any) => {
const dates = Object.keys(financeData)
- const columns = [['Technical Expenses'], ['Business Expenses'], ['MRR'], ['Profit'], ['Revenue'], ['x']]
+ const columns = [
+ ['Technical Expenses'],
+ ['Business Expenses'],
+ ['MRR'],
+ ['Profit'],
+ ['Revenue'],
+ ['x'],
+ ]
dates.forEach((date) => {
columns[0].push(financeData[date]['Technical Expenses'])
columns[1].push(financeData[date]['Business Expenses'])
columns[2].push(financeData[date]['MRR'])
columns[3].push(
- financeData[date]['Revenue'] + financeData[date]['Technical Expenses'] + financeData[date]['Business Expenses'],
+ financeData[date]['Revenue'] +
+ financeData[date]['Technical Expenses'] +
+ financeData[date]['Business Expenses'],
)
columns[4].push(financeData[date]['Revenue'])
columns[5].push(date)
@@ -292,7 +301,13 @@ const financeDataToColumns = (financeData: any) => {
const columns = financeDataToColumns(financeData)
-const groups = ['Revenue', 'MRR', 'Profit', 'Technical Expenses', 'Business Expenses']
+const groups = [
+ 'Revenue',
+ 'MRR',
+ 'Profit',
+ 'Technical Expenses',
+ 'Business Expenses',
+]
const getSettings = () => {
return {
@@ -404,41 +419,67 @@ const OpenStartup = ({ stats }: OpenStartupProps) => {
return (
<div className='min-h-page bg-gray-50 dark:bg-slate-900'>
<div className='mx-auto px-4 pt-12 pb-16 whitespace-pre-line sm:px-6 md:w-4/5 lg:px-8'>
- <h1 className='text-4xl font-bold text-gray-900 dark:text-gray-50'>{t('titles.open')}</h1>
+ <h1 className='text-4xl font-bold text-gray-900 dark:text-gray-50'>
+ {t('titles.open')}
+ </h1>
- <p className='mt-2 text-lg text-gray-900 dark:text-gray-50'>{t('open.desc')}</p>
+ <p className='mt-2 text-lg text-gray-900 dark:text-gray-50'>
+ {t('open.desc')}
+ </p>
- <p className='mt-2 text-lg text-gray-900 dark:text-gray-50'>{t('open.updated')}</p>
+ <p className='mt-2 text-lg text-gray-900 dark:text-gray-50'>
+ {t('open.updated')}
+ </p>
- <h2 className='mt-8 text-2xl font-bold text-gray-900 dark:text-gray-50'>{t('open.finance.title')}</h2>
+ <h2 className='mt-8 text-2xl font-bold text-gray-900 dark:text-gray-50'>
+ {t('open.finance.title')}
+ </h2>
- <p className='mt-2 text-lg text-gray-900 dark:text-gray-50'>{t('open.finance.desc')}</p>
+ <p className='mt-2 text-lg text-gray-900 dark:text-gray-50'>
+ {t('open.finance.desc')}
+ </p>
<div className='mt-4 h-80' id='open-startup' />
- <h2 className='mt-8 text-2xl font-bold text-gray-900 dark:text-gray-50'>{t('open.usage.title')}</h2>
+ <h2 className='mt-8 text-2xl font-bold text-gray-900 dark:text-gray-50'>
+ {t('open.usage.title')}
+ </h2>
- <p className='mt-2 text-lg text-gray-900 dark:text-gray-50'>{t('open.usage.desc')}</p>
+ <p className='mt-2 text-lg text-gray-900 dark:text-gray-50'>
+ {t('open.usage.desc')}
+ </p>
<p className='text-md mt-2 text-gray-900 dark:text-gray-50'>
{t('main.users')}
{': '}
{users[0]}
- {users[1] ? <span className='text-gray-900 dark:text-indigo-200'>{users[1]}+</span> : null}
+ {users[1] ? (
+ <span className='text-gray-900 dark:text-indigo-200'>
+ {users[1]}+
+ </span>
+ ) : null}
</p>
<p className='text-md mt-2 text-gray-900 dark:text-gray-50'>
{t('main.websites')}
{': '}
{websites[0]}
- {websites[1] ? <span className='text-gray-900 dark:text-indigo-200'>{websites[1]}+</span> : null}
+ {websites[1] ? (
+ <span className='text-gray-900 dark:text-indigo-200'>
+ {websites[1]}+
+ </span>
+ ) : null}
</p>
<p className='text-md mt-2 text-gray-900 dark:text-gray-50'>
{t('main.pageviews')}
{': '}
{events[0]}
- {events[1] ? <span className='text-gray-900 dark:text-indigo-200'>{events[1]}+</span> : null}
+ {events[1] ? (
+ <span className='text-gray-900 dark:text-indigo-200'>
+ {events[1]}+
+ </span>
+ ) : null}
</p>
<p className='text-md mt-2 text-gray-900 dark:text-gray-50'>
diff --git a/web/app/pages/Organisations/AddOrganisation.tsx b/web/app/pages/Organisations/AddOrganisation.tsx
index 85938585b..627912335 100644
--- a/web/app/pages/Organisations/AddOrganisation.tsx
+++ b/web/app/pages/Organisations/AddOrganisation.tsx
@@ -7,7 +7,10 @@ interface AddOrganisationProps {
sitesCount: number
}
-export const AddOrganisation = ({ onClick, sitesCount }: AddOrganisationProps) => {
+export const AddOrganisation = ({
+ onClick,
+ sitesCount,
+}: AddOrganisationProps) => {
const { t } = useTranslation('common')
return (
diff --git a/web/app/pages/Organisations/NoOrganisations.tsx b/web/app/pages/Organisations/NoOrganisations.tsx
index 767146db5..b0db977d3 100644
--- a/web/app/pages/Organisations/NoOrganisations.tsx
+++ b/web/app/pages/Organisations/NoOrganisations.tsx
@@ -13,12 +13,20 @@ export const NoOrganisations = ({ onClick }: NoOrganisationsProps) => {
return (
<div className='mx-auto w-full max-w-2xl py-16 text-center'>
<div className='mx-auto mb-6 flex size-14 items-center justify-center rounded-xl bg-gray-100 dark:bg-slate-800'>
- <BuildingOffice2Icon className='size-7 text-gray-700 dark:text-gray-200' strokeWidth={1.5} />
+ <BuildingOffice2Icon
+ className='size-7 text-gray-700 dark:text-gray-200'
+ strokeWidth={1.5}
+ />
</div>
<Text as='h3' size='xl' weight='medium' className='tracking-tight'>
{t('organisations.noOrganisations')}
</Text>
- <Text as='p' size='sm' colour='secondary' className='mx-auto mt-2 max-w-md'>
+ <Text
+ as='p'
+ size='sm'
+ colour='secondary'
+ className='mx-auto mt-2 max-w-md'
+ >
{t('organisations.createOrganisation')}
</Text>
<button
diff --git a/web/app/pages/Organisations/OrganisationCard.tsx b/web/app/pages/Organisations/OrganisationCard.tsx
index d338748ad..de192031c 100644
--- a/web/app/pages/Organisations/OrganisationCard.tsx
+++ b/web/app/pages/Organisations/OrganisationCard.tsx
@@ -28,7 +28,9 @@ export const OrganisationCard = ({ organisation }: OrganisationCardProps) => {
const { name, members } = organisation
- const isAccepting = fetcher.state === 'submitting' && fetcher.formData?.get('intent') === 'accept-invitation'
+ const isAccepting =
+ fetcher.state === 'submitting' &&
+ fetcher.formData?.get('intent') === 'accept-invitation'
const membership = useMemo(
() => _find(members, (member) => member.user.email === user?.email),
@@ -66,7 +68,10 @@ export const OrganisationCard = ({ organisation }: OrganisationCardProps) => {
list.push({
colour: 'slate',
- label: membersCount === 1 ? t('common.oneMember') : t('common.xMembers', { number: membersCount }),
+ label:
+ membersCount === 1
+ ? t('common.oneMember')
+ : t('common.xMembers', { number: membersCount }),
})
return list
@@ -83,7 +88,9 @@ export const OrganisationCard = ({ organisation }: OrganisationCardProps) => {
fetcher.submit(formData, { method: 'post' })
}
- const onElementClick = (e: React.MouseEvent<HTMLAnchorElement | HTMLDivElement>) => {
+ const onElementClick = (
+ e: React.MouseEvent<HTMLAnchorElement | HTMLDivElement>,
+ ) => {
if (membership?.confirmed) {
return
}
@@ -96,7 +103,8 @@ export const OrganisationCard = ({ organisation }: OrganisationCardProps) => {
const cardClassName = cx(
'min-h-[153.1px] overflow-hidden rounded-xl border border-gray-200 bg-gray-50 transition-colors dark:border-slate-800/25 dark:bg-slate-800/70',
{
- 'cursor-pointer hover:bg-gray-200/70 dark:hover:bg-slate-700/60': !isViewer,
+ 'cursor-pointer hover:bg-gray-200/70 dark:hover:bg-slate-700/60':
+ !isViewer,
},
)
@@ -153,7 +161,11 @@ export const OrganisationCard = ({ organisation }: OrganisationCardProps) => {
}
return (
- <Link to={_replace(routes.organisation, ':id', organisation.id)} onClick={onElementClick} className={cardClassName}>
+ <Link
+ to={_replace(routes.organisation, ':id', organisation.id)}
+ onClick={onElementClick}
+ className={cardClassName}
+ >
{cardContent}
</Link>
)
diff --git a/web/app/pages/Organisations/Organisations.tsx b/web/app/pages/Organisations/Organisations.tsx
index 1de17ea23..edd57ca4e 100644
--- a/web/app/pages/Organisations/Organisations.tsx
+++ b/web/app/pages/Organisations/Organisations.tsx
@@ -5,13 +5,21 @@ import _size from 'lodash/size'
import { SearchIcon, XIcon } from 'lucide-react'
import React, { useState, useEffect, useRef, useCallback } from 'react'
import { useTranslation } from 'react-i18next'
-import { useFetcher, useLoaderData, useNavigate, useRevalidator } from 'react-router'
+import {
+ useFetcher,
+ useLoaderData,
+ useNavigate,
+ useRevalidator,
+} from 'react-router'
import { toast } from 'sonner'
import EventsRunningOutBanner from '~/components/EventsRunningOutBanner'
import useDebounce from '~/hooks/useDebounce'
import { ENTRIES_PER_PAGE_DASHBOARD } from '~/lib/constants'
-import type { OrganisationsActionData, OrganisationsLoaderData } from '~/routes/organisations._index'
+import type {
+ OrganisationsActionData,
+ OrganisationsLoaderData,
+} from '~/routes/organisations._index'
import Input from '~/ui/Input'
import Modal from '~/ui/Modal'
import Pagination from '~/ui/Pagination'
@@ -30,15 +38,20 @@ const Organisations = () => {
const { revalidate } = useRevalidator()
const { t } = useTranslation('common')
- const [isSearchActive, setIsSearchActive] = useState(() => !!loaderData?.search)
+ const [isSearchActive, setIsSearchActive] = useState(
+ () => !!loaderData?.search,
+ )
const searchInputRef = useRef<HTMLInputElement>(null)
const [showActivateEmailModal, setShowActivateEmailModal] = useState(false)
const [search, setSearch] = useState(loaderData?.search || '')
const debouncedSearch = useDebounce<string>(search, 500)
- const [newOrganisationModalOpen, setNewOrganisationModalOpen] = useState(false)
+ const [newOrganisationModalOpen, setNewOrganisationModalOpen] =
+ useState(false)
const [newOrganisationName, setNewOrganisationName] = useState('')
- const [newOrganisationError, setNewOrganisationError] = useState<string | null>(null)
+ const [newOrganisationError, setNewOrganisationError] = useState<
+ string | null
+ >(null)
const isNewOrganisationLoading = fetcher.state === 'submitting'
@@ -53,7 +66,10 @@ const Organisations = () => {
const params = new URLSearchParams()
if (newPage > 1) params.set('page', String(newPage))
if (newSearch) params.set('search', newSearch)
- navigate(`${routes.organisations}${params.toString() ? `?${params.toString()}` : ''}`, { replace: true })
+ navigate(
+ `${routes.organisations}${params.toString() ? `?${params.toString()}` : ''}`,
+ { replace: true },
+ )
}
const closeNewOrganisationModal = useCallback(() => {
@@ -137,7 +153,11 @@ const Organisations = () => {
title={t('apiNotifications.somethingWentWrong')}
description={t('apiNotifications.errorCode', { error })}
actions={[
- { label: t('dashboard.reloadPage'), onClick: () => window.location.reload(), primary: true },
+ {
+ label: t('dashboard.reloadPage'),
+ onClick: () => window.location.reload(),
+ primary: true,
+ },
{ label: t('notFoundPage.support'), to: routes.contact },
]}
/>
@@ -156,7 +176,12 @@ const Organisations = () => {
<div className='mx-auto w-full max-w-7xl px-4 py-6 sm:px-6 lg:px-8'>
<div className='mb-6 flex flex-wrap justify-between gap-2'>
<div className='flex items-end justify-between'>
- <Text as='h2' size='3xl' weight='bold' className='mt-2 flex items-baseline gap-2'>
+ <Text
+ as='h2'
+ size='3xl'
+ weight='bold'
+ className='mt-2 flex items-baseline gap-2'
+ >
<span>{t('titles.organisations')}</span>
{isSearchActive ? (
<button
@@ -255,9 +280,15 @@ const Organisations = () => {
) : (
<div className='grid grid-cols-1 gap-x-6 gap-y-3 lg:grid-cols-3 lg:gap-y-6'>
{_map(organisations, (organisation) => (
- <OrganisationCard key={organisation.id} organisation={organisation} />
+ <OrganisationCard
+ key={organisation.id}
+ organisation={organisation}
+ />
))}
- <AddOrganisation sitesCount={_size(organisations)} onClick={onNewOrganisation} />
+ <AddOrganisation
+ sitesCount={_size(organisations)}
+ onClick={onNewOrganisation}
+ />
</div>
)}
</div>
@@ -296,8 +327,16 @@ const Organisations = () => {
onChange={(e) => setNewOrganisationName(e.target.value)}
/>
{newOrganisationError ? (
- <Text as='p' size='sm' weight='medium' colour='error' className='mt-2'>
- {t('apiNotifications.errorOccured', { error: newOrganisationError })}
+ <Text
+ as='p'
+ size='sm'
+ weight='medium'
+ colour='error'
+ className='mt-2'
+ >
+ {t('apiNotifications.errorOccured', {
+ error: newOrganisationError,
+ })}
</Text>
) : null}
</div>
diff --git a/web/app/pages/Organisations/Settings/People.tsx b/web/app/pages/Organisations/Settings/People.tsx
index bb1a73d49..b647192d1 100644
--- a/web/app/pages/Organisations/Settings/People.tsx
+++ b/web/app/pages/Organisations/Settings/People.tsx
@@ -27,7 +27,9 @@ const NoPeople = () => {
return (
<div className='flex flex-col py-6 sm:px-6 lg:px-8'>
<div className='mx-auto w-full max-w-7xl text-gray-900 dark:text-gray-50'>
- <h2 className='mb-8 px-4 text-center text-xl leading-snug'>{t('project.settings.noPeople')}</h2>
+ <h2 className='mb-8 px-4 text-center text-xl leading-snug'>
+ {t('project.settings.noPeople')}
+ </h2>
</div>
</div>
)
@@ -46,7 +48,9 @@ const UsersList = ({ members, onRemove, fetcher }: UsersListProps) => {
} = useTranslation('common')
const { user } = useAuth()
- const [roleEditDropdownId, setRoleEditDropdownId] = useState<string | null>(null)
+ const [roleEditDropdownId, setRoleEditDropdownId] = useState<string | null>(
+ null,
+ )
const openRef = useRef<HTMLUListElement>(null)
useOnClickOutside(openRef, () => setRoleEditDropdownId(null))
@@ -73,14 +77,23 @@ const UsersList = ({ members, onRemove, fetcher }: UsersListProps) => {
{member.confirmed ? (
<div>
<button
- onClick={() => setRoleEditDropdownId((prev) => (prev === member.id ? null : member.id))}
+ onClick={() =>
+ setRoleEditDropdownId((prev) =>
+ prev === member.id ? null : member.id,
+ )
+ }
type='button'
- disabled={member.user.email === user?.email || member.role === 'owner'}
+ disabled={
+ member.user.email === user?.email || member.role === 'owner'
+ }
className='inline-flex items-center rounded-full border border-gray-200 bg-white py-0.5 pr-1 pl-2 text-sm leading-5 font-medium text-gray-700 hover:bg-gray-50 disabled:cursor-not-allowed disabled:opacity-80 dark:border-gray-600 dark:bg-slate-800 dark:text-gray-200 dark:hover:bg-gray-600'
>
{t(`organisations.role.${member.role}.name`)}
<ChevronDownIcon
- style={{ transform: roleEditDropdownId === member.id ? 'rotate(180deg)' : '' }}
+ style={{
+ transform:
+ roleEditDropdownId === member.id ? 'rotate(180deg)' : '',
+ }}
className='ml-0.5 h-4 w-4 pt-px'
/>
</button>
@@ -120,14 +133,20 @@ const UsersList = ({ members, onRemove, fetcher }: UsersListProps) => {
}}
className='group flex cursor-pointer items-center justify-between rounded-b-md p-4 hover:bg-gray-200 dark:hover:bg-gray-700'
>
- <p className='font-bold text-red-600 dark:text-red-500'>{t('project.settings.removeMember')}</p>
+ <p className='font-bold text-red-600 dark:text-red-500'>
+ {t('project.settings.removeMember')}
+ </p>
</li>
</ul>
) : null}
</div>
) : (
<div className='flex items-center justify-end'>
- <Badge colour='yellow' className='mr-3' label={t('common.pending')} />
+ <Badge
+ colour='yellow'
+ className='mr-3'
+ label={t('common.pending')}
+ />
<Button
type='button'
className='rounded-md bg-white text-base font-medium text-indigo-700 hover:bg-indigo-50 dark:border-gray-600 dark:bg-slate-800 dark:text-gray-50 dark:hover:bg-slate-700'
@@ -167,12 +186,15 @@ const People = ({ organisation }: PeopleProps) => {
const [validated, setValidated] = useState(false)
const [showDeleteModal, setShowDeleteModal] = useState(false)
- const [memberToRemove, setMemberToRemove] = useState<DetailedOrganisation['members'][number] | null>(null)
+ const [memberToRemove, setMemberToRemove] = useState<
+ DetailedOrganisation['members'][number] | null
+ >(null)
const { name, members } = organisation
const isSubmitting = fetcher.state === 'submitting'
- const isDeleting = isSubmitting && fetcher.formData?.get('intent') === 'remove-member'
+ const isDeleting =
+ isSubmitting && fetcher.formData?.get('intent') === 'remove-member'
const closeModal = () => {
setShowModal(false)
@@ -276,9 +298,17 @@ const People = ({ organisation }: PeopleProps) => {
<h3 className='mt-2 flex items-center text-lg font-bold text-gray-900 dark:text-gray-50'>
{t('project.settings.people')}
</h3>
- <p className='text-sm text-gray-500 dark:text-gray-400'>{t('project.settings.inviteCoworkers')}</p>
+ <p className='text-sm text-gray-500 dark:text-gray-400'>
+ {t('project.settings.inviteCoworkers')}
+ </p>
</div>
- <Button className='h-8 pl-2' primary regular type='button' onClick={() => setShowModal(true)}>
+ <Button
+ className='h-8 pl-2'
+ primary
+ regular
+ type='button'
+ onClick={() => setShowModal(true)}
+ >
<>
<UserRoundPlusIcon className='mr-1 h-5 w-5' strokeWidth={1.5} />
{t('project.settings.invite')}
@@ -337,7 +367,9 @@ const People = ({ organisation }: PeopleProps) => {
submitText={t('common.yes')}
type='confirmed'
closeText={t('common.no')}
- title={t('project.settings.removeUser', { user: memberToRemove?.user.email })}
+ title={t('project.settings.removeUser', {
+ user: memberToRemove?.user.email,
+ })}
message={t('project.settings.removeConfirm')}
isOpened={showDeleteModal}
isLoading={isDeleting}
@@ -378,13 +410,19 @@ const People = ({ organisation }: PeopleProps) => {
/>
<fieldset className='mt-4'>
{}
- <label className='block text-sm font-medium text-gray-700 dark:text-gray-300' htmlFor='role'>
+ <label
+ className='block text-sm font-medium text-gray-700 dark:text-gray-300'
+ htmlFor='role'
+ >
{t('project.settings.role')}
</label>
<div
- className={cx('mt-1 -space-y-px rounded-md bg-white dark:bg-slate-900', {
- 'border border-red-300': errors.role,
- })}
+ className={cx(
+ 'mt-1 -space-y-px rounded-md bg-white dark:bg-slate-900',
+ {
+ 'border border-red-300': errors.role,
+ },
+ )}
>
{/* eslint-disable-next-line jsx-a11y/label-has-associated-control */}
<label
@@ -409,16 +447,20 @@ const People = ({ organisation }: PeopleProps) => {
<div className='ml-3 flex flex-col'>
<span
className={cx('block text-sm font-medium', {
- 'text-indigo-900 dark:text-white': form.role === 'admin',
- 'text-gray-700 dark:text-gray-200': form.role !== 'admin',
+ 'text-indigo-900 dark:text-white':
+ form.role === 'admin',
+ 'text-gray-700 dark:text-gray-200':
+ form.role !== 'admin',
})}
>
{t('organisations.role.admin.name')}
</span>
<span
className={cx('block text-sm', {
- 'text-indigo-700 dark:text-gray-100': form.role === 'admin',
- 'text-gray-700 dark:text-gray-200': form.role !== 'admin',
+ 'text-indigo-700 dark:text-gray-100':
+ form.role === 'admin',
+ 'text-gray-700 dark:text-gray-200':
+ form.role !== 'admin',
})}
>
{t('organisations.role.admin.desc')}
@@ -448,16 +490,20 @@ const People = ({ organisation }: PeopleProps) => {
<div className='ml-3 flex flex-col'>
<span
className={cx('block text-sm font-medium', {
- 'text-indigo-900 dark:text-white': form.role === 'viewer',
- 'text-gray-700 dark:text-gray-200': form.role !== 'viewer',
+ 'text-indigo-900 dark:text-white':
+ form.role === 'viewer',
+ 'text-gray-700 dark:text-gray-200':
+ form.role !== 'viewer',
})}
>
{t('organisations.role.viewer.name')}
</span>
<span
className={cx('block text-sm', {
- 'text-indigo-700 dark:text-gray-100': form.role === 'viewer',
- 'text-gray-700 dark:text-gray-200': form.role !== 'viewer',
+ 'text-indigo-700 dark:text-gray-100':
+ form.role === 'viewer',
+ 'text-gray-700 dark:text-gray-200':
+ form.role !== 'viewer',
})}
>
{t('organisations.role.viewer.desc')}
@@ -466,7 +512,10 @@ const People = ({ organisation }: PeopleProps) => {
</label>
</div>
{errors.role ? (
- <p className='mt-2 text-sm text-red-600 dark:text-red-500' id='email-error'>
+ <p
+ className='mt-2 text-sm text-red-600 dark:text-red-500'
+ id='email-error'
+ >
{errors.role}
</p>
) : null}
diff --git a/web/app/pages/Organisations/Settings/Projects.tsx b/web/app/pages/Organisations/Settings/Projects.tsx
index 3e5aa2611..1eba44a22 100644
--- a/web/app/pages/Organisations/Settings/Projects.tsx
+++ b/web/app/pages/Organisations/Settings/Projects.tsx
@@ -1,4 +1,9 @@
-import { InformationCircleIcon, MagnifyingGlassIcon, FolderPlusIcon, XMarkIcon } from '@heroicons/react/24/outline'
+import {
+ InformationCircleIcon,
+ MagnifyingGlassIcon,
+ FolderPlusIcon,
+ XMarkIcon,
+} from '@heroicons/react/24/outline'
import _filter from 'lodash/filter'
import _isEmpty from 'lodash/isEmpty'
import _map from 'lodash/map'
@@ -38,7 +43,8 @@ const SelectAProject = ({ onSelect }: SelectAProjectProps) => {
const debouncedSearch = useDebounce(search, 500)
const pageAmount = Math.ceil(total / PROJECT_SELECT_PAGE_SIZE)
- const isLoading = fetcher.state === 'submitting' || fetcher.state === 'loading'
+ const isLoading =
+ fetcher.state === 'submitting' || fetcher.state === 'loading'
// Fetch projects when page or search changes
useEffect(() => {
@@ -52,7 +58,10 @@ const SelectAProject = ({ onSelect }: SelectAProjectProps) => {
// Update local state when fetcher returns data
useEffect(() => {
- if (fetcher.data?.intent === 'get-available-projects' && fetcher.data?.availableProjects) {
+ if (
+ fetcher.data?.intent === 'get-available-projects' &&
+ fetcher.data?.availableProjects
+ ) {
setTimeout(() => {
setProjects(fetcher.data!.availableProjects!.results as Project[])
setTotal(fetcher.data!.availableProjects!.total)
@@ -96,7 +105,9 @@ const SelectAProject = ({ onSelect }: SelectAProjectProps) => {
>
<div className='flex items-center px-4 py-4 sm:px-6'>
<div className='min-w-0 flex-1'>
- <p className='truncate text-sm font-medium text-gray-900 dark:text-white'>{project.name}</p>
+ <p className='truncate text-sm font-medium text-gray-900 dark:text-white'>
+ {project.name}
+ </p>
</div>
</div>
</li>
@@ -126,7 +137,9 @@ const NoProjects = () => {
return (
<div className='flex flex-col py-6 sm:px-6 lg:px-8'>
<div className='mx-auto w-full max-w-7xl text-gray-900 dark:text-gray-50'>
- <h2 className='mb-8 px-4 text-center text-xl leading-snug'>{t('organisations.noProjectsFound')}</h2>
+ <h2 className='mb-8 px-4 text-center text-xl leading-snug'>
+ {t('organisations.noProjectsFound')}
+ </h2>
</div>
</div>
)
@@ -144,7 +157,10 @@ const ProjectList = ({ projects, onRemove }: ProjectListProps) => {
return projects.map((project) => (
<tr key={project.id} className='dark:bg-slate-800'>
<td className='py-4 pr-3 pl-4 text-sm font-medium whitespace-nowrap text-gray-900 sm:pl-6 dark:text-white'>
- <Link to={_replace(routes.project, ':id', project.id)} className='hover:underline'>
+ <Link
+ to={_replace(routes.project, ':id', project.id)}
+ className='hover:underline'
+ >
{project.name}
</Link>
</td>
@@ -153,8 +169,12 @@ const ProjectList = ({ projects, onRemove }: ProjectListProps) => {
{project.admin.email !== user?.email ? (
<Tooltip
className='mr-2'
- text={t('organisations.projectOwnedBy', { email: project.admin.email })}
- tooltipNode={<InformationCircleIcon className='size-5 text-gray-400' />}
+ text={t('organisations.projectOwnedBy', {
+ email: project.admin.email,
+ })}
+ tooltipNode={
+ <InformationCircleIcon className='size-5 text-gray-400' />
+ }
/>
) : null}
@@ -177,7 +197,9 @@ export const Projects = ({ organisation }: ProjectsProps) => {
const [showDeleteModal, setShowDeleteModal] = useState(false)
const [showAddProjectModal, setShowAddProjectModal] = useState(false)
- const [projectToRemove, setProjectToRemove] = useState<DetailedOrganisation['projects'][number] | null>(null)
+ const [projectToRemove, setProjectToRemove] = useState<
+ DetailedOrganisation['projects'][number] | null
+ >(null)
const [selectedProject, setSelectedProject] = useState<any>(null)
const [currentPage, setCurrentPage] = useState(1)
@@ -186,8 +208,10 @@ export const Projects = ({ organisation }: ProjectsProps) => {
const { projects } = organisation
const isSubmitting = fetcher.state === 'submitting'
- const isAddingProject = isSubmitting && fetcher.formData?.get('intent') === 'add-project'
- const isRemovingProject = isSubmitting && fetcher.formData?.get('intent') === 'remove-project'
+ const isAddingProject =
+ isSubmitting && fetcher.formData?.get('intent') === 'add-project'
+ const isRemovingProject =
+ isSubmitting && fetcher.formData?.get('intent') === 'remove-project'
/* eslint-disable react-hooks/set-state-in-effect */
useEffect(() => {
@@ -213,7 +237,9 @@ export const Projects = ({ organisation }: ProjectsProps) => {
return projects
}
- return projects.filter((project) => project.name.toLowerCase().includes(search))
+ return projects.filter((project) =>
+ project.name.toLowerCase().includes(search),
+ )
}, [projects, search])
const pageAmount = Math.ceil(filteredProjects.length / PROJECT_LIST_PAGE_SIZE)
@@ -354,7 +380,9 @@ export const Projects = ({ organisation }: ProjectsProps) => {
</button>
}
closeText={t('common.cancel')}
- title={t('organisations.modals.addProject.title', { organisation: organisation.name })}
+ title={t('organisations.modals.addProject.title', {
+ organisation: organisation.name,
+ })}
message={
<div>
<p className='mt-2 text-base text-gray-700 dark:text-gray-200'>
@@ -363,7 +391,9 @@ export const Projects = ({ organisation }: ProjectsProps) => {
{selectedProject ? (
<div className='mt-4 flex items-center justify-between rounded-lg border border-gray-200 p-4 dark:border-slate-600'>
- <span className='text-sm font-medium text-gray-900 dark:text-white'>{selectedProject.name}</span>
+ <span className='text-sm font-medium text-gray-900 dark:text-white'>
+ {selectedProject.name}
+ </span>
<button
type='button'
onClick={() => setSelectedProject(null)}
@@ -391,7 +421,9 @@ export const Projects = ({ organisation }: ProjectsProps) => {
}}
submitText={t('common.yes')}
closeText={t('common.no')}
- title={t('organisations.modals.remove.title', { project: projectToRemove?.name })}
+ title={t('organisations.modals.remove.title', {
+ project: projectToRemove?.name,
+ })}
message={t('organisations.modals.remove.message')}
isOpened={showDeleteModal}
type='warning'
diff --git a/web/app/pages/Organisations/Settings/index.tsx b/web/app/pages/Organisations/Settings/index.tsx
index 59c622747..ae9eee907 100644
--- a/web/app/pages/Organisations/Settings/index.tsx
+++ b/web/app/pages/Organisations/Settings/index.tsx
@@ -4,13 +4,22 @@ import _size from 'lodash/size'
import { Trash2Icon } from 'lucide-react'
import React, { useState, useEffect, useMemo } from 'react'
import { useTranslation } from 'react-i18next'
-import { Link, useNavigate, useFetcher, useLoaderData, useRevalidator } from 'react-router'
+import {
+ Link,
+ useNavigate,
+ useFetcher,
+ useLoaderData,
+ useRevalidator,
+} from 'react-router'
import { toast } from 'sonner'
import { TITLE_SUFFIX } from '~/lib/constants'
import { DetailedOrganisation } from '~/lib/models/Organisation'
import { useAuth } from '~/providers/AuthProvider'
-import type { OrganisationSettingsActionData, OrganisationLoaderData } from '~/routes/organisations.$id'
+import type {
+ OrganisationSettingsActionData,
+ OrganisationLoaderData,
+} from '~/routes/organisations.$id'
import Button from '~/ui/Button'
import Input from '~/ui/Input'
import Loader from '~/ui/Loader'
@@ -54,8 +63,12 @@ const OrganisationSettings = () => {
}
}, [organisation, isFormDirty])
- const isSaving = fetcher.state === 'submitting' && fetcher.formData?.get('intent') === 'update-organisation'
- const isDeleting = fetcher.state === 'submitting' && fetcher.formData?.get('intent') === 'delete-organisation'
+ const isSaving =
+ fetcher.state === 'submitting' &&
+ fetcher.formData?.get('intent') === 'update-organisation'
+ const isDeleting =
+ fetcher.state === 'submitting' &&
+ fetcher.formData?.get('intent') === 'delete-organisation'
useEffect(() => {
if (fetcher.data?.success) {
@@ -125,7 +138,9 @@ const OrganisationSettings = () => {
}
if (_size(form.name) > MAX_NAME_LENGTH) {
- allErrors.name = t('project.settings.pxCharsError', { amount: MAX_NAME_LENGTH })
+ allErrors.name = t('project.settings.pxCharsError', {
+ amount: MAX_NAME_LENGTH,
+ })
}
const valid = _isEmpty(_keys(allErrors))
@@ -174,7 +189,11 @@ const OrganisationSettings = () => {
title={t('apiNotifications.somethingWentWrong')}
description={t('apiNotifications.errorCode', { error })}
actions={[
- { label: t('dashboard.reloadPage'), onClick: () => window.location.reload(), primary: true },
+ {
+ label: t('dashboard.reloadPage'),
+ onClick: () => window.location.reload(),
+ primary: true,
+ },
{ label: t('notFoundPage.support'), to: routes.contact },
]}
/>
@@ -191,9 +210,16 @@ const OrganisationSettings = () => {
return (
<div className='flex min-h-min-footer flex-col bg-gray-50 pb-40 dark:bg-slate-900'>
- <form className='mx-auto w-full max-w-7xl px-4 py-6 sm:px-6 lg:px-8' onSubmit={handleSubmit}>
- <h2 className='mt-2 text-3xl font-bold text-gray-900 dark:text-gray-50'>{title}</h2>
- <h3 className='mt-4 text-lg font-bold text-gray-900 dark:text-gray-50'>{t('profileSettings.general')}</h3>
+ <form
+ className='mx-auto w-full max-w-7xl px-4 py-6 sm:px-6 lg:px-8'
+ onSubmit={handleSubmit}
+ >
+ <h2 className='mt-2 text-3xl font-bold text-gray-900 dark:text-gray-50'>
+ {title}
+ </h2>
+ <h3 className='mt-4 text-lg font-bold text-gray-900 dark:text-gray-50'>
+ {t('profileSettings.general')}
+ </h3>
<Input
name='name'
label={t('common.name')}
@@ -224,7 +250,12 @@ const OrganisationSettings = () => {
<ArrowLeftRight className='mr-1 h-5 w-5' />
{t('project.settings.transfer')}
</Button> */}
- <Button onClick={() => setShowDelete(true)} disabled={isDeleting} danger semiSmall>
+ <Button
+ onClick={() => setShowDelete(true)}
+ disabled={isDeleting}
+ danger
+ semiSmall
+ >
<Trash2Icon className='mr-1 h-5 w-5' strokeWidth={1.5} />
{t('organisations.delete')}
</Button>
diff --git a/web/app/pages/Performance/index.tsx b/web/app/pages/Performance/index.tsx
index 3cf3d8e05..22e588c4f 100644
--- a/web/app/pages/Performance/index.tsx
+++ b/web/app/pages/Performance/index.tsx
@@ -19,7 +19,10 @@ const Performance = () => {
<main className='bg-gray-50 dark:bg-slate-900'>
<div className='relative isolate bg-gray-100/80 pt-2 dark:bg-slate-800/50'>
<div className='relative mx-2 overflow-hidden rounded-4xl'>
- <div aria-hidden className='pointer-events-none absolute inset-0 -z-10'>
+ <div
+ aria-hidden
+ className='pointer-events-none absolute inset-0 -z-10'
+ >
<div className='absolute inset-0 rounded-4xl bg-linear-115 from-amber-200 from-15% via-orange-400 via-70% to-orange-700 opacity-50 ring-1 ring-black/5 ring-inset sm:bg-linear-145 dark:from-slate-600 dark:opacity-60' />
</div>
<Header transparent />
@@ -55,7 +58,11 @@ const Performance = () => {
<div className='col-span-6 mt-10 overflow-visible lg:mt-0 lg:mr-0 lg:ml-4'>
<div className='relative z-20 mx-auto mt-10 overflow-hidden rounded-xl ring-2 ring-gray-900/10 lg:hidden dark:ring-white/10'>
<img
- src={theme === 'dark' ? '/assets/screenshot_perf_dark.png' : '/assets/screenshot_perf_light.png'}
+ src={
+ theme === 'dark'
+ ? '/assets/screenshot_perf_dark.png'
+ : '/assets/screenshot_perf_light.png'
+ }
className='relative w-full'
width='100%'
height='auto'
@@ -77,7 +84,11 @@ const Performance = () => {
<div className='group relative -mr-6 hidden w-[140%] overflow-hidden rounded-2xl bg-white shadow-2xl ring-1 ring-black/5 transition-shadow ease-out hover:ring-indigo-300/50 sm:-mr-12 sm:w-[160%] lg:-mr-16 lg:block lg:w-[180%] xl:-mr-24 2xl:-mr-32 dark:bg-slate-800 dark:ring-white/10 dark:hover:ring-indigo-400/40'>
<div className='relative h-[580px] lg:h-[640px] xl:h-[700px]'>
<img
- src={theme === 'dark' ? '/assets/screenshot_perf_dark.png' : '/assets/screenshot_perf_light.png'}
+ src={
+ theme === 'dark'
+ ? '/assets/screenshot_perf_dark.png'
+ : '/assets/screenshot_perf_light.png'
+ }
className='size-full object-cover object-left'
alt='Swetrix Analytics dashboard'
/>
@@ -101,7 +112,9 @@ const Performance = () => {
</div>
<div className='mx-auto mt-12 max-w-7xl bg-white px-4 pb-16 whitespace-pre-line dark:bg-slate-900'>
- <h2 className='text-4xl font-extrabold text-slate-900 dark:text-white'>{t('performance.fast.title')}</h2>
+ <h2 className='text-4xl font-extrabold text-slate-900 dark:text-white'>
+ {t('performance.fast.title')}
+ </h2>
<p className='mt-6 text-lg text-gray-900 dark:text-gray-50'>
<Trans
t={t}
@@ -126,22 +139,29 @@ const Performance = () => {
/>
</p>
<ul className='mt-2 list-inside list-disc text-lg text-gray-900 dark:text-gray-50'>
- {_map(t('performance.fast.list', { returnObjects: true }), (item) => (
- <li key={item} className='mb-2'>
- {item}
- </li>
- ))}
+ {_map(
+ t('performance.fast.list', { returnObjects: true }),
+ (item) => (
+ <li key={item} className='mb-2'>
+ {item}
+ </li>
+ ),
+ )}
</ul>
<h2 className='mt-10 text-4xl font-extrabold text-slate-900 dark:text-white'>
{t('performance.metrics.title')}
</h2>
- <p className='mt-6 text-lg text-gray-900 dark:text-gray-50'>{t('performance.metrics.desc')}</p>
+ <p className='mt-6 text-lg text-gray-900 dark:text-gray-50'>
+ {t('performance.metrics.desc')}
+ </p>
<h2 className='mt-10 text-4xl font-extrabold text-slate-900 dark:text-white'>
{t('performance.privacy.title')}
</h2>
- <p className='mt-6 text-lg text-gray-900 dark:text-gray-50'>{t('performance.privacy.desc')}</p>
+ <p className='mt-6 text-lg text-gray-900 dark:text-gray-50'>
+ {t('performance.privacy.desc')}
+ </p>
</div>
<MarketingPricing />
diff --git a/web/app/pages/Project/Settings/Annotations.tsx b/web/app/pages/Project/Settings/Annotations.tsx
index bc493ccb1..e82142b84 100644
--- a/web/app/pages/Project/Settings/Annotations.tsx
+++ b/web/app/pages/Project/Settings/Annotations.tsx
@@ -33,13 +33,19 @@ const Annotations = ({ projectId, allowedToManage }: AnnotationsProps) => {
// Modal states
const [isModalOpen, setIsModalOpen] = useState(false)
- const [editingAnnotation, setEditingAnnotation] = useState<Annotation | undefined>()
- const [deleteAnnotationItem, setDeleteAnnotationItem] = useState<Annotation | null>(null)
+ const [editingAnnotation, setEditingAnnotation] = useState<
+ Annotation | undefined
+ >()
+ const [deleteAnnotationItem, setDeleteAnnotationItem] =
+ useState<Annotation | null>(null)
const actionLoading = fetcher.state !== 'idle'
const loadAnnotations = useCallback(() => {
- fetcher.submit({ intent: 'get-annotations', password: '' }, { method: 'POST', action: `/projects/${projectId}` })
+ fetcher.submit(
+ { intent: 'get-annotations', password: '' },
+ { method: 'POST', action: `/projects/${projectId}` },
+ )
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [projectId])
@@ -54,9 +60,14 @@ const Annotations = ({ projectId, allowedToManage }: AnnotationsProps) => {
if (success) {
if (intent === 'get-annotations' && data) {
const result = data as Annotation[]
- const sorted = result.sort((a, b) => new Date(b.date).getTime() - new Date(a.date).getTime())
+ const sorted = result.sort(
+ (a, b) => new Date(b.date).getTime() - new Date(a.date).getTime(),
+ )
setAnnotations(sorted)
- const totalPages = Math.max(1, Math.ceil(sorted.length / ANNOTATIONS_PER_PAGE))
+ const totalPages = Math.max(
+ 1,
+ Math.ceil(sorted.length / ANNOTATIONS_PER_PAGE),
+ )
setPage((prev) => Math.min(prev, totalPages))
setIsLoading(false)
} else if (intent === 'create-annotation') {
@@ -87,7 +98,10 @@ const Annotations = ({ projectId, allowedToManage }: AnnotationsProps) => {
}, [loadAnnotations])
const totalPages = Math.ceil(_size(annotations) / ANNOTATIONS_PER_PAGE)
- const paginatedAnnotations = annotations.slice((page - 1) * ANNOTATIONS_PER_PAGE, page * ANNOTATIONS_PER_PAGE)
+ const paginatedAnnotations = annotations.slice(
+ (page - 1) * ANNOTATIONS_PER_PAGE,
+ page * ANNOTATIONS_PER_PAGE,
+ )
const openCreateModal = () => {
setEditingAnnotation(undefined)
@@ -109,11 +123,19 @@ const Annotations = ({ projectId, allowedToManage }: AnnotationsProps) => {
if (editingAnnotation) {
fetcher.submit(
- { intent: 'update-annotation', annotationId: editingAnnotation.id, date, text },
+ {
+ intent: 'update-annotation',
+ annotationId: editingAnnotation.id,
+ date,
+ text,
+ },
{ method: 'POST', action: `/projects/${projectId}` },
)
} else {
- fetcher.submit({ intent: 'create-annotation', date, text }, { method: 'POST', action: `/projects/${projectId}` })
+ fetcher.submit(
+ { intent: 'create-annotation', date, text },
+ { method: 'POST', action: `/projects/${projectId}` },
+ )
}
}
@@ -164,9 +186,17 @@ const Annotations = ({ projectId, allowedToManage }: AnnotationsProps) => {
{_isEmpty(annotations) ? (
<div className='rounded-lg border border-dashed border-gray-300 p-8 text-center dark:border-slate-700'>
- <p className='text-gray-500 dark:text-gray-400'>{t('project.settings.annotations.empty')}</p>
+ <p className='text-gray-500 dark:text-gray-400'>
+ {t('project.settings.annotations.empty')}
+ </p>
{allowedToManage ? (
- <Button type='button' onClick={openCreateModal} className='mt-4' primary regular>
+ <Button
+ type='button'
+ onClick={openCreateModal}
+ className='mt-4'
+ primary
+ regular
+ >
<PlusIcon className='mr-1 h-4 w-4' />
{t('project.settings.annotations.addFirst')}
</Button>
@@ -195,7 +225,10 @@ const Annotations = ({ projectId, allowedToManage }: AnnotationsProps) => {
</thead>
<tbody className='divide-y divide-gray-200 bg-white dark:divide-slate-700 dark:bg-slate-900'>
{_map(paginatedAnnotations, (annotation) => (
- <tr key={annotation.id} className='hover:bg-gray-50 dark:hover:bg-slate-800/50'>
+ <tr
+ key={annotation.id}
+ className='hover:bg-gray-50 dark:hover:bg-slate-800/50'
+ >
<td className='px-4 py-3 text-sm whitespace-nowrap text-gray-900 dark:text-gray-100'>
{new Date(annotation.date).toLocaleDateString()}
</td>
@@ -232,7 +265,12 @@ const Annotations = ({ projectId, allowedToManage }: AnnotationsProps) => {
{totalPages > 1 ? (
<div className='mt-4 flex justify-center'>
- <Pagination page={page} setPage={setPage} pageAmount={totalPages} total={_size(annotations)} />
+ <Pagination
+ page={page}
+ setPage={setPage}
+ pageAmount={totalPages}
+ total={_size(annotations)}
+ />
</div>
) : null}
</>
diff --git a/web/app/pages/Project/Settings/Emails/Emails.tsx b/web/app/pages/Project/Settings/Emails/Emails.tsx
index d4f2c13f9..d9c1629d7 100644
--- a/web/app/pages/Project/Settings/Emails/Emails.tsx
+++ b/web/app/pages/Project/Settings/Emails/Emails.tsx
@@ -36,13 +36,22 @@ interface ModalMessageProps {
}
}
-const ModalMessage = ({ handleInput, beenSubmitted, errors, form }: ModalMessageProps) => {
+const ModalMessage = ({
+ handleInput,
+ beenSubmitted,
+ errors,
+ form,
+}: ModalMessageProps) => {
const { t } = useTranslation('common')
return (
<div>
- <h2 className='text-xl font-bold text-gray-700 dark:text-gray-200'>{t('project.settings.addARecipient')}</h2>
- <p className='mt-2 text-base text-gray-700 dark:text-gray-200'>{t('project.settings.addARecipientDesc')}</p>
+ <h2 className='text-xl font-bold text-gray-700 dark:text-gray-200'>
+ {t('project.settings.addARecipient')}
+ </h2>
+ <p className='mt-2 text-base text-gray-700 dark:text-gray-200'>
+ {t('project.settings.addARecipientDesc')}
+ </p>
<Input
name='email'
type='email'
@@ -58,9 +67,12 @@ const ModalMessage = ({ handleInput, beenSubmitted, errors, form }: ModalMessage
{t('project.emails.reportFrequency')}
</legend>
<div
- className={cx('mt-1 -space-y-px rounded-md bg-white dark:bg-slate-900', {
- 'border border-red-300': errors.reportFrequency,
- })}
+ className={cx(
+ 'mt-1 -space-y-px rounded-md bg-white dark:bg-slate-900',
+ {
+ 'border border-red-300': errors.reportFrequency,
+ },
+ )}
>
{reportFrequencyForEmailsOptions.map((item, index) => (
<ReportFrequencyOption
@@ -74,7 +86,10 @@ const ModalMessage = ({ handleInput, beenSubmitted, errors, form }: ModalMessage
))}
</div>
{errors.reportFrequency ? (
- <p className='mt-2 text-sm text-red-600 dark:text-red-500' id='reportFrequency-error'>
+ <p
+ className='mt-2 text-sm text-red-600 dark:text-red-500'
+ id='reportFrequency-error'
+ >
{errors.reportFrequency}
</p>
) : null}
@@ -91,18 +106,27 @@ interface ReportFrequencyOptionProps {
totalOptions: number
}
-const ReportFrequencyOption = ({ item, index, form, handleInput, totalOptions }: ReportFrequencyOptionProps) => {
+const ReportFrequencyOption = ({
+ item,
+ index,
+ form,
+ handleInput,
+ totalOptions,
+}: ReportFrequencyOptionProps) => {
const { t } = useTranslation('common')
return (
<label
- className={cx('relative flex cursor-pointer border border-gray-200 p-4 dark:border-slate-600', {
- 'z-10 border-indigo-200 bg-indigo-50 dark:border-indigo-800/40 dark:bg-indigo-600/40':
- item.value === form.reportFrequency,
- 'border-gray-200': form.reportFrequency !== item.value,
- 'rounded-t-md': index === 0,
- 'rounded-b-md': index === totalOptions - 1,
- })}
+ className={cx(
+ 'relative flex cursor-pointer border border-gray-200 p-4 dark:border-slate-600',
+ {
+ 'z-10 border-indigo-200 bg-indigo-50 dark:border-indigo-800/40 dark:bg-indigo-600/40':
+ item.value === form.reportFrequency,
+ 'border-gray-200': form.reportFrequency !== item.value,
+ 'rounded-t-md': index === 0,
+ 'rounded-b-md': index === totalOptions - 1,
+ },
+ )}
>
<input
name='reportFrequency'
@@ -114,8 +138,10 @@ const ReportFrequencyOption = ({ item, index, form, handleInput, totalOptions }:
/>
<span
className={cx('ml-3 block text-sm font-medium', {
- 'text-indigo-900 dark:text-white': form.reportFrequency === item.value,
- 'text-gray-700 dark:text-gray-200': form.reportFrequency !== item.value,
+ 'text-indigo-900 dark:text-white':
+ form.reportFrequency === item.value,
+ 'text-gray-700 dark:text-gray-200':
+ form.reportFrequency !== item.value,
})}
>
{t(`profileSettings.${item.value}`)}
@@ -134,7 +160,9 @@ interface EmailListProps {
reportFrequency: string
}
onRemove: () => void
- setEmails: (value: Subscriber[] | ((prevVar: Subscriber[]) => Subscriber[])) => void
+ setEmails: (
+ value: Subscriber[] | ((prevVar: Subscriber[]) => Subscriber[]),
+ ) => void
}
const EmailList = ({ data, onRemove, setEmails }: EmailListProps) => {
@@ -153,7 +181,9 @@ const EmailList = ({ data, onRemove, setEmails }: EmailListProps) => {
if (fetcher.data?.intent === 'update-subscriber') {
if (fetcher.data.success && fetcher.data.subscriber) {
const updated = fetcher.data.subscriber
- setEmails((prev) => _map(prev, (item) => (item.id === updated.id ? updated : item)))
+ setEmails((prev) =>
+ _map(prev, (item) => (item.id === updated.id ? updated : item)),
+ )
toast.success(t('apiNotifications.updatedPeriodEmailReports'))
} else if (fetcher.data.error) {
toast.error(
@@ -167,7 +197,11 @@ const EmailList = ({ data, onRemove, setEmails }: EmailListProps) => {
const changeRole = (reportType: { value: string; label: string }) => {
fetcher.submit(
- { intent: 'update-subscriber', subscriberId: id, reportFrequency: reportType.value },
+ {
+ intent: 'update-subscriber',
+ subscriberId: id,
+ reportFrequency: reportType.value,
+ },
{ method: 'post', action: `/projects/settings/${projectId}` },
)
setOpen(false)
@@ -175,7 +209,9 @@ const EmailList = ({ data, onRemove, setEmails }: EmailListProps) => {
return (
<tr className='bg-white hover:bg-gray-50 dark:bg-slate-900 dark:hover:bg-slate-800/50'>
- <td className='px-4 py-3 text-sm whitespace-nowrap text-gray-900 dark:text-gray-100'>{email}</td>
+ <td className='px-4 py-3 text-sm whitespace-nowrap text-gray-900 dark:text-gray-100'>
+ {email}
+ </td>
<td className='px-4 py-3 text-sm whitespace-nowrap text-gray-900 dark:text-gray-100'>
{language === 'en'
? dayjs(addedAt).locale(language).format('MMMM D, YYYY')
@@ -190,7 +226,10 @@ const EmailList = ({ data, onRemove, setEmails }: EmailListProps) => {
className='inline-flex items-center rounded-full border border-gray-200 bg-white py-0.5 pr-1 pl-2 text-sm leading-5 font-medium text-gray-700 hover:bg-gray-50 dark:border-gray-600 dark:bg-slate-800 dark:text-gray-200 dark:hover:bg-gray-600'
>
{t(`profileSettings.${_toLower(reportFrequency)}`)}
- <ChevronDownIcon style={{ transform: open ? 'rotate(180deg)' : '' }} className='ml-0.5 h-4 w-4 pt-px' />
+ <ChevronDownIcon
+ style={{ transform: open ? 'rotate(180deg)' : '' }}
+ className='ml-0.5 h-4 w-4 pt-px'
+ />
</button>
{open ? (
<ul
@@ -222,14 +261,20 @@ const EmailList = ({ data, onRemove, setEmails }: EmailListProps) => {
onClick={onRemove}
className='group flex cursor-pointer items-center justify-between rounded-b-md p-4 hover:bg-gray-200 dark:hover:bg-gray-700'
>
- <p className='font-bold text-red-600 dark:text-red-500'>{t('project.settings.removeMember')}</p>
+ <p className='font-bold text-red-600 dark:text-red-500'>
+ {t('project.settings.removeMember')}
+ </p>
</li>
</ul>
) : null}
</div>
) : (
<div className='flex items-center justify-end'>
- <Badge colour='yellow' className='mr-3' label={t('common.pending')} />
+ <Badge
+ colour='yellow'
+ className='mr-3'
+ label={t('common.pending')}
+ />
<Button
type='button'
className='rounded-md bg-white text-base font-medium text-indigo-700 hover:bg-indigo-50 dark:border-gray-600 dark:bg-slate-800 dark:text-gray-50 dark:hover:bg-slate-700'
@@ -251,7 +296,9 @@ const NoSubscribers = () => {
return (
<div className='flex flex-col py-6 sm:px-6 lg:px-8'>
<div className='mx-auto w-full max-w-7xl text-gray-900 dark:text-gray-50'>
- <h2 className='mb-8 px-4 text-center text-xl leading-snug'>{t('project.settings.noPeople')}</h2>
+ <h2 className='mb-8 px-4 text-center text-xl leading-snug'>
+ {t('project.settings.noPeople')}
+ </h2>
</div>
</div>
)
@@ -292,7 +339,11 @@ const Emails = ({ projectId }: { projectId: string }) => {
useEffect(() => {
loadFetcher.submit(
- { intent: 'get-subscribers', offset: String(pagination.page - 1), limit: String(pagination.limit) },
+ {
+ intent: 'get-subscribers',
+ offset: String(pagination.page - 1),
+ limit: String(pagination.limit),
+ },
{ method: 'post', action: `/projects/settings/${projectId}` },
)
}, []) // eslint-disable-line
@@ -302,7 +353,10 @@ const Emails = ({ projectId }: { projectId: string }) => {
if (loadFetcher.data.success) {
setTimeout(() => {
setEmails(loadFetcher.data!.subscribers || [])
- setPagination((old) => ({ ...old, total: loadFetcher.data!.subscribersCount || 0 }))
+ setPagination((old) => ({
+ ...old,
+ total: loadFetcher.data!.subscribersCount || 0,
+ }))
}, 0)
}
setTimeout(() => setLoading(false), 0)
@@ -312,16 +366,26 @@ const Emails = ({ projectId }: { projectId: string }) => {
useEffect(() => {
if (fetcher.data?.intent === 'add-subscriber') {
if (fetcher.data.success && fetcher.data.subscriber) {
- setTimeout(() => setEmails((prev) => [...prev, fetcher.data!.subscriber!]), 0)
+ setTimeout(
+ () => setEmails((prev) => [...prev, fetcher.data!.subscriber!]),
+ 0,
+ )
toast.success(t('apiNotifications.userInvited'))
} else if (fetcher.data.error) {
- toast.error(typeof fetcher.data.error === 'string' ? fetcher.data.error : t('apiNotifications.userInviteError'))
+ toast.error(
+ typeof fetcher.data.error === 'string'
+ ? fetcher.data.error
+ : t('apiNotifications.userInviteError'),
+ )
}
}
}, [fetcher.data, t])
useEffect(() => {
- if (removeFetcher.state === 'idle' && removeFetcher.data?.intent === 'remove-subscriber') {
+ if (
+ removeFetcher.state === 'idle' &&
+ removeFetcher.data?.intent === 'remove-subscriber'
+ ) {
if (removeFetcher.data.success) {
const capturedId = removingEmailId.current
setTimeout(() => {
@@ -378,11 +442,22 @@ const Emails = ({ projectId }: { projectId: string }) => {
setValidated(false)
fetcher.submit(
- { intent: 'add-subscriber', email: form.email, reportFrequency: form.reportFrequency },
+ {
+ intent: 'add-subscriber',
+ email: form.email,
+ reportFrequency: form.reportFrequency,
+ },
{ method: 'post', action: `/projects/settings/${projectId}` },
)
- setTimeout(() => setForm({ email: '', reportFrequency: reportFrequencyForEmailsOptions[3].value }), 300)
+ setTimeout(
+ () =>
+ setForm({
+ email: '',
+ reportFrequency: reportFrequencyForEmailsOptions[3].value,
+ }),
+ 300,
+ )
}
const handleSubmit = (e: React.MouseEvent<HTMLButtonElement, MouseEvent>) => {
@@ -401,7 +476,14 @@ const Emails = ({ projectId }: { projectId: string }) => {
setShowModal(false)
setBeenSubmitted(false)
// a timeout is needed to prevent the flicker of data fields in the modal when closing
- setTimeout(() => setForm({ email: '', reportFrequency: reportFrequencyForEmailsOptions[3].value }), 300)
+ setTimeout(
+ () =>
+ setForm({
+ email: '',
+ reportFrequency: reportFrequencyForEmailsOptions[3].value,
+ }),
+ 300,
+ )
setErrors({})
}
@@ -421,10 +503,20 @@ const Emails = ({ projectId }: { projectId: string }) => {
<div>
<div className='mb-3 flex flex-col items-start justify-between gap-y-2 sm:flex-row sm:items-center'>
<div>
- <h3 className='text-lg font-bold text-gray-900 dark:text-gray-50'>{t('project.emails.title')}</h3>
- <p className='text-sm text-gray-500 dark:text-gray-400'>{t('project.emails.description')}</p>
+ <h3 className='text-lg font-bold text-gray-900 dark:text-gray-50'>
+ {t('project.emails.title')}
+ </h3>
+ <p className='text-sm text-gray-500 dark:text-gray-400'>
+ {t('project.emails.description')}
+ </p>
</div>
- <Button className='h-8 pl-2 whitespace-nowrap' primary regular type='button' onClick={() => setShowModal(true)}>
+ <Button
+ className='h-8 pl-2 whitespace-nowrap'
+ primary
+ regular
+ type='button'
+ onClick={() => setShowModal(true)}
+ >
<>
<MailPlusIcon className='mr-1 h-5 w-5' strokeWidth={1.5} />
{t('project.emails.add')}
@@ -487,7 +579,14 @@ const Emails = ({ projectId }: { projectId: string }) => {
</button>
}
closeText={t('common.cancel')}
- message={<ModalMessage form={form} handleInput={handleInput} errors={errors} beenSubmitted={beenSubmitted} />}
+ message={
+ <ModalMessage
+ form={form}
+ handleInput={handleInput}
+ errors={errors}
+ beenSubmitted={beenSubmitted}
+ />
+ }
isOpened={showModal}
/>
diff --git a/web/app/pages/Project/Settings/People/People.tsx b/web/app/pages/Project/Settings/People/People.tsx
index 95841df5e..aa0c89404 100644
--- a/web/app/pages/Project/Settings/People/People.tsx
+++ b/web/app/pages/Project/Settings/People/People.tsx
@@ -29,7 +29,9 @@ const NoPeople = () => {
return (
<div className='flex flex-col py-6 sm:px-6 lg:px-8'>
<div className='mx-auto w-full max-w-7xl text-gray-900 dark:text-gray-50'>
- <h2 className='mb-8 px-4 text-center text-xl leading-snug'>{t('project.settings.noPeople')}</h2>
+ <h2 className='mb-8 px-4 text-center text-xl leading-snug'>
+ {t('project.settings.noPeople')}
+ </h2>
</div>
</div>
)
@@ -43,7 +45,13 @@ interface TableUserRowProps {
projectId: string
}
-const TableUserRow = ({ data, onRemove, language, authedUserEmail, projectId }: TableUserRowProps) => {
+const TableUserRow = ({
+ data,
+ onRemove,
+ language,
+ authedUserEmail,
+ projectId,
+}: TableUserRowProps) => {
const { t } = useTranslation('common')
const [open, setOpen] = useState(false)
const openRef = useRef<HTMLUListElement>(null)
@@ -75,7 +83,9 @@ const TableUserRow = ({ data, onRemove, language, authedUserEmail, projectId }:
return (
<tr className='bg-white hover:bg-gray-50 dark:bg-slate-900 dark:hover:bg-slate-800/50'>
- <td className='px-4 py-3 text-sm whitespace-nowrap text-gray-900 dark:text-gray-100'>{user?.email || 'N/A'}</td>
+ <td className='px-4 py-3 text-sm whitespace-nowrap text-gray-900 dark:text-gray-100'>
+ {user?.email || 'N/A'}
+ </td>
<td className='px-4 py-3 text-sm whitespace-nowrap text-gray-900 dark:text-gray-100'>
{language === 'en'
? dayjs(created).locale(language).format('MMMM D, YYYY')
@@ -91,7 +101,10 @@ const TableUserRow = ({ data, onRemove, language, authedUserEmail, projectId }:
className='inline-flex items-center rounded-full border border-gray-200 bg-white py-0.5 pr-1 pl-2 text-sm leading-5 font-medium text-gray-700 hover:bg-gray-50 disabled:cursor-not-allowed disabled:opacity-80 dark:border-gray-600 dark:bg-slate-800 dark:text-gray-200 dark:hover:bg-gray-600'
>
{t(`project.settings.roles.${role}.name`)}
- <ChevronDownIcon style={{ transform: open ? 'rotate(180deg)' : '' }} className='ml-0.5 h-4 w-4 pt-px' />
+ <ChevronDownIcon
+ style={{ transform: open ? 'rotate(180deg)' : '' }}
+ className='ml-0.5 h-4 w-4 pt-px'
+ />
</button>
{open ? (
<ul
@@ -126,14 +139,20 @@ const TableUserRow = ({ data, onRemove, language, authedUserEmail, projectId }:
onClick={onRemove}
className='group flex cursor-pointer items-center justify-between rounded-b-md p-4 hover:bg-gray-200 dark:hover:bg-gray-700'
>
- <p className='font-bold text-red-600 dark:text-red-500'>{t('project.settings.removeMember')}</p>
+ <p className='font-bold text-red-600 dark:text-red-500'>
+ {t('project.settings.removeMember')}
+ </p>
</li>
</ul>
) : null}
</div>
) : (
<div className='flex items-center justify-end'>
- <Badge colour='yellow' className='mr-3' label={t('common.pending')} />
+ <Badge
+ colour='yellow'
+ className='mr-3'
+ label={t('common.pending')}
+ />
<Button
type='button'
className='rounded-md bg-white text-base font-medium text-indigo-700 hover:bg-indigo-50 dark:border-gray-600 dark:bg-slate-800 dark:text-gray-50 dark:hover:bg-slate-700'
@@ -178,7 +197,8 @@ const People = ({ project }: PeopleProps) => {
const [validated, setValidated] = useState(false)
const [showDeleteModal, setShowDeleteModal] = useState(false)
- const [memberToRemove, setMemberToRemove] = useState<ShareOwnerProject | null>(null)
+ const [memberToRemove, setMemberToRemove] =
+ useState<ShareOwnerProject | null>(null)
const { id, name, share } = project
@@ -289,9 +309,17 @@ const People = ({ project }: PeopleProps) => {
<h3 className='flex items-center text-lg font-bold text-gray-900 dark:text-gray-50'>
{t('project.settings.people')}
</h3>
- <p className='text-sm text-gray-500 dark:text-gray-400'>{t('project.settings.inviteCoworkers')}</p>
+ <p className='text-sm text-gray-500 dark:text-gray-400'>
+ {t('project.settings.inviteCoworkers')}
+ </p>
</div>
- <Button className='h-8 pl-2' primary regular type='button' onClick={() => setShowModal(true)}>
+ <Button
+ className='h-8 pl-2'
+ primary
+ regular
+ type='button'
+ onClick={() => setShowModal(true)}
+ >
<>
<UserRoundPlusIcon className='mr-1 h-5 w-5' strokeWidth={1.5} />
{t('project.settings.invite')}
@@ -340,7 +368,10 @@ const People = ({ project }: PeopleProps) => {
</div>
)}
</div>
- <PaidFeature isOpened={isPaidFeatureOpened} onClose={() => setIsPaidFeatureOpened(false)} />
+ <PaidFeature
+ isOpened={isPaidFeatureOpened}
+ onClose={() => setIsPaidFeatureOpened(false)}
+ />
<Modal
onClose={() => {
setShowDeleteModal(false)
@@ -353,10 +384,16 @@ const People = ({ project }: PeopleProps) => {
submitText={t('common.yes')}
type='confirmed'
closeText={t('common.no')}
- title={t('project.settings.removeUser', { user: memberToRemove?.user?.email })}
+ title={t('project.settings.removeUser', {
+ user: memberToRemove?.user?.email,
+ })}
message={t('project.settings.removeConfirm')}
isOpened={showDeleteModal}
- isLoading={isSubmitting ? fetcher.formData?.get('intent') === 'delete-share-user' : undefined}
+ isLoading={
+ isSubmitting
+ ? fetcher.formData?.get('intent') === 'delete-share-user'
+ : undefined
+ }
/>
<Modal
onClose={closeModal}
@@ -376,10 +413,16 @@ const People = ({ project }: PeopleProps) => {
{t('project.settings.inviteTo', { project: name })}
</h2>
<p className='mt-2 text-base text-gray-700 dark:text-gray-200'>
- {t(isSelfhosted ? 'project.settings.inviteDescSelfhosted' : 'project.settings.inviteDesc')}
+ {t(
+ isSelfhosted
+ ? 'project.settings.inviteDescSelfhosted'
+ : 'project.settings.inviteDesc',
+ )}
</p>
<p className='mt-2 text-base text-gray-700 dark:text-gray-200'>
- {t('project.settings.inviteExpity', { amount: INVITATION_EXPIRES_IN })}
+ {t('project.settings.inviteExpity', {
+ amount: INVITATION_EXPIRES_IN,
+ })}
</p>
<Input
name='email'
@@ -393,13 +436,19 @@ const People = ({ project }: PeopleProps) => {
/>
<fieldset className='mt-4'>
{}
- <label className='block text-sm font-medium text-gray-700 dark:text-gray-300' htmlFor='role'>
+ <label
+ className='block text-sm font-medium text-gray-700 dark:text-gray-300'
+ htmlFor='role'
+ >
{t('project.settings.role')}
</label>
<div
- className={cx('mt-1 -space-y-px rounded-md bg-white dark:bg-slate-900', {
- 'border border-red-300': errors.role,
- })}
+ className={cx(
+ 'mt-1 -space-y-px rounded-md bg-white dark:bg-slate-900',
+ {
+ 'border border-red-300': errors.role,
+ },
+ )}
>
{/* eslint-disable-next-line jsx-a11y/label-has-associated-control */}
<label
@@ -424,16 +473,20 @@ const People = ({ project }: PeopleProps) => {
<div className='ml-3 flex flex-col'>
<span
className={cx('block text-sm font-medium', {
- 'text-indigo-900 dark:text-white': form.role === 'admin',
- 'text-gray-700 dark:text-gray-200': form.role !== 'admin',
+ 'text-indigo-900 dark:text-white':
+ form.role === 'admin',
+ 'text-gray-700 dark:text-gray-200':
+ form.role !== 'admin',
})}
>
{t('project.settings.roles.admin.name')}
</span>
<span
className={cx('block text-sm', {
- 'text-indigo-700 dark:text-gray-100': form.role === 'admin',
- 'text-gray-700 dark:text-gray-200': form.role !== 'admin',
+ 'text-indigo-700 dark:text-gray-100':
+ form.role === 'admin',
+ 'text-gray-700 dark:text-gray-200':
+ form.role !== 'admin',
})}
>
{t('project.settings.roles.admin.desc')}
@@ -463,16 +516,20 @@ const People = ({ project }: PeopleProps) => {
<div className='ml-3 flex flex-col'>
<span
className={cx('block text-sm font-medium', {
- 'text-indigo-900 dark:text-white': form.role === 'viewer',
- 'text-gray-700 dark:text-gray-200': form.role !== 'viewer',
+ 'text-indigo-900 dark:text-white':
+ form.role === 'viewer',
+ 'text-gray-700 dark:text-gray-200':
+ form.role !== 'viewer',
})}
>
{t('project.settings.roles.viewer.name')}
</span>
<span
className={cx('block text-sm', {
- 'text-indigo-700 dark:text-gray-100': form.role === 'viewer',
- 'text-gray-700 dark:text-gray-200': form.role !== 'viewer',
+ 'text-indigo-700 dark:text-gray-100':
+ form.role === 'viewer',
+ 'text-gray-700 dark:text-gray-200':
+ form.role !== 'viewer',
})}
>
{t('project.settings.roles.viewer.desc')}
@@ -481,7 +538,10 @@ const People = ({ project }: PeopleProps) => {
</label>
</div>
{errors.role ? (
- <p className='mt-2 text-sm text-red-600 dark:text-red-500' id='email-error'>
+ <p
+ className='mt-2 text-sm text-red-600 dark:text-red-500'
+ id='email-error'
+ >
{errors.role}
</p>
) : null}
diff --git a/web/app/pages/Project/Settings/ProjectSettings.tsx b/web/app/pages/Project/Settings/ProjectSettings.tsx
index 7290f7058..52f922532 100644
--- a/web/app/pages/Project/Settings/ProjectSettings.tsx
+++ b/web/app/pages/Project/Settings/ProjectSettings.tsx
@@ -24,12 +24,23 @@ import {
} from 'lucide-react'
import React, { useState, useEffect, useMemo, useRef } from 'react'
import { Trans, useTranslation } from 'react-i18next'
-import { useLoaderData, useNavigate, Link, useSearchParams, useFetcher } from 'react-router'
+import {
+ useLoaderData,
+ useNavigate,
+ Link,
+ useSearchParams,
+ useFetcher,
+} from 'react-router'
import { toast } from 'sonner'
import { useFiltersProxy } from '~/hooks/useAnalyticsProxy'
import { useRequiredParams } from '~/hooks/useRequiredParams'
-import { isSelfhosted, TITLE_SUFFIX, FILTERS_PANELS_ORDER, isBrowser } from '~/lib/constants'
+import {
+ isSelfhosted,
+ TITLE_SUFFIX,
+ FILTERS_PANELS_ORDER,
+ isBrowser,
+} from '~/lib/constants'
import { Project } from '~/lib/models/Project'
import { useAuth } from '~/providers/AuthProvider'
import type { ProjectSettingsActionData } from '~/routes/projects.settings.$id'
@@ -87,7 +98,10 @@ interface ModalMessageProps {
setActiveFilter: any
filterType: string
setFilterType: (a: string) => void
- fetchFilters: (projectId: string, filterType: string) => Promise<string[] | null>
+ fetchFilters: (
+ projectId: string,
+ filterType: string,
+ ) => Promise<string[] | null>
}
const ModalMessage = ({
@@ -127,7 +141,9 @@ const ModalMessage = ({
return (
<>
- <p className='mt-1 mb-4 text-sm text-gray-500 italic dark:text-gray-300'>{t('project.settings.resetHint')}</p>
+ <p className='mt-1 mb-4 text-sm text-gray-500 italic dark:text-gray-300'>
+ {t('project.settings.resetHint')}
+ </p>
<div className='mt-6'>
<nav className='-mb-px flex space-x-6'>
{_map(DELETE_DATA_MODAL_TABS, (tabDelete) => (
@@ -135,11 +151,15 @@ const ModalMessage = ({
key={tabDelete.name}
type='button'
onClick={() => setTab(tabDelete.name)}
- className={cx('text-md border-b-2 px-1 pb-2 font-medium whitespace-nowrap', {
- 'border-indigo-500 text-indigo-600 dark:border-gray-50 dark:text-gray-50': tabDelete.name === tab,
- 'border-transparent text-gray-500 hover:border-gray-300 hover:text-gray-700 dark:text-gray-400 dark:hover:border-gray-300 dark:hover:text-gray-300':
- tab !== tabDelete.name,
- })}
+ className={cx(
+ 'text-md border-b-2 px-1 pb-2 font-medium whitespace-nowrap',
+ {
+ 'border-indigo-500 text-indigo-600 dark:border-gray-50 dark:text-gray-50':
+ tabDelete.name === tab,
+ 'border-transparent text-gray-500 hover:border-gray-300 hover:text-gray-700 dark:text-gray-400 dark:hover:border-gray-300 dark:hover:text-gray-300':
+ tab !== tabDelete.name,
+ },
+ )}
>
{t(tabDelete.title)}
</button>
@@ -183,7 +203,9 @@ const ModalMessage = ({
<Dropdown
className='min-w-[160px]'
title={
- !_isEmpty(filterType) ? t(`project.mapping.${filterType}`) : t('project.settings.reseted.selectFilters')
+ !_isEmpty(filterType)
+ ? t(`project.mapping.${filterType}`)
+ : t('project.settings.reseted.selectFilters')
}
items={FILTERS_PANELS_ORDER}
labelExtractor={(item) => t(`project.mapping.${item}`)}
@@ -216,13 +238,20 @@ const ModalMessage = ({
if (filterType === 'cc') {
setSearchList(
_filter(filterList, (item) =>
- _includes(_toUpper(countries.getName(item, language)), _toUpper(search)),
+ _includes(
+ _toUpper(countries.getName(item, language)),
+ _toUpper(search),
+ ),
),
)
return
}
- setSearchList(_filter(filterList, (item) => _includes(_toUpper(item), _toUpper(search))))
+ setSearchList(
+ _filter(filterList, (item) =>
+ _includes(_toUpper(item), _toUpper(search)),
+ ),
+ )
} else {
setSearchList(filterList)
}
@@ -237,7 +266,9 @@ const ModalMessage = ({
})
}
onRemove={(item: string) =>
- setActiveFilter((oldItems: string[]) => _filter(oldItems, (i) => i !== item))
+ setActiveFilter((oldItems: string[]) =>
+ _filter(oldItems, (i) => i !== item),
+ )
}
/>
) : (
@@ -281,12 +312,15 @@ const ProjectSettings = () => {
id: initialProject.id,
public: initialProject.public || false,
isPasswordProtected: initialProject.isPasswordProtected || false,
- origins: _isString(initialProject.origins) ? initialProject.origins : _join(initialProject.origins, ', '),
+ origins: _isString(initialProject.origins)
+ ? initialProject.origins
+ : _join(initialProject.origins, ', '),
ipBlacklist: _isString(initialProject.ipBlacklist)
? initialProject.ipBlacklist
: _join(initialProject.ipBlacklist, ', '),
countryBlacklist: initialProject.countryBlacklist || [],
- botsProtectionLevel: (initialProject.botsProtectionLevel as 'off' | 'basic') || 'basic',
+ botsProtectionLevel:
+ (initialProject.botsProtectionLevel as 'off' | 'basic') || 'basic',
gscPropertyUri: initialProject.gscPropertyUri || null,
websiteUrl: initialProject.websiteUrl || null,
}))
@@ -329,9 +363,24 @@ const ProjectSettings = () => {
const tabs = useMemo(
() =>
[
- { id: 'general', label: t('project.settings.tabs.general'), icon: Settings2Icon, visible: true },
- { id: 'access', label: t('project.settings.tabs.access'), icon: LockIcon, visible: true },
- { id: 'shields', label: t('project.settings.tabs.shields'), icon: ShieldIcon, visible: true },
+ {
+ id: 'general',
+ label: t('project.settings.tabs.general'),
+ icon: Settings2Icon,
+ visible: true,
+ },
+ {
+ id: 'access',
+ label: t('project.settings.tabs.access'),
+ icon: LockIcon,
+ visible: true,
+ },
+ {
+ id: 'shields',
+ label: t('project.settings.tabs.shields'),
+ icon: ShieldIcon,
+ visible: true,
+ },
{
id: 'captcha',
label: t('project.settings.tabs.captcha'),
@@ -350,9 +399,24 @@ const ProjectSettings = () => {
icon: DollarSignIcon,
visible: !isSelfhosted,
},
- { id: 'emails', label: t('project.settings.tabs.emails'), icon: MailIcon, visible: !isSelfhosted },
- { id: 'people', label: t('project.settings.tabs.people'), icon: UserRoundIcon, visible: true },
- { id: 'annotations', label: t('project.settings.tabs.annotations'), icon: StickyNoteIcon, visible: true },
+ {
+ id: 'emails',
+ label: t('project.settings.tabs.emails'),
+ icon: MailIcon,
+ visible: !isSelfhosted,
+ },
+ {
+ id: 'people',
+ label: t('project.settings.tabs.people'),
+ icon: UserRoundIcon,
+ visible: true,
+ },
+ {
+ id: 'annotations',
+ label: t('project.settings.tabs.annotations'),
+ icon: StickyNoteIcon,
+ visible: true,
+ },
{
id: 'danger',
label: t('project.settings.tabs.danger'),
@@ -377,11 +441,15 @@ const ProjectSettings = () => {
// Google Search Console integration state
const [gscConnected, setGscConnected] = useState<boolean | null>(null)
- const [gscProperties, setGscProperties] = useState<{ siteUrl: string; permissionLevel?: string }[]>([])
+ const [gscProperties, setGscProperties] = useState<
+ { siteUrl: string; permissionLevel?: string }[]
+ >([])
const [gscEmail, setGscEmail] = useState<string | null>(null)
// CAPTCHA state
- const [captchaSecretKey, setCaptchaSecretKey] = useState<string | null>(() => initialProject.captchaSecretKey || null)
+ const [captchaSecretKey, setCaptchaSecretKey] = useState<string | null>(
+ () => initialProject.captchaSecretKey || null,
+ )
const [captchaDifficulty, setCaptchaDifficulty] = useState<number>(4)
const [showRegenerateSecret, setShowRegenerateSecret] = useState(false)
@@ -409,7 +477,9 @@ const ProjectSettings = () => {
name: t('common.notSet'),
},
...(user?.organisationMemberships || [])
- .filter((om) => om.confirmed && (om.role === 'admin' || om.role === 'owner'))
+ .filter(
+ (om) => om.confirmed && (om.role === 'admin' || om.role === 'owner'),
+ )
.map((om) => om.organisation),
],
[user?.organisationMemberships, t],
@@ -423,7 +493,9 @@ const ProjectSettings = () => {
}
const sharableLink = useMemo(() => {
- const origin = requestOrigin ?? (isBrowser ? window.location.origin : 'https://swetrix.com')
+ const origin =
+ requestOrigin ??
+ (isBrowser ? window.location.origin : 'https://swetrix.com')
return `${origin}/projects/${id}`
}, [requestOrigin, id])
@@ -440,7 +512,14 @@ const ProjectSettings = () => {
if (lastHandledGscData.current === gscFetcher.data) return
lastHandledGscData.current = gscFetcher.data
- const { intent, success, gscStatus, gscProperties: properties, gscAuthUrl, error: gscError } = gscFetcher.data
+ const {
+ intent,
+ success,
+ gscStatus,
+ gscProperties: properties,
+ gscAuthUrl,
+ error: gscError,
+ } = gscFetcher.data
if (success) {
if (intent === 'gsc-status' && gscStatus) {
@@ -486,7 +565,11 @@ const ProjectSettings = () => {
toast.success(t('project.settings.gsc.propertyConnected'))
}
} else if (gscError) {
- toast.error(typeof gscError === 'string' ? gscError : t('apiNotifications.somethingWentWrong'))
+ toast.error(
+ typeof gscError === 'string'
+ ? gscError
+ : t('apiNotifications.somethingWentWrong'),
+ )
setGscPropertiesPending(false)
}
}, [gscFetcher.state, gscFetcher.data, t])
@@ -518,21 +601,30 @@ 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))
+ setProject((prev) =>
+ prev ? { ...prev, ...updatedProject } : updatedProject,
+ )
}
setBeenSubmitted(false)
toast.success(t('project.settings.updated'))
} else if (intent === 'delete-project') {
toast.success(t('project.settings.deleted'))
navigate(routes.dashboard)
- } else if (intent === 'reset-project' || intent === 'delete-partially' || intent === 'reset-filters') {
+ } else if (
+ intent === 'reset-project' ||
+ intent === 'delete-partially' ||
+ intent === 'reset-filters'
+ ) {
toast.success(t('project.settings.resetSuccess'))
setShowReset(false)
} else if (intent === 'transfer-project') {
toast.success(t('apiNotifications.transferRequestSent'))
setShowTransfer(false)
setTransferEmail('')
- } else if (intent === 'regenerate-captcha-key' && updatedProject?.captchaSecretKey) {
+ } else if (
+ intent === 'regenerate-captcha-key' &&
+ updatedProject?.captchaSecretKey
+ ) {
setCaptchaSecretKey(updatedProject.captchaSecretKey)
toast.success(t('project.settings.updated'))
} else if (intent === 'assign-organisation') {
@@ -563,13 +655,19 @@ const ProjectSettings = () => {
formData.set('intent', 'update-project')
if (data.name) formData.set('name', data.name)
formData.set('public', data.public ? 'true' : 'false')
- formData.set('isPasswordProtected', data.isPasswordProtected ? '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.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 || '')
fetcher.submit(formData, { method: 'post' })
}
@@ -585,7 +683,12 @@ const ProjectSettings = () => {
fetcher.submit(formData, { method: 'post' })
}
- const onReset = (resetTab: string, dateRange?: Date[], filterType?: string, filterValue?: string[]) => {
+ const onReset = (
+ resetTab: string,
+ dateRange?: Date[],
+ filterType?: string,
+ filterValue?: string[],
+ ) => {
if (fetcher.state === 'submitting') return
setIsResetting(true)
@@ -597,7 +700,12 @@ const ProjectSettings = () => {
formData.set('intent', 'delete-partially')
formData.set('from', dateRange[0]?.toISOString() || '')
formData.set('to', dateRange[1]?.toISOString() || '')
- } else if (resetTab === 'viaFilters' && filterType && filterValue && filterValue.length > 0) {
+ } else if (
+ resetTab === 'viaFilters' &&
+ filterType &&
+ filterValue &&
+ filterValue.length > 0
+ ) {
formData.set('intent', 'reset-filters')
formData.set('type', filterType)
formData.set('value', JSON.stringify(filterValue))
@@ -661,15 +769,21 @@ const ProjectSettings = () => {
}
if (_size(form.name) > MAX_NAME_LENGTH) {
- allErrors.name = t('project.settings.pxCharsError', { amount: 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 })
+ 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 })
+ allErrors.ipBlacklist = t('project.settings.oxCharsError', {
+ amount: MAX_IPBLACKLIST_LENGTH,
+ })
}
// Validate websiteUrl if provided
@@ -752,7 +866,9 @@ const ProjectSettings = () => {
<ChevronLeftIcon className='mr-1 size-3' strokeWidth={1.5} />
{t('project.backToStats')}
</Link>
- <h2 className='mt-1 text-3xl font-bold text-gray-900 dark:text-gray-50'>{title}</h2>
+ <h2 className='mt-1 text-3xl font-bold text-gray-900 dark:text-gray-50'>
+ {title}
+ </h2>
<hr className='mt-5 border-gray-200 dark:border-gray-600' />
@@ -768,7 +884,9 @@ const ProjectSettings = () => {
const Icon = item.icon
return <Icon className='h-4 w-4' strokeWidth={1.5} />
}}
- onSelect={(item: any) => setActiveTab(item.id as typeof activeTab)}
+ onSelect={(item: any) =>
+ setActiveTab(item.id as typeof activeTab)
+ }
selectedItem={tabs.find((tab) => tab.id === activeTab)}
/>
</div>
@@ -787,7 +905,8 @@ const ProjectSettings = () => {
className={cx(
'group flex items-center rounded-md px-3 py-2 text-left text-sm text-gray-900 transition-colors',
{
- 'bg-gray-200 font-semibold dark:bg-slate-800 dark:text-gray-50': isCurrent,
+ 'bg-gray-200 font-semibold dark:bg-slate-800 dark:text-gray-50':
+ isCurrent,
'hover:bg-gray-200 dark:text-gray-200 dark:hover:bg-slate-800 dark:hover:text-gray-50':
!isCurrent,
},
@@ -864,10 +983,17 @@ const ProjectSettings = () => {
</form>
) : null}
- {activeTab === 'emails' && !isSelfhosted ? <Emails projectId={id} /> : null}
+ {activeTab === 'emails' && !isSelfhosted ? (
+ <Emails projectId={id} />
+ ) : null}
{activeTab === 'people' ? <People project={project} /> : null}
{activeTab === 'annotations' ? (
- <Annotations projectId={id} allowedToManage={project?.role === 'owner' || project?.role === 'admin'} />
+ <Annotations
+ projectId={id}
+ allowedToManage={
+ project?.role === 'owner' || project?.role === 'admin'
+ }
+ />
) : null}
{activeTab === 'integrations' ? (
@@ -881,15 +1007,23 @@ const ProjectSettings = () => {
<Loader />
) : !gscConnected ? (
<div className='flex flex-col items-center justify-between gap-4 md:flex-row'>
- <p className='text-sm text-gray-800 dark:text-gray-200'>{t('project.settings.gsc.connect')}</p>
+ <p className='text-sm text-gray-800 dark:text-gray-200'>
+ {t('project.settings.gsc.connect')}
+ </p>
<Button
className='flex items-center gap-2'
type='button'
onClick={() => {
- gscFetcher.submit({ intent: 'gsc-connect' }, { method: 'post' })
+ gscFetcher.submit(
+ { intent: 'gsc-connect' },
+ { method: 'post' },
+ )
}}
loading={
- gscFetcher.state !== 'idle' ? gscFetcher.formData?.get('intent') === 'gsc-connect' : undefined
+ gscFetcher.state !== 'idle'
+ ? gscFetcher.formData?.get('intent') ===
+ 'gsc-connect'
+ : undefined
}
primary
regular
@@ -913,11 +1047,15 @@ const ProjectSettings = () => {
semiDanger
regular
onClick={() => {
- gscFetcher.submit({ intent: 'gsc-disconnect' }, { method: 'post' })
+ gscFetcher.submit(
+ { intent: 'gsc-disconnect' },
+ { method: 'post' },
+ )
}}
loading={
gscFetcher.state !== 'idle'
- ? gscFetcher.formData?.get('intent') === 'gsc-disconnect'
+ ? gscFetcher.formData?.get('intent') ===
+ 'gsc-disconnect'
: undefined
}
>
@@ -930,7 +1068,10 @@ const ProjectSettings = () => {
hintClassName='lg:w-2/3'
label={t('project.settings.gsc.websiteProperty')}
hint={t('project.settings.gsc.websitePropertyHint')}
- items={_map(gscProperties, (p) => ({ key: p.siteUrl, label: p.siteUrl }))}
+ items={_map(gscProperties, (p) => ({
+ key: p.siteUrl,
+ label: p.siteUrl,
+ }))}
keyExtractor={(item) => item.key}
labelExtractor={(item) => item.label}
onSelect={(item: { key: string; label: string }) => {
@@ -939,9 +1080,17 @@ const ProjectSettings = () => {
gscPropertyUri: item.key,
}))
}}
- title={form.gscPropertyUri || t('project.settings.gsc.selectProperty')}
+ title={
+ form.gscPropertyUri ||
+ t('project.settings.gsc.selectProperty')
+ }
selectedItem={
- form.gscPropertyUri ? { key: form.gscPropertyUri, label: form.gscPropertyUri } : undefined
+ form.gscPropertyUri
+ ? {
+ key: form.gscPropertyUri,
+ label: form.gscPropertyUri,
+ }
+ : undefined
}
/>
@@ -951,13 +1100,17 @@ const ProjectSettings = () => {
onClick={() => {
if (!form.gscPropertyUri) return
gscFetcher.submit(
- { intent: 'gsc-set-property', propertyUri: form.gscPropertyUri },
+ {
+ intent: 'gsc-set-property',
+ propertyUri: form.gscPropertyUri,
+ },
{ method: 'post' },
)
}}
loading={
gscFetcher.state !== 'idle'
- ? gscFetcher.formData?.get('intent') === 'gsc-set-property'
+ ? gscFetcher.formData?.get('intent') ===
+ 'gsc-set-property'
: undefined
}
primary
@@ -1015,7 +1168,12 @@ const ProjectSettings = () => {
disabled
/>
<div className='mt-4 flex gap-2'>
- <Button type='button' onClick={() => setShowRegenerateSecret(true)} danger regular>
+ <Button
+ type='button'
+ onClick={() => setShowRegenerateSecret(true)}
+ danger
+ regular
+ >
{t('project.settings.captcha.regenerateKey')}
</Button>
</div>
@@ -1027,28 +1185,66 @@ const ProjectSettings = () => {
className='lg:w-1/2'
hintClassName='lg:w-2/3'
items={[
- { value: 2, label: t('project.settings.captcha.difficultyLevels.veryEasy') },
- { value: 3, label: t('project.settings.captcha.difficultyLevels.easy') },
- { value: 4, label: t('project.settings.captcha.difficultyLevels.medium') },
- { value: 5, label: t('project.settings.captcha.difficultyLevels.hard') },
- { value: 6, label: t('project.settings.captcha.difficultyLevels.veryHard') },
+ {
+ value: 2,
+ label: t(
+ 'project.settings.captcha.difficultyLevels.veryEasy',
+ ),
+ },
+ {
+ value: 3,
+ label: t(
+ 'project.settings.captcha.difficultyLevels.easy',
+ ),
+ },
+ {
+ value: 4,
+ label: t(
+ 'project.settings.captcha.difficultyLevels.medium',
+ ),
+ },
+ {
+ value: 5,
+ label: t(
+ 'project.settings.captcha.difficultyLevels.hard',
+ ),
+ },
+ {
+ value: 6,
+ label: t(
+ 'project.settings.captcha.difficultyLevels.veryHard',
+ ),
+ },
]}
keyExtractor={(item) => String(item.value)}
labelExtractor={(item) => item.label}
selectedItem={{ value: captchaDifficulty, label: '' }}
- onSelect={(item: { value: number; label: string }) => {
+ onSelect={(item: {
+ value: number
+ label: string
+ }) => {
setCaptchaDifficulty(item.value)
}}
title={
captchaDifficulty === 2
- ? t('project.settings.captcha.difficultyLevels.veryEasy')
+ ? t(
+ 'project.settings.captcha.difficultyLevels.veryEasy',
+ )
: captchaDifficulty === 3
- ? t('project.settings.captcha.difficultyLevels.easy')
+ ? t(
+ 'project.settings.captcha.difficultyLevels.easy',
+ )
: captchaDifficulty === 4
- ? t('project.settings.captcha.difficultyLevels.medium')
+ ? t(
+ 'project.settings.captcha.difficultyLevels.medium',
+ )
: captchaDifficulty === 5
- ? t('project.settings.captcha.difficultyLevels.hard')
- : t('project.settings.captcha.difficultyLevels.veryHard')
+ ? t(
+ 'project.settings.captcha.difficultyLevels.hard',
+ )
+ : t(
+ 'project.settings.captcha.difficultyLevels.veryHard',
+ )
}
/>
<Button
@@ -1058,7 +1254,10 @@ const ProjectSettings = () => {
onClick={() => {
const formData = new FormData()
formData.set('intent', 'update-project')
- formData.set('captchaDifficulty', captchaDifficulty.toString())
+ formData.set(
+ 'captchaDifficulty',
+ captchaDifficulty.toString(),
+ )
fetcher.submit(formData, { method: 'post' })
}}
primary
@@ -1073,7 +1272,12 @@ const ProjectSettings = () => {
<p className='mb-4 text-sm text-gray-600 dark:text-gray-300'>
{t('project.settings.captcha.noKeyGenerated')}
</p>
- <Button type='button' onClick={onRegenerateCaptchaKey} primary regular>
+ <Button
+ type='button'
+ onClick={onRegenerateCaptchaKey}
+ primary
+ regular
+ >
{t('project.settings.captcha.generateKey')}
</Button>
</>
@@ -1146,7 +1350,9 @@ const ProjectSettings = () => {
title={t('project.settings.protected')}
message={
<div>
- <p className='mt-1 mb-4 text-sm text-gray-500 dark:text-gray-300'>{t('project.settings.protectedHint')}</p>
+ <p className='mt-1 mb-4 text-sm text-gray-500 dark:text-gray-300'>
+ {t('project.settings.protectedHint')}
+ </p>
<Input
name='password'
type='password'
@@ -1168,7 +1374,9 @@ const ProjectSettings = () => {
closeText={t('common.cancel')}
message={
<div>
- <h2 className='text-xl font-bold text-gray-700 dark:text-gray-200'>{t('project.settings.transferTo')}</h2>
+ <h2 className='text-xl font-bold text-gray-700 dark:text-gray-200'>
+ {t('project.settings.transferTo')}
+ </h2>
<p className='mt-2 text-base text-gray-700 dark:text-gray-200'>
{t('project.settings.transferHint', {
name: form.name || DEFAULT_PROJECT_NAME,
diff --git a/web/app/pages/Project/Settings/tabs/AccessSettings.tsx b/web/app/pages/Project/Settings/tabs/AccessSettings.tsx
index c949e0176..2f886ceb8 100644
--- a/web/app/pages/Project/Settings/tabs/AccessSettings.tsx
+++ b/web/app/pages/Project/Settings/tabs/AccessSettings.tsx
@@ -29,7 +29,9 @@ const AccessSettings = ({
return (
<>
- <h3 className='text-lg font-bold text-gray-900 dark:text-gray-50'>{t('project.settings.access')}</h3>
+ <h3 className='text-lg font-bold text-gray-900 dark:text-gray-50'>
+ {t('project.settings.access')}
+ </h3>
<Checkbox
checked={Boolean(form.active)}
onChange={(checked) =>
@@ -104,8 +106,12 @@ const AccessSettings = ({
}))
}}
label={t('project.settings.organisation')}
- title={organisations.find((org) => org.id === form.organisationId)?.name}
- selectedItem={organisations.find((org) => org.id === form.organisationId)}
+ title={
+ organisations.find((org) => org.id === form.organisationId)?.name
+ }
+ selectedItem={organisations.find(
+ (org) => org.id === form.organisationId,
+ )}
/>
</div>
) : null}
diff --git a/web/app/pages/Project/Settings/tabs/DangerZone.tsx b/web/app/pages/Project/Settings/tabs/DangerZone.tsx
index 36360f881..ad7775026 100644
--- a/web/app/pages/Project/Settings/tabs/DangerZone.tsx
+++ b/web/app/pages/Project/Settings/tabs/DangerZone.tsx
@@ -12,12 +12,20 @@ interface DangerZoneProps {
setResetting: boolean
}
-const DangerZone = ({ setShowTransfer, setShowReset, setShowDelete, isDeleting, setResetting }: DangerZoneProps) => {
+const DangerZone = ({
+ setShowTransfer,
+ setShowReset,
+ setShowDelete,
+ isDeleting,
+ setResetting,
+}: DangerZoneProps) => {
const { t } = useTranslation('common')
return (
<div>
- <h3 className='text-lg font-bold text-gray-900 dark:text-gray-50'>Danger zone</h3>
+ <h3 className='text-lg font-bold text-gray-900 dark:text-gray-50'>
+ Danger zone
+ </h3>
<div className='mt-4 space-y-3'>
<div className='rounded-md border border-gray-200 p-3 dark:border-gray-800'>
@@ -27,9 +35,15 @@ const DangerZone = ({ setShowTransfer, setShowReset, setShowDelete, isDeleting,
<div className='text-sm font-medium text-gray-900 dark:text-gray-50'>
{t('project.settings.transfer')}
</div>
- <p className='mt-0.5 text-sm text-gray-500 dark:text-gray-400'>{t('project.settings.transferShort')}</p>
+ <p className='mt-0.5 text-sm text-gray-500 dark:text-gray-400'>
+ {t('project.settings.transferShort')}
+ </p>
<div className='mt-3'>
- <Button onClick={() => setShowTransfer(true)} semiDanger semiSmall>
+ <Button
+ onClick={() => setShowTransfer(true)}
+ semiDanger
+ semiSmall
+ >
{t('project.settings.transfer')}
</Button>
</div>
@@ -41,10 +55,19 @@ const DangerZone = ({ setShowTransfer, setShowReset, setShowDelete, isDeleting,
<div className='flex items-start'>
<RotateCcw className='mt-0.5 h-5 w-5 text-red-700 dark:text-red-500' />
<div className='ml-3 flex-1'>
- <div className='text-sm font-medium text-gray-900 dark:text-gray-50'>{t('project.settings.reset')}</div>
- <p className='mt-0.5 text-sm text-gray-500 dark:text-gray-400'>{t('project.settings.resetShort')}</p>
+ <div className='text-sm font-medium text-gray-900 dark:text-gray-50'>
+ {t('project.settings.reset')}
+ </div>
+ <p className='mt-0.5 text-sm text-gray-500 dark:text-gray-400'>
+ {t('project.settings.resetShort')}
+ </p>
<div className='mt-3'>
- <Button onClick={() => !setResetting && setShowReset(true)} loading={isDeleting} semiDanger semiSmall>
+ <Button
+ onClick={() => !setResetting && setShowReset(true)}
+ loading={isDeleting}
+ semiDanger
+ semiSmall
+ >
{t('project.settings.reset')}
</Button>
</div>
@@ -54,12 +77,24 @@ const DangerZone = ({ setShowTransfer, setShowReset, setShowDelete, isDeleting,
<div className='rounded-md border border-gray-200 p-3 dark:border-gray-800'>
<div className='flex items-start'>
- <Trash2Icon className='mt-0.5 h-5 w-5 text-red-700 dark:text-red-500' strokeWidth={1.5} />
+ <Trash2Icon
+ className='mt-0.5 h-5 w-5 text-red-700 dark:text-red-500'
+ strokeWidth={1.5}
+ />
<div className='ml-3 flex-1'>
- <div className='text-sm font-medium text-gray-900 dark:text-gray-50'>{t('project.settings.delete')}</div>
- <p className='mt-0.5 text-sm text-gray-500 dark:text-gray-400'>{t('project.settings.deleteShort')}</p>
+ <div className='text-sm font-medium text-gray-900 dark:text-gray-50'>
+ {t('project.settings.delete')}
+ </div>
+ <p className='mt-0.5 text-sm text-gray-500 dark:text-gray-400'>
+ {t('project.settings.deleteShort')}
+ </p>
<div className='mt-3'>
- <Button onClick={() => !isDeleting && setShowDelete(true)} loading={isDeleting} danger semiSmall>
+ <Button
+ onClick={() => !isDeleting && setShowDelete(true)}
+ loading={isDeleting}
+ danger
+ semiSmall
+ >
{t('project.settings.delete')}
</Button>
</div>
diff --git a/web/app/pages/Project/Settings/tabs/General.tsx b/web/app/pages/Project/Settings/tabs/General.tsx
index 822ac327a..3f855e579 100644
--- a/web/app/pages/Project/Settings/tabs/General.tsx
+++ b/web/app/pages/Project/Settings/tabs/General.tsx
@@ -18,12 +18,20 @@ interface GeneralProps {
sharableLink: string
}
-const General = ({ form, errors, beenSubmitted, handleInput, sharableLink }: GeneralProps) => {
+const General = ({
+ form,
+ errors,
+ beenSubmitted,
+ handleInput,
+ sharableLink,
+}: GeneralProps) => {
const { t } = useTranslation('common')
return (
<>
- <h3 className='text-lg font-bold text-gray-900 dark:text-gray-50'>{t('profileSettings.general')}</h3>
+ <h3 className='text-lg font-bold text-gray-900 dark:text-gray-50'>
+ {t('profileSettings.general')}
+ </h3>
<Input
name='name'
label={t('project.settings.name')}
diff --git a/web/app/pages/Project/Settings/tabs/Revenue.tsx b/web/app/pages/Project/Settings/tabs/Revenue.tsx
index 2fe0561d3..42354a417 100644
--- a/web/app/pages/Project/Settings/tabs/Revenue.tsx
+++ b/web/app/pages/Project/Settings/tabs/Revenue.tsx
@@ -6,7 +6,10 @@ import { useFetcher } from 'react-router'
import { toast } from 'sonner'
import { DOCS_URL } from '~/lib/constants'
-import type { ProjectSettingsActionData, RevenueStatus } from '~/routes/projects.settings.$id'
+import type {
+ ProjectSettingsActionData,
+ RevenueStatus,
+} from '~/routes/projects.settings.$id'
import Button from '~/ui/Button'
import PaddleSVG from '~/ui/icons/Paddle'
import StripeSVG from '~/ui/icons/Stripe'
@@ -85,15 +88,27 @@ const Revenue = ({ projectId }: Props) => {
const [status, setStatus] = useState<RevenueStatus | null>(null)
const [isLoading, setIsLoading] = useState(true)
const [apiKey, setApiKey] = useState('')
- const [selectedProvider, setSelectedProvider] = useState<RevenueProvider>('stripe')
- const [selectedCurrency, setSelectedCurrency] = useState<'USD' | 'EUR' | 'GBP'>('USD')
-
- const isConnecting = fetcher.state !== 'idle' && fetcher.formData?.get('intent') === 'connect-revenue'
- const isDisconnecting = fetcher.state !== 'idle' && fetcher.formData?.get('intent') === 'disconnect-revenue'
- const isSavingCurrency = fetcher.state !== 'idle' && fetcher.formData?.get('intent') === 'update-revenue-currency'
+ const [selectedProvider, setSelectedProvider] =
+ useState<RevenueProvider>('stripe')
+ const [selectedCurrency, setSelectedCurrency] = useState<
+ 'USD' | 'EUR' | 'GBP'
+ >('USD')
+
+ const isConnecting =
+ fetcher.state !== 'idle' &&
+ fetcher.formData?.get('intent') === 'connect-revenue'
+ 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' }, { method: 'POST', action: `/projects/settings/${projectId}` })
+ fetcher.submit(
+ { intent: 'get-revenue-status' },
+ { method: 'POST', action: `/projects/settings/${projectId}` },
+ )
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [projectId])
@@ -105,7 +120,10 @@ const Revenue = ({ projectId }: Props) => {
setIsLoading(false)
if (success && revenueStatus) {
setStatus(revenueStatus)
- if (revenueStatus.provider === 'stripe' || revenueStatus.provider === 'paddle') {
+ if (
+ revenueStatus.provider === 'stripe' ||
+ revenueStatus.provider === 'paddle'
+ ) {
setSelectedProvider(revenueStatus.provider)
}
if (
@@ -139,7 +157,9 @@ 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))
+ setStatus((prev) =>
+ prev ? { ...prev, currency: selectedCurrency } : prev,
+ )
} else if (error) {
toast.error(error)
}
@@ -154,13 +174,21 @@ const Revenue = ({ projectId }: Props) => {
}
fetcher.submit(
- { intent: 'connect-revenue', provider: selectedProvider, apiKey, currency: selectedCurrency },
+ {
+ intent: 'connect-revenue',
+ provider: selectedProvider,
+ apiKey,
+ currency: selectedCurrency,
+ },
{ method: 'POST', action: `/projects/settings/${projectId}` },
)
}
const handleDisconnect = () => {
- fetcher.submit({ intent: 'disconnect-revenue' }, { method: 'POST', action: `/projects/settings/${projectId}` })
+ fetcher.submit(
+ { intent: 'disconnect-revenue' },
+ { method: 'POST', action: `/projects/settings/${projectId}` },
+ )
}
const handleCurrencyChange = () => {
@@ -183,8 +211,12 @@ const Revenue = ({ projectId }: Props) => {
const providerConfig = PROVIDER_CONFIG[selectedProvider]
const isConnected = Boolean(status?.connected)
const connectedProvider = status?.provider as RevenueProvider | undefined
- const connectedProviderConfig = connectedProvider ? PROVIDER_CONFIG[connectedProvider] : null
- const selectedProviderItem = PROVIDER_ITEMS.find((p) => p.id === selectedProvider)
+ const connectedProviderConfig = connectedProvider
+ ? PROVIDER_CONFIG[connectedProvider]
+ : null
+ const selectedProviderItem = PROVIDER_ITEMS.find(
+ (p) => p.id === selectedProvider,
+ )
return (
<div>
@@ -203,7 +235,11 @@ const Revenue = ({ projectId }: Props) => {
{t('project.settings.revenue.paymentProvider')}
</Text>
{isConnected ? (
- <Text size='sm' colour='success' className='ml-auto flex items-center gap-1'>
+ <Text
+ size='sm'
+ colour='success'
+ className='ml-auto flex items-center gap-1'
+ >
<CheckCircleIcon className='h-4 w-4' />
{t('common.connected')}
</Text>
@@ -221,7 +257,9 @@ const Revenue = ({ projectId }: Props) => {
{status?.lastSyncAt ? (
<Text as='p' size='sm' colour='muted'>
- {t('project.settings.revenue.lastSync', { date: new Date(status.lastSyncAt).toLocaleString() })}{' '}
+ {t('project.settings.revenue.lastSync', {
+ date: new Date(status.lastSyncAt).toLocaleString(),
+ })}{' '}
</Text>
) : null}
@@ -271,7 +309,8 @@ const Revenue = ({ projectId }: Props) => {
rel='noreferrer noopener'
className='inline-flex items-center font-medium text-indigo-600 hover:underline dark:text-indigo-400'
>
- {providerConfig.label} {t('project.settings.revenue.dashboard')}
+ {providerConfig.label}{' '}
+ {t('project.settings.revenue.dashboard')}
<ArrowUpRightIcon className='ml-0.5 h-3 w-3' />
</a>
</Text>
@@ -285,7 +324,14 @@ const Revenue = ({ projectId }: Props) => {
/>
</div>
- <Button type='button' className='max-w-max' onClick={handleConnect} loading={isConnecting} primary regular>
+ <Button
+ type='button'
+ className='max-w-max'
+ onClick={handleConnect}
+ loading={isConnecting}
+ primary
+ regular
+ >
{t('common.connect')}
</Button>
</div>
@@ -307,8 +353,12 @@ const Revenue = ({ projectId }: Props) => {
title={`${selectedCurrency} – ${SUPPORTED_CURRENCIES.find((c) => c.code === selectedCurrency)?.name} (${SUPPORTED_CURRENCIES.find((c) => c.code === selectedCurrency)?.symbol})`}
items={SUPPORTED_CURRENCIES}
keyExtractor={(item) => item.code}
- labelExtractor={(item) => `${item.code} – ${item.name} (${item.symbol})`}
- selectedItem={SUPPORTED_CURRENCIES.find((c) => c.code === selectedCurrency)}
+ labelExtractor={(item) =>
+ `${item.code} – ${item.name} (${item.symbol})`
+ }
+ selectedItem={SUPPORTED_CURRENCIES.find(
+ (c) => c.code === selectedCurrency,
+ )}
onSelect={(item: { code: string; name: string; symbol: string }) =>
setSelectedCurrency(item.code as 'USD' | 'EUR' | 'GBP')
}
diff --git a/web/app/pages/Project/Settings/tabs/Shields.tsx b/web/app/pages/Project/Settings/tabs/Shields.tsx
index f9d8d1c8f..ded14014e 100644
--- a/web/app/pages/Project/Settings/tabs/Shields.tsx
+++ b/web/app/pages/Project/Settings/tabs/Shields.tsx
@@ -54,14 +54,18 @@ const Shields = ({
})
}, [language])
- const [searchedCountries, setSearchedCountries] = useState<string[]>(allCountries)
+ const [searchedCountries, setSearchedCountries] =
+ useState<string[]>(allCountries)
const handleCountrySearch = (search: string) => {
if (search.length > 0) {
setSearchedCountries(
_filter(allCountries, (cc) => {
const countryName = countries.getName(cc, language) || cc
- return _includes(_toUpper(countryName), _toUpper(search)) || _includes(_toUpper(cc), _toUpper(search))
+ return (
+ _includes(_toUpper(countryName), _toUpper(search)) ||
+ _includes(_toUpper(cc), _toUpper(search))
+ )
}),
)
} else {
@@ -83,7 +87,13 @@ const Shields = ({
const renderCountryOption = (cc: string) => (
<div className='flex items-center gap-2'>
- <Flag className='rounded-xs' country={cc} size={21} alt='' aria-hidden='true' />
+ <Flag
+ className='rounded-xs'
+ country={cc}
+ size={21}
+ alt=''
+ aria-hidden='true'
+ />
<span>{countries.getName(cc, language) || cc}</span>
<span className='text-gray-400'>{cc}</span>
</div>
@@ -91,7 +101,9 @@ const Shields = ({
return (
<>
- <h3 className='text-lg font-bold text-gray-900 dark:text-gray-50'>{t('project.settings.shields')}</h3>
+ <h3 className='text-lg font-bold text-gray-900 dark:text-gray-50'>
+ {t('project.settings.shields')}
+ </h3>
<Input
name='origins'
label={t('project.settings.origins')}
@@ -134,11 +146,17 @@ const Shields = ({
label={t('project.settings.botsProtectionLevel.title')}
// @ts-expect-error
items={botsProtectionLevels}
- title={botsProtectionLevels.find((predicate) => predicate.name === form.botsProtectionLevel)?.title || ''}
+ title={
+ botsProtectionLevels.find(
+ (predicate) => predicate.name === form.botsProtectionLevel,
+ )?.title || ''
+ }
labelExtractor={(item: any) => item.title}
onSelect={(item) => setBotsLevel(item.name)}
capitalise
- selectedItem={botsProtectionLevels.find((predicate) => predicate.name === form.botsProtectionLevel)}
+ selectedItem={botsProtectionLevels.find(
+ (predicate) => predicate.name === form.botsProtectionLevel,
+ )}
/>
</div>
</>
diff --git a/web/app/pages/Project/View/Panels.tsx b/web/app/pages/Project/View/Panels.tsx
index 249673fbd..d0e2b3b21 100644
--- a/web/app/pages/Project/View/Panels.tsx
+++ b/web/app/pages/Project/View/Panels.tsx
@@ -1,6 +1,9 @@
import { ChevronUpIcon, ChevronDownIcon } from '@heroicons/react/20/solid'
import { ChevronRightIcon, CircleStackIcon } from '@heroicons/react/24/outline'
-import { ArrowLongRightIcon, ArrowLongLeftIcon } from '@heroicons/react/24/solid'
+import {
+ ArrowLongRightIcon,
+ ArrowLongLeftIcon,
+} from '@heroicons/react/24/solid'
import { useVirtualizer, type VirtualItem } from '@tanstack/react-virtual'
import type { ChartOptions } from 'billboard.js'
import cx from 'clsx'
@@ -20,7 +23,14 @@ import _sortBy from 'lodash/sortBy'
import _sum from 'lodash/sum'
import _toPairs from 'lodash/toPairs'
import { FilterIcon, ScanIcon } from 'lucide-react'
-import React, { memo, useState, useEffect, useMemo, Fragment, useRef } from 'react'
+import React, {
+ memo,
+ useState,
+ useEffect,
+ useMemo,
+ Fragment,
+ useRef,
+} from 'react'
import { useTranslation } from 'react-i18next'
import { Link, LinkProps, useNavigate } from 'react-router'
@@ -40,7 +50,11 @@ import countries from '~/utils/isoCountries'
import { MainChart } from './components/MainChart'
import { Customs, Filter } from './interfaces/traffic'
import { useViewProjectContext } from './ViewProject'
-import { getFormatDate, getSettingsCustomEventsStacked, typeNameMapping } from './ViewProject.helpers'
+import {
+ getFormatDate,
+ getSettingsCustomEventsStacked,
+ typeNameMapping,
+} from './ViewProject.helpers'
const ENTRIES_PER_PANEL = 8
const ENTRIES_PER_CUSTOM_EVENTS_PANEL = 7
@@ -98,13 +112,19 @@ const PanelContainer = ({
'overflow-hidden rounded-lg border border-gray-200 bg-white px-4 pb-3 dark:border-slate-800/60 dark:bg-slate-800/25',
hideHeader ? 'pt-3' : 'pt-5',
{
- 'col-span-full sm:col-span-2': type === 'metadata' || type === 'customEvents',
+ 'col-span-full sm:col-span-2':
+ type === 'metadata' || type === 'customEvents',
},
)}
>
{!hideHeader ? (
<div className='mb-2 flex items-center justify-between gap-4'>
- <Text as='h3' size='lg' weight='semibold' className='flex items-center leading-6 whitespace-nowrap'>
+ <Text
+ as='h3'
+ size='lg'
+ weight='semibold'
+ className='flex items-center leading-6 whitespace-nowrap'
+ >
{icon ? <span className='mr-1'>{icon}</span> : null}
{name}
</Text>
@@ -114,7 +134,9 @@ const PanelContainer = ({
{tabs.map((tab, index) => {
if (Array.isArray(tab)) {
const dropdownTabs = tab
- const activeDropdownTab = dropdownTabs.find((t) => t.id === activeTabId)
+ const activeDropdownTab = dropdownTabs.find(
+ (t) => t.id === activeTabId,
+ )
const dropdownTitle = activeDropdownTab
? activeDropdownTab.label
: dropdownPlaceholder || t('project.campaigns')
@@ -130,11 +152,10 @@ const PanelContainer = ({
onTabChange(item.id)
}}
buttonClassName={cx(
- 'relative border-b-2 px-0 md:px-0 py-1 text-sm font-bold whitespace-nowrap transition-all duration-200',
+ 'relative border-b-2 px-0 py-1 text-sm font-bold whitespace-nowrap transition-all duration-200 md:px-0',
{
- 'border-slate-900 text-slate-900 dark:border-gray-50 dark:text-gray-50': dropdownTabs.some(
- (t) => t.id === activeTabId,
- ),
+ 'border-slate-900 text-slate-900 dark:border-gray-50 dark:text-gray-50':
+ dropdownTabs.some((t) => t.id === activeTabId),
'border-transparent text-gray-500 hover:border-gray-200 hover:text-gray-700 dark:text-gray-400 dark:hover:border-gray-200 dark:hover:text-gray-300':
!dropdownTabs.some((t) => t.id === activeTabId),
},
@@ -172,7 +193,9 @@ const PanelContainer = ({
</div>
</div>
) : null}
- <div className='relative flex h-[19.6rem] flex-col overflow-auto'>{children}</div>
+ <div className='relative flex h-[19.6rem] flex-col overflow-auto'>
+ {children}
+ </div>
{onDetailsClick ? (
<div className='mt-2 flex items-center justify-center'>
<Button
@@ -221,7 +244,12 @@ interface KVTableProps {
displayKeyAsHeader?: KVTableContainerProps['displayKeyAsHeader']
}
-const KVTable = ({ listId, data, displayKeyAsHeader, onClick }: KVTableProps) => {
+const KVTable = ({
+ listId,
+ data,
+ displayKeyAsHeader,
+ onClick,
+}: KVTableProps) => {
const { t } = useTranslation('common')
const [sort, setSort] = useState<SortRows>({
label: 'quantity',
@@ -232,14 +260,20 @@ const KVTable = ({ listId, data, displayKeyAsHeader, onClick }: KVTableProps) =>
const sortedData = useMemo(() => {
return data.sort((a: any, b: any) => {
if (sort.label === 'quantity') {
- return sort.sortByAscend ? a.quantity - b.quantity : b.quantity - a.quantity
+ return sort.sortByAscend
+ ? a.quantity - b.quantity
+ : b.quantity - a.quantity
}
if (sort.label === 'conversion') {
- return sort.sortByAscend ? a.conversion - b.conversion : b.conversion - a.conversion
+ return sort.sortByAscend
+ ? a.conversion - b.conversion
+ : b.conversion - a.conversion
}
- return sort.sortByAscend ? a.event.localeCompare(b.event) : b.event.localeCompare(a.event)
+ return sort.sortByAscend
+ ? a.event.localeCompare(b.event)
+ : b.event.localeCompare(a.event)
})
}, [data, sort])
@@ -285,22 +319,36 @@ const KVTable = ({ listId, data, displayKeyAsHeader, onClick }: KVTableProps) =>
/>
</th>
<th className='w-[30%] sm:w-1/6'>
- <p onClick={() => onSortBy('quantity')} className='flex cursor-pointer items-center justify-end'>
+ <p
+ onClick={() => onSortBy('quantity')}
+ className='flex cursor-pointer items-center justify-end'
+ >
{t('project.quantity')}
<Sort
className='ml-1'
- sortByAscend={sort.label === 'quantity' ? sort.sortByAscend : null}
- sortByDescend={sort.label === 'quantity' ? sort.sortByDescend : null}
+ sortByAscend={
+ sort.label === 'quantity' ? sort.sortByAscend : null
+ }
+ sortByDescend={
+ sort.label === 'quantity' ? sort.sortByDescend : null
+ }
/>
</p>
</th>
<th className='w-[30%] pr-2 sm:w-1/6'>
- <p onClick={() => onSortBy('conversion')} className='flex cursor-pointer items-center justify-end'>
+ <p
+ onClick={() => onSortBy('conversion')}
+ className='flex cursor-pointer items-center justify-end'
+ >
{t('project.conversion')}
<Sort
className='ml-1'
- sortByAscend={sort.label === 'conversion' ? sort.sortByAscend : null}
- sortByDescend={sort.label === 'conversion' ? sort.sortByDescend : null}
+ sortByAscend={
+ sort.label === 'conversion' ? sort.sortByAscend : null
+ }
+ sortByDescend={
+ sort.label === 'conversion' ? sort.sortByDescend : null
+ }
/>
</p>
</th>
@@ -327,7 +375,9 @@ const KVTable = ({ listId, data, displayKeyAsHeader, onClick }: KVTableProps) =>
{quantity}
&nbsp;&nbsp;
</td>
- <td className='w-[30%] py-1 pr-2 text-right sm:w-1/6'>{conversion}%</td>
+ <td className='w-[30%] py-1 pr-2 text-right sm:w-1/6'>
+ {conversion}%
+ </td>
</tr>
))}
</tbody>
@@ -335,7 +385,12 @@ const KVTable = ({ listId, data, displayKeyAsHeader, onClick }: KVTableProps) =>
)
}
-const KVTableContainer = ({ data, uniques, displayKeyAsHeader, onClick }: KVTableContainerProps) => {
+const KVTableContainer = ({
+ data,
+ uniques,
+ displayKeyAsHeader,
+ onClick,
+}: KVTableContainerProps) => {
const { t } = useTranslation('common')
const processed = useMemo(() => {
return _reduce(
@@ -348,7 +403,8 @@ const KVTableContainer = ({ data, uniques, displayKeyAsHeader, onClick }: KVTabl
acc[curr.key].push({
event: curr.value,
quantity: curr.count,
- conversion: uniques === 0 ? 100 : _round((curr.count / uniques) * 100, 2),
+ conversion:
+ uniques === 0 ? 100 : _round((curr.count / uniques) * 100, 2),
})
return acc
@@ -362,7 +418,15 @@ const KVTableContainer = ({ data, uniques, displayKeyAsHeader, onClick }: KVTabl
}
return _map(processed, (value, key) => {
- return <KVTable key={key} listId={key} data={value} displayKeyAsHeader={displayKeyAsHeader} onClick={onClick} />
+ return (
+ <KVTable
+ key={key}
+ listId={key}
+ data={value}
+ displayKeyAsHeader={displayKeyAsHeader}
+ onClick={onClick}
+ />
+ )
})
}
@@ -394,10 +458,17 @@ function sortDesc<T>(obj: T, sortByKeys?: boolean): T {
) as T
}
-const CustomEvents = ({ customs, chartData, filters, getCustomEventMetadata, getFilterLink }: CustomEventsProps) => {
+const CustomEvents = ({
+ customs,
+ chartData,
+ filters,
+ getCustomEventMetadata,
+ getFilterLink,
+}: CustomEventsProps) => {
const { t } = useTranslation('common')
const { id } = useCurrentProject()
- const { timeBucket, timezone, period, dateRange, timeFormat, rotateXAxis } = useViewProjectContext()
+ const { timeBucket, timezone, period, dateRange, timeFormat, rotateXAxis } =
+ useViewProjectContext()
const { fetchCustomEvents } = useProjectDataCustomEventsProxy()
const [detailsOpened, setDetailsOpened] = useState(false)
@@ -405,7 +476,8 @@ const CustomEvents = ({ customs, chartData, filters, getCustomEventMetadata, get
const [loadingEvents, setLoadingEvents] = useState<any>({})
const [eventsMetadata, setEventsMetadata] = useState<any>({})
const [eventsData, setEventsData] = useState<any>(customs)
- const [triggerEventWhenFiltersChange, setTriggerEventWhenFiltersChange] = useState<string | null>(null)
+ const [triggerEventWhenFiltersChange, setTriggerEventWhenFiltersChange] =
+ useState<string | null>(null)
const [stackedChartLoading, setStackedChartLoading] = useState(false)
const [stackedChart, setStackedChart] = useState<{
x: string[]
@@ -413,7 +485,10 @@ const CustomEvents = ({ customs, chartData, filters, getCustomEventMetadata, get
} | null>(null)
const keys = _keys(eventsData)
- const keysToDisplay = useMemo(() => _slice(keys, 0, ENTRIES_PER_CUSTOM_EVENTS_PANEL), [keys])
+ const keysToDisplay = useMemo(
+ () => _slice(keys, 0, ENTRIES_PER_CUSTOM_EVENTS_PANEL),
+ [keys],
+ )
const uniques = _sum(chartData.uniques)
const totalCustomEvents = useMemo(
@@ -426,7 +501,10 @@ const CustomEvents = ({ customs, chartData, filters, getCustomEventMetadata, get
}
const sorted = _orderBy(
- _map(_toPairs(customs), ([event, count]) => ({ event, count: Number(count) || 0 })),
+ _map(_toPairs(customs), ([event, count]) => ({
+ event,
+ count: Number(count) || 0,
+ })),
'count',
'desc',
)
@@ -482,7 +560,10 @@ const CustomEvents = ({ customs, chartData, filters, getCustomEventMetadata, get
setStackedChart((data?.chart as unknown as typeof stackedChart) || null)
} catch (reason) {
- console.error('[ERROR](CustomEvents) Failed to load stacked custom events chart', reason)
+ console.error(
+ '[ERROR](CustomEvents) Failed to load stacked custom events chart',
+ reason,
+ )
if (!cancelled) {
setStackedChart(null)
}
@@ -498,12 +579,23 @@ const CustomEvents = ({ customs, chartData, filters, getCustomEventMetadata, get
return () => {
cancelled = true
}
- }, [id, timeBucket, period, dateRange, timezone, filters, topEventsForChart, fetchCustomEvents])
+ }, [
+ id,
+ timeBucket,
+ period,
+ dateRange,
+ timezone,
+ filters,
+ topEventsForChart,
+ fetchCustomEvents,
+ ])
useEffect(() => {
setEventsMetadata({})
const evToSkip = triggerEventWhenFiltersChange
- const openEvents = Object.keys(activeEvents).filter((key) => activeEvents[key] && key !== evToSkip)
+ const openEvents = Object.keys(activeEvents).filter(
+ (key) => activeEvents[key] && key !== evToSkip,
+ )
openEvents.forEach((ev) => {
toggleDetails(ev)()
})
@@ -521,42 +613,46 @@ const CustomEvents = ({ customs, chartData, filters, getCustomEventMetadata, get
}, [filters, triggerEventWhenFiltersChange])
// is "e" is not set, then details loading is forced and all checks are skipped
- const toggleDetails = (ev: string) => async (e?: React.MouseEvent<HTMLButtonElement>) => {
- if (e) {
- e.stopPropagation()
-
- setActiveEvents((events: any) => ({
- ...events,
- [ev]: !events[ev],
- }))
- }
-
- if (!e || !eventsMetadata[ev]) {
- setLoadingEvents((events: any) => ({
- ...events,
- [ev]: true,
- }))
+ const toggleDetails =
+ (ev: string) => async (e?: React.MouseEvent<HTMLButtonElement>) => {
+ if (e) {
+ e.stopPropagation()
+
+ setActiveEvents((events: any) => ({
+ ...events,
+ [ev]: !events[ev],
+ }))
+ }
- try {
- const { result } = await getCustomEventMetadata(ev)
- setEventsMetadata((metadata: any) => ({
- ...metadata,
- [ev]: result,
+ if (!e || !eventsMetadata[ev]) {
+ setLoadingEvents((events: any) => ({
+ ...events,
+ [ev]: true,
}))
- } catch (reason) {
- console.error(`[ERROR](toggleDetails) Failed to get metadata for event ${ev}`, reason)
- setEventsMetadata((metadata: any) => ({
- ...metadata,
- [ev]: [],
+
+ try {
+ const { result } = await getCustomEventMetadata(ev)
+ setEventsMetadata((metadata: any) => ({
+ ...metadata,
+ [ev]: result,
+ }))
+ } catch (reason) {
+ console.error(
+ `[ERROR](toggleDetails) Failed to get metadata for event ${ev}`,
+ reason,
+ )
+ setEventsMetadata((metadata: any) => ({
+ ...metadata,
+ [ev]: [],
+ }))
+ }
+
+ setLoadingEvents((events: any) => ({
+ ...events,
+ [ev]: false,
}))
}
-
- setLoadingEvents((events: any) => ({
- ...events,
- [ev]: false,
- }))
}
- }
const onModalClose = () => {
setDetailsOpened(false)
@@ -616,7 +712,9 @@ const CustomEvents = ({ customs, chartData, filters, getCustomEventMetadata, get
<Sort
className='ml-1'
sortByAscend={sort.label === 'event' ? sort.sortByAscend : null}
- sortByDescend={sort.label === 'event' ? sort.sortByDescend : null}
+ sortByDescend={
+ sort.label === 'event' ? sort.sortByDescend : null
+ }
/>
</th>
<th className='w-[40%] pr-2 sm:w-2/6'>
@@ -627,8 +725,12 @@ const CustomEvents = ({ customs, chartData, filters, getCustomEventMetadata, get
{t('project.quantity')}
<Sort
className='ml-1'
- sortByAscend={sort.label === 'quantity' ? sort.sortByAscend : null}
- sortByDescend={sort.label === 'quantity' ? sort.sortByDescend : null}
+ sortByAscend={
+ sort.label === 'quantity' ? sort.sortByAscend : null
+ }
+ sortByDescend={
+ sort.label === 'quantity' ? sort.sortByDescend : null
+ }
/>
&nbsp;&nbsp;
</p>
@@ -678,7 +780,10 @@ const CustomEvents = ({ customs, chartData, filters, getCustomEventMetadata, get
|
</Text>
<Text size='sm' colour='muted'>
- {totalCustomEvents === 0 ? 0 : _round((eventsData[ev] / totalCustomEvents) * 100, 0)}%
+ {totalCustomEvents === 0
+ ? 0
+ : _round((eventsData[ev] / totalCustomEvents) * 100, 0)}
+ %
</Text>
</span>
</td>
@@ -717,7 +822,12 @@ const CustomEvents = ({ customs, chartData, filters, getCustomEventMetadata, get
<Text size='sm' weight='medium' colour='muted' className='w-4/6'>
{t('project.event')}
</Text>
- <Text size='sm' weight='medium' colour='muted' className='w-2/6 text-right'>
+ <Text
+ size='sm'
+ weight='medium'
+ colour='muted'
+ className='w-2/6 text-right'
+ >
{t('project.quantity')}
</Text>
</div>
@@ -731,9 +841,14 @@ const CustomEvents = ({ customs, chartData, filters, getCustomEventMetadata, get
),
(item) => {
const ev = item.key
- const maxValue = Math.max(...(Object.values(eventsData) as number[]))
+ const maxValue = Math.max(
+ ...(Object.values(eventsData) as number[]),
+ )
const link = _getFilterLink(null, ev)
- const perc = totalCustomEvents === 0 ? 0 : _round((eventsData[ev] / totalCustomEvents) * 100, 0)
+ const perc =
+ totalCustomEvents === 0
+ ? 0
+ : _round((eventsData[ev] / totalCustomEvents) * 100, 0)
return (
<div
@@ -792,7 +907,12 @@ const CustomEvents = ({ customs, chartData, filters, getCustomEventMetadata, get
return {}
}
- return getSettingsCustomEventsStacked(stackedChart, timeBucket, rotateXAxis, timeFormat)
+ return getSettingsCustomEventsStacked(
+ stackedChart,
+ timeBucket,
+ rotateXAxis,
+ timeFormat,
+ )
}, [stackedChart, timeBucket, rotateXAxis, timeFormat])
const renderStackedChart = () => {
@@ -831,7 +951,11 @@ const CustomEvents = ({ customs, chartData, filters, getCustomEventMetadata, get
{renderContent()}
</PanelContainer>
- <PanelContainer name={t('dashboard.events')} type='customEventsChart' hideHeader>
+ <PanelContainer
+ name={t('dashboard.events')}
+ type='customEventsChart'
+ hideHeader
+ >
{renderStackedChart()}
</PanelContainer>
</div>
@@ -841,7 +965,9 @@ const CustomEvents = ({ customs, chartData, filters, getCustomEventMetadata, get
interface MetadataKeyPanelProps {
title: string
metadataKeys: string[]
- getMetadataValues: (key: string) => Promise<{ result: Array<{ key: string; value: string; count: number }> }>
+ getMetadataValues: (
+ key: string,
+ ) => Promise<{ result: Array<{ key: string; value: string; count: number }> }>
getFilterLink: (column: string, value: string | null) => LinkProps['to']
chartData: any
filters: Filter[]
@@ -870,8 +996,12 @@ const MetadataKeyPanel = ({
const [loading, setLoading] = useState(false)
// For property mode: simple value/count pairs
// For customEvent mode: raw data with key/value/count (grouped by metadata key)
- const [valuesData, setValuesData] = useState<Array<{ value: string; count: number }>>([])
- const [rawMetadata, setRawMetadata] = useState<Array<{ key: string; value: string; count: number }>>([])
+ const [valuesData, setValuesData] = useState<
+ Array<{ value: string; count: number }>
+ >([])
+ const [rawMetadata, setRawMetadata] = useState<
+ Array<{ key: string; value: string; count: number }>
+ >([])
const [detailsOpened, setDetailsOpened] = useState(false)
const uniques = _sum(chartData.uniques)
@@ -898,11 +1028,17 @@ const MetadataKeyPanel = ({
// For custom events: show all metadata (result is already for this event)
setRawMetadata(result)
// Flatten for display purposes
- const values = result.map((item) => ({ value: `${item.key}: ${item.value}`, count: item.count }))
+ const values = result.map((item) => ({
+ value: `${item.key}: ${item.value}`,
+ count: item.count,
+ }))
setValuesData(values)
}
} catch (error) {
- console.error(`[ERROR](MetadataKeyPanel) Failed to load values for key ${activeKey}`, error)
+ console.error(
+ `[ERROR](MetadataKeyPanel) Failed to load values for key ${activeKey}`,
+ error,
+ )
setValuesData([])
setRawMetadata([])
} finally {
@@ -927,11 +1063,17 @@ const MetadataKeyPanel = ({
setValuesData(values)
} else {
setRawMetadata(result)
- const values = result.map((item) => ({ value: `${item.key}: ${item.value}`, count: item.count }))
+ const values = result.map((item) => ({
+ value: `${item.key}: ${item.value}`,
+ count: item.count,
+ }))
setValuesData(values)
}
} catch (error) {
- console.error(`[ERROR](MetadataKeyPanel) Failed to reload values for key ${activeKey}`, error)
+ console.error(
+ `[ERROR](MetadataKeyPanel) Failed to reload values for key ${activeKey}`,
+ error,
+ )
setValuesData([])
setRawMetadata([])
} finally {
@@ -966,8 +1108,14 @@ const MetadataKeyPanel = ({
return metadataKeys.map((key) => ({ id: key, label: key }))
}, [metadataKeys])
- const sortedRawMetadata = useMemo(() => _orderBy(rawMetadata, 'count', 'desc'), [rawMetadata])
- const sortedValuesData = useMemo(() => _orderBy(valuesData, 'count', 'desc'), [valuesData])
+ const sortedRawMetadata = useMemo(
+ () => _orderBy(rawMetadata, 'count', 'desc'),
+ [rawMetadata],
+ )
+ const sortedValuesData = useMemo(
+ () => _orderBy(valuesData, 'count', 'desc'),
+ [valuesData],
+ )
const DetailsTable = () => {
if (mode === 'customEvent') {
@@ -992,7 +1140,8 @@ const MetadataKeyPanel = ({
</thead>
<tbody>
{_map(sortedRawMetadata, ({ key, value, count }) => {
- const perc = uniques === 0 ? 100 : _round((count / uniques) * 100, 2)
+ const perc =
+ uniques === 0 ? 100 : _round((count / uniques) * 100, 2)
const link = _getFilterLink(key, value)
return (
@@ -1044,7 +1193,8 @@ const MetadataKeyPanel = ({
</thead>
<tbody>
{_map(sortedValuesData, ({ value, count }) => {
- const perc = uniques === 0 ? 100 : _round((count / uniques) * 100, 2)
+ const perc =
+ uniques === 0 ? 100 : _round((count / uniques) * 100, 2)
const link = _getFilterLink(null, value)
return (
@@ -1091,7 +1241,10 @@ const MetadataKeyPanel = ({
)
}
- if (_isEmpty(valuesData) && (mode === 'property' || _isEmpty(rawMetadata))) {
+ if (
+ _isEmpty(valuesData) &&
+ (mode === 'property' || _isEmpty(rawMetadata))
+ ) {
return <PanelEmptyState message={t('project.noData')} />
}
@@ -1108,62 +1261,80 @@ const MetadataKeyPanel = ({
<Text size='sm' weight='medium' colour='muted' className='w-2/6'>
{t('project.value')}
</Text>
- <Text size='sm' weight='medium' colour='muted' className='w-1/6 text-right'>
+ <Text
+ size='sm'
+ weight='medium'
+ colour='muted'
+ className='w-1/6 text-right'
+ >
{t('project.quantity')}
</Text>
- <Text size='sm' weight='medium' colour='muted' className='w-1/6 text-right'>
+ <Text
+ size='sm'
+ weight='medium'
+ colour='muted'
+ className='w-1/6 text-right'
+ >
{t('project.conversion')}
</Text>
</div>
<div className='space-y-0.5'>
- {_map(valuesToDisplay as Array<{ key: string; value: string; count: number }>, ({ key, value, count }) => {
- const perc = uniques === 0 ? 100 : _round((count / uniques) * 100, 2)
- const link = _getFilterLink(key, value)
+ {_map(
+ valuesToDisplay as Array<{
+ key: string
+ value: string
+ count: number
+ }>,
+ ({ key, value, count }) => {
+ const perc =
+ uniques === 0 ? 100 : _round((count / uniques) * 100, 2)
+ const link = _getFilterLink(key, value)
- return (
- <div
- key={`${key}-${value}`}
- className='group relative flex cursor-pointer items-center rounded-sm px-1 py-1.5 hover:bg-gray-50 dark:text-gray-50 hover:dark:bg-slate-800'
- onClick={() => {
- navigate(link)
- }}
- >
+ return (
<div
- className='absolute inset-0 rounded-sm bg-blue-50 dark:bg-blue-900/10'
- style={{
- width: `${(count / maxValue) * 100}%`,
+ key={`${key}-${value}`}
+ className='group relative flex cursor-pointer items-center rounded-sm px-1 py-1.5 hover:bg-gray-50 dark:text-gray-50 hover:dark:bg-slate-800'
+ onClick={() => {
+ navigate(link)
}}
- />
-
- <div className='relative z-10 w-2/6 min-w-0 truncate'>
- <Text size='sm' truncate>
- {key}
- </Text>
- </div>
- <div className='relative z-10 flex w-2/6 min-w-0 items-center'>
- <Text size='sm' truncate>
- {value}
- </Text>
- <FilterIcon
- className='ml-2 hidden h-4 w-4 shrink-0 text-gray-500 group-hover:block dark:text-gray-300'
- strokeWidth={1.5}
+ >
+ <div
+ className='absolute inset-0 rounded-sm bg-blue-50 dark:bg-blue-900/10'
+ style={{
+ width: `${(count / maxValue) * 100}%`,
+ }}
/>
- <div className='ml-2 h-4 w-4 group-hover:hidden' />
- </div>
- <div className='relative z-10 w-1/6 text-right'>
- <Text size='sm' weight='medium'>
- {count}
- </Text>
- </div>
- <div className='relative z-10 w-1/6 text-right'>
- <Text size='sm' weight='medium'>
- {perc}%
- </Text>
+
+ <div className='relative z-10 w-2/6 min-w-0 truncate'>
+ <Text size='sm' truncate>
+ {key}
+ </Text>
+ </div>
+ <div className='relative z-10 flex w-2/6 min-w-0 items-center'>
+ <Text size='sm' truncate>
+ {value}
+ </Text>
+ <FilterIcon
+ className='ml-2 hidden h-4 w-4 shrink-0 text-gray-500 group-hover:block dark:text-gray-300'
+ strokeWidth={1.5}
+ />
+ <div className='ml-2 h-4 w-4 group-hover:hidden' />
+ </div>
+ <div className='relative z-10 w-1/6 text-right'>
+ <Text size='sm' weight='medium'>
+ {count}
+ </Text>
+ </div>
+ <div className='relative z-10 w-1/6 text-right'>
+ <Text size='sm' weight='medium'>
+ {perc}%
+ </Text>
+ </div>
</div>
- </div>
- )
- })}
+ )
+ },
+ )}
</div>
<Modal
@@ -1186,57 +1357,71 @@ const MetadataKeyPanel = ({
<Text size='sm' weight='medium' colour='muted' className='w-4/6'>
{t('project.value')}
</Text>
- <Text size='sm' weight='medium' colour='muted' className='w-1/6 text-right'>
+ <Text
+ size='sm'
+ weight='medium'
+ colour='muted'
+ className='w-1/6 text-right'
+ >
{t('project.quantity')}
</Text>
- <Text size='sm' weight='medium' colour='muted' className='w-1/6 text-right'>
+ <Text
+ size='sm'
+ weight='medium'
+ colour='muted'
+ className='w-1/6 text-right'
+ >
{t('project.conversion')}
</Text>
</div>
<div className='space-y-0.5'>
- {_map(valuesToDisplay as Array<{ value: string; count: number }>, ({ value, count }) => {
- const perc = uniques === 0 ? 100 : _round((count / uniques) * 100, 2)
- const link = _getFilterLink(null, value)
-
- return (
- <div
- key={value}
- className='group relative flex cursor-pointer items-center rounded-sm px-1 py-1.5 hover:bg-gray-50 dark:text-gray-50 hover:dark:bg-slate-800'
- onClick={() => {
- navigate(link)
- }}
- >
+ {_map(
+ valuesToDisplay as Array<{ value: string; count: number }>,
+ ({ value, count }) => {
+ const perc =
+ uniques === 0 ? 100 : _round((count / uniques) * 100, 2)
+ const link = _getFilterLink(null, value)
+
+ return (
<div
- className='absolute inset-0 rounded-sm bg-blue-50 dark:bg-blue-900/10'
- style={{
- width: `${(count / maxValue) * 100}%`,
+ key={value}
+ className='group relative flex cursor-pointer items-center rounded-sm px-1 py-1.5 hover:bg-gray-50 dark:text-gray-50 hover:dark:bg-slate-800'
+ onClick={() => {
+ navigate(link)
}}
- />
-
- <div className='relative z-10 flex w-4/6 min-w-0 items-center'>
- <Text size='sm' truncate>
- {value}
- </Text>
- <FilterIcon
- className='ml-2 hidden h-4 w-4 shrink-0 text-gray-500 group-hover:block dark:text-gray-300'
- strokeWidth={1.5}
+ >
+ <div
+ className='absolute inset-0 rounded-sm bg-blue-50 dark:bg-blue-900/10'
+ style={{
+ width: `${(count / maxValue) * 100}%`,
+ }}
/>
- <div className='ml-2 h-4 w-4 group-hover:hidden' />
- </div>
- <div className='relative z-10 w-1/6 text-right'>
- <Text size='sm' weight='medium'>
- {count}
- </Text>
- </div>
- <div className='relative z-10 w-1/6 text-right'>
- <Text size='sm' weight='medium'>
- {perc}%
- </Text>
+
+ <div className='relative z-10 flex w-4/6 min-w-0 items-center'>
+ <Text size='sm' truncate>
+ {value}
+ </Text>
+ <FilterIcon
+ className='ml-2 hidden h-4 w-4 shrink-0 text-gray-500 group-hover:block dark:text-gray-300'
+ strokeWidth={1.5}
+ />
+ <div className='ml-2 h-4 w-4 group-hover:hidden' />
+ </div>
+ <div className='relative z-10 w-1/6 text-right'>
+ <Text size='sm' weight='medium'>
+ {count}
+ </Text>
+ </div>
+ <div className='relative z-10 w-1/6 text-right'>
+ <Text size='sm' weight='medium'>
+ {perc}%
+ </Text>
+ </div>
</div>
- </div>
- )
- })}
+ )
+ },
+ )}
</div>
<Modal
@@ -1251,7 +1436,9 @@ const MetadataKeyPanel = ({
}
const hasData =
- mode === 'customEvent' ? _size(rawMetadata) > ENTRIES_PER_PANEL : _size(valuesData) > ENTRIES_PER_PANEL
+ mode === 'customEvent'
+ ? _size(rawMetadata) > ENTRIES_PER_PANEL
+ : _size(valuesData) > ENTRIES_PER_PANEL
return (
<PanelContainer
@@ -1261,7 +1448,11 @@ const MetadataKeyPanel = ({
onTabChange={onKeyChange}
activeTabId={activeKey}
onDetailsClick={hasData ? () => setDetailsOpened(true) : undefined}
- dropdownPlaceholder={mode === 'customEvent' ? t('project.selectEvent') : t('project.selectProperty')}
+ dropdownPlaceholder={
+ mode === 'customEvent'
+ ? t('project.selectEvent')
+ : t('project.selectProperty')
+ }
>
{renderContent()}
</PanelContainer>
@@ -1312,7 +1503,10 @@ interface PanelProps {
activeTabId?: string
customRenderer?: () => React.ReactNode
versionData?: { [key: string]: Entry[] }
- getVersionFilterLink?: (parent: string | null, version: string | null) => LinkProps['to']
+ getVersionFilterLink?: (
+ parent: string | null,
+ version: string | null,
+ ) => LinkProps['to']
valuesHeaderName?: string
highlightColour?: 'blue' | 'red' | 'orange'
disableRowClick?: boolean
@@ -1398,7 +1592,11 @@ const DetailsTable = ({
}
if (activeTabId === 'lc') {
try {
- return (getLocaleDisplayName(entry?.name, language) || entry?.name || '').toLowerCase()
+ return (
+ getLocaleDisplayName(entry?.name, language) ||
+ entry?.name ||
+ ''
+ ).toLowerCase()
} catch {
return (entry?.name || '').toLowerCase()
}
@@ -1429,7 +1627,8 @@ const DetailsTable = ({
if (sort.sortByAscend) {
const newData = [...sortedData].sort((a, b) => {
- if (label === 'name') return (getValue(a) as string).localeCompare(getValue(b) as string)
+ if (label === 'name')
+ return (getValue(a) as string).localeCompare(getValue(b) as string)
return (getValue(a) as number) - (getValue(b) as number)
})
setSortedData(newData)
@@ -1444,7 +1643,8 @@ const DetailsTable = ({
}
const newData = [...sortedData].sort((a, b) => {
- if (label === 'name') return (getValue(a) as string).localeCompare(getValue(b) as string)
+ if (label === 'name')
+ return (getValue(a) as string).localeCompare(getValue(b) as string)
return (getValue(b) as number) - (getValue(a) as number)
})
setSortedData(newData)
@@ -1483,12 +1683,19 @@ const DetailsTable = ({
{tnMapping[activeTabId as keyof typeof tnMapping]}
<Sort
className='ml-1'
- sortByAscend={sort.label === 'name' ? sort.sortByAscend : null}
- sortByDescend={sort.label === 'name' ? sort.sortByDescend : null}
+ sortByAscend={
+ sort.label === 'name' ? sort.sortByAscend : null
+ }
+ sortByDescend={
+ sort.label === 'name' ? sort.sortByDescend : null
+ }
/>
</th>
{(() => {
- const numericColsCount = 1 + (detailsExtraColumns?.length || 0) + (!hidePercentageInDetails ? 1 : 0)
+ const numericColsCount =
+ 1 +
+ (detailsExtraColumns?.length || 0) +
+ (!hidePercentageInDetails ? 1 : 0)
const numericColWidth = `${(60 / numericColsCount).toFixed(3)}%`
return (
<th style={{ width: numericColWidth }}>
@@ -1499,8 +1706,12 @@ const DetailsTable = ({
{valuesHeaderName || t('project.visitors')}
<Sort
className='ml-1'
- sortByAscend={sort.label === 'quantity' ? sort.sortByAscend : null}
- sortByDescend={sort.label === 'quantity' ? sort.sortByDescend : null}
+ sortByAscend={
+ sort.label === 'quantity' ? sort.sortByAscend : null
+ }
+ sortByDescend={
+ sort.label === 'quantity' ? sort.sortByDescend : null
+ }
/>
&nbsp;&nbsp;
</p>
@@ -1508,12 +1719,19 @@ const DetailsTable = ({
)
})()}
{(() => {
- const numericColsCount = 1 + (detailsExtraColumns?.length || 0) + (!hidePercentageInDetails ? 1 : 0)
+ const numericColsCount =
+ 1 +
+ (detailsExtraColumns?.length || 0) +
+ (!hidePercentageInDetails ? 1 : 0)
const numericColWidth = `${(60 / numericColsCount).toFixed(3)}%`
return (
<>
{detailsExtraColumns?.map((col, idx) => (
- <th key={`extra-col-${idx}`} style={{ width: numericColWidth }} className='pr-2'>
+ <th
+ key={`extra-col-${idx}`}
+ style={{ width: numericColWidth }}
+ className='pr-2'
+ >
<p
className='flex cursor-pointer items-center justify-end hover:opacity-90'
onClick={() => onSortBy(col.sortLabel)}
@@ -1521,15 +1739,25 @@ const DetailsTable = ({
{col.header}
<Sort
className='ml-1'
- sortByAscend={sort.label === col.sortLabel ? sort.sortByAscend : null}
- sortByDescend={sort.label === col.sortLabel ? sort.sortByDescend : null}
+ sortByAscend={
+ sort.label === col.sortLabel
+ ? sort.sortByAscend
+ : null
+ }
+ sortByDescend={
+ sort.label === col.sortLabel
+ ? sort.sortByDescend
+ : null
+ }
/>
</p>
</th>
))}
{!hidePercentageInDetails ? (
<th style={{ width: numericColWidth }} className='pr-2'>
- <p className='flex items-center justify-end'>{t('project.percentage')}</p>
+ <p className='flex items-center justify-end'>
+ {t('project.percentage')}
+ </p>
</th>
) : null}
</>
@@ -1538,7 +1766,12 @@ const DetailsTable = ({
</tr>
</thead>
- <tbody style={{ position: 'relative', height: `${rowVirtualizer.getTotalSize()}px` }}>
+ <tbody
+ style={{
+ position: 'relative',
+ height: `${rowVirtualizer.getTotalSize()}px`,
+ }}
+ >
{rowVirtualizer.getVirtualItems().map((virtualRow: VirtualItem) => {
const entry = filteredData[virtualRow.index]
if (!entry) return null
@@ -1573,11 +1806,17 @@ const DetailsTable = ({
}
}}
>
- <td className='flex items-center py-1 pl-2 text-left' style={{ width: '40%' }}>
+ <td
+ className='flex items-center py-1 pl-2 text-left'
+ style={{ width: '40%' }}
+ >
<span
- className={cx('scrollbar-thin hover-always-overflow flex items-center whitespace-nowrap', {
- capitalize,
- })}
+ className={cx(
+ 'scrollbar-thin hover-always-overflow flex items-center whitespace-nowrap',
+ {
+ capitalize,
+ },
+ )}
>
{linkContent ? (
<a
@@ -1604,17 +1843,28 @@ const DetailsTable = ({
) : null}
</td>
{(() => {
- const numericColsCount = 1 + (detailsExtraColumns?.length || 0) + (!hidePercentageInDetails ? 1 : 0)
+ const numericColsCount =
+ 1 +
+ (detailsExtraColumns?.length || 0) +
+ (!hidePercentageInDetails ? 1 : 0)
const numericColWidth = `${(60 / numericColsCount).toFixed(3)}%`
return (
- <td style={{ width: numericColWidth }} className='py-1 text-right'>
- {activeTab === PROJECT_TABS.traffic ? nFormatter(valueData, 1) : valueData}
+ <td
+ style={{ width: numericColWidth }}
+ className='py-1 text-right'
+ >
+ {activeTab === PROJECT_TABS.traffic
+ ? nFormatter(valueData, 1)
+ : valueData}
&nbsp;&nbsp;
</td>
)
})()}
{(() => {
- const numericColsCount = 1 + (detailsExtraColumns?.length || 0) + (!hidePercentageInDetails ? 1 : 0)
+ const numericColsCount =
+ 1 +
+ (detailsExtraColumns?.length || 0) +
+ (!hidePercentageInDetails ? 1 : 0)
const numericColWidth = `${(60 / numericColsCount).toFixed(3)}%`
return (
<>
@@ -1628,7 +1878,10 @@ const DetailsTable = ({
</td>
))}
{!hidePercentageInDetails ? (
- <td style={{ width: numericColWidth }} className='py-1 pr-2 text-right'>
+ <td
+ style={{ width: numericColWidth }}
+ className='py-1 pr-2 text-right'
+ >
{perc}%
</td>
) : null}
@@ -1674,9 +1927,14 @@ const Panel = ({
const dataLoading = dataLoadingProp ?? ctx.dataLoading
const activeTab = activeTabProp ?? ctx.activeTab
const { t } = useTranslation('common')
- const total = useMemo(() => _reduce(data, (prev, curr) => prev + curr.count, 0), [data])
+ const total = useMemo(
+ () => _reduce(data, (prev, curr) => prev + curr.count, 0),
+ [data],
+ )
const [detailsOpened, setDetailsOpened] = useState(false)
- const [expandedItems, setExpandedItems] = useState<Set<string | null>>(new Set())
+ const [expandedItems, setExpandedItems] = useState<Set<string | null>>(
+ new Set(),
+ )
const tnMapping = typeNameMapping(t)
@@ -1699,12 +1957,18 @@ const Panel = ({
const hasVersions = (itemName: string | null) => {
if (itemName === null) return false
- return versionData && versionData[itemName] && versionData[itemName].length > 0
+ return (
+ versionData && versionData[itemName] && versionData[itemName].length > 0
+ )
}
return (
<PanelContainer
- onDetailsClick={_size(data) > ENTRIES_PER_PANEL ? () => setDetailsOpened(true) : undefined}
+ onDetailsClick={
+ _size(data) > ENTRIES_PER_PANEL
+ ? () => setDetailsOpened(true)
+ : undefined
+ }
name={name}
icon={icon}
type={id}
@@ -1740,22 +2004,30 @@ const Panel = ({
const link = getFilterLink(id, entryName)
return (
- <div key={`${id}-${entryName}-${Object.values(rest).join('-')}`} className='space-y-0.5'>
+ <div
+ key={`${id}-${entryName}-${Object.values(rest).join('-')}`}
+ className='space-y-0.5'
+ >
<div
className={cx(
'relative flex h-8 items-center justify-between rounded-sm px-1 py-1.5 dark:text-gray-50',
{
'group hover:bg-gray-50 hover:dark:bg-slate-800':
- !hideFilters && !dataLoading && (link || hasVersionsForItem),
+ !hideFilters &&
+ !dataLoading &&
+ (link || hasVersionsForItem),
'cursor-wait': dataLoading,
},
)}
>
<div
className={cx('absolute inset-0 rounded-sm', {
- 'bg-blue-50 dark:bg-blue-900/30': highlightColour === 'blue',
- 'bg-red-50 dark:bg-red-900/20': highlightColour === 'red',
- 'bg-orange-50 dark:bg-orange-400/20': highlightColour === 'orange',
+ 'bg-blue-50 dark:bg-blue-900/30':
+ highlightColour === 'blue',
+ 'bg-red-50 dark:bg-red-900/20':
+ highlightColour === 'red',
+ 'bg-orange-50 dark:bg-orange-400/20':
+ highlightColour === 'orange',
})}
style={{ width: `${perc}%` }}
/>
@@ -1770,12 +2042,17 @@ const Panel = ({
toggleExpanded(entryName)
}}
className='mr-1 rounded p-0.5 hover:bg-gray-200 dark:hover:bg-slate-600'
- aria-label={isExpanded ? 'Collapse versions' : 'Expand versions'}
+ aria-label={
+ isExpanded ? 'Collapse versions' : 'Expand versions'
+ }
>
<ChevronRightIcon
- className={cx('h-4 w-4 text-gray-500 transition-transform dark:text-gray-400', {
- 'rotate-90': isExpanded,
- })}
+ className={cx(
+ 'h-4 w-4 text-gray-500 transition-transform dark:text-gray-400',
+ {
+ 'rotate-90': isExpanded,
+ },
+ )}
/>
</button>
) : null}
@@ -1784,7 +2061,11 @@ const Panel = ({
as={!disableRowClick && link ? 'Link' : 'div'}
to={link}
className={cx('flex min-w-0 flex-1 items-center', {
- 'cursor-pointer': !disableRowClick && !hideFilters && !dataLoading && link,
+ 'cursor-pointer':
+ !disableRowClick &&
+ !hideFilters &&
+ !dataLoading &&
+ link,
'cursor-wait': dataLoading,
})}
>
@@ -1822,7 +2103,9 @@ const Panel = ({
({perc}%)
</span>
<span className='text-sm font-medium text-gray-900 dark:text-gray-50'>
- {activeTab === PROJECT_TABS.traffic ? nFormatter(valueData, 1) : valueData}
+ {activeTab === PROJECT_TABS.traffic
+ ? nFormatter(valueData, 1)
+ : valueData}
</span>
</div>
</div>
@@ -1830,7 +2113,10 @@ const Panel = ({
{hasVersionsForItem && isExpanded ? (
<div className='ml-6 space-y-0.5'>
{_map(versions, (versionEntry) => {
- const versionPerc = _round((versionEntry.count / total) * 100, 2)
+ const versionPerc = _round(
+ (versionEntry.count / total) * 100,
+ 2,
+ )
const versionValueData = valueMapper(versionEntry.count)
const versionLink = disableRowClick
? undefined
@@ -1839,13 +2125,18 @@ const Panel = ({
return (
<FilterWrapper
key={`${id}-${entryName}-${versionEntry.name}`}
- as={!disableRowClick && versionLink ? 'Link' : 'div'}
+ as={
+ !disableRowClick && versionLink ? 'Link' : 'div'
+ }
to={versionLink}
className={cx(
'relative flex items-center justify-between rounded-sm px-1 py-1.5 dark:text-gray-50',
{
'group cursor-pointer hover:bg-gray-50 hover:dark:bg-slate-800':
- !disableRowClick && !hideFilters && !dataLoading && versionLink,
+ !disableRowClick &&
+ !hideFilters &&
+ !dataLoading &&
+ versionLink,
'cursor-wait': dataLoading,
},
)}
@@ -1857,12 +2148,19 @@ const Panel = ({
<div className='relative z-10 flex min-w-0 flex-1 items-center'>
<span
- className={cx('flex items-center truncate text-sm text-gray-700 dark:text-gray-200', {
- capitalize,
- })}
+ className={cx(
+ 'flex items-center truncate text-sm text-gray-700 dark:text-gray-200',
+ {
+ capitalize,
+ },
+ )}
>
{rowMapper
- ? rowMapper({ ...entry, name: entryName, version: versionEntry.name })
+ ? rowMapper({
+ ...entry,
+ name: entryName,
+ version: versionEntry.name,
+ })
: `${entryName} ${versionEntry.name}`}
</span>
</div>
@@ -1900,7 +2198,11 @@ const Panel = ({
})
const found = flatTabs.find((t) => t.id === activeTabId)
return (
- found?.label || (tnMapping[activeTabId as keyof typeof tnMapping] as unknown as string) || (name as string)
+ found?.label ||
+ (tnMapping[
+ activeTabId as keyof typeof tnMapping
+ ] as unknown as string) ||
+ (name as string)
)
})()}
message={
@@ -1915,7 +2217,11 @@ const Panel = ({
valueMapper={valueMapper}
capitalize={capitalize || false}
linkContent={linkContent || false}
- getFilterLink={disableRowClick ? () => '' : (getFilterLink as (id: string, name: string | null) => string)}
+ getFilterLink={
+ disableRowClick
+ ? () => ''
+ : (getFilterLink as (id: string, name: string | null) => string)
+ }
disableRowClick={disableRowClick}
hidePercentageInDetails={hidePercentageInDetails}
detailsExtraColumns={detailsExtraColumns}
@@ -1948,9 +2254,13 @@ const MetadataPanel = ({ metadata }: MetadataPanelProps) => {
})
const currentIndex = page * ENTRIES_PER_PANEL
- const totalPages = useMemo(() => _ceil(_size(metadata) / ENTRIES_PER_PANEL), [metadata])
+ const totalPages = useMemo(
+ () => _ceil(_size(metadata) / ENTRIES_PER_PANEL),
+ [metadata],
+ )
const canGoPrev = () => page > 0
- const canGoNext = () => page < _floor((_size(metadata) - 1) / ENTRIES_PER_PANEL)
+ const canGoNext = () =>
+ page < _floor((_size(metadata) - 1) / ENTRIES_PER_PANEL)
const sortedData = useMemo(() => {
return [...metadata].sort((a, b) => {
@@ -1959,10 +2269,14 @@ const MetadataPanel = ({ metadata }: MetadataPanelProps) => {
}
if (sort.label === 'value') {
- return sort.sortByAscend ? a.value.localeCompare(b.value) : b.value.localeCompare(a.value)
+ return sort.sortByAscend
+ ? a.value.localeCompare(b.value)
+ : b.value.localeCompare(a.value)
}
- return sort.sortByAscend ? a.key.localeCompare(b.key) : b.key.localeCompare(a.key)
+ return sort.sortByAscend
+ ? a.key.localeCompare(b.key)
+ : b.key.localeCompare(a.key)
})
}, [metadata, sort])
@@ -2036,8 +2350,12 @@ const MetadataPanel = ({ metadata }: MetadataPanelProps) => {
{t('project.key')}
<Sort
className='ml-1'
- sortByAscend={sort.label === 'key' ? sort.sortByAscend : null}
- sortByDescend={sort.label === 'key' ? sort.sortByDescend : null}
+ sortByAscend={
+ sort.label === 'key' ? sort.sortByAscend : null
+ }
+ sortByDescend={
+ sort.label === 'key' ? sort.sortByDescend : null
+ }
/>
</th>
<th className='w-[30%] sm:w-1/6'>
@@ -2048,8 +2366,12 @@ const MetadataPanel = ({ metadata }: MetadataPanelProps) => {
{t('project.value')}
<Sort
className='ml-1'
- sortByAscend={sort.label === 'value' ? sort.sortByAscend : null}
- sortByDescend={sort.label === 'value' ? sort.sortByDescend : null}
+ sortByAscend={
+ sort.label === 'value' ? sort.sortByAscend : null
+ }
+ sortByDescend={
+ sort.label === 'value' ? sort.sortByDescend : null
+ }
/>
&nbsp;&nbsp;
</p>
@@ -2062,8 +2384,12 @@ const MetadataPanel = ({ metadata }: MetadataPanelProps) => {
{t('project.quantity')}
<Sort
className='ml-1'
- sortByAscend={sort.label === 'count' ? sort.sortByAscend : null}
- sortByDescend={sort.label === 'count' ? sort.sortByDescend : null}
+ sortByAscend={
+ sort.label === 'count' ? sort.sortByAscend : null
+ }
+ sortByDescend={
+ sort.label === 'count' ? sort.sortByDescend : null
+ }
/>
</p>
</th>
@@ -2080,7 +2406,9 @@ const MetadataPanel = ({ metadata }: MetadataPanelProps) => {
{value}
&nbsp;&nbsp;
</td>
- <td className='w-[30%] py-1 pr-2 text-right sm:w-1/6'>{count}</td>
+ <td className='w-[30%] py-1 pr-2 text-right sm:w-1/6'>
+ {count}
+ </td>
</tr>
))}
</tbody>
diff --git a/web/app/pages/Project/View/ViewProject.helpers.tsx b/web/app/pages/Project/View/ViewProject.helpers.tsx
index 4f0a011b2..f3beec6fa 100644
--- a/web/app/pages/Project/View/ViewProject.helpers.tsx
+++ b/web/app/pages/Project/View/ViewProject.helpers.tsx
@@ -56,7 +56,12 @@ import {
} from '~/lib/constants'
import { Entry } from '~/lib/models/Entry'
import { AnalyticsFunnel, Annotation } from '~/lib/models/Project'
-import { getTimeFromSeconds, getStringFromTime, sumArrays, nFormatter } from '~/utils/generic'
+import {
+ getTimeFromSeconds,
+ getStringFromTime,
+ sumArrays,
+ nFormatter,
+} from '~/utils/generic'
import countries from '~/utils/isoCountries'
import { TrafficLogResponse } from './interfaces/traffic'
@@ -75,7 +80,10 @@ const getSum = (arr: any) => {
return _reduce(arr, (acc, c) => acc + c, 0)
}
-const calculateOptimalTicks = (data: number[], targetCount: number = 6): number[] => {
+const calculateOptimalTicks = (
+ data: number[],
+ targetCount: number = 6,
+): number[] => {
const min = Math.min(...data.filter((n) => n !== undefined && n !== null))
const max = Math.max(...data.filter((n) => n !== undefined && n !== null))
@@ -165,7 +173,10 @@ const trendline = (data: any[]): string[] => {
const getExportFilename = (prefix: string) => {
// turn something like 2022-03-02T19:31:00.100Z into 2022-03-02
- const date = _split(_replace(_split(new Date().toISOString(), '.')[0], /:/g, '-'), 'T')[0]
+ const date = _split(
+ _replace(_split(new Date().toISOString(), '.')[0], /:/g, '-'),
+ 'T',
+ )[0]
return `${prefix}-${date}.zip`
}
@@ -262,8 +273,16 @@ const getColumns = (
activeChartMetrics: Record<string, boolean>,
compareChart?: TrafficLogResponse['chart'] & { [key: string]: number[] },
) => {
- const { views, bounce, viewsPerUnique, unique, trendlines, sessionDuration, occurrences, avgResponseTime } =
- activeChartMetrics
+ const {
+ views,
+ bounce,
+ viewsPerUnique,
+ unique,
+ trendlines,
+ sessionDuration,
+ occurrences,
+ avgResponseTime,
+ } = activeChartMetrics
const columns: any[] = [['x', ..._map(chart.x, (el) => dayjs(el).toDate())]]
@@ -331,7 +350,10 @@ const getColumns = (
columns.push(['revenue', ...chart.revenue])
// Add refundsAmount if available for stacked bar display
if (chart.refundsAmount) {
- const hasAnyRefunds = _some(chart.refundsAmount, (v) => Number(v || 0) > 0)
+ const hasAnyRefunds = _some(
+ chart.refundsAmount,
+ (v) => Number(v || 0) > 0,
+ )
if (hasAnyRefunds) {
columns.push(['refundsAmount', ...chart.refundsAmount])
}
@@ -348,7 +370,12 @@ const getColumnsPerf = (
) => {
const columns: any[] = [['x', ..._map(chart.x, (el) => dayjs(el).toDate())]]
- if (activeChartMetrics === CHART_METRICS_MAPPING_PERF.quantiles && chart?.p50 && chart?.p75 && chart?.p95) {
+ if (
+ activeChartMetrics === CHART_METRICS_MAPPING_PERF.quantiles &&
+ chart?.p50 &&
+ chart?.p75 &&
+ chart?.p95
+ ) {
columns.push(['p50', ...chart.p50])
columns.push(['p75', ...chart.p75])
columns.push(['p95', ...chart.p95])
@@ -390,7 +417,10 @@ const getColumnsPerf = (
if (activeChartMetrics === CHART_METRICS_MAPPING_PERF.timing && chart.ttfb) {
columns.push(['frontend', ...sumArrays(chart.render, chart.domLoad)])
- columns.push(['network', ...sumArrays(chart.dns, chart.tls, chart.conn, chart.response)])
+ columns.push([
+ 'network',
+ ...sumArrays(chart.dns, chart.tls, chart.conn, chart.response),
+ ])
columns.push(['backend', ...chart.ttfb])
if (
@@ -402,10 +432,18 @@ const getColumnsPerf = (
compareChart?.domLoad &&
compareChart?.ttfb
) {
- columns.push(['frontendCompare', ...sumArrays(compareChart.render, compareChart.domLoad)])
+ columns.push([
+ 'frontendCompare',
+ ...sumArrays(compareChart.render, compareChart.domLoad),
+ ])
columns.push([
'networkCompare',
- ...sumArrays(compareChart.dns, compareChart.tls, compareChart.conn, compareChart.response),
+ ...sumArrays(
+ compareChart.dns,
+ compareChart.tls,
+ compareChart.conn,
+ compareChart.response,
+ ),
])
columns.push(['backendCompare', ...compareChart.ttfb])
}
@@ -417,7 +455,12 @@ const getColumnsPerf = (
columns.push(['conn', ...chart.conn])
columns.push(['response', ...chart.response])
- if (compareChart?.dns && compareChart?.tls && compareChart?.conn && compareChart?.response) {
+ if (
+ compareChart?.dns &&
+ compareChart?.tls &&
+ compareChart?.conn &&
+ compareChart?.response
+ ) {
columns.push(['dnsCompare', ...compareChart.dns])
columns.push(['tlsCompare', ...compareChart.tls])
columns.push(['connCompare', ...compareChart.conn])
@@ -425,7 +468,10 @@ const getColumnsPerf = (
}
}
- if (activeChartMetrics === CHART_METRICS_MAPPING_PERF.frontend && chart.render) {
+ if (
+ activeChartMetrics === CHART_METRICS_MAPPING_PERF.frontend &&
+ chart.render
+ ) {
columns.push(['render', ...chart.render])
columns.push(['dom_load', ...chart.domLoad])
@@ -446,12 +492,23 @@ const getColumnsPerf = (
return columns
}
-const getValueForTooltipPerfomance = (chart: Record<string, string[]>, id: string, index: number) => {
+const getValueForTooltipPerfomance = (
+ chart: Record<string, string[]>,
+ id: string,
+ index: number,
+) => {
if (id === 'p50' || id === 'p75' || id === 'p95') {
return chart[id] ? chart[id][index] : 0
}
- if (id === 'dns' || id === 'tls' || id === 'conn' || id === 'response' || id === 'render' || id === 'ttfb') {
+ if (
+ id === 'dns' ||
+ id === 'tls' ||
+ id === 'conn' ||
+ id === 'response' ||
+ id === 'render' ||
+ id === 'ttfb'
+ ) {
return chart[id] ? chart[id][index] : 0
}
@@ -559,16 +616,23 @@ const getSettings = (
// Calculate optimal Y axis ticks based on the data
const allYValues: number[] = []
if (activeChartMetrics.unique && chart.uniques) {
- allYValues.push(...chart.uniques.filter((n) => n !== undefined && n !== null))
+ allYValues.push(
+ ...chart.uniques.filter((n) => n !== undefined && n !== null),
+ )
}
if (activeChartMetrics.views && chart.visits) {
- allYValues.push(...chart.visits.filter((n) => n !== undefined && n !== null))
+ allYValues.push(
+ ...chart.visits.filter((n) => n !== undefined && n !== null),
+ )
}
if (activeChartMetrics.occurrences && chart.occurrences) {
- allYValues.push(...chart.occurrences.filter((n) => n !== undefined && n !== null))
+ allYValues.push(
+ ...chart.occurrences.filter((n) => n !== undefined && n !== null),
+ )
}
- const optimalTicks = allYValues.length > 0 ? calculateOptimalTicks(allYValues) : undefined
+ const optimalTicks =
+ allYValues.length > 0 ? calculateOptimalTicks(allYValues) : undefined
if (applyRegions) {
let regionStart
@@ -630,7 +694,8 @@ const getSettings = (
trendlineUnique: spline(),
trendlineTotal: spline(),
sessionDuration: chartType === chartTypes.line ? spline() : bar(),
- sessionDurationCompare: chartType === chartTypes.line ? spline() : bar(),
+ sessionDurationCompare:
+ chartType === chartTypes.line ? spline() : bar(),
// Revenue is always bars (stacked with refunds)
revenue: bar(),
refundsAmount: bar(),
@@ -652,7 +717,9 @@ const getSettings = (
...customEventsColors,
},
// Stack revenue and refundsAmount together
- groups: activeChartMetrics.revenue ? [['revenue', 'refundsAmount']] : undefined,
+ groups: activeChartMetrics.revenue
+ ? [['revenue', 'refundsAmount']]
+ : undefined,
// Prevent billboard/c3 from auto-reordering stacked series
// (we need refunds stacked on top of revenue consistently)
order: activeChartMetrics.revenue ? null : undefined,
@@ -690,8 +757,14 @@ const getSettings = (
format:
// @ts-expect-error
timeFormat === TimeFormat['24-hour']
- ? (x: string) => d3.timeFormat(tbsFormatMapper24h[timeBucket])(x as unknown as Date)
- : (x: string) => d3.timeFormat(tbsFormatMapper[timeBucket])(x as unknown as Date),
+ ? (x: string) =>
+ d3.timeFormat(tbsFormatMapper24h[timeBucket])(
+ x as unknown as Date,
+ )
+ : (x: string) =>
+ d3.timeFormat(tbsFormatMapper[timeBucket])(
+ x as unknown as Date,
+ ),
},
localtime: timeFormat === TimeFormat['24-hour'],
type: 'timeseries',
@@ -705,7 +778,10 @@ const getSettings = (
inner: true,
},
y2: {
- show: activeChartMetrics.bounce || activeChartMetrics.sessionDuration || activeChartMetrics.revenue,
+ show:
+ activeChartMetrics.bounce ||
+ activeChartMetrics.sessionDuration ||
+ activeChartMetrics.revenue,
tick: {
// @ts-expect-error
format: activeChartMetrics.bounce
@@ -734,9 +810,17 @@ const getSettings = (
? d3.timeFormat(tbsFormatMapperTooltip24h[timeBucket])(item[0].x)
: d3.timeFormat(tbsFormatMapperTooltip[timeBucket])(item[0].x)
}</li>
- ${_map(item, (el: { id: string; index: number; name: string; value: string; x: Date }) => {
- if (el.id === 'sessionDuration') {
- return `
+ ${_map(
+ item,
+ (el: {
+ id: string
+ index: number
+ name: string
+ value: string
+ x: Date
+ }) => {
+ if (el.id === 'sessionDuration') {
+ return `
<li class='flex justify-between items-center py-px leading-snug'>
<div class='flex items-center min-w-0 mr-4'>
<div class='w-2.5 h-2.5 rounded-xs mr-1.5 flex-shrink-0' style=background-color:${color(el.id)}></div>
@@ -745,15 +829,15 @@ const getSettings = (
<span class='font-mono whitespace-nowrap'>${getStringFromTime(getTimeFromSeconds(el.value))}</span>
</li>
`
- }
+ }
- if (el.id === 'trendlineUnique' || el.id === 'trendlineTotal') {
- return ''
- }
+ if (el.id === 'trendlineUnique' || el.id === 'trendlineTotal') {
+ return ''
+ }
- // Format revenue and refunds as currency
- if (el.id === 'revenue') {
- return `
+ // Format revenue and refunds as currency
+ if (el.id === 'revenue') {
+ return `
<li class='flex justify-between items-center py-px leading-snug'>
<div class='flex items-center min-w-0 mr-4'>
<div class='w-2.5 h-2.5 rounded-xs mr-1.5 flex-shrink-0' style='background-color:${color(el.id)}'></div>
@@ -762,10 +846,10 @@ const getSettings = (
<span class='font-mono whitespace-nowrap'>$${nFormatter(Number(el.value) || 0, 2)}</span>
</li>
`
- }
+ }
- if (el.id === 'refundsAmount') {
- return `
+ if (el.id === 'refundsAmount') {
+ return `
<li class='flex justify-between items-center py-px leading-snug'>
<div class='flex items-center min-w-0 mr-4'>
<div class='w-2.5 h-2.5 rounded-xs mr-1.5 flex-shrink-0' style='background-color:rgba(234,88,12,0.25);border:1.5px dashed #ea580c'></div>
@@ -774,9 +858,9 @@ const getSettings = (
<span class='font-mono whitespace-nowrap'>$${nFormatter(Number(el.value) || 0, 2)}</span>
</li>
`
- }
+ }
- return `
+ return `
<li class='flex justify-between items-center py-px leading-snug'>
<div class='flex items-center min-w-0 mr-4'>
<div class='w-2.5 h-2.5 rounded-xs mr-1.5 flex-shrink-0' style=background-color:${color(el.id)}></div>
@@ -785,38 +869,61 @@ const getSettings = (
<span class='font-mono whitespace-nowrap'>${el.value}</span>
</li>
`
- }).join('')}</ul>`
+ },
+ ).join('')}</ul>`
}
return `
<ul class='bg-gray-50 dark:text-gray-50 dark:bg-slate-800 rounded-md ring-1 ring-black/10 px-2 py-1 text-xs md:text-sm max-h-[250px] md:max-h-[350px] overflow-y-auto shadow-lg z-50'>
- ${_map(item, (el: { id: string; index: number; name: string; value: string; x: Date }) => {
- const { id, index, name, value, x } = el
-
- const xDataValueCompare =
- timeFormat === TimeFormat['24-hour']
- ? d3.timeFormat(tbsFormatMapperTooltip24h[timeBucket])(dayjs(compareChart?.x[index]).toDate())
- : d3.timeFormat(tbsFormatMapperTooltip[timeBucket])(dayjs(compareChart?.x[index]).toDate())
- const xDataValue =
- timeFormat === TimeFormat['24-hour']
- ? d3.timeFormat(tbsFormatMapperTooltip24h[timeBucket])(x as unknown as Date)
- : d3.timeFormat(tbsFormatMapperTooltip[timeBucket])(x as unknown as Date)
- const valueCompare =
- id === 'sessionDuration'
- ? getStringFromTime(getTimeFromSeconds(compareChart?.[typesOptionsToTypesCompare?.[id]]?.[index]))
- : compareChart?.[typesOptionsToTypesCompare[id]]?.[index]
-
- if (
- id === 'uniqueCompare' ||
- id === 'totalCompare' ||
- id === 'bounceCompare' ||
- id === 'sessionDurationCompare'
- ) {
- return ''
- }
+ ${_map(
+ item,
+ (el: {
+ id: string
+ index: number
+ name: string
+ value: string
+ x: Date
+ }) => {
+ const { id, index, name, value, x } = el
+
+ const xDataValueCompare =
+ timeFormat === TimeFormat['24-hour']
+ ? d3.timeFormat(tbsFormatMapperTooltip24h[timeBucket])(
+ dayjs(compareChart?.x[index]).toDate(),
+ )
+ : d3.timeFormat(tbsFormatMapperTooltip[timeBucket])(
+ dayjs(compareChart?.x[index]).toDate(),
+ )
+ const xDataValue =
+ timeFormat === TimeFormat['24-hour']
+ ? d3.timeFormat(tbsFormatMapperTooltip24h[timeBucket])(
+ x as unknown as Date,
+ )
+ : d3.timeFormat(tbsFormatMapperTooltip[timeBucket])(
+ x as unknown as Date,
+ )
+ const valueCompare =
+ id === 'sessionDuration'
+ ? getStringFromTime(
+ getTimeFromSeconds(
+ compareChart?.[typesOptionsToTypesCompare?.[id]]?.[
+ index
+ ],
+ ),
+ )
+ : compareChart?.[typesOptionsToTypesCompare[id]]?.[index]
+
+ if (
+ id === 'uniqueCompare' ||
+ id === 'totalCompare' ||
+ id === 'bounceCompare' ||
+ id === 'sessionDurationCompare'
+ ) {
+ return ''
+ }
- if (id === 'sessionDuration') {
- return `
+ if (id === 'sessionDuration') {
+ return `
<div class='flex justify-between items-center py-px leading-snug'>
<div class='flex items-center min-w-0 mr-4'>
<div class='w-2.5 h-2.5 rounded-xs mr-1.5 flex-shrink-0' style=background-color:${color(id)}></div>
@@ -830,7 +937,10 @@ const getSettings = (
<span class='font-mono whitespace-nowrap'>${getStringFromTime(getTimeFromSeconds(value))}</span>
</p>
${
- valueCompare && Number(compareChart?.[typesOptionsToTypesCompare?.[id]]?.[index]) > 0
+ valueCompare &&
+ Number(
+ compareChart?.[typesOptionsToTypesCompare?.[id]]?.[index],
+ ) > 0
? `<p class='flex justify-between'>
<span class="mr-2">${xDataValueCompare}</span> -
<span class='font-mono whitespace-nowrap'>${valueCompare}</span>
@@ -839,9 +949,9 @@ const getSettings = (
}
</li>
`
- }
+ }
- return `
+ return `
<div class='flex justify-between items-center py-px leading-snug'>
<div class='flex items-center min-w-0 mr-4'>
<div class='w-2.5 h-2.5 rounded-xs mr-1.5 flex-shrink-0' style=background-color:${color(id)}></div>
@@ -863,7 +973,8 @@ const getSettings = (
}
</li>
`
- }).join('')}
+ },
+ ).join('')}
</ul>`
},
},
@@ -885,7 +996,13 @@ const getSettings = (
r: 3,
},
},
- hide: ['uniqueCompare', 'totalCompare', 'bounceCompare', 'sessionDurationCompare', 'refundsAmount'],
+ hide: [
+ 'uniqueCompare',
+ 'totalCompare',
+ 'bounceCompare',
+ 'sessionDurationCompare',
+ 'refundsAmount',
+ ],
},
area: {
linearGradient: true,
@@ -950,7 +1067,9 @@ const getSettings = (
// Stacked bar chart for custom events
const getSettingsCustomEventsStacked = (
- chart: { x: string[]; events: Record<string, Array<number | string>> } | undefined,
+ chart:
+ | { x: string[]; events: Record<string, Array<number | string>> }
+ | undefined,
timeBucket: string,
rotateXAxis: boolean,
timeFormat: string,
@@ -963,7 +1082,10 @@ const getSettingsCustomEventsStacked = (
id,
total: _sum(_map(chart.events[id] || [], (v) => Number(v) || 0)),
}))
- const eventIds = _map(_orderBy(eventTotals, 'total', 'desc'), 'id') as string[]
+ const eventIds = _map(
+ _orderBy(eventTotals, 'total', 'desc'),
+ 'id',
+ ) as string[]
const columns: any[] = [['x', ..._map(chart.x, (el) => dayjs(el).toDate())]]
eventIds.forEach((id) => {
@@ -993,7 +1115,8 @@ const getSettingsCustomEventsStacked = (
eventIds.forEach((id) => {
allYValues.push(..._map(chart.events[id] || [], (v) => Number(v) || 0))
})
- const optimalTicks = allYValues.length > 0 ? calculateOptimalTicks(allYValues) : undefined
+ const optimalTicks =
+ allYValues.length > 0 ? calculateOptimalTicks(allYValues) : undefined
return {
data: {
@@ -1019,8 +1142,14 @@ const getSettingsCustomEventsStacked = (
format:
// @ts-expect-error
timeFormat === TimeFormat['24-hour']
- ? (x: string) => d3.timeFormat(tbsFormatMapper24h[timeBucket])(x as unknown as Date)
- : (x: string) => d3.timeFormat(tbsFormatMapper[timeBucket])(x as unknown as Date),
+ ? (x: string) =>
+ d3.timeFormat(tbsFormatMapper24h[timeBucket])(
+ x as unknown as Date,
+ )
+ : (x: string) =>
+ d3.timeFormat(tbsFormatMapper[timeBucket])(
+ x as unknown as Date,
+ ),
},
localtime: timeFormat === TimeFormat['24-hour'],
type: 'timeseries',
@@ -1048,7 +1177,13 @@ const getSettingsCustomEventsStacked = (
}</li>
${_map(
item,
- (el: { id: string; index: number; name: string; value: string; x: Date }) => `
+ (el: {
+ id: string
+ index: number
+ name: string
+ value: string
+ x: Date
+ }) => `
<li class='flex justify-between items-center py-px leading-snug'>
<div class='flex items-center min-w-0 mr-4'>
<div class='w-2.5 h-2.5 rounded-xs mr-1.5 flex-shrink-0' style=background-color:${color(el.id)}></div>
@@ -1105,7 +1240,9 @@ const getSettingsSession = (
const chartData = chartInput || { x: [] } // Default to an empty chart structure if undefined
const xAxisSize = _size(chartData.x)
- const columns: any[] = [['x', ..._map(chartData.x, (el) => dayjs(el).toDate())]]
+ const columns: any[] = [
+ ['x', ..._map(chartData.x, (el) => dayjs(el).toDate())],
+ ]
const dataTypes: Record<string, any> = {}
const dataColors: Record<string, string> = {}
@@ -1130,16 +1267,23 @@ const getSettingsSession = (
// Calculate optimal Y axis ticks based on the data
const allYValues: number[] = []
if (chartData.pageviews && !_isEmpty(chartData.pageviews)) {
- allYValues.push(...chartData.pageviews.filter((n) => n !== undefined && n !== null))
+ allYValues.push(
+ ...chartData.pageviews.filter((n) => n !== undefined && n !== null),
+ )
}
if (chartData.customEvents && !_isEmpty(chartData.customEvents)) {
- allYValues.push(...chartData.customEvents.filter((n) => n !== undefined && n !== null))
+ allYValues.push(
+ ...chartData.customEvents.filter((n) => n !== undefined && n !== null),
+ )
}
if (chartData.errors && !_isEmpty(chartData.errors)) {
- allYValues.push(...chartData.errors.filter((n) => n !== undefined && n !== null))
+ allYValues.push(
+ ...chartData.errors.filter((n) => n !== undefined && n !== null),
+ )
}
- const optimalTicks = allYValues.length > 0 ? calculateOptimalTicks(allYValues) : undefined
+ const optimalTicks =
+ allYValues.length > 0 ? calculateOptimalTicks(allYValues) : undefined
return {
data: {
@@ -1177,8 +1321,14 @@ const getSettingsSession = (
format:
// @ts-expect-error
timeFormat === TimeFormat['24-hour']
- ? (x: string) => d3.timeFormat(tbsFormatMapper24h[timeBucket])(x as unknown as Date)
- : (x: string) => d3.timeFormat(tbsFormatMapper[timeBucket])(x as unknown as Date),
+ ? (x: string) =>
+ d3.timeFormat(tbsFormatMapper24h[timeBucket])(
+ x as unknown as Date,
+ )
+ : (x: string) =>
+ d3.timeFormat(tbsFormatMapper[timeBucket])(
+ x as unknown as Date,
+ ),
},
localtime: timeFormat === TimeFormat['24-hour'],
type: 'timeseries',
@@ -1203,8 +1353,16 @@ const getSettingsSession = (
? d3.timeFormat(tbsFormatMapperTooltip24h[timeBucket])(item[0].x)
: d3.timeFormat(tbsFormatMapperTooltip[timeBucket])(item[0].x)
}</li>
- ${_map(item, (el: { id: string; index: number; name: string; value: string; x: Date }) => {
- return `
+ ${_map(
+ item,
+ (el: {
+ id: string
+ index: number
+ name: string
+ value: string
+ x: Date
+ }) => {
+ return `
<li class='flex justify-between items-center py-px leading-snug'>
<div class='flex items-center min-w-0 mr-4'>
<div class='w-2.5 h-2.5 rounded-xs mr-1.5 flex-shrink-0' style=background-color:${color(el.id)}></div>
@@ -1213,7 +1371,8 @@ const getSettingsSession = (
<span class='font-mono whitespace-nowrap'>${el.value}</span>
</li>
`
- }).join('')}</ul>`
+ },
+ ).join('')}</ul>`
},
},
point:
@@ -1262,18 +1421,23 @@ const getSettingsError = (
// Convert annotations to grid lines
// Each annotation gets a unique class identifier for DOM-based lookup
- const annotationLines: GridLineOptions[] = _map(annotations || [], (annotation) => ({
- value: dayjs(annotation.date).toDate(),
- text:
- annotation.text.length > ANNOTATION_CHART_TEXT_MAX_LENGTH
- ? `${annotation.text.substring(0, ANNOTATION_CHART_TEXT_MAX_LENGTH)}...`
- : annotation.text,
- class: `annotation-line annotation-id-${annotation.id}`,
- position: 'start',
- }))
+ const annotationLines: GridLineOptions[] = _map(
+ annotations || [],
+ (annotation) => ({
+ value: dayjs(annotation.date).toDate(),
+ text:
+ annotation.text.length > ANNOTATION_CHART_TEXT_MAX_LENGTH
+ ? `${annotation.text.substring(0, ANNOTATION_CHART_TEXT_MAX_LENGTH)}...`
+ : annotation.text,
+ class: `annotation-line annotation-id-${annotation.id}`,
+ position: 'start',
+ }),
+ )
// Build columns with both occurrences and affectedUsers if available
- const columns: any[] = [['x', ..._map(chart.x, (el: string) => dayjs(el).toDate())]]
+ const columns: any[] = [
+ ['x', ..._map(chart.x, (el: string) => dayjs(el).toDate())],
+ ]
if (chart.occurrences) {
columns.push(['occurrences', ...chart.occurrences])
@@ -1284,13 +1448,18 @@ const getSettingsError = (
const allYValues: number[] = []
if (chart.occurrences) {
- allYValues.push(...chart.occurrences.filter((n: any) => n !== undefined && n !== null))
+ allYValues.push(
+ ...chart.occurrences.filter((n: any) => n !== undefined && n !== null),
+ )
}
if (chart.affectedUsers) {
- allYValues.push(...chart.affectedUsers.filter((n: any) => n !== undefined && n !== null))
+ allYValues.push(
+ ...chart.affectedUsers.filter((n: any) => n !== undefined && n !== null),
+ )
}
- const optimalTicks = allYValues.length > 0 ? calculateOptimalTicks(allYValues) : undefined
+ const optimalTicks =
+ allYValues.length > 0 ? calculateOptimalTicks(allYValues) : undefined
let regionStart
@@ -1355,8 +1524,14 @@ const getSettingsError = (
format:
// @ts-expect-error
timeFormat === TimeFormat['24-hour']
- ? (x: string) => d3.timeFormat(tbsFormatMapper24h[timeBucket])(x as unknown as Date)
- : (x: string) => d3.timeFormat(tbsFormatMapper[timeBucket])(x as unknown as Date),
+ ? (x: string) =>
+ d3.timeFormat(tbsFormatMapper24h[timeBucket])(
+ x as unknown as Date,
+ )
+ : (x: string) =>
+ d3.timeFormat(tbsFormatMapper[timeBucket])(
+ x as unknown as Date,
+ ),
},
localtime: timeFormat === TimeFormat['24-hour'],
type: 'timeseries',
@@ -1380,7 +1555,13 @@ const getSettingsError = (
}</li>
${_map(
item,
- (el: { id: string; index: number; name: string; value: string; x: Date }) => `
+ (el: {
+ id: string
+ index: number
+ name: string
+ value: string
+ x: Date
+ }) => `
<li class='flex justify-between items-center py-px leading-snug'>
<div class='flex items-center min-w-0 mr-4'>
<div class='w-2.5 h-2.5 rounded-xs mr-1.5 flex-shrink-0' style=background-color:${color(el.id)}></div>
@@ -1423,7 +1604,11 @@ const getSettingsError = (
}
}
-const getSettingsFunnels = (funnel: AnalyticsFunnel[], totalPageviews: number, t: typeof i18next.t): ChartOptions => {
+const getSettingsFunnels = (
+ funnel: AnalyticsFunnel[],
+ totalPageviews: number,
+ t: typeof i18next.t,
+): ChartOptions => {
const values = _map(funnel, (step) => {
if (_startsWith(step.value, '/')) {
return t('project.visitPage', { page: step.value })
@@ -1442,7 +1627,8 @@ const getSettingsFunnels = (funnel: AnalyticsFunnel[], totalPageviews: number, t
if (dropoff && !_isEmpty(dropoff)) {
allYValues.push(...dropoff.filter((n) => n !== undefined && n !== null))
}
- const optimalTicks = allYValues.length > 0 ? calculateOptimalTicks(allYValues) : undefined
+ const optimalTicks =
+ allYValues.length > 0 ? calculateOptimalTicks(allYValues) : undefined
return {
data: {
@@ -1546,7 +1732,12 @@ const getSettingsFunnels = (funnel: AnalyticsFunnel[], totalPageviews: number, t
</td>
<td class='text-right font-mono'>
${
- index === 0 ? _round(((totalPageviews - step.events) / totalPageviews) * 100, 2) : step.dropoffPercStep
+ index === 0
+ ? _round(
+ ((totalPageviews - step.events) / totalPageviews) * 100,
+ 2,
+ )
+ : step.dropoffPercStep
}%
</td>
</tr>
@@ -1619,15 +1810,18 @@ const getSettingsPerf = (
// Convert annotations to grid lines
// Each annotation gets a unique class identifier for DOM-based lookup
- const annotationLines: GridLineOptions[] = _map(annotations || [], (annotation) => ({
- value: dayjs(annotation.date).toDate(),
- text:
- annotation.text.length > ANNOTATION_CHART_TEXT_MAX_LENGTH
- ? `${annotation.text.substring(0, ANNOTATION_CHART_TEXT_MAX_LENGTH)}...`
- : annotation.text,
- class: `annotation-line annotation-id-${annotation.id}`,
- position: 'start',
- }))
+ const annotationLines: GridLineOptions[] = _map(
+ annotations || [],
+ (annotation) => ({
+ value: dayjs(annotation.date).toDate(),
+ text:
+ annotation.text.length > ANNOTATION_CHART_TEXT_MAX_LENGTH
+ ? `${annotation.text.substring(0, ANNOTATION_CHART_TEXT_MAX_LENGTH)}...`
+ : annotation.text,
+ class: `annotation-line annotation-id-${annotation.id}`,
+ position: 'start',
+ }),
+ )
return {
data: {
@@ -1691,7 +1885,18 @@ const getSettingsPerf = (
backendCompare: 'rgba(0, 168, 232, 0.4)',
},
groups: [
- ['dns', 'tls', 'conn', 'response', 'render', 'dom_load', 'ttfb', 'frontend', 'network', 'backend'],
+ [
+ 'dns',
+ 'tls',
+ 'conn',
+ 'response',
+ 'render',
+ 'dom_load',
+ 'ttfb',
+ 'frontend',
+ 'network',
+ 'backend',
+ ],
[
'dnsCompare',
'tlsCompare',
@@ -1724,8 +1929,14 @@ const getSettingsPerf = (
format:
// @ts-expect-error
timeFormat === TimeFormat['24-hour']
- ? (x: string) => d3.timeFormat(tbsFormatMapper24h[timeBucket])(x as unknown as Date)
- : (x: string) => d3.timeFormat(tbsFormatMapper[timeBucket])(x as unknown as Date),
+ ? (x: string) =>
+ d3.timeFormat(tbsFormatMapper24h[timeBucket])(
+ x as unknown as Date,
+ )
+ : (x: string) =>
+ d3.timeFormat(tbsFormatMapper[timeBucket])(
+ x as unknown as Date,
+ ),
},
localtime: timeFormat === TimeFormat['24-hour'],
type: 'timeseries',
@@ -1755,8 +1966,16 @@ const getSettingsPerf = (
? d3.timeFormat(tbsFormatMapperTooltip24h[timeBucket])(item[0].x)
: d3.timeFormat(tbsFormatMapperTooltip[timeBucket])(item[0].x)
}</li>
- ${_map(item, (el: { id: string; index: number; name: string; value: string; x: Date }) => {
- return `
+ ${_map(
+ item,
+ (el: {
+ id: string
+ index: number
+ name: string
+ value: string
+ x: Date
+ }) => {
+ return `
<li class='flex justify-between items-center py-px leading-snug'>
<div class='flex items-center min-w-0 mr-4'>
<div class='w-2.5 h-2.5 rounded-xs mr-1.5 flex-shrink-0' style=background-color:${color(el.id)}></div>
@@ -1765,29 +1984,50 @@ const getSettingsPerf = (
<span class='font-mono whitespace-nowrap'>${getStringFromTime(getTimeFromSeconds(el.value), true)}</span>
</li>
`
- }).join('')}</ul>`
+ },
+ ).join('')}</ul>`
}
return `
<ul class='bg-gray-50 dark:text-gray-50 dark:bg-slate-800 rounded-md ring-1 ring-black/10 px-2 py-1 text-xs md:text-sm max-h-[250px] md:max-h-[350px] overflow-y-auto shadow-lg z-50'>
- ${_map(item, (el: { id: string; index: number; name: string; value: string; x: Date }) => {
- const { id, index, name, value, x } = el
-
- const xDataValueCompare =
- timeFormat === TimeFormat['24-hour']
- ? d3.timeFormat(tbsFormatMapperTooltip24h[timeBucket])(dayjs(compareChart?.x[index]).toDate())
- : d3.timeFormat(tbsFormatMapperTooltip[timeBucket])(dayjs(compareChart?.x[index]).toDate())
- const xDataValue =
- timeFormat === TimeFormat['24-hour']
- ? d3.timeFormat(tbsFormatMapperTooltip24h[timeBucket])(x as unknown as Date)
- : d3.timeFormat(tbsFormatMapperTooltip[timeBucket])(x as unknown as Date)
- const valueCompare = getValueForTooltipPerfomance(compareChart, id, index)
+ ${_map(
+ item,
+ (el: {
+ id: string
+ index: number
+ name: string
+ value: string
+ x: Date
+ }) => {
+ const { id, index, name, value, x } = el
- if (_includes(perfomanceChartCompare, id)) {
- return ''
- }
+ const xDataValueCompare =
+ timeFormat === TimeFormat['24-hour']
+ ? d3.timeFormat(tbsFormatMapperTooltip24h[timeBucket])(
+ dayjs(compareChart?.x[index]).toDate(),
+ )
+ : d3.timeFormat(tbsFormatMapperTooltip[timeBucket])(
+ dayjs(compareChart?.x[index]).toDate(),
+ )
+ const xDataValue =
+ timeFormat === TimeFormat['24-hour']
+ ? d3.timeFormat(tbsFormatMapperTooltip24h[timeBucket])(
+ x as unknown as Date,
+ )
+ : d3.timeFormat(tbsFormatMapperTooltip[timeBucket])(
+ x as unknown as Date,
+ )
+ const valueCompare = getValueForTooltipPerfomance(
+ compareChart,
+ id,
+ index,
+ )
+
+ if (_includes(perfomanceChartCompare, id)) {
+ return ''
+ }
- return `
+ return `
<div class='flex justify-between items-center py-px leading-snug'>
<div class='flex items-center min-w-0 mr-4'>
<div class='w-2.5 h-2.5 rounded-xs mr-1.5 flex-shrink-0' style=background-color:${color(id)}></div>
@@ -1809,7 +2049,8 @@ const getSettingsPerf = (
}
</li>
`
- }).join('')}
+ },
+ ).join('')}
</ul>`
},
},
@@ -1932,8 +2173,11 @@ const SHORTCUTS_TABS_MAP = {
R: PROJECT_TABS.errors,
}
-const _SHORTCUTS_TABS_LISTENERS = 'shift+t, shift+p, shift+u, shift+s, shift+f, shift+e, shift+r'
-const SHORTCUTS_TABS_LISTENERS = isSelfhosted ? _SHORTCUTS_TABS_LISTENERS : _SHORTCUTS_TABS_LISTENERS + ', shift+a'
+const _SHORTCUTS_TABS_LISTENERS =
+ 'shift+t, shift+p, shift+u, shift+s, shift+f, shift+e, shift+r'
+const SHORTCUTS_TABS_LISTENERS = isSelfhosted
+ ? _SHORTCUTS_TABS_LISTENERS
+ : _SHORTCUTS_TABS_LISTENERS + ', shift+a'
const _SHORTCUTS_GENERAL_LISTENERS = 'alt+s,alt+ß, alt+b,alt+∫, alt+l,alt+¬, r'
const SHORTCUTS_GENERAL_LISTENERS = isSelfhosted
@@ -1942,7 +2186,11 @@ const SHORTCUTS_GENERAL_LISTENERS = isSelfhosted
const SHORTCUTS_TIMEBUCKETS_LISTENERS = 'h, t, y, d, w, m, q, l, z, a, u, c'
-export const getDeviceRowMapper = (activeTab: string, theme: string, t: typeof i18next.t) => {
+export const getDeviceRowMapper = (
+ activeTab: string,
+ theme: string,
+ t: typeof i18next.t,
+) => {
if (activeTab === 'br') {
// eslint-disable-next-line
return (entry: any) => {
@@ -2076,10 +2324,13 @@ const getSettingsCaptcha = (
const allYValues: number[] = []
if (chart.results) {
- allYValues.push(...chart.results.filter((n: any) => n !== undefined && n !== null))
+ allYValues.push(
+ ...chart.results.filter((n: any) => n !== undefined && n !== null),
+ )
}
- const optimalTicks = allYValues.length > 0 ? calculateOptimalTicks(allYValues) : undefined
+ const optimalTicks =
+ allYValues.length > 0 ? calculateOptimalTicks(allYValues) : undefined
let regionStart
@@ -2132,8 +2383,14 @@ const getSettingsCaptcha = (
format:
// @ts-expect-error
timeFormat === TimeFormat['24-hour']
- ? (x: string) => d3.timeFormat(tbsFormatMapper24h[timeBucket])(x as unknown as Date)
- : (x: string) => d3.timeFormat(tbsFormatMapper[timeBucket])(x as unknown as Date),
+ ? (x: string) =>
+ d3.timeFormat(tbsFormatMapper24h[timeBucket])(
+ x as unknown as Date,
+ )
+ : (x: string) =>
+ d3.timeFormat(tbsFormatMapper[timeBucket])(
+ x as unknown as Date,
+ ),
},
localtime: timeFormat === TimeFormat['24-hour'],
type: 'timeseries',
@@ -2157,7 +2414,13 @@ const getSettingsCaptcha = (
}</li>
${_map(
item,
- (el: { id: string; index: number; name: string; value: string; x: Date }) => `
+ (el: {
+ id: string
+ index: number
+ name: string
+ value: string
+ x: Date
+ }) => `
<li class='flex justify-between items-center py-px leading-snug'>
<div class='flex items-center min-w-0 mr-4'>
<div class='w-2.5 h-2.5 rounded-xs mr-1.5 flex-shrink-0' style=background-color:${color(el.id)}></div>
diff --git a/web/app/pages/Project/View/ViewProject.tsx b/web/app/pages/Project/View/ViewProject.tsx
index 0dacc8cda..af1ffa23b 100644
--- a/web/app/pages/Project/View/ViewProject.tsx
+++ b/web/app/pages/Project/View/ViewProject.tsx
@@ -23,10 +23,24 @@ import {
FlaskConicalIcon,
FileUser,
} from 'lucide-react'
-import React, { useState, useEffect, useMemo, useRef, useCallback, createContext, useContext, lazy } from 'react'
+import React, {
+ useState,
+ useEffect,
+ useMemo,
+ useRef,
+ useCallback,
+ createContext,
+ useContext,
+ lazy,
+} from 'react'
import { useHotkeys } from 'react-hotkeys-hook'
import { useTranslation } from 'react-i18next'
-import { useNavigate, useSearchParams, LinkProps, useFetcher } from 'react-router'
+import {
+ useNavigate,
+ useSearchParams,
+ LinkProps,
+ useFetcher,
+} from 'react-router'
import { ClientOnly } from 'remix-utils/client-only'
import { toast } from 'sonner'
@@ -66,7 +80,10 @@ import { trackCustom } from '~/utils/analytics'
import { getItem, setItem } from '~/utils/localstorage'
import routes from '~/utils/routes'
-import { useCurrentProject, useProjectPassword } from '../../../providers/CurrentProjectProvider'
+import {
+ useCurrentProject,
+ useProjectPassword,
+} from '../../../providers/CurrentProjectProvider'
import ProjectAlertsView from '../tabs/Alerts/ProjectAlertsView'
import AskAIView from '../tabs/AskAI'
import ErrorsView from '../tabs/Errors/ErrorsView'
@@ -84,9 +101,15 @@ import { ChartManagerProvider } from './components/ChartManager'
const CaptchaView = lazy(() => import('../tabs/Captcha/CaptchaView'))
import LockedDashboard from './components/LockedDashboard'
import PasswordRequiredModal from './components/PasswordRequiredModal'
-import ProjectSidebar, { MobileSidebarTrigger } from './components/ProjectSidebar'
+import ProjectSidebar, {
+ MobileSidebarTrigger,
+} from './components/ProjectSidebar'
import SearchFilters from './components/SearchFilters'
-import { Filter, ProjectView, ProjectViewCustomEvent } from './interfaces/traffic'
+import {
+ Filter,
+ ProjectView,
+ ProjectViewCustomEvent,
+} from './interfaces/traffic'
import { parseFilters } from './utils/filters'
import {
getFormatDate,
@@ -131,7 +154,11 @@ interface ViewProjectContextType {
shouldEnableZoom: boolean
getFilterLink: (column: string, value: string | null) => LinkProps['to']
- getVersionFilterLink: (parent: string | null, version: string | null, panelType: 'br' | 'os') => string
+ getVersionFilterLink: (
+ parent: string | null,
+ version: string | null,
+ panelType: 'br' | 'os',
+ ) => string
updatePeriod: (newPeriod: { period: Period; label?: string }) => void
updateTimebucket: (newTimebucket: TimeBucket) => void
@@ -221,8 +248,12 @@ const defaultRefreshTriggersContext: RefreshTriggersContextType = {
profilesRefreshTrigger: 0,
}
-export const ViewProjectContext = createContext<ViewProjectContextType>(defaultViewProjectContext)
-export const RefreshTriggersContext = createContext<RefreshTriggersContextType>(defaultRefreshTriggersContext)
+export const ViewProjectContext = createContext<ViewProjectContextType>(
+ defaultViewProjectContext,
+)
+export const RefreshTriggersContext = createContext<RefreshTriggersContextType>(
+ defaultRefreshTriggersContext,
+)
export const useViewProjectContext = () => {
const context = useContext(ViewProjectContext)
@@ -284,14 +315,17 @@ const ViewProjectContent = () => {
const [captchaRefreshTrigger, setCaptchaRefreshTrigger] = useState(0)
const [goalsRefreshTrigger, setGoalsRefreshTrigger] = useState(0)
const [experimentsRefreshTrigger, setExperimentsRefreshTrigger] = useState(0)
- const [featureFlagsRefreshTrigger, setFeatureFlagsRefreshTrigger] = useState(0)
+ const [featureFlagsRefreshTrigger, setFeatureFlagsRefreshTrigger] =
+ useState(0)
const [sessionsRefreshTrigger, setSessionsRefreshTrigger] = useState(0)
const [errorsRefreshTrigger, setErrorsRefreshTrigger] = useState(0)
const [performanceRefreshTrigger, setPerformanceRefreshTrigger] = useState(0)
const [trafficRefreshTrigger, setTrafficRefreshTrigger] = useState(0)
const [funnelsRefreshTrigger, setFunnelsRefreshTrigger] = useState(0)
const [profilesRefreshTrigger, setProfilesRefreshTrigger] = useState(0)
- const [activeChartMetrics] = useState<Record<keyof typeof CHART_METRICS_MAPPING, boolean>>({
+ const [activeChartMetrics] = useState<
+ Record<keyof typeof CHART_METRICS_MAPPING, boolean>
+ >({
[CHART_METRICS_MAPPING.unique]: true,
[CHART_METRICS_MAPPING.views]: false,
[CHART_METRICS_MAPPING.sessionDuration]: false,
@@ -303,7 +337,9 @@ const ViewProjectContent = () => {
[CHART_METRICS_MAPPING.revenue]: false,
...(preferences.metricsVisualisation || {}),
} as Record<keyof typeof CHART_METRICS_MAPPING, boolean>)
- const [customMetrics, setCustomMetrics] = useState<ProjectViewCustomEvent[]>([])
+ const [customMetrics, setCustomMetrics] = useState<ProjectViewCustomEvent[]>(
+ [],
+ )
const filters = useMemo<Filter[]>(() => {
return parseFilters(searchParams)
}, [searchParams])
@@ -361,7 +397,10 @@ const ViewProjectContent = () => {
let tbs = null
if (dateRange) {
- const days = Math.ceil(Math.abs(dateRange[1].getTime() - dateRange[0].getTime()) / (1000 * 3600 * 24))
+ const days = Math.ceil(
+ Math.abs(dateRange[1].getTime() - dateRange[0].getTime()) /
+ (1000 * 3600 * 24),
+ )
for (const index in timeBucketToDays) {
if (timeBucketToDays[index].lt >= days) {
@@ -391,7 +430,10 @@ const ViewProjectContent = () => {
}
if (dateRange) {
- const days = Math.ceil(Math.abs(dateRange[1].getTime() - dateRange[0].getTime()) / (1000 * 3600 * 24))
+ const days = Math.ceil(
+ Math.abs(dateRange[1].getTime() - dateRange[0].getTime()) /
+ (1000 * 3600 * 24),
+ )
for (const index in timeBucketToDays) {
if (timeBucketToDays[index].lt >= days) {
@@ -407,18 +449,27 @@ const ViewProjectContent = () => {
return _timeBucket
}, [searchParams, preferences.timeBucket, periodPairs, period, dateRange])
- const activePeriod = useMemo(() => _find(periodPairs, (p) => p.period === period), [period, periodPairs])
+ const activePeriod = useMemo(
+ () => _find(periodPairs, (p) => p.period === period),
+ [period, periodPairs],
+ )
const [isHotkeysHelpOpened, setIsHotkeysHelpOpened] = useState(false)
// null -> not loaded yet
const [projectViews, setProjectViews] = useState<ProjectView[]>([])
- const [projectViewsLoading, setProjectViewsLoading] = useState<boolean | null>(null) // // null - not loaded, true - loading, false - loaded
- const [projectViewToUpdate, setProjectViewToUpdate] = useState<ProjectView | undefined>()
+ const [projectViewsLoading, setProjectViewsLoading] = useState<
+ boolean | null
+ >(null) // // null - not loaded, true - loading, false - loaded
+ const [projectViewToUpdate, setProjectViewToUpdate] = useState<
+ ProjectView | undefined
+ >()
const viewsLoadFetcher = useFetcher<ProjectViewActionData>()
- const mode = activeChartMetrics[CHART_METRICS_MAPPING.cumulativeMode] ? 'cumulative' : 'periodical'
+ const mode = activeChartMetrics[CHART_METRICS_MAPPING.cumulativeMode]
+ ? 'cumulative'
+ : 'periodical'
const loadProjectViews = useCallback(
(forced?: boolean) => {
@@ -475,7 +526,10 @@ const ViewProjectContent = () => {
[searchParams],
)
- const timeFormat = useMemo<'12-hour' | '24-hour'>(() => user?.timeFormat || TimeFormat['12-hour'], [user])
+ const timeFormat = useMemo<'12-hour' | '24-hour'>(
+ () => user?.timeFormat || TimeFormat['12-hour'],
+ [user],
+ )
const [ref, size] = useSize()
const rotateXAxis = useMemo(() => size.width > 0 && size.width < 500, [size])
const [chartType, setChartType] = useState<keyof typeof chartTypes>(
@@ -488,8 +542,12 @@ const ViewProjectContent = () => {
period: string
}[]
>(tbPeriodPairsCompare(t, undefined, language))
- const [isActiveCompare, setIsActiveCompare] = useState(getItem(LS_IS_ACTIVE_COMPARE_KEY) === 'true')
- const [activePeriodCompare, setActivePeriodCompare] = useState(periodPairsCompare[0].period)
+ const [isActiveCompare, setIsActiveCompare] = useState(
+ getItem(LS_IS_ACTIVE_COMPARE_KEY) === 'true',
+ )
+ const [activePeriodCompare, setActivePeriodCompare] = useState(
+ periodPairsCompare[0].period,
+ )
const maxRangeCompare = useMemo(() => {
if (!isActiveCompare) {
return 0
@@ -509,7 +567,9 @@ const ViewProjectContent = () => {
return
}
- let pageTitle = user?.showLiveVisitorsInTitle ? `👀 ${liveVisitors} - ${project.name}` : project.name
+ let pageTitle = user?.showLiveVisitorsInTitle
+ ? `👀 ${liveVisitors} - ${project.name}`
+ : project.name
if (!pageTitle) {
pageTitle = t('titles.main')
@@ -618,7 +678,10 @@ const ViewProjectContent = () => {
return newTabs
}, [t, projectQueryTabs, allowedToManage])
- const activeTabLabel = useMemo(() => _find(tabs, (tab) => tab.id === activeTab)?.label, [tabs, activeTab])
+ const activeTabLabel = useMemo(
+ () => _find(tabs, (tab) => tab.id === activeTab)?.label,
+ [tabs, activeTab],
+ )
const compareDisable = useCallback(() => {
setIsActiveCompare(false)
@@ -639,7 +702,10 @@ const ViewProjectContent = () => {
return
}
- const newMetrics = _filter(customMetrics, (metric) => metric.id !== metricId)
+ const newMetrics = _filter(
+ customMetrics,
+ (metric) => metric.id !== metricId,
+ )
setCustomMetrics(newMetrics)
}
@@ -797,8 +863,11 @@ const ViewProjectContent = () => {
const isTouchDevice = useMemo(() => {
if (typeof window === 'undefined') return false
const hasTouchEvent = 'ontouchstart' in window
- const hasMaxTouchPoints = typeof navigator !== 'undefined' && navigator.maxTouchPoints > 0
- const coarsePointer = window.matchMedia ? window.matchMedia('(pointer: coarse)').matches : false
+ const hasMaxTouchPoints =
+ typeof navigator !== 'undefined' && navigator.maxTouchPoints > 0
+ const coarsePointer = window.matchMedia
+ ? window.matchMedia('(pointer: coarse)').matches
+ : false
return hasTouchEvent || hasMaxTouchPoints || coarsePointer
}, [])
@@ -812,13 +881,18 @@ const ViewProjectContent = () => {
}
// Enable zoom only if the range is more than 1 day
- const daysDiff = Math.ceil((dateRange[1].getTime() - dateRange[0].getTime()) / (1000 * 3600 * 24))
+ const daysDiff = Math.ceil(
+ (dateRange[1].getTime() - dateRange[0].getTime()) / (1000 * 3600 * 24),
+ )
return daysDiff > 1
}, [period, dateRange, isTouchDevice])
const getFilterLink = useCallback(
(column: string, value: string | null): LinkProps['to'] => {
- const isFilterActive = filters.findIndex((filter) => filter.column === column && filter.filter === value) >= 0
+ const isFilterActive =
+ filters.findIndex(
+ (filter) => filter.column === column && filter.filter === value,
+ ) >= 0
const newSearchParams = new URLSearchParams(searchParams.toString())
let searchString = ''
@@ -911,7 +985,10 @@ const ViewProjectContent = () => {
useHotkeys(SHORTCUTS_TIMEBUCKETS_LISTENERS, ({ key }) => {
const pairs = tbPeriodPairs(t, undefined, undefined, language)
// @ts-expect-error
- const pair = _find(pairs, ({ period }) => period === timebucketShortcutsMap[key])
+ const pair = _find(
+ pairs,
+ ({ period }) => period === timebucketShortcutsMap[key],
+ )
if (!pair) {
return
@@ -943,7 +1020,10 @@ const ViewProjectContent = () => {
})
const openMobileSidebar = useCallback(() => setIsMobileSidebarOpen(true), [])
- const closeMobileSidebar = useCallback(() => setIsMobileSidebarOpen(false), [])
+ const closeMobileSidebar = useCallback(
+ () => setIsMobileSidebarOpen(false),
+ [],
+ )
const contextValue = useMemo(
() => ({
@@ -1096,7 +1176,10 @@ const ViewProjectContent = () => {
{/* Skeleton metric cards */}
<div className='mb-6 grid grid-cols-2 gap-4 md:grid-cols-4'>
{[...Array(4)].map((_, i) => (
- <div key={i} className='h-24 animate-pulse rounded-lg bg-gray-200 dark:bg-slate-700' />
+ <div
+ key={i}
+ className='h-24 animate-pulse rounded-lg bg-gray-200 dark:bg-slate-700'
+ />
))}
</div>
@@ -1106,7 +1189,10 @@ const ViewProjectContent = () => {
{/* Skeleton panels */}
<div className='grid grid-cols-1 gap-4 md:grid-cols-2'>
{[...Array(4)].map((_, i) => (
- <div key={i} className='h-48 animate-pulse rounded-lg bg-gray-200 dark:bg-slate-700' />
+ <div
+ key={i}
+ className='h-48 animate-pulse rounded-lg bg-gray-200 dark:bg-slate-700'
+ />
))}
</div>
</div>
@@ -1117,7 +1203,10 @@ const ViewProjectContent = () => {
</div>
{/* Password Modal */}
- <PasswordRequiredModal isOpen={isPasswordRequired} onSubmit={submitPassword} />
+ <PasswordRequiredModal
+ isOpen={isPasswordRequired}
+ onSubmit={submitPassword}
+ />
</>
)
}
@@ -1144,10 +1233,13 @@ const ViewProjectContent = () => {
<>
{!isEmbedded ? <Header /> : null}
<div
- className={cx('flex min-h-screen flex-col bg-gray-50 dark:bg-slate-900', {
- 'min-h-including-header': !isEmbedded,
- 'min-h-screen': isEmbedded,
- })}
+ className={cx(
+ 'flex min-h-screen flex-col bg-gray-50 dark:bg-slate-900',
+ {
+ 'min-h-including-header': !isEmbedded,
+ 'min-h-screen': isEmbedded,
+ },
+ )}
>
<div className='mx-auto w-full max-w-7xl flex-1 px-4 py-2 sm:px-6 lg:px-8'>
<div className='relative flex gap-4'>
@@ -1186,7 +1278,10 @@ const ViewProjectContent = () => {
{/* Main Content */}
<div className='flex min-w-0 flex-1 flex-col'>
<div className='pointer-events-auto'>
- <MobileSidebarTrigger onClick={openMobileSidebar} activeTabLabel={activeTabLabel} />
+ <MobileSidebarTrigger
+ onClick={openMobileSidebar}
+ activeTabLabel={activeTabLabel}
+ />
</div>
<LockedDashboard />
</div>
@@ -1206,20 +1301,28 @@ const ViewProjectContent = () => {
<RefreshTriggersContext.Provider value={refreshTriggersValue}>
<>
<div
- className={cx('flex min-h-screen flex-col bg-gray-50 dark:bg-slate-900', {
- 'min-h-including-header': !isEmbedded,
- 'min-h-screen': isEmbedded,
- })}
+ className={cx(
+ 'flex min-h-screen flex-col bg-gray-50 dark:bg-slate-900',
+ {
+ 'min-h-including-header': !isEmbedded,
+ 'min-h-screen': isEmbedded,
+ },
+ )}
>
{!isEmbedded ? <Header /> : null}
<div className='grid flex-1 grid-cols-1'>
- <div ref={fullscreenMapRef} className='z-0 col-start-1 row-start-1 min-h-full w-full empty:hidden' />
+ <div
+ ref={fullscreenMapRef}
+ className='z-0 col-start-1 row-start-1 min-h-full w-full empty:hidden'
+ />
<div
className={cx(
'z-10 col-start-1 row-start-1 mx-auto w-full max-w-7xl px-4 py-2 sm:px-6 lg:px-8',
- isMapFullscreen ? 'pointer-events-none' : 'pointer-events-auto',
+ isMapFullscreen
+ ? 'pointer-events-none'
+ : 'pointer-events-auto',
)}
>
<div ref={ref} className='relative flex gap-4'>
@@ -1256,13 +1359,18 @@ const ViewProjectContent = () => {
<div
className={cx(
'pointer-events-auto flex min-w-0 flex-1 flex-col',
- isMapFullscreen ? 'pointer-events-none' : 'pointer-events-auto',
+ isMapFullscreen
+ ? 'pointer-events-none'
+ : 'pointer-events-auto',
)}
ref={dashboardRef}
>
<EventsRunningOutBanner />
<div className='pointer-events-auto'>
- <MobileSidebarTrigger onClick={openMobileSidebar} activeTabLabel={activeTabLabel} />
+ <MobileSidebarTrigger
+ onClick={openMobileSidebar}
+ activeTabLabel={activeTabLabel}
+ />
</div>
<AnimatePresence mode='wait'>
<motion.div
@@ -1272,7 +1380,9 @@ const ViewProjectContent = () => {
exit={{ opacity: 0 }}
transition={{ duration: 0.15 }}
>
- {activeTab === PROJECT_TABS.ai ? <AskAIView projectId={id} /> : null}
+ {activeTab === PROJECT_TABS.ai ? (
+ <AskAIView projectId={id} />
+ ) : null}
{activeTab === PROJECT_TABS.traffic ? (
<TrafficView
tnMapping={tnMapping}
@@ -1288,39 +1398,66 @@ const ViewProjectContent = () => {
onCustomMetric={onCustomMetric}
/>
) : null}
- {activeTab === PROJECT_TABS.performance ? <PerformanceView tnMapping={tnMapping} /> : null}
- {activeTab === PROJECT_TABS.funnels ? <FunnelsView /> : null}
- {activeTab === PROJECT_TABS.alerts ? <ProjectAlertsView /> : null}
- {activeTab === PROJECT_TABS.profiles ? <ProfilesView tnMapping={tnMapping} /> : null}
+ {activeTab === PROJECT_TABS.performance ? (
+ <PerformanceView tnMapping={tnMapping} />
+ ) : null}
+ {activeTab === PROJECT_TABS.funnels ? (
+ <FunnelsView />
+ ) : null}
+ {activeTab === PROJECT_TABS.alerts ? (
+ <ProjectAlertsView />
+ ) : null}
+ {activeTab === PROJECT_TABS.profiles ? (
+ <ProfilesView tnMapping={tnMapping} />
+ ) : null}
{activeTab === PROJECT_TABS.sessions ? (
- <SessionsView tnMapping={tnMapping} rotateXAxis={rotateXAxis} />
+ <SessionsView
+ tnMapping={tnMapping}
+ rotateXAxis={rotateXAxis}
+ />
+ ) : null}
+ {activeTab === PROJECT_TABS.errors ? (
+ <ErrorsView />
) : null}
- {activeTab === PROJECT_TABS.errors ? <ErrorsView /> : null}
{activeTab === PROJECT_TABS.goals ? (
<GoalsView
period={period}
- from={dateRange ? getFormatDate(dateRange[0]) : ''}
- to={dateRange ? getFormatDate(dateRange[1]) : ''}
+ from={
+ dateRange ? getFormatDate(dateRange[0]) : ''
+ }
+ to={
+ dateRange ? getFormatDate(dateRange[1]) : ''
+ }
timezone={timezone}
/>
) : null}
{activeTab === PROJECT_TABS.experiments ? (
<ExperimentsView
period={period}
- from={dateRange ? getFormatDate(dateRange[0]) : ''}
- to={dateRange ? getFormatDate(dateRange[1]) : ''}
+ from={
+ dateRange ? getFormatDate(dateRange[0]) : ''
+ }
+ to={
+ dateRange ? getFormatDate(dateRange[1]) : ''
+ }
timezone={timezone}
/>
) : null}
{activeTab === PROJECT_TABS.featureFlags ? (
<FeatureFlagsView
period={period}
- from={dateRange ? getFormatDate(dateRange[0]) : ''}
- to={dateRange ? getFormatDate(dateRange[1]) : ''}
+ from={
+ dateRange ? getFormatDate(dateRange[0]) : ''
+ }
+ to={
+ dateRange ? getFormatDate(dateRange[1]) : ''
+ }
timezone={timezone}
/>
) : null}
- {activeTab === PROJECT_TABS.captcha ? <CaptchaView projectId={id} /> : null}
+ {activeTab === PROJECT_TABS.captcha ? (
+ <CaptchaView projectId={id} />
+ ) : null}
</motion.div>
</AnimatePresence>
@@ -1370,37 +1507,62 @@ const ViewProjectContent = () => {
<Dropdown
title={
<span className='flex items-center justify-center'>
- <span className='sr-only'>{t('header.switchTheme')}</span>
+ <span className='sr-only'>
+ {t('header.switchTheme')}
+ </span>
{theme === 'dark' ? (
- <SunIcon className='h-6 w-6 text-gray-200' aria-hidden='true' />
+ <SunIcon
+ className='h-6 w-6 text-gray-200'
+ aria-hidden='true'
+ />
) : (
- <MoonIcon className='h-6 w-6 text-slate-700' aria-hidden='true' />
+ <MoonIcon
+ className='h-6 w-6 text-slate-700'
+ aria-hidden='true'
+ />
)}
</span>
}
items={[
- { key: 'light', label: t('header.light'), icon: SunIcon },
- { key: 'dark', label: t('header.dark'), icon: MoonIcon },
+ {
+ key: 'light',
+ label: t('header.light'),
+ icon: SunIcon,
+ },
+ {
+ key: 'dark',
+ label: t('header.dark'),
+ icon: MoonIcon,
+ },
]}
keyExtractor={(item) => item.key}
labelExtractor={(item) => (
<div
- className={cx('flex w-full items-center', {
- 'light:text-indigo-600': item.key === 'light',
- 'dark:text-indigo-400': item.key === 'dark',
- })}
+ className={cx(
+ 'flex w-full items-center',
+ {
+ 'light:text-indigo-600':
+ item.key === 'light',
+ 'dark:text-indigo-400':
+ item.key === 'dark',
+ },
+ )}
>
<item.icon
className={cx('mr-2 h-5 w-5', {
- 'dark:text-gray-300': item.key === 'light',
- 'light:text-gray-400': item.key === 'dark',
+ 'dark:text-gray-300':
+ item.key === 'light',
+ 'light:text-gray-400':
+ item.key === 'dark',
})}
aria-hidden='true'
/>
{item.label}
</div>
)}
- onSelect={(item) => setTheme(item.key as 'light' | 'dark')}
+ onSelect={(item) =>
+ setTheme(item.key as 'light' | 'dark')
+ }
className='flex'
chevron={null}
headless
@@ -1419,7 +1581,10 @@ const ViewProjectContent = () => {
{isEmbedded ? null : <Footer showDBIPMessage />}
</div>
- <ViewProjectHotkeys isOpened={isHotkeysHelpOpened} onClose={() => setIsHotkeysHelpOpened(false)} />
+ <ViewProjectHotkeys
+ isOpened={isHotkeysHelpOpened}
+ onClose={() => setIsHotkeysHelpOpened(false)}
+ />
<SearchFilters
type={activeTab === PROJECT_TABS.errors ? 'errors' : 'traffic'}
showModal={showFiltersSearch}
diff --git a/web/app/pages/Project/View/components/AddAViewModal.tsx b/web/app/pages/Project/View/components/AddAViewModal.tsx
index 1560a28a1..8d2187b00 100644
--- a/web/app/pages/Project/View/components/AddAViewModal.tsx
+++ b/web/app/pages/Project/View/components/AddAViewModal.tsx
@@ -36,7 +36,13 @@ interface AddAViewModalProps {
defaultView?: ProjectView
}
-const InlineButton = ({ text, onClick }: { text: string; onClick: () => void }) => (
+const InlineButton = ({
+ text,
+ onClick,
+}: {
+ text: string
+ onClick: () => void
+}) => (
<button
type='button'
onClick={onClick}
@@ -54,7 +60,13 @@ interface EditMetricProps {
onDelete: () => void
}
-const EditMetric = ({ metric, onChange, onDelete, errors, setErrors }: EditMetricProps) => {
+const EditMetric = ({
+ metric,
+ onChange,
+ onDelete,
+ errors,
+ setErrors,
+}: EditMetricProps) => {
const { t } = useTranslation('common')
const customEventTypes = useMemo(
@@ -76,7 +88,8 @@ const EditMetric = ({ metric, onChange, onDelete, errors, setErrors }: EditMetri
)
const activeCustomEventType = useMemo(
- () => _find(customEventTypes, ({ key }) => key === metric.metaValueType)?.label,
+ () =>
+ _find(customEventTypes, ({ key }) => key === metric.metaValueType)?.label,
[customEventTypes, metric.metaValueType],
)
@@ -167,7 +180,9 @@ const EditMetric = ({ metric, onChange, onDelete, errors, setErrors }: EditMetri
hint={t('project.metrics.metricType.description')}
title={activeCustomEventType}
capitalise
- selectedItem={customEventTypes.find((item) => item.key === metric.metaValueType)}
+ selectedItem={customEventTypes.find(
+ (item) => item.key === metric.metaValueType,
+ )}
/>
</div>
</div>
@@ -189,7 +204,13 @@ interface AddAViewModalErrors {
const MAX_METRICS_IN_VIEW = 3
-const AddAViewModal = ({ onSubmit, showModal, setShowModal, tnMapping, defaultView }: AddAViewModalProps) => {
+const AddAViewModal = ({
+ onSubmit,
+ showModal,
+ setShowModal,
+ tnMapping,
+ defaultView,
+}: AddAViewModalProps) => {
const { id } = useCurrentProject()
const {
t,
@@ -199,8 +220,12 @@ const AddAViewModal = ({ onSubmit, showModal, setShowModal, tnMapping, defaultVi
const [name, setName] = useState(defaultView?.name || '')
const [filterType, setFilterType] = useState('')
const [searchList, setSearchList] = useState<any[]>([])
- const [activeFilters, setActiveFilters] = useState<FilterType[]>(defaultView?.filters || [])
- const [customEvents, setCustomEvents] = useState<Partial<ProjectViewCustomEvent>[]>(defaultView?.customEvents || [])
+ const [activeFilters, setActiveFilters] = useState<FilterType[]>(
+ defaultView?.filters || [],
+ )
+ const [customEvents, setCustomEvents] = useState<
+ Partial<ProjectViewCustomEvent>[]
+ >(defaultView?.customEvents || [])
const [errors, setErrors] = useState<AddAViewModalErrors>({})
const { fetchFilters } = useFiltersProxy()
@@ -257,7 +282,10 @@ const AddAViewModal = ({ onSubmit, showModal, setShowModal, tnMapping, defaultVi
processedItem = countries.getAlpha2Code(item, language) as string
}
- const itemExists = _find(activeFilters, ({ column, filter }) => filter === processedItem && column === filterType)
+ const itemExists = _find(
+ activeFilters,
+ ({ column, filter }) => filter === processedItem && column === filterType,
+ )
if (itemExists) {
return
@@ -290,12 +318,16 @@ const AddAViewModal = ({ onSubmit, showModal, setShowModal, tnMapping, defaultVi
const { id, customEventName, metricKey } = customEvents[i]
if (!customEventName) {
- metricErrors[`${id}_customEventName`] = t('apiNotifications.inputCannotBeEmpty')
+ metricErrors[`${id}_customEventName`] = t(
+ 'apiNotifications.inputCannotBeEmpty',
+ )
valid = false
}
if (!metricKey) {
- metricErrors[`${id}_metricKey`] = t('apiNotifications.inputCannotBeEmpty')
+ metricErrors[`${id}_metricKey`] = t(
+ 'apiNotifications.inputCannotBeEmpty',
+ )
valid = false
}
}
@@ -322,7 +354,11 @@ const AddAViewModal = ({ onSubmit, showModal, setShowModal, tnMapping, defaultVi
// Handle fetcher response
useEffect(() => {
- if (fetcher.state === 'idle' && fetcher.data && !hasHandledResponse.current) {
+ if (
+ fetcher.state === 'idle' &&
+ fetcher.data &&
+ !hasHandledResponse.current
+ ) {
hasHandledResponse.current = true
if (fetcher.data.success) {
onSubmit()
@@ -393,13 +429,17 @@ const AddAViewModal = ({ onSubmit, showModal, setShowModal, tnMapping, defaultVi
labelExtractor={(item) => t(`project.mapping.${item}`)}
onSelect={(item) => setFilterType(item)}
title={
- _isEmpty(filterType) ? t('project.settings.reseted.selectFilters') : t(`project.mapping.${filterType}`)
+ _isEmpty(filterType)
+ ? t('project.settings.reseted.selectFilters')
+ : t(`project.mapping.${filterType}`)
}
selectedItem={_isEmpty(filterType) ? undefined : filterType}
/>
{filterType && !_isEmpty(searchList) ? (
<>
- <p className='mt-5 text-sm font-medium text-gray-700 dark:text-gray-200'>{t('project.filters')}</p>
+ <p className='mt-5 text-sm font-medium text-gray-700 dark:text-gray-200'>
+ {t('project.filters')}
+ </p>
<Combobox
items={searchList}
labelExtractor={(item) => {
@@ -415,60 +455,71 @@ const AddAViewModal = ({ onSubmit, showModal, setShowModal, tnMapping, defaultVi
</>
) : null}
<div className='mt-2'>
- {_map(activeFilters, ({ filter, column, isExclusive, isContains }) => (
- <Filter
- key={`${column}-${filter}-${isExclusive}-${isContains}`}
- onRemoveFilter={(e) => {
- e.preventDefault()
-
- setActiveFilters((prevFilters: any) => {
- return _filter(
- prevFilters,
- ({ column: prevColumn, filter: prevFilter }) => prevFilter !== filter || prevColumn !== column,
- )
- })
- }}
- onChangeExclusive={(e) => {
- e.preventDefault()
-
- setActiveFilters((prevFilters: any) => {
- return _map(prevFilters, (item) => {
- if (item.column === column && item.filter === filter) {
- let nextContains = isContains
- let nextExclusive = isExclusive
- if (!isContains && !isExclusive) {
- nextContains = false
- nextExclusive = true
- } else if (!isContains && isExclusive) {
- nextContains = true
- nextExclusive = false
- } else if (isContains && !isExclusive) {
- nextContains = true
- nextExclusive = true
- } else {
- nextContains = false
- nextExclusive = false
+ {_map(
+ activeFilters,
+ ({ filter, column, isExclusive, isContains }) => (
+ <Filter
+ key={`${column}-${filter}-${isExclusive}-${isContains}`}
+ onRemoveFilter={(e) => {
+ e.preventDefault()
+
+ setActiveFilters((prevFilters: any) => {
+ return _filter(
+ prevFilters,
+ ({ column: prevColumn, filter: prevFilter }) =>
+ prevFilter !== filter || prevColumn !== column,
+ )
+ })
+ }}
+ onChangeExclusive={(e) => {
+ e.preventDefault()
+
+ setActiveFilters((prevFilters: any) => {
+ return _map(prevFilters, (item) => {
+ if (item.column === column && item.filter === filter) {
+ let nextContains = isContains
+ let nextExclusive = isExclusive
+ if (!isContains && !isExclusive) {
+ nextContains = false
+ nextExclusive = true
+ } else if (!isContains && isExclusive) {
+ nextContains = true
+ nextExclusive = false
+ } else if (isContains && !isExclusive) {
+ nextContains = true
+ nextExclusive = true
+ } else {
+ nextContains = false
+ nextExclusive = false
+ }
+
+ return {
+ column,
+ filter,
+ isExclusive: nextExclusive,
+ isContains: nextContains,
+ }
}
- return { column, filter, isExclusive: nextExclusive, isContains: nextContains }
- }
-
- return item
+ return item
+ })
})
- })
- }}
- isExclusive={isExclusive}
- column={column}
- filter={filter}
- tnMapping={tnMapping}
- isContains={isContains}
- canChangeExclusive
- removable
- />
- ))}
+ }}
+ isExclusive={isExclusive}
+ column={column}
+ filter={filter}
+ tnMapping={tnMapping}
+ isContains={isContains}
+ canChangeExclusive
+ removable
+ />
+ ),
+ )}
</div>
<hr className='my-4' />
- <p className='text-sm font-medium text-gray-700 dark:text-gray-100'>{t('project.customEventsAndMetrics')}</p>
+ <p className='text-sm font-medium text-gray-700 dark:text-gray-100'>
+ {t('project.customEventsAndMetrics')}
+ </p>
<div className='divide-y divide-gray-300/80 dark:divide-slate-900/60'>
{_map(customEvents, (ev) => (
<EditMetric
@@ -491,7 +542,9 @@ const AddAViewModal = ({ onSubmit, showModal, setShowModal, tnMapping, defaultVi
)
}}
onDelete={() => {
- setCustomEvents((prev) => _filter(prev, ({ id }) => id !== ev.id))
+ setCustomEvents((prev) =>
+ _filter(prev, ({ id }) => id !== ev.id),
+ )
}}
/>
))}
@@ -500,7 +553,10 @@ const AddAViewModal = ({ onSubmit, showModal, setShowModal, tnMapping, defaultVi
<InlineButton
text={t('project.addAMetric')}
onClick={() => {
- setCustomEvents((prev) => [...prev, { ...EMPTY_CUSTOM_EVENT, id: Math.random().toString() }])
+ setCustomEvents((prev) => [
+ ...prev,
+ { ...EMPTY_CUSTOM_EVENT, id: Math.random().toString() },
+ ])
}}
/>
) : null}
diff --git a/web/app/pages/Project/View/components/BackButton.tsx b/web/app/pages/Project/View/components/BackButton.tsx
index 0344a1463..ea0e279d8 100644
--- a/web/app/pages/Project/View/components/BackButton.tsx
+++ b/web/app/pages/Project/View/components/BackButton.tsx
@@ -20,25 +20,37 @@ interface BackButtonCallbackProps {
type BackButtonProps = BackButtonLinkProps | BackButtonCallbackProps
-export const BackButton = ({ to, onClick, className, label }: BackButtonProps) => {
+export const BackButton = ({
+ to,
+ onClick,
+ className,
+ label,
+}: BackButtonProps) => {
const { t } = useTranslation('common')
const backLabel = label || t('common.goBack')
const buttonClasses = cn(
- 'flex items-center gap-2 transition-colors rounded-md border border-transparent p-2 hover:border-gray-300 hover:bg-white focus:z-10 focus:ring-1 focus:ring-indigo-500 focus:outline-hidden ring-inset hover:dark:border-slate-700/80 dark:hover:bg-slate-800 focus:dark:ring-gray-200',
+ 'flex items-center gap-2 rounded-md border border-transparent p-2 transition-colors ring-inset hover:border-gray-300 hover:bg-white focus:z-10 focus:ring-1 focus:ring-indigo-500 focus:outline-hidden hover:dark:border-slate-700/80 dark:hover:bg-slate-800 focus:dark:ring-gray-200',
className,
)
const content = (
<>
<ChevronLeftIcon className='h-5 w-5 text-gray-700 dark:text-gray-50' />
- <span className='text-sm font-medium text-gray-700 dark:text-gray-50'>{backLabel}</span>
+ <span className='text-sm font-medium text-gray-700 dark:text-gray-50'>
+ {backLabel}
+ </span>
</>
)
if (onClick) {
return (
- <button type='button' title={backLabel} onClick={onClick} className={buttonClasses}>
+ <button
+ type='button'
+ title={backLabel}
+ onClick={onClick}
+ className={buttonClasses}
+ >
{content}
</button>
)
diff --git a/web/app/pages/Project/View/components/CCRow.tsx b/web/app/pages/Project/View/components/CCRow.tsx
index 9e7dcc174..2fd886aa0 100644
--- a/web/app/pages/Project/View/components/CCRow.tsx
+++ b/web/app/pages/Project/View/components/CCRow.tsx
@@ -16,9 +16,20 @@ const CCRow = ({ cc, name, language, size = 21 }: CCRowProps) => {
return (
<>
- <Flag className='rounded-xs' country={cc} size={size} alt='' aria-hidden='true' />
+ <Flag
+ className='rounded-xs'
+ country={cc}
+ size={size}
+ alt=''
+ aria-hidden='true'
+ />
&nbsp;
- {name || (cc ? countries.getName(cc, language) : <span className='italic'>{t('common.unknown')}</span>)}
+ {name ||
+ (cc ? (
+ countries.getName(cc, language)
+ ) : (
+ <span className='italic'>{t('common.unknown')}</span>
+ ))}
</>
)
}
diff --git a/web/app/pages/Project/View/components/ChartContextMenu.tsx b/web/app/pages/Project/View/components/ChartContextMenu.tsx
index 68f7d9745..e23f218bf 100644
--- a/web/app/pages/Project/View/components/ChartContextMenu.tsx
+++ b/web/app/pages/Project/View/components/ChartContextMenu.tsx
@@ -78,7 +78,9 @@ export const ChartContextMenu = ({
top: y,
}}
>
- <div className='px-3 py-2 text-sm text-gray-500 dark:text-gray-400'>{t('project.annotationsViewOnly')}</div>
+ <div className='px-3 py-2 text-sm text-gray-500 dark:text-gray-400'>
+ {t('project.annotationsViewOnly')}
+ </div>
</div>
)
}
diff --git a/web/app/pages/Project/View/components/ChartManager.tsx b/web/app/pages/Project/View/components/ChartManager.tsx
index bcd587a86..7f12d2a1a 100644
--- a/web/app/pages/Project/View/components/ChartManager.tsx
+++ b/web/app/pages/Project/View/components/ChartManager.tsx
@@ -1,5 +1,11 @@
import { Chart } from 'billboard.js'
-import React, { createContext, useContext, useRef, useCallback, ReactNode } from 'react'
+import React, {
+ createContext,
+ useContext,
+ useRef,
+ useCallback,
+ ReactNode,
+} from 'react'
interface ChartManagerContextType {
registerChart: (id: string, chart: Chart | null) => void
@@ -14,7 +20,9 @@ const ChartManagerContext = createContext<ChartManagerContextType | null>(null)
export const useChartManager = () => {
const context = useContext(ChartManagerContext)
if (!context) {
- throw new Error('useChartManager must be used within a ChartManagerProvider')
+ throw new Error(
+ 'useChartManager must be used within a ChartManagerProvider',
+ )
}
return context
}
@@ -23,7 +31,9 @@ interface ChartManagerProviderProps {
children: ReactNode
}
-export const ChartManagerProvider = ({ children }: ChartManagerProviderProps) => {
+export const ChartManagerProvider = ({
+ children,
+}: ChartManagerProviderProps) => {
const chartsRef = useRef<Map<string, Chart>>(new Map())
const registerChart = useCallback((id: string, chart: Chart | null) => {
@@ -73,5 +83,9 @@ export const ChartManagerProvider = ({ children }: ChartManagerProviderProps) =>
destroyAllCharts,
}
- return <ChartManagerContext.Provider value={value}>{children}</ChartManagerContext.Provider>
+ return (
+ <ChartManagerContext.Provider value={value}>
+ {children}
+ </ChartManagerContext.Provider>
+ )
}
diff --git a/web/app/pages/Project/View/components/CurrentTime.tsx b/web/app/pages/Project/View/components/CurrentTime.tsx
index 83acec744..a1e4b8629 100644
--- a/web/app/pages/Project/View/components/CurrentTime.tsx
+++ b/web/app/pages/Project/View/components/CurrentTime.tsx
@@ -33,7 +33,9 @@ const CurrentTime = () => {
</Text>
{isEmbedded ? null : (
<Text size='xs' colour='secondary' className='mt-1 text-gray-200'>
- {isAuthenticated ? t('project.changeInSettings') : t('project.signInToChange')}
+ {isAuthenticated
+ ? t('project.changeInSettings')
+ : t('project.signInToChange')}
</Text>
)}
</div>
diff --git a/web/app/pages/Project/View/components/DashboardHeader.tsx b/web/app/pages/Project/View/components/DashboardHeader.tsx
index 20da138f1..8ddf55bdb 100644
--- a/web/app/pages/Project/View/components/DashboardHeader.tsx
+++ b/web/app/pages/Project/View/components/DashboardHeader.tsx
@@ -6,7 +6,11 @@ import React from 'react'
import { useTranslation } from 'react-i18next'
import { useSearchParams } from 'react-router'
-import { MAX_MONTHS_IN_PAST, PERIOD_PAIRS_COMPARE, TBPeriodPairsProps } from '~/lib/constants'
+import {
+ MAX_MONTHS_IN_PAST,
+ PERIOD_PAIRS_COMPARE,
+ TBPeriodPairsProps,
+} from '~/lib/constants'
import { useAuth } from '~/providers/AuthProvider'
import DatePicker from '~/ui/Datepicker'
import Dropdown from '~/ui/Dropdown'
@@ -83,9 +87,16 @@ const DashboardHeader = ({
const [searchParams, setSearchParams] = useSearchParams()
const timeBucketSelectorItems = customTimeBucketSelectorItems || periodPairs
- const activeDropdownLabelCompare = _find(periodPairsCompare, (p) => p.period === activePeriodCompare)?.label
+ const activeDropdownLabelCompare = _find(
+ periodPairsCompare,
+ (p) => p.period === activePeriodCompare,
+ )?.label
- const tbPeriodPairsCompare = (tFn: typeof t, customDateRange?: Date[], lng?: string) => {
+ const tbPeriodPairsCompare = (
+ tFn: typeof t,
+ customDateRange?: Date[],
+ lng?: string,
+ ) => {
const result = [
{
label: tFn('project.previousPeriod'),
@@ -126,12 +137,16 @@ const DashboardHeader = ({
<div className='relative top-0 z-20 -mt-2 flex flex-col items-center justify-between bg-gray-50/50 py-2 backdrop-blur-md lg:sticky lg:flex-row dark:bg-slate-900/50'>
<div className='flex flex-wrap items-center justify-center gap-2'>
{backLink ? <BackButton to={backLink} label={backButtonLabel} /> : null}
- {onBack ? <BackButton onClick={onBack} label={backButtonLabel} /> : null}
+ {onBack ? (
+ <BackButton onClick={onBack} label={backButtonLabel} />
+ ) : null}
{leftContent}
{showLiveVisitors ? <LiveVisitorsDropdown /> : null}
</div>
<div className='mx-auto mt-3 flex w-full max-w-[420px] flex-wrap items-center justify-center gap-x-2 gap-y-1 sm:mx-0 sm:w-auto sm:max-w-none sm:flex-nowrap sm:justify-between lg:mt-0'>
- {showRefreshButton ? <RefreshStatsButton onRefresh={refreshStats} /> : null}
+ {showRefreshButton ? (
+ <RefreshStatsButton onRefresh={refreshStats} />
+ ) : null}
{showSearchButton ? (
<div className='border-gray-200 dark:border-gray-600'>
<button
@@ -193,7 +208,9 @@ const DashboardHeader = ({
<DatePicker
ref={refCalendar}
onChange={([from, to]) => {
- const newSearchParams = new URLSearchParams(searchParams.toString())
+ const newSearchParams = new URLSearchParams(
+ searchParams.toString(),
+ )
newSearchParams.set('from', from.toISOString())
newSearchParams.set('to', to.toISOString())
newSearchParams.set('period', 'custom')
@@ -218,7 +235,9 @@ const DashboardHeader = ({
) : null}
{isActiveCompare ? (
<>
- <div className='text-md mx-2 font-medium whitespace-pre-line text-gray-600 dark:text-gray-200'>vs</div>
+ <div className='text-md mx-2 font-medium whitespace-pre-line text-gray-600 dark:text-gray-200'>
+ vs
+ </div>
<Dropdown
items={periodPairsCompare}
title={activeDropdownLabelCompare}
@@ -235,7 +254,9 @@ const DashboardHeader = ({
refCalendarCompare.current?.openCalendar()
}, 100)
} else {
- setPeriodPairsCompare(tbPeriodPairsCompare(t, undefined, language))
+ setPeriodPairsCompare(
+ tbPeriodPairsCompare(t, undefined, language),
+ )
setDateRangeCompare(null)
setActivePeriodCompare(pair.period)
}
diff --git a/web/app/pages/Project/View/components/Filters.tsx b/web/app/pages/Project/View/components/Filters.tsx
index 6a36fc704..1a00ef5a8 100644
--- a/web/app/pages/Project/View/components/Filters.tsx
+++ b/web/app/pages/Project/View/components/Filters.tsx
@@ -61,7 +61,9 @@ export const Filter = ({
}
// Normalise "null" filter values to human-friendly labels
- if ((displayFilter as unknown as string)?.toString().toLowerCase() === 'null') {
+ if (
+ (displayFilter as unknown as string)?.toString().toLowerCase() === 'null'
+ ) {
if (column === 'ref') {
displayFilter = t('project.directNone')
} else if (column === 'host') {
@@ -89,7 +91,13 @@ export const Filter = ({
const createRemoveFilterPath = () => {
const newSearchParams = new URLSearchParams(searchParams.toString())
- const paramKeyInUrl = isContains ? (isExclusive ? `^${column}` : `~${column}`) : isExclusive ? `!${column}` : column
+ const paramKeyInUrl = isContains
+ ? isExclusive
+ ? `^${column}`
+ : `~${column}`
+ : isExclusive
+ ? `!${column}`
+ : column
newSearchParams.delete(paramKeyInUrl, filter)
return { search: newSearchParams.toString() }
}
@@ -98,7 +106,13 @@ export const Filter = ({
const newSearchParams = new URLSearchParams(searchParams.toString())
const getKey = (contains: boolean, exclusive: boolean) =>
- contains ? (exclusive ? `^${column}` : `~${column}`) : exclusive ? `!${column}` : column
+ contains
+ ? exclusive
+ ? `^${column}`
+ : `~${column}`
+ : exclusive
+ ? `!${column}`
+ : column
const c = Boolean(isContains)
const e = Boolean(isExclusive)
@@ -174,7 +188,10 @@ export const Filter = ({
: c && !e
? 'toggleFilterToNotContains'
: 'toggleFilterToIs'
- return t(`project.${nextKey}`, { column: displayColumn, filter: truncatedFilter })
+ return t(`project.${nextKey}`, {
+ column: displayColumn,
+ filter: truncatedFilter,
+ })
})()}
aria-label={(() => {
const c = Boolean(isContains)
@@ -187,7 +204,10 @@ export const Filter = ({
: c && !e
? 'toggleFilterToNotContains'
: 'toggleFilterToIs'
- return t(`project.${nextKey}`, { column: displayColumn, filter: truncatedFilter })
+ return t(`project.${nextKey}`, {
+ column: displayColumn,
+ filter: truncatedFilter,
+ })
})()}
>
{isContains
@@ -202,7 +222,9 @@ export const Filter = ({
</span>
)}
&nbsp;
- <span className='font-semibold text-gray-800 dark:text-gray-50'>{truncatedFilter}</span>
+ <span className='font-semibold text-gray-800 dark:text-gray-50'>
+ {truncatedFilter}
+ </span>
{removable ? (
<Link
to={createRemoveFilterPath()}
@@ -222,8 +244,17 @@ export const Filter = ({
onRemoveFilter?.(e)
}}
>
- <svg className='h-2 w-2' stroke='currentColor' fill='none' viewBox='0 0 8 8'>
- <path strokeLinecap='round' strokeWidth='1.5' d='M1 1l6 6m0-6L1 7' />
+ <svg
+ className='h-2 w-2'
+ stroke='currentColor'
+ fill='none'
+ viewBox='0 0 8 8'
+ >
+ <path
+ strokeLinecap='round'
+ strokeWidth='1.5'
+ d='M1 1l6 6m0-6L1 7'
+ />
</svg>
</Link>
) : null}
@@ -274,13 +305,24 @@ const Filters = ({ tnMapping, className }: FiltersProps) => {
)}
>
<div className='flex min-w-0 flex-1 items-center gap-1'>
- <FilterIcon className='size-5 shrink-0 text-gray-500 dark:text-gray-400' strokeWidth={1.5} />
+ <FilterIcon
+ className='size-5 shrink-0 text-gray-500 dark:text-gray-400'
+ strokeWidth={1.5}
+ />
<div className='flex flex-wrap'>
{_map(filters, (props) => {
const { column, filter } = props
const key = `${column}${filter}`
- return <Filter key={key} tnMapping={tnMapping} canChangeExclusive removable {...props} />
+ return (
+ <Filter
+ key={key}
+ tnMapping={tnMapping}
+ canChangeExclusive
+ removable
+ {...props}
+ />
+ )
})}
</div>
</div>
diff --git a/web/app/pages/Project/View/components/InteractiveMap.tsx b/web/app/pages/Project/View/components/InteractiveMap.tsx
index 3982afb6a..903e820ba 100644
--- a/web/app/pages/Project/View/components/InteractiveMap.tsx
+++ b/web/app/pages/Project/View/components/InteractiveMap.tsx
@@ -5,7 +5,14 @@ import { Feature, GeoJsonObject } from 'geojson'
import { Layer, Path } from 'leaflet'
import 'leaflet/dist/leaflet.css'
import _round from 'lodash/round'
-import React, { memo, useState, useMemo, useEffect, useCallback, useRef } from 'react'
+import React, {
+ memo,
+ useState,
+ useMemo,
+ useEffect,
+ useCallback,
+ useRef,
+} from 'react'
import { useTranslation } from 'react-i18next'
import { GeoJSON, MapContainer, useMapEvent } from 'react-leaflet'
import { ClientOnly } from 'remix-utils/client-only'
@@ -15,7 +22,11 @@ import { Entry } from '~/lib/models/Entry'
import { useTheme } from '~/providers/ThemeProvider'
import Flag from '~/ui/Flag'
import Spin from '~/ui/icons/Spin'
-import { getTimeFromSeconds, getStringFromTime, nFormatter } from '~/utils/generic'
+import {
+ getTimeFromSeconds,
+ getStringFromTime,
+ nFormatter,
+} from '~/utils/generic'
import { loadCountriesGeoData, loadRegionsGeoData } from '~/utils/geoData'
import { useViewProjectContext } from '../ViewProject'
@@ -43,9 +54,13 @@ const InteractiveMapCore = ({
const { activeTab, dataLoading } = useViewProjectContext()
const { theme } = useTheme()
- const [countriesGeoData, setCountriesGeoData] = useState<GeoJsonObject | null>(null)
- const [regionsGeoData, setRegionsGeoData] = useState<GeoJsonObject | null>(null)
- const [filteredRegionsGeoData, setFilteredRegionsGeoData] = useState<GeoJsonObject | null>(null)
+ const [countriesGeoData, setCountriesGeoData] =
+ useState<GeoJsonObject | null>(null)
+ const [regionsGeoData, setRegionsGeoData] = useState<GeoJsonObject | null>(
+ null,
+ )
+ const [filteredRegionsGeoData, setFilteredRegionsGeoData] =
+ useState<GeoJsonObject | null>(null)
const [mapView, setMapView] = useState<'countries' | 'regions'>('countries')
const [tooltipContent, setTooltipContent] = useState<{
name: string
@@ -63,7 +78,8 @@ const InteractiveMapCore = ({
const isTrafficTab = activeTab === PROJECT_TABS.traffic
const isErrorsTab = activeTab === PROJECT_TABS.errors
const isPerformanceTab = activeTab === PROJECT_TABS.performance
- const isGeoDataLoading = mapView === 'regions' ? !regionsGeoData : !countriesGeoData
+ const isGeoDataLoading =
+ mapView === 'regions' ? !regionsGeoData : !countriesGeoData
useEffect(() => {
const loadGeoData = async () => {
@@ -192,7 +208,9 @@ const InteractiveMapCore = ({
]
// Fixed thresholds in seconds for absolute performance classification
const thresholds = [1, 2, 3, 4, 5]
- return scaleThreshold<number, string>().domain(thresholds).range(perfColors)
+ return scaleThreshold<number, string>()
+ .domain(thresholds)
+ .range(perfColors)
}
// Traffic (default): blue/indigo gradient to match site color scheme
@@ -261,11 +279,15 @@ const InteractiveMapCore = ({
const metricValue = result?.data?.count || 0
// No-data countries: subtle, muted gray that blends with the background
- const noDataFill = theme === 'dark' ? 'rgba(51, 65, 85, 0.5)' : 'rgba(226, 232, 240, 0.6)'
+ const noDataFill =
+ theme === 'dark' ? 'rgba(51, 65, 85, 0.5)' : 'rgba(226, 232, 240, 0.6)'
const fill = metricValue > 0 ? colorScale(metricValue) : noDataFill
// Borders: very subtle, almost invisible for cleaner look
- const borderBaseColour = theme === 'dark' ? 'rgba(71, 85, 105, 0.4)' : 'rgba(148, 163, 184, 0.35)'
+ const borderBaseColour =
+ theme === 'dark'
+ ? 'rgba(71, 85, 105, 0.4)'
+ : 'rgba(148, 163, 184, 0.35)'
return {
color: borderBaseColour,
@@ -275,7 +297,8 @@ const InteractiveMapCore = ({
fillOpacity: metricValue > 0 ? 0.85 : 0.4,
opacity: 1,
smoothFactor: mapView === 'regions' ? 1 : 0.3,
- className: 'transition-[stroke,stroke-width,fill-opacity] duration-200 ease-out',
+ className:
+ 'transition-[stroke,stroke-width,fill-opacity] duration-200 ease-out',
}
},
[mapView, colorScale, findDataForFeature, theme],
@@ -296,11 +319,15 @@ const InteractiveMapCore = ({
} else {
borderHoverColour = theme === 'dark' ? '#818cf8' : '#4f46e5' // indigo-400/600 for traffic
}
- const borderNeutralHoverColour = theme === 'dark' ? '#64748b' : '#94a3b8' // slate-500/400
+ const borderNeutralHoverColour =
+ theme === 'dark' ? '#64748b' : '#94a3b8' // slate-500/400
const pathLayer = layer as unknown as Path
const canSetStyle = typeof (pathLayer as any).setStyle === 'function'
if (canSetStyle) {
- pathLayer.setStyle({ color: hasData ? borderHoverColour : borderNeutralHoverColour, weight: 1.5 } as any)
+ pathLayer.setStyle({
+ color: hasData ? borderHoverColour : borderNeutralHoverColour,
+ weight: 1.5,
+ } as any)
;(pathLayer as any).bringToFront?.()
}
const cx = e?.originalEvent?.clientX ?? 0
@@ -316,12 +343,16 @@ const InteractiveMapCore = ({
const props: any = feature.properties || {}
const isCountryView = mapView === 'countries'
- const name = props['name'] || props['ADMIN'] || result?.key || 'Unknown'
+ const name =
+ props['name'] || props['ADMIN'] || result?.key || 'Unknown'
const count = result?.data?.count ?? 0
const percentage = total > 0 ? _round((count / total) * 100, 2) : 0
- const ccFromProps = isCountryView ? props?.iso_a2 : (props?.iso_3166_2 || '').split('-')[0]
- const cc = (result?.data?.cc as string | undefined) || ccFromProps || ''
+ const ccFromProps = isCountryView
+ ? props?.iso_a2
+ : (props?.iso_3166_2 || '').split('-')[0]
+ const cc =
+ (result?.data?.cc as string | undefined) || ccFromProps || ''
setTooltipContent({
name,
@@ -363,13 +394,24 @@ const InteractiveMapCore = ({
const props: any = feature.properties || {}
const iso = props?.iso_3166_2 as string | undefined
const isTaiwanRegion = !!(iso && iso.toUpperCase() === 'TW')
- const clickType = mapView === 'regions' ? (isTaiwanRegion ? 'cc' : 'rg') : 'cc'
+ const clickType =
+ mapView === 'regions' ? (isTaiwanRegion ? 'cc' : 'rg') : 'cc'
onClick(clickType, key)
},
})
},
- [findDataForFeature, total, onClick, mapView, theme, handleStyle, repositionTooltip, isErrorsTab, isPerformanceTab],
+ [
+ findDataForFeature,
+ total,
+ onClick,
+ mapView,
+ theme,
+ handleStyle,
+ repositionTooltip,
+ isErrorsTab,
+ isPerformanceTab,
+ ],
)
const MapEventHandler = () => {
@@ -436,7 +478,9 @@ const InteractiveMapCore = ({
<div className='absolute inset-0 z-10 flex items-center justify-center rounded-md bg-slate-900/20 backdrop-blur-sm'>
<div className='flex flex-col items-center gap-2'>
<Spin />
- <span className='text-sm text-slate-900 dark:text-gray-50'>{t('project.loadingMapData')}</span>
+ <span className='text-sm text-slate-900 dark:text-gray-50'>
+ {t('project.loadingMapData')}
+ </span>
</div>
</div>
) : null}
@@ -500,18 +544,34 @@ const InteractiveMapCore = ({
style={{ left: 0, top: 0, transform: 'translate(-50%, -100%)' }}
>
<div className='flex items-center gap-1.5 font-medium'>
- <Flag className='rounded-xs' country={tooltipContent.code} size={18} alt='' aria-hidden='true' />
+ <Flag
+ className='rounded-xs'
+ country={tooltipContent.code}
+ size={18}
+ alt=''
+ aria-hidden='true'
+ />
<span>{tooltipContent.name}</span>
</div>
<div className='mt-0.5'>
- <span className='font-bold' style={{ color: getTooltipColor(tooltipContent.count) }}>
+ <span
+ className='font-bold'
+ style={{ color: getTooltipColor(tooltipContent.count) }}
+ >
{isTrafficTab || isErrorsTab
? nFormatter(tooltipContent.count, 1)
- : getStringFromTime(getTimeFromSeconds(tooltipContent.count), true)}
+ : getStringFromTime(
+ getTimeFromSeconds(tooltipContent.count),
+ true,
+ )}
</span>{' '}
<span className='text-gray-500 dark:text-gray-400'>
({tooltipContent.percentage.toFixed(1)}%)
- {isTrafficTab ? ' visitors' : isErrorsTab ? ' occurrences' : ' avg load time'}
+ {isTrafficTab
+ ? ' visitors'
+ : isErrorsTab
+ ? ' occurrences'
+ : ' avg load time'}
</span>
</div>
</div>
@@ -536,7 +596,9 @@ const InteractiveMap = ({
<div className='relative flex h-full w-full items-center justify-center'>
<div className='flex flex-col items-center gap-2'>
<div className='h-8 w-8 animate-spin rounded-full border-2 border-indigo-400 border-t-transparent'></div>
- <span className='text-sm text-neutral-600 dark:text-neutral-300'>{t('project.loadingMapData')}</span>
+ <span className='text-sm text-neutral-600 dark:text-neutral-300'>
+ {t('project.loadingMapData')}
+ </span>
</div>
</div>
}
diff --git a/web/app/pages/Project/View/components/LiveVisitorsDropdown.tsx b/web/app/pages/Project/View/components/LiveVisitorsDropdown.tsx
index 95041376b..218a78e8d 100644
--- a/web/app/pages/Project/View/components/LiveVisitorsDropdown.tsx
+++ b/web/app/pages/Project/View/components/LiveVisitorsDropdown.tsx
@@ -28,7 +28,10 @@ const LiveVisitorsDropdown = () => {
try {
// Getting live sessions list and updating live visitors count to make sure it matches the list length
- const [info] = await Promise.all([fetchLiveVisitorsInfo(id), updateLiveVisitors()])
+ const [info] = await Promise.all([
+ fetchLiveVisitorsInfo(id),
+ updateLiveVisitors(),
+ ])
setLiveInfo(info || [])
} catch (reason) {
console.error('[LiveVisitorsDropdown] getLiveVisitors:', reason)
@@ -66,9 +69,12 @@ const LiveVisitorsDropdown = () => {
})}{' '}
</span>
<ChevronDownIcon
- className={cn('ml-1 inline h-4 w-4 transition-transform duration-150 ease-out', {
- 'rotate-180': isDropdownVisible,
- })}
+ className={cn(
+ 'ml-1 inline h-4 w-4 transition-transform duration-150 ease-out',
+ {
+ 'rotate-180': isDropdownVisible,
+ },
+ )}
/>
</button>
@@ -85,7 +91,9 @@ const LiveVisitorsDropdown = () => {
>
<div className='flex w-full flex-col'>
<div className='flex items-center justify-between border-b border-black/10 bg-white p-2 dark:border-slate-700/50 dark:bg-slate-900'>
- <p className='text-sm font-semibold text-gray-900 dark:text-gray-50'>{t('dashboard.liveVisitors')}</p>
+ <p className='text-sm font-semibold text-gray-900 dark:text-gray-50'>
+ {t('dashboard.liveVisitors')}
+ </p>
<button
className='-m-1 rounded-md p-1 transition-colors hover:bg-gray-200 dark:hover:bg-slate-700'
@@ -103,7 +111,9 @@ const LiveVisitorsDropdown = () => {
{t('common.loading')}
</p>
) : liveInfo.length === 0 ? (
- <p className='py-2 text-sm text-gray-900 dark:text-gray-50'>{t('project.noData')}</p>
+ <p className='py-2 text-sm text-gray-900 dark:text-gray-50'>
+ {t('project.noData')}
+ </p>
) : (
<div className='table w-full border-separate border-spacing-y-2'>
<div className='table-row-group'>
@@ -120,7 +130,13 @@ const LiveVisitorsDropdown = () => {
to={stringifiedUrl}
>
<div className='table-cell rounded-l-lg bg-gray-100 pr-2 align-middle transition-colors group-hover:bg-gray-200 dark:bg-slate-800 dark:group-hover:bg-slate-700'>
- <Flag className='m-2 rounded-xs' country={cc} size={21} alt='' aria-hidden='true' />
+ <Flag
+ className='m-2 rounded-xs'
+ country={cc}
+ size={21}
+ alt=''
+ aria-hidden='true'
+ />
</div>
<div className='table-cell bg-gray-100 pr-2 align-middle transition-colors group-hover:bg-gray-200 dark:bg-slate-800 dark:group-hover:bg-slate-700'>
{os}
diff --git a/web/app/pages/Project/View/components/LockedDashboard.tsx b/web/app/pages/Project/View/components/LockedDashboard.tsx
index 6638b3e45..8f7b60aa4 100644
--- a/web/app/pages/Project/View/components/LockedDashboard.tsx
+++ b/web/app/pages/Project/View/components/LockedDashboard.tsx
@@ -15,7 +15,10 @@ const LockedDashboard = () => {
const message = useMemo(() => {
if (project?.role === 'owner') {
- if (user?.dashboardBlockReason === DashboardBlockReason.exceeding_plan_limits) {
+ if (
+ user?.dashboardBlockReason ===
+ DashboardBlockReason.exceeding_plan_limits
+ ) {
return t('project.locked.descExceedingTier')
}
if (user?.dashboardBlockReason === DashboardBlockReason.trial_ended) {
@@ -24,7 +27,10 @@ const LockedDashboard = () => {
if (user?.dashboardBlockReason === DashboardBlockReason.payment_failed) {
return t('project.locked.descPaymentFailed')
}
- if (user?.dashboardBlockReason === DashboardBlockReason.subscription_cancelled) {
+ if (
+ user?.dashboardBlockReason ===
+ DashboardBlockReason.subscription_cancelled
+ ) {
return t('project.locked.descSubCancelled')
}
}
diff --git a/web/app/pages/Project/View/components/MainChart.tsx b/web/app/pages/Project/View/components/MainChart.tsx
index fc74554fd..86c423891 100644
--- a/web/app/pages/Project/View/components/MainChart.tsx
+++ b/web/app/pages/Project/View/components/MainChart.tsx
@@ -13,11 +13,20 @@ interface MainChartProps {
deps?: any[]
}
-export const MainChart = ({ chartId, options, dataNames, className, deps }: MainChartProps) => {
+export const MainChart = ({
+ chartId,
+ options,
+ dataNames,
+ className,
+ deps,
+}: MainChartProps) => {
const { registerChart, unregisterChart } = useChartManager()
const chartRef = useRef<any>(null)
- const mergedDeps = useMemo(() => deps || [options, dataNames], [deps, options, dataNames])
+ const mergedDeps = useMemo(
+ () => deps || [options, dataNames],
+ [deps, options, dataNames],
+ )
const handleChartReady = (chart: any) => {
chartRef.current = chart
diff --git a/web/app/pages/Project/View/components/NoEvents.tsx b/web/app/pages/Project/View/components/NoEvents.tsx
index 8d6689df9..ad121e5f7 100644
--- a/web/app/pages/Project/View/components/NoEvents.tsx
+++ b/web/app/pages/Project/View/components/NoEvents.tsx
@@ -33,8 +33,15 @@ const NoEvents = ({ filters }: NoEventsProps) => {
<Text as='h3' size='xl' weight='medium' className='tracking-tight'>
{t('project.noEvTitle')}
</Text>
- <Text as='p' size='sm' colour='secondary' className='mx-auto mt-2 max-w-md'>
- {hasFilters ? t('project.noEventsFiltersDesc') : t('project.noEvContent')}
+ <Text
+ as='p'
+ size='sm'
+ colour='secondary'
+ className='mx-auto mt-2 max-w-md'
+ >
+ {hasFilters
+ ? t('project.noEventsFiltersDesc')
+ : t('project.noEvContent')}
</Text>
</div>
</>
diff --git a/web/app/pages/Project/View/components/PasswordRequiredModal.tsx b/web/app/pages/Project/View/components/PasswordRequiredModal.tsx
index 5103ec83c..5e7c94cf7 100644
--- a/web/app/pages/Project/View/components/PasswordRequiredModal.tsx
+++ b/web/app/pages/Project/View/components/PasswordRequiredModal.tsx
@@ -17,7 +17,10 @@ interface PasswordRequiredModalProps {
onSubmit: (password: string) => Promise<{ success: boolean; error?: string }>
}
-const PasswordRequiredModal = ({ isOpen, onSubmit }: PasswordRequiredModalProps) => {
+const PasswordRequiredModal = ({
+ isOpen,
+ onSubmit,
+}: PasswordRequiredModalProps) => {
const { t } = useTranslation('common')
const [password, setPassword] = useState('')
const [error, setError] = useState<string | null>(null)
@@ -83,7 +86,9 @@ const PasswordRequiredModal = ({ isOpen, onSubmit }: PasswordRequiredModalProps)
<h3 className='mt-4 text-lg font-semibold text-gray-900 dark:text-gray-50'>
{t('titles.passwordProtected')}
</h3>
- <p className='mt-2 text-sm text-gray-600 dark:text-gray-400'>{t('project.passwordProtectedHint')}</p>
+ <p className='mt-2 text-sm text-gray-600 dark:text-gray-400'>
+ {t('project.passwordProtectedHint')}
+ </p>
</div>
<Input
diff --git a/web/app/pages/Project/View/components/ProjectSidebar.tsx b/web/app/pages/Project/View/components/ProjectSidebar.tsx
index dafd664ca..8dc74214b 100644
--- a/web/app/pages/Project/View/components/ProjectSidebar.tsx
+++ b/web/app/pages/Project/View/components/ProjectSidebar.tsx
@@ -8,7 +8,14 @@ import {
XIcon,
MenuIcon,
} from 'lucide-react'
-import React, { useState, useMemo, useCallback, useEffect, useRef, memo } from 'react'
+import React, {
+ useState,
+ useMemo,
+ useCallback,
+ useEffect,
+ useRef,
+ memo,
+} from 'react'
import { useTranslation } from 'react-i18next'
import { Link, LinkProps } from 'react-router'
@@ -108,158 +115,213 @@ const CollapsibleGroup: React.FC<{
searchParams: URLSearchParams
isCollapsed?: boolean
onMobileClose?: () => void
-}> = memo(({ group, activeTab, onTabChange, projectId, dataLoading, searchParams, isCollapsed, onMobileClose }) => {
- const [isExpanded, setIsExpanded] = useState(() => getGroupExpandedState(group.id))
+}> = memo(
+ ({
+ group,
+ activeTab,
+ onTabChange,
+ projectId,
+ dataLoading,
+ searchParams,
+ isCollapsed,
+ onMobileClose,
+ }) => {
+ const [isExpanded, setIsExpanded] = useState(() =>
+ getGroupExpandedState(group.id),
+ )
+
+ const hasActiveTab = useMemo(() => {
+ return group.tabs.some((tab) => tab.id === activeTab)
+ }, [group.tabs, activeTab])
- const hasActiveTab = useMemo(() => {
- return group.tabs.some((tab) => tab.id === activeTab)
- }, [group.tabs, activeTab])
+ const prevHasActiveTab = useRef(hasActiveTab)
- const prevHasActiveTab = useRef(hasActiveTab)
+ React.useEffect(() => {
+ // Only auto-expand when user navigates TO this group (not on initial mount)
+ if (hasActiveTab && !prevHasActiveTab.current && !isExpanded) {
+ setIsExpanded(true)
+ setGroupExpandedState(group.id, true)
+ }
+ prevHasActiveTab.current = hasActiveTab
+ }, [hasActiveTab, group.id]) // eslint-disable-line react-hooks/exhaustive-deps
+
+ if (isCollapsed) {
+ return (
+ <div className='mb-1'>
+ <nav className='flex flex-col gap-0.5'>
+ {_map(group.tabs, (tab) => {
+ const isCurrent = tab.id === activeTab
+ const TabIcon = tab.icon
+ const iconColorClass = ICON_COLORS[tab.id] || 'text-gray-500'
+
+ const handleClick = (e: React.MouseEvent) => {
+ if (tab.id === 'settings') {
+ onMobileClose?.()
+ return
+ }
- React.useEffect(() => {
- // Only auto-expand when user navigates TO this group (not on initial mount)
- if (hasActiveTab && !prevHasActiveTab.current && !isExpanded) {
- setIsExpanded(true)
- setGroupExpandedState(group.id, true)
+ e.preventDefault()
+ if (!dataLoading) {
+ onTabChange(tab.id as keyof typeof PROJECT_TABS)
+ onMobileClose?.()
+ }
+ }
+
+ const newSearchParams = new URLSearchParams(
+ searchParams.toString(),
+ )
+ newSearchParams.set('tab', tab.id)
+ const tabUrl: LinkProps['to'] =
+ tab.id === 'settings'
+ ? routes.project_settings.replace(':id', projectId)
+ : { search: newSearchParams.toString() }
+
+ return (
+ <Tooltip
+ key={tab.id}
+ text={tab.label}
+ tooltipNode={
+ <Link
+ to={tabUrl}
+ onClick={handleClick}
+ className={cn(
+ 'group flex items-center justify-center rounded-md p-2 transition-colors',
+ {
+ 'bg-gray-100 dark:bg-slate-800': isCurrent,
+ 'hover:bg-gray-100 dark:hover:bg-slate-800/60':
+ !isCurrent,
+ 'cursor-wait': dataLoading && tab.id !== 'settings',
+ },
+ )}
+ aria-current={isCurrent ? 'page' : undefined}
+ aria-label={tab.label}
+ >
+ <TabIcon
+ className={cn('size-5 shrink-0', iconColorClass)}
+ strokeWidth={1.5}
+ aria-hidden='true'
+ />
+ </Link>
+ }
+ disableHoverableContent
+ />
+ )
+ })}
+ </nav>
+ </div>
+ )
}
- prevHasActiveTab.current = hasActiveTab
- }, [hasActiveTab, group.id]) // eslint-disable-line react-hooks/exhaustive-deps
- if (isCollapsed) {
return (
<div className='mb-1'>
- <nav className='flex flex-col gap-0.5'>
- {_map(group.tabs, (tab) => {
- const isCurrent = tab.id === activeTab
- const TabIcon = tab.icon
- const iconColorClass = ICON_COLORS[tab.id] || 'text-gray-500'
-
- const handleClick = (e: React.MouseEvent) => {
- if (tab.id === 'settings') {
- onMobileClose?.()
- return
- }
+ <button
+ type='button'
+ onClick={() => {
+ const newValue = !isExpanded
+ setIsExpanded(newValue)
+ setGroupExpandedState(group.id, newValue)
+ }}
+ className='group flex w-full items-center justify-between rounded-md px-2 py-1.5 text-left transition-colors hover:bg-gray-100 dark:hover:bg-slate-800/60'
+ >
+ <Text
+ as='span'
+ size='xs'
+ colour='secondary'
+ weight='semibold'
+ truncate
+ className='max-w-full'
+ >
+ {group.label}
+ </Text>
+ {isExpanded ? (
+ <ChevronDownIcon
+ className='size-3.5 text-gray-400'
+ strokeWidth={2}
+ />
+ ) : (
+ <ChevronRightIcon
+ className='size-3.5 text-gray-400'
+ strokeWidth={2}
+ />
+ )}
+ </button>
+
+ <div
+ className={cn(
+ 'overflow-hidden transition-all duration-200 ease-in-out',
+ {
+ 'max-h-96 opacity-100': isExpanded,
+ 'max-h-0 opacity-0': !isExpanded,
+ },
+ )}
+ >
+ <nav className='mt-1 flex flex-col gap-0.5 pl-2'>
+ {_map(group.tabs, (tab) => {
+ const isCurrent = tab.id === activeTab
+ const TabIcon = tab.icon
+ const iconColorClass = ICON_COLORS[tab.id] || 'text-gray-500'
- e.preventDefault()
- if (!dataLoading) {
- onTabChange(tab.id as keyof typeof PROJECT_TABS)
- onMobileClose?.()
+ const handleClick = (e: React.MouseEvent) => {
+ if (tab.id === 'settings') {
+ onMobileClose?.()
+ return // Let the Link handle navigation
+ }
+
+ e.preventDefault()
+ if (!dataLoading) {
+ onTabChange(tab.id as keyof typeof PROJECT_TABS)
+ onMobileClose?.()
+ }
}
- }
- const newSearchParams = new URLSearchParams(searchParams.toString())
- newSearchParams.set('tab', tab.id)
- const tabUrl: LinkProps['to'] =
- tab.id === 'settings'
- ? routes.project_settings.replace(':id', projectId)
- : { search: newSearchParams.toString() }
-
- return (
- <Tooltip
- key={tab.id}
- text={tab.label}
- tooltipNode={
- <Link
- to={tabUrl}
- onClick={handleClick}
- className={cn('group flex items-center justify-center rounded-md p-2 transition-colors', {
+ const newSearchParams = new URLSearchParams(
+ searchParams.toString(),
+ )
+ newSearchParams.set('tab', tab.id)
+ const tabUrl: LinkProps['to'] =
+ tab.id === 'settings'
+ ? routes.project_settings.replace(':id', projectId)
+ : { search: newSearchParams.toString() }
+
+ return (
+ <Link
+ key={tab.id}
+ to={tabUrl}
+ onClick={handleClick}
+ className={cn(
+ 'group flex items-center gap-1.5 rounded-md px-2.5 py-2 transition-colors',
+ {
'bg-gray-100 dark:bg-slate-800': isCurrent,
- 'hover:bg-gray-100 dark:hover:bg-slate-800/60': !isCurrent,
+ 'hover:bg-gray-100 dark:hover:bg-slate-800/60':
+ !isCurrent,
'cursor-wait': dataLoading && tab.id !== 'settings',
- })}
- aria-current={isCurrent ? 'page' : undefined}
- aria-label={tab.label}
+ },
+ )}
+ aria-current={isCurrent ? 'page' : undefined}
+ >
+ <TabIcon
+ className={cn('size-4 shrink-0', iconColorClass)}
+ strokeWidth={1.5}
+ aria-hidden='true'
+ />
+ <Text
+ as='span'
+ size='sm'
+ weight='medium'
+ truncate
+ className='max-w-full'
>
- <TabIcon className={cn('size-5 shrink-0', iconColorClass)} strokeWidth={1.5} aria-hidden='true' />
- </Link>
- }
- disableHoverableContent
- />
- )
- })}
- </nav>
+ {tab.label}
+ </Text>
+ </Link>
+ )
+ })}
+ </nav>
+ </div>
</div>
)
- }
-
- return (
- <div className='mb-1'>
- <button
- type='button'
- onClick={() => {
- const newValue = !isExpanded
- setIsExpanded(newValue)
- setGroupExpandedState(group.id, newValue)
- }}
- className='group flex w-full items-center justify-between rounded-md px-2 py-1.5 text-left transition-colors hover:bg-gray-100 dark:hover:bg-slate-800/60'
- >
- <Text as='span' size='xs' colour='secondary' weight='semibold' truncate className='max-w-full'>
- {group.label}
- </Text>
- {isExpanded ? (
- <ChevronDownIcon className='size-3.5 text-gray-400' strokeWidth={2} />
- ) : (
- <ChevronRightIcon className='size-3.5 text-gray-400' strokeWidth={2} />
- )}
- </button>
-
- <div
- className={cn('overflow-hidden transition-all duration-200 ease-in-out', {
- 'max-h-96 opacity-100': isExpanded,
- 'max-h-0 opacity-0': !isExpanded,
- })}
- >
- <nav className='mt-1 flex flex-col gap-0.5 pl-2'>
- {_map(group.tabs, (tab) => {
- const isCurrent = tab.id === activeTab
- const TabIcon = tab.icon
- const iconColorClass = ICON_COLORS[tab.id] || 'text-gray-500'
-
- const handleClick = (e: React.MouseEvent) => {
- if (tab.id === 'settings') {
- onMobileClose?.()
- return // Let the Link handle navigation
- }
-
- e.preventDefault()
- if (!dataLoading) {
- onTabChange(tab.id as keyof typeof PROJECT_TABS)
- onMobileClose?.()
- }
- }
-
- const newSearchParams = new URLSearchParams(searchParams.toString())
- newSearchParams.set('tab', tab.id)
- const tabUrl: LinkProps['to'] =
- tab.id === 'settings'
- ? routes.project_settings.replace(':id', projectId)
- : { search: newSearchParams.toString() }
-
- return (
- <Link
- key={tab.id}
- to={tabUrl}
- onClick={handleClick}
- className={cn('group flex items-center gap-1.5 rounded-md px-2.5 py-2 transition-colors', {
- 'bg-gray-100 dark:bg-slate-800': isCurrent,
- 'hover:bg-gray-100 dark:hover:bg-slate-800/60': !isCurrent,
- 'cursor-wait': dataLoading && tab.id !== 'settings',
- })}
- aria-current={isCurrent ? 'page' : undefined}
- >
- <TabIcon className={cn('size-4 shrink-0', iconColorClass)} strokeWidth={1.5} aria-hidden='true' />
- <Text as='span' size='sm' weight='medium' truncate className='max-w-full'>
- {tab.label}
- </Text>
- </Link>
- )
- })}
- </nav>
- </div>
- </div>
- )
-})
+ },
+)
CollapsibleGroup.displayName = 'CollapsibleGroup'
@@ -277,7 +339,10 @@ const ProjectSidebar: React.FC<ProjectSidebarProps> = ({
onMobileClose,
className,
}) => {
- const faviconHost = useMemo(() => getFaviconHost(websiteUrl || null), [websiteUrl])
+ const faviconHost = useMemo(
+ () => getFaviconHost(websiteUrl || null),
+ [websiteUrl],
+ )
const { t } = useTranslation('common')
const [isCollapsed, setIsCollapsed] = useState(() => {
if (typeof window !== 'undefined') {
@@ -342,7 +407,12 @@ const ProjectSidebar: React.FC<ProjectSidebarProps> = ({
const groups: TabGroup[] = []
const webAnalyticsTabs = tabs.filter((tab) =>
- [PROJECT_TABS.traffic, PROJECT_TABS.performance, PROJECT_TABS.funnels, PROJECT_TABS.alerts]
+ [
+ PROJECT_TABS.traffic,
+ PROJECT_TABS.performance,
+ PROJECT_TABS.funnels,
+ PROJECT_TABS.alerts,
+ ]
.filter(Boolean)
.includes(tab.id as any),
)
@@ -374,7 +444,9 @@ const ProjectSidebar: React.FC<ProjectSidebarProps> = ({
})
}
- const securityTabs = tabs.filter((tab) => PROJECT_TABS.captcha && tab.id === PROJECT_TABS.captcha)
+ const securityTabs = tabs.filter(
+ (tab) => PROJECT_TABS.captcha && tab.id === PROJECT_TABS.captcha,
+ )
if (securityTabs.length > 0) {
groups.push({
id: 'security',
@@ -394,7 +466,9 @@ const ProjectSidebar: React.FC<ProjectSidebarProps> = ({
? 'h-screen w-64'
: cn(
'transition-[width,height] duration-300 ease-in-out',
- isScrolled ? 'h-[calc(100vh-1.5rem)]' : 'h-[calc(100vh-60px-1rem)]',
+ isScrolled
+ ? 'h-[calc(100vh-1.5rem)]'
+ : 'h-[calc(100vh-60px-1rem)]',
isCollapsed ? 'w-14' : 'w-56',
),
className,
@@ -413,7 +487,12 @@ const ProjectSidebar: React.FC<ProjectSidebarProps> = ({
alt={projectName}
/>
) : (
- <Text as='h2' size='lg' weight='semibold' className='text-center'>
+ <Text
+ as='h2'
+ size='lg'
+ weight='semibold'
+ className='text-center'
+ >
{projectName.charAt(0).toUpperCase()}
</Text>
)
@@ -435,7 +514,13 @@ const ProjectSidebar: React.FC<ProjectSidebarProps> = ({
aria-hidden='true'
/>
) : null}
- <Text as='h2' size='lg' weight='semibold' truncate className='text-left'>
+ <Text
+ as='h2'
+ size='lg'
+ weight='semibold'
+ truncate
+ className='text-left'
+ >
{projectName}
</Text>
</div>
@@ -470,7 +555,9 @@ const ProjectSidebar: React.FC<ProjectSidebarProps> = ({
}
}
- const newSearchParams = new URLSearchParams(searchParams.toString())
+ const newSearchParams = new URLSearchParams(
+ searchParams.toString(),
+ )
newSearchParams.set('tab', askAiTab.id)
if (isCollapsed && !isMobileOpen) {
@@ -481,12 +568,16 @@ const ProjectSidebar: React.FC<ProjectSidebarProps> = ({
<Link
to={{ search: newSearchParams.toString() }}
onClick={handleClick}
- className={cn('group flex items-center justify-center rounded-md p-2 transition-colors', {
- 'bg-linear-to-r from-violet-500/10 to-purple-500/10 dark:from-violet-500/20 dark:to-purple-500/20':
- isCurrent,
- 'hover:bg-gray-100 dark:hover:bg-slate-800/60': !isCurrent,
- 'cursor-wait': dataLoading,
- })}
+ className={cn(
+ 'group flex items-center justify-center rounded-md p-2 transition-colors',
+ {
+ 'bg-linear-to-r from-violet-500/10 to-purple-500/10 dark:from-violet-500/20 dark:to-purple-500/20':
+ isCurrent,
+ 'hover:bg-gray-100 dark:hover:bg-slate-800/60':
+ !isCurrent,
+ 'cursor-wait': dataLoading,
+ },
+ )}
aria-current={isCurrent ? 'page' : undefined}
aria-label={askAiTab.label}
>
@@ -506,16 +597,30 @@ const ProjectSidebar: React.FC<ProjectSidebarProps> = ({
<Link
to={{ search: newSearchParams.toString() }}
onClick={handleClick}
- className={cn('group flex items-center gap-2 rounded-md px-2.5 py-2 transition-colors', {
- 'bg-linear-to-r from-violet-500/10 to-purple-500/10 dark:from-violet-500/20 dark:to-purple-500/20':
- isCurrent,
- 'hover:bg-gray-100 dark:hover:bg-slate-800/60': !isCurrent,
- 'cursor-wait': dataLoading,
- })}
+ className={cn(
+ 'group flex items-center gap-2 rounded-md px-2.5 py-2 transition-colors',
+ {
+ 'bg-linear-to-r from-violet-500/10 to-purple-500/10 dark:from-violet-500/20 dark:to-purple-500/20':
+ isCurrent,
+ 'hover:bg-gray-100 dark:hover:bg-slate-800/60':
+ !isCurrent,
+ 'cursor-wait': dataLoading,
+ },
+ )}
aria-current={isCurrent ? 'page' : undefined}
>
- <TabIcon className={cn('size-4 shrink-0', iconColorClass)} strokeWidth={1.5} aria-hidden='true' />
- <Text as='span' size='sm' weight='medium' truncate className='max-w-full'>
+ <TabIcon
+ className={cn('size-4 shrink-0', iconColorClass)}
+ strokeWidth={1.5}
+ aria-hidden='true'
+ />
+ <Text
+ as='span'
+ size='sm'
+ weight='medium'
+ truncate
+ className='max-w-full'
+ >
{askAiTab.label}
</Text>
</Link>
@@ -552,10 +657,18 @@ const ProjectSidebar: React.FC<ProjectSidebarProps> = ({
aria-label={isCollapsed ? t('common.expand') : t('common.collapse')}
>
{isCollapsed ? (
- <PanelLeftOpenIcon className='h-5 w-5 shrink-0' strokeWidth={1.5} aria-hidden='true' />
+ <PanelLeftOpenIcon
+ className='h-5 w-5 shrink-0'
+ strokeWidth={1.5}
+ aria-hidden='true'
+ />
) : (
<>
- <PanelLeftCloseIcon className='h-5 w-5 shrink-0' strokeWidth={1.5} aria-hidden='true' />
+ <PanelLeftCloseIcon
+ className='h-5 w-5 shrink-0'
+ strokeWidth={1.5}
+ aria-hidden='true'
+ />
<span className='truncate'>{t('common.collapse')}</span>
</>
)}
@@ -578,7 +691,9 @@ const ProjectSidebar: React.FC<ProjectSidebarProps> = ({
strokeWidth={1.5}
aria-hidden='true'
/>
- {!isCollapsed || isMobileOpen ? <span className='truncate'>{t('common.settings')}</span> : null}
+ {!isCollapsed || isMobileOpen ? (
+ <span className='truncate'>{t('common.settings')}</span>
+ ) : null}
</Link>
) : null}
</div>
@@ -588,8 +703,14 @@ const ProjectSidebar: React.FC<ProjectSidebarProps> = ({
if (isMobileOpen) {
return (
<div className='pointer-events-auto fixed inset-0 z-50 md:hidden'>
- <div className='animate-fade-in absolute inset-0 bg-black/50' onClick={onMobileClose} aria-hidden='true' />
- <div className='animate-slide-in-left relative h-full w-fit'>{sidebarContent}</div>
+ <div
+ className='animate-fade-in absolute inset-0 bg-black/50'
+ onClick={onMobileClose}
+ aria-hidden='true'
+ />
+ <div className='animate-slide-in-left relative h-full w-fit'>
+ {sidebarContent}
+ </div>
</div>
)
}
@@ -602,7 +723,10 @@ interface MobileSidebarTriggerProps {
activeTabLabel?: string
}
-export const MobileSidebarTrigger: React.FC<MobileSidebarTriggerProps> = ({ onClick, activeTabLabel }) => {
+export const MobileSidebarTrigger: React.FC<MobileSidebarTriggerProps> = ({
+ onClick,
+ activeTabLabel,
+}) => {
const { t } = useTranslation('common')
return (
@@ -616,7 +740,9 @@ export const MobileSidebarTrigger: React.FC<MobileSidebarTriggerProps> = ({ onCl
<MenuIcon className='h-5 w-5' strokeWidth={1.5} />
</button>
{activeTabLabel ? (
- <span className='text-sm font-medium text-gray-700 dark:text-gray-200'>{activeTabLabel}</span>
+ <span className='text-sm font-medium text-gray-700 dark:text-gray-200'>
+ {activeTabLabel}
+ </span>
) : null}
</div>
)
diff --git a/web/app/pages/Project/View/components/RefreshStatsButton.tsx b/web/app/pages/Project/View/components/RefreshStatsButton.tsx
index ab3a30528..2cce31a3e 100644
--- a/web/app/pages/Project/View/components/RefreshStatsButton.tsx
+++ b/web/app/pages/Project/View/components/RefreshStatsButton.tsx
@@ -33,13 +33,22 @@ export const RefreshStatsButton = ({ onRefresh }: RefreshStatsButtonProps) => {
const newProgress = Math.min((elapsed / REFRESH_INTERVAL_MS) * 100, 100)
// Only update state if progress changed by at least 1% (reduces re-renders)
- if (Math.abs(newProgress - lastRenderedProgress) >= 1 || newProgress >= 100) {
+ if (
+ Math.abs(newProgress - lastRenderedProgress) >= 1 ||
+ newProgress >= 100
+ ) {
lastRenderedProgress = newProgress
setProgress(newProgress)
}
// Check if we should trigger auto-refresh
- if (newProgress >= 100 && !hasTriggeredRefresh.current && !isRefreshing && !authLoading && !dataLoading) {
+ if (
+ newProgress >= 100 &&
+ !hasTriggeredRefresh.current &&
+ !isRefreshing &&
+ !authLoading &&
+ !dataLoading
+ ) {
hasTriggeredRefresh.current = true
;(async () => {
setIsRefreshing(true)
@@ -70,7 +79,10 @@ export const RefreshStatsButton = ({ onRefresh }: RefreshStatsButtonProps) => {
setIsRefreshing(false)
}
- const remainingSeconds = Math.max(1, Math.ceil(AUTO_REFRESH_INTERVAL_SECONDS * (1 - progress / 100)))
+ const remainingSeconds = Math.max(
+ 1,
+ Math.ceil(AUTO_REFRESH_INTERVAL_SECONDS * (1 - progress / 100)),
+ )
const showSpinner = isRefreshing || dataLoading
return (
@@ -87,9 +99,12 @@ export const RefreshStatsButton = ({ onRefresh }: RefreshStatsButtonProps) => {
>
<div className='relative h-5 w-5'>
<RotateCw
- className={cn('absolute inset-0 h-5 w-5 text-gray-400/80 dark:text-slate-600', {
- 'animate-spin': showSpinner,
- })}
+ className={cn(
+ 'absolute inset-0 h-5 w-5 text-gray-400/80 dark:text-slate-600',
+ {
+ 'animate-spin': showSpinner,
+ },
+ )}
/>
{!showSpinner ? (
<div
@@ -107,7 +122,9 @@ export const RefreshStatsButton = ({ onRefresh }: RefreshStatsButtonProps) => {
) : null}
</div>
<div className='pointer-events-none absolute bottom-full left-1/2 z-30 mb-2 -translate-x-1/2 rounded bg-gray-900 px-2 py-1 text-xs whitespace-nowrap text-white opacity-0 transition-opacity group-hover:opacity-100 dark:bg-slate-700'>
- {showSpinner ? t('project.refreshing') : t('project.refreshingIn', { seconds: remainingSeconds })}
+ {showSpinner
+ ? t('project.refreshing')
+ : t('project.refreshingIn', { seconds: remainingSeconds })}
<div className='absolute top-full left-1/2 -translate-x-1/2 border-4 border-transparent border-t-gray-900 dark:border-t-slate-700' />
</div>
</button>
diff --git a/web/app/pages/Project/View/components/SearchFilters.tsx b/web/app/pages/Project/View/components/SearchFilters.tsx
index cde55504f..73528f115 100644
--- a/web/app/pages/Project/View/components/SearchFilters.tsx
+++ b/web/app/pages/Project/View/components/SearchFilters.tsx
@@ -1,16 +1,35 @@
-import { Listbox, Transition, ListboxButton, ListboxOptions, ListboxOption } from '@headlessui/react'
+import {
+ Listbox,
+ Transition,
+ ListboxButton,
+ ListboxOptions,
+ ListboxOption,
+} from '@headlessui/react'
import cx from 'clsx'
import _isEmpty from 'lodash/isEmpty'
-import { CheckIcon, ChevronsUpDownIcon, PlusIcon, SlidersHorizontalIcon, Trash2Icon } from 'lucide-react'
+import {
+ CheckIcon,
+ ChevronsUpDownIcon,
+ PlusIcon,
+ SlidersHorizontalIcon,
+ Trash2Icon,
+} from 'lucide-react'
import { useState, useEffect, useCallback, Fragment } from 'react'
import { useTranslation } from 'react-i18next'
import { useNavigate, useSearchParams } from 'react-router'
import { useFiltersProxy } from '~/hooks/useAnalyticsProxy'
-import { FILTERS_PANELS_ORDER, ERRORS_FILTERS_PANELS_ORDER } from '~/lib/constants'
+import {
+ FILTERS_PANELS_ORDER,
+ ERRORS_FILTERS_PANELS_ORDER,
+} from '~/lib/constants'
import { useCurrentProject } from '~/providers/CurrentProjectProvider'
import { useTheme } from '~/providers/ThemeProvider'
-import FilterValueInput, { filterCategoryIcons, createVersionValue, parseVersionValue } from '~/ui/FilterValueInput'
+import FilterValueInput, {
+ filterCategoryIcons,
+ createVersionValue,
+ parseVersionValue,
+} from '~/ui/FilterValueInput'
import Modal from '~/ui/Modal'
import countries from '~/utils/isoCountries'
@@ -85,7 +104,9 @@ const OPERATORS: { value: FilterOperator; labelKey: string }[] = [
{ value: 'notContains', labelKey: 'project.contains.not' },
]
-const operatorToFilter = (operator: FilterOperator): { isExclusive: boolean; isContains: boolean } => {
+const operatorToFilter = (
+ operator: FilterOperator,
+): { isExclusive: boolean; isContains: boolean } => {
switch (operator) {
case 'is':
return { isExclusive: false, isContains: false }
@@ -106,7 +127,13 @@ interface SearchFiltersProps {
type: 'traffic' | 'errors'
}
-const SearchFilters = ({ showModal, setShowModal, tnMapping, filters, type }: SearchFiltersProps) => {
+const SearchFilters = ({
+ showModal,
+ setShowModal,
+ tnMapping,
+ filters,
+ type,
+}: SearchFiltersProps) => {
const { id } = useCurrentProject()
const { theme } = useTheme()
const {
@@ -114,13 +141,17 @@ const SearchFilters = ({ showModal, setShowModal, tnMapping, filters, type }: Se
i18n: { language },
} = useTranslation('common')
const [filterRows, setFilterRows] = useState<FilterRow[]>([])
- const [filterValuesCache, setFilterValuesCache] = useState<Record<string, string[]>>({})
+ const [filterValuesCache, setFilterValuesCache] = useState<
+ Record<string, string[]>
+ >({})
const [loadingColumns, setLoadingColumns] = useState<Set<string>>(new Set())
const [searchParams] = useSearchParams()
const navigate = useNavigate()
- const { fetchFilters, fetchErrorsFilters, fetchVersionFilters } = useFiltersProxy()
+ const { fetchFilters, fetchErrorsFilters, fetchVersionFilters } =
+ useFiltersProxy()
- const panelOptions = type === 'traffic' ? FILTERS_PANELS_ORDER : ERRORS_FILTERS_PANELS_ORDER
+ const panelOptions =
+ type === 'traffic' ? FILTERS_PANELS_ORDER : ERRORS_FILTERS_PANELS_ORDER
const fetchFilterValues = useCallback(
async (column: string) => {
@@ -162,7 +193,15 @@ const SearchFilters = ({ showModal, setShowModal, tnMapping, filters, type }: Se
})
}
},
- [id, type, filterValuesCache, loadingColumns, fetchFilters, fetchErrorsFilters, fetchVersionFilters],
+ [
+ id,
+ type,
+ filterValuesCache,
+ loadingColumns,
+ fetchFilters,
+ fetchErrorsFilters,
+ fetchVersionFilters,
+ ],
)
// Pre-fetch all filter values when modal opens
@@ -175,20 +214,31 @@ const SearchFilters = ({ showModal, setShowModal, tnMapping, filters, type }: Se
}
})
}
- }, [showModal, panelOptions, fetchFilterValues, filterValuesCache, loadingColumns])
+ }, [
+ showModal,
+ panelOptions,
+ fetchFilterValues,
+ filterValuesCache,
+ loadingColumns,
+ ])
// Initialize filter rows when modal opens
useEffect(() => {
if (showModal) {
if (_isEmpty(filterRows)) {
// Start with one empty filter row
- setFilterRows([{ id: crypto.randomUUID(), column: '', operator: 'is', value: '' }])
+ setFilterRows([
+ { id: crypto.randomUUID(), column: '', operator: 'is', value: '' },
+ ])
}
}
}, [showModal, filterRows])
const addFilterRow = () => {
- setFilterRows((prev) => [...prev, { id: crypto.randomUUID(), column: '', operator: 'is', value: '' }])
+ setFilterRows((prev) => [
+ ...prev,
+ { id: crypto.randomUUID(), column: '', operator: 'is', value: '' },
+ ])
}
const removeFilterRow = (rowId: string) => {
@@ -196,20 +246,30 @@ const SearchFilters = ({ showModal, setShowModal, tnMapping, filters, type }: Se
const newRows = prev.filter((r) => r.id !== rowId)
// Keep at least one row
if (newRows.length === 0) {
- return [{ id: crypto.randomUUID(), column: '', operator: 'is', value: '' }]
+ return [
+ { id: crypto.randomUUID(), column: '', operator: 'is', value: '' },
+ ]
}
return newRows
})
}
- const updateFilterRow = (rowId: string, field: keyof FilterRow, fieldValue: string) => {
+ const updateFilterRow = (
+ rowId: string,
+ field: keyof FilterRow,
+ fieldValue: string,
+ ) => {
setFilterRows((prev) =>
prev.map((row) => {
if (row.id !== rowId) return row
if (field === 'column') {
// Reset value when column changes, but fetch values immediately
- if (fieldValue && !filterValuesCache[fieldValue] && !loadingColumns.has(fieldValue)) {
+ if (
+ fieldValue &&
+ !filterValuesCache[fieldValue] &&
+ !loadingColumns.has(fieldValue)
+ ) {
fetchFilterValues(fieldValue)
}
return { ...row, column: fieldValue, value: '' }
@@ -227,7 +287,9 @@ const SearchFilters = ({ showModal, setShowModal, tnMapping, filters, type }: Se
}
const clearAllFilters = () => {
- setFilterRows([{ id: crypto.randomUUID(), column: '', operator: 'is', value: '' }])
+ setFilterRows([
+ { id: crypto.randomUUID(), column: '', operator: 'is', value: '' },
+ ])
}
const onSubmit = () => {
@@ -312,7 +374,12 @@ const SearchFilters = ({ showModal, setShowModal, tnMapping, filters, type }: Se
})
})
- const newUrlParams = getFiltersUrlParams(filters, validFilters, true, searchParams)
+ const newUrlParams = getFiltersUrlParams(
+ filters,
+ validFilters,
+ true,
+ searchParams,
+ )
navigate({ search: newUrlParams.toString() })
closeModal()
}
@@ -339,14 +406,22 @@ const SearchFilters = ({ showModal, setShowModal, tnMapping, filters, type }: Se
{filterRows.map((row) => (
<div key={row.id} className='flex items-center gap-2'>
{/* Column Select */}
- <Listbox value={row.column} onChange={(value) => updateFilterRow(row.id, 'column', value)}>
+ <Listbox
+ value={row.column}
+ onChange={(value) => updateFilterRow(row.id, 'column', value)}
+ >
{({ open }) => (
<div className='relative w-44'>
<ListboxButton className='relative w-full rounded-md border border-gray-300 bg-white py-2 pr-8 pl-3 text-left text-sm transition-colors hover:bg-gray-50 focus:ring-2 focus:ring-indigo-500 focus:ring-offset-1 focus:outline-hidden dark:border-gray-700 dark:bg-slate-800 dark:text-gray-50 dark:hover:bg-slate-700'>
- <span className={cx('flex items-center gap-2 truncate', { 'text-gray-400': !row.column })}>
+ <span
+ className={cx('flex items-center gap-2 truncate', {
+ 'text-gray-400': !row.column,
+ })}
+ >
{row.column ? filterCategoryIcons[row.column] : null}
{row.column
- ? tnMapping[row.column] || t(`project.mapping.${row.column}`)
+ ? tnMapping[row.column] ||
+ t(`project.mapping.${row.column}`)
: t('project.selectColumn')}
</span>
<span className='pointer-events-none absolute inset-y-0 right-0 flex items-center pr-2'>
@@ -372,19 +447,27 @@ const SearchFilters = ({ showModal, setShowModal, tnMapping, filters, type }: Se
key={option}
value={option}
className={({ focus }) =>
- cx('relative cursor-pointer py-2 pr-4 pl-3 select-none', {
- 'bg-gray-100 dark:bg-slate-700': focus,
- 'text-gray-700 dark:text-gray-50': !focus,
- })
+ cx(
+ 'relative cursor-pointer py-2 pr-4 pl-3 select-none',
+ {
+ 'bg-gray-100 dark:bg-slate-700': focus,
+ 'text-gray-700 dark:text-gray-50': !focus,
+ },
+ )
}
>
{({ selected }) => (
- <span className={cx('flex items-center gap-2', { 'font-medium': selected })}>
+ <span
+ className={cx('flex items-center gap-2', {
+ 'font-medium': selected,
+ })}
+ >
<span className='shrink-0 text-gray-500 dark:text-gray-400'>
{filterCategoryIcons[option]}
</span>
<span className='truncate'>
- {tnMapping[option] || t(`project.mapping.${option}`)}
+ {tnMapping[option] ||
+ t(`project.mapping.${option}`)}
</span>
{selected ? (
<CheckIcon className='ml-auto h-4 w-4 shrink-0 text-indigo-600 dark:text-indigo-400' />
@@ -400,12 +483,20 @@ const SearchFilters = ({ showModal, setShowModal, tnMapping, filters, type }: Se
</Listbox>
{/* Operator Select */}
- <Listbox value={row.operator} onChange={(value) => updateFilterRow(row.id, 'operator', value)}>
+ <Listbox
+ value={row.operator}
+ onChange={(value) =>
+ updateFilterRow(row.id, 'operator', value)
+ }
+ >
{({ open }) => (
<div className='relative w-32'>
<ListboxButton className='relative w-full rounded-md border border-gray-300 bg-white py-2 pr-8 pl-3 text-left text-sm transition-colors hover:bg-gray-50 focus:ring-2 focus:ring-indigo-500 focus:ring-offset-1 focus:outline-hidden dark:border-gray-700 dark:bg-slate-800 dark:text-gray-50 dark:hover:bg-slate-700'>
<span className='block truncate'>
- {t(OPERATORS.find((o) => o.value === row.operator)?.labelKey || '')}
+ {t(
+ OPERATORS.find((o) => o.value === row.operator)
+ ?.labelKey || '',
+ )}
</span>
<span className='pointer-events-none absolute inset-y-0 right-0 flex items-center pr-2'>
<ChevronsUpDownIcon className='h-4 w-4 text-gray-400' />
@@ -430,15 +521,22 @@ const SearchFilters = ({ showModal, setShowModal, tnMapping, filters, type }: Se
key={op.value}
value={op.value}
className={({ focus }) =>
- cx('relative cursor-pointer py-2 pr-4 pl-8 select-none', {
- 'bg-gray-100 dark:bg-slate-700': focus,
- 'text-gray-700 dark:text-gray-50': !focus,
- })
+ cx(
+ 'relative cursor-pointer py-2 pr-4 pl-8 select-none',
+ {
+ 'bg-gray-100 dark:bg-slate-700': focus,
+ 'text-gray-700 dark:text-gray-50': !focus,
+ },
+ )
}
>
{({ selected }) => (
<>
- <span className={cx('block truncate', { 'font-medium': selected })}>
+ <span
+ className={cx('block truncate', {
+ 'font-medium': selected,
+ })}
+ >
{t(op.labelKey)}
</span>
{selected ? (
@@ -514,7 +612,8 @@ const SearchFilters = ({ showModal, setShowModal, tnMapping, filters, type }: Se
{filters.map(({ column, filter, isExclusive, isContains }) => {
let displayFilter = filter
if (column === 'cc') {
- displayFilter = countries.getName(filter, language) || filter
+ displayFilter =
+ countries.getName(filter, language) || filter
}
const operatorLabel = isContains
? isExclusive
@@ -534,10 +633,14 @@ const SearchFilters = ({ showModal, setShowModal, tnMapping, filters, type }: Se
</span>
<span
className={cx({
- 'text-green-600 dark:text-green-400': !isExclusive && !isContains,
- 'text-red-600 dark:text-red-400': isExclusive && !isContains,
- 'text-yellow-600 dark:text-yellow-400': !isExclusive && isContains,
- 'text-orange-600 dark:text-orange-400': isExclusive && isContains,
+ 'text-green-600 dark:text-green-400':
+ !isExclusive && !isContains,
+ 'text-red-600 dark:text-red-400':
+ isExclusive && !isContains,
+ 'text-yellow-600 dark:text-yellow-400':
+ !isExclusive && isContains,
+ 'text-orange-600 dark:text-orange-400':
+ isExclusive && isContains,
})}
>
{operatorLabel}
diff --git a/web/app/pages/Project/View/components/TBPeriodSelector.tsx b/web/app/pages/Project/View/components/TBPeriodSelector.tsx
index 18b4b880f..1686600ec 100644
--- a/web/app/pages/Project/View/components/TBPeriodSelector.tsx
+++ b/web/app/pages/Project/View/components/TBPeriodSelector.tsx
@@ -1,4 +1,9 @@
-import { Popover, PopoverButton, PopoverPanel, Transition } from '@headlessui/react'
+import {
+ Popover,
+ PopoverButton,
+ PopoverPanel,
+ Transition,
+} from '@headlessui/react'
import { ChevronDownIcon } from '@heroicons/react/20/solid'
import cx from 'clsx'
import _includes from 'lodash/includes'
@@ -7,7 +12,11 @@ import { CalendarIcon } from 'lucide-react'
import React, { memo, Fragment, useMemo } from 'react'
import { useTranslation } from 'react-i18next'
-import { TBPeriodPairsProps, TimeBucket, VALID_TIME_BUCKETS } from '~/lib/constants'
+import {
+ TBPeriodPairsProps,
+ TimeBucket,
+ VALID_TIME_BUCKETS,
+} from '~/lib/constants'
import { PERIOD_HOTKEYS_MAP } from '~/modals/ViewProjectHotkeys'
import { Badge } from '~/ui/Badge'
@@ -19,7 +28,10 @@ interface TBPeriodSelectorProps {
title: string | number | React.ReactNode
items: TBPeriodPairsProps[]
/* (function): A function that is called when an item is selected. */
- onSelect: (item: TBPeriodPairsProps, e?: React.MouseEvent<HTMLElement>) => void | null
+ onSelect: (
+ item: TBPeriodPairsProps,
+ e?: React.MouseEvent<HTMLElement>,
+ ) => void | null
activePeriod?: TBPeriodPairsProps
classes?: {
timeBucket?: string
@@ -27,7 +39,13 @@ interface TBPeriodSelectorProps {
}
}
-const TBPeriodSelector = ({ items, title, onSelect, activePeriod, classes }: TBPeriodSelectorProps) => {
+const TBPeriodSelector = ({
+ items,
+ title,
+ onSelect,
+ activePeriod,
+ classes,
+}: TBPeriodSelectorProps) => {
const { dataLoading, updateTimebucket, timeBucket } = useViewProjectContext()
const { t } = useTranslation('common')
@@ -93,7 +111,8 @@ const TBPeriodSelector = ({ items, title, onSelect, activePeriod, classes }: TBP
timeBucket === value,
'text-gray-800 hover:bg-gray-300 dark:text-gray-200 dark:hover:bg-slate-800':
available && timeBucket !== value,
- 'text-gray-400 dark:text-gray-500': !available && timeBucket !== value,
+ 'text-gray-400 dark:text-gray-500':
+ !available && timeBucket !== value,
'cursor-pointer': available && !dataLoading,
'cursor-wait': available && dataLoading,
'cursor-not-allowed': !available,
@@ -109,7 +128,9 @@ const TBPeriodSelector = ({ items, title, onSelect, activePeriod, classes }: TBP
<PopoverButton
as='li'
key={item.label}
- onClick={(e: React.MouseEvent<HTMLElement>) => onSelect(item, e)}
+ onClick={(e: React.MouseEvent<HTMLElement>) =>
+ onSelect(item, e)
+ }
className={cx(
'flex cursor-pointer items-center justify-between space-x-1 rounded-md p-2 text-sm text-gray-700 transition-colors hover:bg-gray-200 dark:text-gray-50 dark:hover:bg-slate-700',
{
@@ -118,7 +139,10 @@ const TBPeriodSelector = ({ items, title, onSelect, activePeriod, classes }: TBP
)}
>
<span>{item.dropdownLabel || item.label}</span>
- <Badge colour='slate' label={PERIOD_HOTKEYS_MAP[item.period]} />
+ <Badge
+ colour='slate'
+ label={PERIOD_HOTKEYS_MAP[item.period]}
+ />
</PopoverButton>
))}
</ul>
diff --git a/web/app/pages/Project/View/components/WaitingForAnEvent.tsx b/web/app/pages/Project/View/components/WaitingForAnEvent.tsx
index a28332a53..4212a4c4b 100644
--- a/web/app/pages/Project/View/components/WaitingForAnEvent.tsx
+++ b/web/app/pages/Project/View/components/WaitingForAnEvent.tsx
@@ -21,7 +21,12 @@ const WaitingForAnEvent = () => {
<Text as='h3' size='xl' weight='medium' className='tracking-tight'>
{t('project.waiting.title')}
</Text>
- <Text as='p' size='sm' colour='secondary' className='mx-auto mt-2 max-w-md whitespace-pre-line'>
+ <Text
+ as='p'
+ size='sm'
+ colour='secondary'
+ className='mx-auto mt-2 max-w-md whitespace-pre-line'
+ >
<Trans
t={t}
i18nKey='project.waiting.desc'
@@ -35,7 +40,10 @@ const WaitingForAnEvent = () => {
/>
),
curl: (
- <Link to={routes.contact} className='font-medium text-indigo-600 hover:underline dark:text-indigo-400' />
+ <Link
+ to={routes.contact}
+ className='font-medium text-indigo-600 hover:underline dark:text-indigo-400'
+ />
),
snippet: (
<span
@@ -48,7 +56,10 @@ const WaitingForAnEvent = () => {
}}
/>
</Text>
- <TrackingSnippet isOpened={isModalOpened} onClose={() => setIsModalOpened(false)} />
+ <TrackingSnippet
+ isOpened={isModalOpened}
+ onClose={() => setIsModalOpened(false)}
+ />
</div>
)
}
diff --git a/web/app/pages/Project/View/utils/cache.ts b/web/app/pages/Project/View/utils/cache.ts
index cb7b4fd68..e847b0fff 100644
--- a/web/app/pages/Project/View/utils/cache.ts
+++ b/web/app/pages/Project/View/utils/cache.ts
@@ -1,4 +1,8 @@
-import { isBrowser, LS_PROJECTS_PROTECTED_KEY, LS_VIEW_PREFS_SETTING } from '~/lib/constants'
+import {
+ isBrowser,
+ LS_PROJECTS_PROTECTED_KEY,
+ LS_VIEW_PREFS_SETTING,
+} from '~/lib/constants'
import { type Project } from '~/lib/models/Project'
import { getItemJSON, removeItem, setItem } from '~/utils/localstorage'
@@ -22,12 +26,17 @@ const getAllProjectPreferences = (): Record<string, ProjectPreferences> => {
return {}
}
-export const getProjectPreferences = (id: Project['id']): ProjectPreferences => {
+export const getProjectPreferences = (
+ id: Project['id'],
+): ProjectPreferences => {
const preferences = getAllProjectPreferences()
return preferences?.[id] || {}
}
-export const setProjectPreferences = (id: Project['id'], preferences: ProjectPreferences) => {
+export const setProjectPreferences = (
+ id: Project['id'],
+ preferences: ProjectPreferences,
+) => {
setItem(
LS_VIEW_PREFS_SETTING,
JSON.stringify({
@@ -37,7 +46,8 @@ export const setProjectPreferences = (id: Project['id'], preferences: ProjectPre
)
}
-const getAllProjectPasswords = () => getItemJSON(LS_PROJECTS_PROTECTED_KEY) || {}
+const getAllProjectPasswords = () =>
+ getItemJSON(LS_PROJECTS_PROTECTED_KEY) || {}
export const setProjectPassword = (id: Project['id'], password: string) => {
setItem(
diff --git a/web/app/pages/Project/View/utils/filters.tsx b/web/app/pages/Project/View/utils/filters.tsx
index 6fe2a1869..3fd4a49b5 100644
--- a/web/app/pages/Project/View/utils/filters.tsx
+++ b/web/app/pages/Project/View/utils/filters.tsx
@@ -13,7 +13,12 @@ export const ERROR_FILTERS_MAPPING = {
showResolved: 'showResolved',
}
-export const FILTER_CHART_METRICS_MAPPING_FOR_COMPARE = ['bounce', 'viewsPerUnique', 'trendlines', 'customEvents']
+export const FILTER_CHART_METRICS_MAPPING_FOR_COMPARE = [
+ 'bounce',
+ 'viewsPerUnique',
+ 'trendlines',
+ 'customEvents',
+]
const validFilters = [
'host',
@@ -55,7 +60,10 @@ export const filterInvalidPreferences = (
(prev: string[], curr: string) => {
const { period, timeBucket } = prefs[curr]
- if (!_includes(VALID_PERIODS, period) || !_includes(VALID_TIME_BUCKETS, timeBucket)) {
+ if (
+ !_includes(VALID_PERIODS, period) ||
+ !_includes(VALID_TIME_BUCKETS, timeBucket)
+ ) {
return prev
}
@@ -79,7 +87,11 @@ export const filterInvalidPreferences = (
export const isFilterValid = (filter: string, checkDynamicFilters = false) => {
// normalise by removing operator prefixes from the URL key
let normalised = filter
- if (_startsWith(normalised, '!') || _startsWith(normalised, '~') || _startsWith(normalised, '^')) {
+ if (
+ _startsWith(normalised, '!') ||
+ _startsWith(normalised, '~') ||
+ _startsWith(normalised, '^')
+ ) {
normalised = normalised.substring(1)
}
@@ -87,7 +99,10 @@ export const isFilterValid = (filter: string, checkDynamicFilters = false) => {
return true
}
- if (checkDynamicFilters && _some(validDynamicFilters, (prefix) => _startsWith(normalised, prefix))) {
+ if (
+ checkDynamicFilters &&
+ _some(validDynamicFilters, (prefix) => _startsWith(normalised, prefix))
+ ) {
return true
}
diff --git a/web/app/pages/Project/tabs/Alerts/ProjectAlertsSettings.tsx b/web/app/pages/Project/tabs/Alerts/ProjectAlertsSettings.tsx
index 75f88581e..afab2aa16 100644
--- a/web/app/pages/Project/tabs/Alerts/ProjectAlertsSettings.tsx
+++ b/web/app/pages/Project/tabs/Alerts/ProjectAlertsSettings.tsx
@@ -1,4 +1,7 @@
-import { ExclamationTriangleIcon, XCircleIcon } from '@heroicons/react/24/outline'
+import {
+ ExclamationTriangleIcon,
+ XCircleIcon,
+} from '@heroicons/react/24/outline'
import _findKey from 'lodash/findKey'
import _isEmpty from 'lodash/isEmpty'
import _keys from 'lodash/keys'
@@ -77,7 +80,9 @@ const ProjectAlertsSettings = ({
}
return Boolean(
- (user.telegramChatId && user.isTelegramChatIdConfirmed) || user.slackWebhookUrl || user.discordWebhookUrl,
+ (user.telegramChatId && user.isTelegramChatIdConfirmed) ||
+ user.slackWebhookUrl ||
+ user.discordWebhookUrl,
)
}, [user])
@@ -123,7 +128,10 @@ const ProjectAlertsSettings = ({
if (alertId && isSettings) {
setIsLoading(true)
- fetcher.submit({ intent: 'get-alert', alertId }, { method: 'POST', action: `/projects/${projectId}` })
+ fetcher.submit(
+ { intent: 'get-alert', alertId },
+ { method: 'POST', action: `/projects/${projectId}` },
+ )
} else {
setIsLoading(false)
}
@@ -205,7 +213,10 @@ const ProjectAlertsSettings = ({
}, [form.queryMetric])
useEffect(() => {
- if (form.queryMetric === QUERY_METRIC.CUSTOM_EVENTS && form.alertOnEveryCustomEvent) {
+ if (
+ form.queryMetric === QUERY_METRIC.CUSTOM_EVENTS &&
+ form.alertOnEveryCustomEvent
+ ) {
setForm((prevForm) => ({
...prevForm,
queryCondition: undefined,
@@ -222,15 +233,24 @@ const ProjectAlertsSettings = ({
allErrors.name = t('alert.noNameError')
}
- if (form.queryMetric === QUERY_METRIC.CUSTOM_EVENTS && _isEmpty(form.queryCustomEvent)) {
+ if (
+ form.queryMetric === QUERY_METRIC.CUSTOM_EVENTS &&
+ _isEmpty(form.queryCustomEvent)
+ ) {
allErrors.queryCustomEvent = t('alert.noCustomEventError')
}
if (
form.queryMetric !== QUERY_METRIC.ERRORS &&
- !(form.queryMetric === QUERY_METRIC.CUSTOM_EVENTS && form.alertOnEveryCustomEvent)
+ !(
+ form.queryMetric === QUERY_METRIC.CUSTOM_EVENTS &&
+ form.alertOnEveryCustomEvent
+ )
) {
- if (form.queryValue === undefined || Number.isNaN(_toNumber(form.queryValue))) {
+ if (
+ form.queryValue === undefined ||
+ Number.isNaN(_toNumber(form.queryValue))
+ ) {
allErrors.queryValue = t('alert.queryValueError')
}
}
@@ -244,12 +264,18 @@ const ProjectAlertsSettings = ({
const shouldIncludeQueryFields =
form.queryMetric !== QUERY_METRIC.ERRORS &&
- !(form.queryMetric === QUERY_METRIC.CUSTOM_EVENTS && form.alertOnEveryCustomEvent)
+ !(
+ form.queryMetric === QUERY_METRIC.CUSTOM_EVENTS &&
+ form.alertOnEveryCustomEvent
+ )
const onDeleteAlert = () => {
if (!alertId || fetcher.state !== 'idle') return
- fetcher.submit({ intent: 'delete-alert', alertId }, { method: 'POST', action: `/projects/${projectId}` })
+ fetcher.submit(
+ { intent: 'delete-alert', alertId },
+ { method: 'POST', action: `/projects/${projectId}` },
+ )
}
useEffect(() => {
@@ -294,7 +320,10 @@ const ProjectAlertsSettings = ({
<div className='px-4 py-16 sm:px-6 sm:py-24 md:grid md:place-items-center lg:px-8'>
<div className='mx-auto max-w-max'>
<main className='sm:flex'>
- <XCircleIcon className='h-12 w-12 text-red-400' aria-hidden='true' />
+ <XCircleIcon
+ className='h-12 w-12 text-red-400'
+ aria-hidden='true'
+ />
<div className='sm:ml-6'>
<div className='max-w-prose sm:border-l sm:border-gray-200 sm:pl-6'>
<h1 className='text-4xl font-extrabold text-gray-900 sm:text-5xl dark:text-gray-50'>
@@ -335,17 +364,41 @@ const ProjectAlertsSettings = ({
showRefreshButton={false}
showPeriodSelector={false}
leftContent={
- <Text as='h2' size='xl' weight='bold' className='wrap-break-word break-all'>
+ <Text
+ as='h2'
+ size='xl'
+ weight='bold'
+ className='wrap-break-word break-all'
+ >
{title}
</Text>
}
/>
- <fetcher.Form method='POST' action={`/projects/${projectId}`} className='w-full pb-4' onSubmit={handleSubmit}>
- <input type='hidden' name='intent' value={isSettings && alertId ? 'update-alert' : 'create-alert'} />
- {isSettings && alertId ? <input type='hidden' name='alertId' value={alertId} /> : null}
- <input type='hidden' name='queryMetric' value={form.queryMetric || QUERY_METRIC.PAGE_VIEWS} />
+ <fetcher.Form
+ method='POST'
+ action={`/projects/${projectId}`}
+ className='w-full pb-4'
+ onSubmit={handleSubmit}
+ >
+ <input
+ type='hidden'
+ name='intent'
+ value={isSettings && alertId ? 'update-alert' : 'create-alert'}
+ />
+ {isSettings && alertId ? (
+ <input type='hidden' name='alertId' value={alertId} />
+ ) : null}
+ <input
+ type='hidden'
+ name='queryMetric'
+ value={form.queryMetric || QUERY_METRIC.PAGE_VIEWS}
+ />
{shouldIncludeQueryFields && form.queryCondition ? (
- <input type='hidden' name='queryCondition' value={form.queryCondition} />
+ <input
+ type='hidden'
+ name='queryCondition'
+ value={form.queryCondition}
+ />
) : null}
{shouldIncludeQueryFields && form.queryTime ? (
<input type='hidden' name='queryTime' value={form.queryTime} />
@@ -358,7 +411,12 @@ const ProjectAlertsSettings = ({
t={t}
i18nKey='alert.noIntegration'
components={{
- url: <Link to={INTEGRATIONS_LINK} className='text-blue-600 hover:underline dark:text-blue-500' />,
+ url: (
+ <Link
+ to={INTEGRATIONS_LINK}
+ className='text-blue-600 hover:underline dark:text-blue-500'
+ />
+ ),
}}
/>
</div>
@@ -392,9 +450,14 @@ const ProjectAlertsSettings = ({
id='queryMetric'
label={t('alert.metric')}
items={_values(queryMetricTMapping)}
- title={form.queryMetric ? queryMetricTMapping[form.queryMetric] : ''}
+ title={
+ form.queryMetric ? queryMetricTMapping[form.queryMetric] : ''
+ }
onSelect={(item) => {
- const key = _findKey(queryMetricTMapping, (predicate) => predicate === item)
+ const key = _findKey(
+ queryMetricTMapping,
+ (predicate) => predicate === item,
+ )
// @ts-expect-error
setForm((prevForm) => ({
@@ -403,7 +466,11 @@ const ProjectAlertsSettings = ({
}))
}}
capitalise
- selectedItem={form.queryMetric ? queryMetricTMapping[form.queryMetric] : undefined}
+ selectedItem={
+ form.queryMetric
+ ? queryMetricTMapping[form.queryMetric]
+ : undefined
+ }
/>
</div>
{form.queryMetric === QUERY_METRIC.CUSTOM_EVENTS ? (
@@ -452,16 +519,26 @@ const ProjectAlertsSettings = ({
/>
) : null}
{form.queryMetric !== QUERY_METRIC.ERRORS &&
- !(form.queryMetric === QUERY_METRIC.CUSTOM_EVENTS && form.alertOnEveryCustomEvent) ? (
+ !(
+ form.queryMetric === QUERY_METRIC.CUSTOM_EVENTS &&
+ form.alertOnEveryCustomEvent
+ ) ? (
<>
<div className='mt-4'>
<Select
id='queryCondition'
label={t('alert.condition')}
items={_values(queryConditionTMapping)}
- title={form.queryCondition ? queryConditionTMapping[form.queryCondition] : ''}
+ title={
+ form.queryCondition
+ ? queryConditionTMapping[form.queryCondition]
+ : ''
+ }
onSelect={(item) => {
- const key = _findKey(queryConditionTMapping, (predicate) => predicate === item)
+ const key = _findKey(
+ queryConditionTMapping,
+ (predicate) => predicate === item,
+ )
// @ts-expect-error
setForm((prevForm) => ({
@@ -470,7 +547,11 @@ const ProjectAlertsSettings = ({
}))
}}
capitalise
- selectedItem={form.queryCondition ? queryConditionTMapping[form.queryCondition] : undefined}
+ selectedItem={
+ form.queryCondition
+ ? queryConditionTMapping[form.queryCondition]
+ : undefined
+ }
/>
</div>
<Input
@@ -489,7 +570,10 @@ const ProjectAlertsSettings = ({
items={_values(queryTimeTMapping)}
title={form.queryTime ? queryTimeTMapping[form.queryTime] : ''}
onSelect={(item) => {
- const key = _findKey(queryTimeTMapping, (predicate) => predicate === item)
+ const key = _findKey(
+ queryTimeTMapping,
+ (predicate) => predicate === item,
+ )
// @ts-expect-error
setForm((prevForm) => ({
@@ -498,7 +582,9 @@ const ProjectAlertsSettings = ({
}))
}}
capitalise
- selectedItem={form.queryTime ? queryTimeTMapping[form.queryTime] : undefined}
+ selectedItem={
+ form.queryTime ? queryTimeTMapping[form.queryTime] : undefined
+ }
/>
</div>
</>
diff --git a/web/app/pages/Project/tabs/Alerts/ProjectAlertsView.tsx b/web/app/pages/Project/tabs/Alerts/ProjectAlertsView.tsx
index c825f3ceb..d258d7183 100644
--- a/web/app/pages/Project/tabs/Alerts/ProjectAlertsView.tsx
+++ b/web/app/pages/Project/tabs/Alerts/ProjectAlertsView.tsx
@@ -19,7 +19,13 @@ import {
} from 'lucide-react'
import { useMemo, useState, useEffect, useRef, Suspense, use } from 'react'
import { useTranslation } from 'react-i18next'
-import { Link, useSearchParams, useFetcher, useLoaderData, useRevalidator } from 'react-router'
+import {
+ Link,
+ useSearchParams,
+ useFetcher,
+ useLoaderData,
+ useRevalidator,
+} from 'react-router'
import { toast } from 'sonner'
import type { AlertsResponse } from '~/api/api.server'
@@ -28,7 +34,10 @@ import { Alerts } from '~/lib/models/Alerts'
import PaidFeature from '~/modals/PaidFeature'
import { useAuth } from '~/providers/AuthProvider'
import { useCurrentProject } from '~/providers/CurrentProjectProvider'
-import type { ProjectLoaderData, ProjectViewActionData } from '~/routes/projects.$id'
+import type {
+ ProjectLoaderData,
+ ProjectViewActionData,
+} from '~/routes/projects.$id'
import { Badge, type BadgeProps } from '~/ui/Badge'
import Button from '~/ui/Button'
import Loader from '~/ui/Loader'
@@ -46,8 +55,13 @@ const NoNotificationChannelSet = () => {
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'>
- <TriangleAlertIcon className='size-5 shrink-0 text-yellow-600 dark:text-yellow-500' strokeWidth={1.5} />
- <p className='flex-1 text-sm text-yellow-800 dark:text-yellow-200'>{t('alert.noNotificationChannel')}</p>
+ <TriangleAlertIcon
+ className='size-5 shrink-0 text-yellow-600 dark:text-yellow-500'
+ strokeWidth={1.5}
+ />
+ <p className='flex-1 text-sm text-yellow-800 dark:text-yellow-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'
@@ -58,7 +72,10 @@ const NoNotificationChannelSet = () => {
)
}
-const COLOUR_QUERY_METRIC_MAPPING: Record<(typeof QUERY_METRIC)[keyof typeof QUERY_METRIC], BadgeProps['colour']> = {
+const COLOUR_QUERY_METRIC_MAPPING: Record<
+ (typeof QUERY_METRIC)[keyof typeof QUERY_METRIC],
+ BadgeProps['colour']
+> = {
[QUERY_METRIC.PAGE_VIEWS]: 'yellow',
[QUERY_METRIC.UNIQUE_PAGE_VIEWS]: 'indigo',
[QUERY_METRIC.ONLINE_USERS]: 'sky',
@@ -70,10 +87,19 @@ const METRIC_ICON_MAPPING: Record<
(typeof QUERY_METRIC)[keyof typeof QUERY_METRIC],
{ icon: React.ElementType; className: string }
> = {
- [QUERY_METRIC.PAGE_VIEWS]: { icon: FileTextIcon, className: 'text-yellow-500' },
- [QUERY_METRIC.UNIQUE_PAGE_VIEWS]: { icon: EyeIcon, className: 'text-indigo-500' },
+ [QUERY_METRIC.PAGE_VIEWS]: {
+ icon: FileTextIcon,
+ className: 'text-yellow-500',
+ },
+ [QUERY_METRIC.UNIQUE_PAGE_VIEWS]: {
+ icon: EyeIcon,
+ className: 'text-indigo-500',
+ },
[QUERY_METRIC.ONLINE_USERS]: { icon: UsersIcon, className: 'text-sky-500' },
- [QUERY_METRIC.CUSTOM_EVENTS]: { icon: MousePointerClickIcon, className: 'text-green-500' },
+ [QUERY_METRIC.CUSTOM_EVENTS]: {
+ icon: MousePointerClickIcon,
+ className: 'text-green-500',
+ },
[QUERY_METRIC.ERRORS]: { icon: BugIcon, className: 'text-red-500' },
}
@@ -105,7 +131,8 @@ const AlertRow = ({
const [showDeleteModal, setShowDeleteModal] = useState(false)
const MetricIcon = METRIC_ICON_MAPPING[queryMetric]?.icon || FileTextIcon
- const metricIconClass = METRIC_ICON_MAPPING[queryMetric]?.className || 'text-gray-500'
+ const metricIconClass =
+ METRIC_ICON_MAPPING[queryMetric]?.className || 'text-gray-500'
const lastTriggeredText = lastTriggered
? language === 'en'
@@ -125,15 +152,29 @@ const AlertRow = ({
<div
className={cx(
'flex size-9 shrink-0 items-center justify-center rounded-lg',
- active ? 'bg-gray-100 dark:bg-slate-700/50' : 'bg-gray-100/50 opacity-60 dark:bg-slate-700/30',
+ active
+ ? 'bg-gray-100 dark:bg-slate-700/50'
+ : 'bg-gray-100/50 opacity-60 dark:bg-slate-700/30',
)}
>
- <MetricIcon className={cx('size-4', metricIconClass, !active && 'opacity-50')} strokeWidth={1.5} />
+ <MetricIcon
+ className={cx(
+ 'size-4',
+ metricIconClass,
+ !active && 'opacity-50',
+ )}
+ strokeWidth={1.5}
+ />
</div>
<div className='min-w-0 flex-1'>
<div className='flex items-center gap-2'>
- <Text as='span' weight='semibold' truncate className={cx(!active && 'opacity-60')}>
+ <Text
+ as='span'
+ weight='semibold'
+ truncate
+ className={cx(!active && 'opacity-60')}
+ >
{name}
</Text>
{!active ? (
@@ -151,7 +192,9 @@ const AlertRow = ({
/>
{/* Mobile: Show last triggered */}
<Text as='span' size='xs' colour='muted' className='sm:hidden'>
- {lastTriggeredText ? `• ${lastTriggeredText}` : `• ${t('alert.never')}`}
+ {lastTriggeredText
+ ? `• ${lastTriggeredText}`
+ : `• ${t('alert.never')}`}
</Text>
</div>
</div>
@@ -164,7 +207,11 @@ const AlertRow = ({
<Text as='p' size='xs' colour='muted'>
{t('alert.lastTriggered')}
</Text>
- <Text as='p' size='sm' colour={lastTriggeredText ? 'primary' : 'muted'}>
+ <Text
+ as='p'
+ size='sm'
+ colour={lastTriggeredText ? 'primary' : 'muted'}
+ >
{lastTriggeredText || t('alert.never')}
</Text>
</div>
@@ -216,7 +263,11 @@ interface DeferredAlertsData {
alertsData: AlertsResponse | null
}
-function AlertsDataResolver({ children }: { children: (data: DeferredAlertsData) => React.ReactNode }) {
+function AlertsDataResolver({
+ children,
+}: {
+ children: (data: DeferredAlertsData) => React.ReactNode
+}) {
const { alertsData: alertsDataPromise } = useLoaderData<ProjectLoaderData>()
const alertsData = alertsDataPromise ? use(alertsDataPromise) : null
return <>{children({ alertsData })}</>
@@ -225,7 +276,9 @@ function AlertsDataResolver({ children }: { children: (data: DeferredAlertsData)
function ProjectAlertsWrapper() {
return (
<Suspense fallback={<Loader />}>
- <AlertsDataResolver>{(deferredData) => <ProjectAlertsInner deferredData={deferredData} />}</AlertsDataResolver>
+ <AlertsDataResolver>
+ {(deferredData) => <ProjectAlertsInner deferredData={deferredData} />}
+ </AlertsDataResolver>
</Suspense>
)
}
@@ -247,7 +300,9 @@ const ProjectAlertsInner = ({ deferredData }: ProjectAlertsInnerProps) => {
// Track if we're in pagination mode
const [isSearchMode, setIsSearchMode] = useState(false)
const [total, setTotal] = useState(() => deferredData.alertsData?.total || 0)
- const [alerts, setAlerts] = useState<Alerts[]>(() => deferredData.alertsData?.results || [])
+ const [alerts, setAlerts] = useState<Alerts[]>(
+ () => deferredData.alertsData?.results || [],
+ )
const [page, setPage] = useState(1)
const [error, setError] = useState<string | null>(null)
@@ -276,7 +331,11 @@ const ProjectAlertsInner = ({ deferredData }: ProjectAlertsInnerProps) => {
// Sync state when loader provides new data
useEffect(() => {
- if (deferredData.alertsData && revalidator.state === 'idle' && !isSearchMode) {
+ if (
+ deferredData.alertsData &&
+ revalidator.state === 'idle' &&
+ !isSearchMode
+ ) {
setAlerts(deferredData.alertsData.results || [])
setTotal(deferredData.alertsData.total || 0)
}
@@ -348,7 +407,9 @@ const ProjectAlertsInner = ({ deferredData }: ProjectAlertsInnerProps) => {
}
return Boolean(
- (user.telegramChatId && user.isTelegramChatIdConfirmed) || user.slackWebhookUrl || user.discordWebhookUrl,
+ (user.telegramChatId && user.isTelegramChatIdConfirmed) ||
+ user.slackWebhookUrl ||
+ user.discordWebhookUrl,
)
}, [user])
@@ -390,7 +451,10 @@ const ProjectAlertsInner = ({ deferredData }: ProjectAlertsInnerProps) => {
const onDelete = (alertId: string) => {
if (fetcher.state !== 'idle') return
- fetcher.submit({ intent: 'delete-alert', alertId }, { method: 'POST', action: `/projects/${id}` })
+ fetcher.submit(
+ { intent: 'delete-alert', alertId },
+ { method: 'POST', action: `/projects/${id}` },
+ )
}
if (!canManageAlerts) {
@@ -400,7 +464,9 @@ const ProjectAlertsInner = ({ deferredData }: ProjectAlertsInnerProps) => {
<BellRingIcon className='mr-2 h-8 w-8' strokeWidth={1.5} />
<p className='text-3xl font-bold'>{t('dashboard.alerts')}</p>
</div>
- <p className='mt-2 text-sm whitespace-pre-wrap text-gray-100'>{t('dashboard.alertsDesc')}</p>
+ <p className='mt-2 text-sm whitespace-pre-wrap text-gray-100'>
+ {t('dashboard.alertsDesc')}
+ </p>
<Link
to={routes.signup}
className='mt-6 block max-w-max rounded-md border border-transparent bg-white px-3 py-2 text-sm font-medium text-slate-900 hover:bg-indigo-50 md:px-4'
@@ -419,7 +485,11 @@ const ProjectAlertsInner = ({ deferredData }: ProjectAlertsInnerProps) => {
title={t('apiNotifications.somethingWentWrong')}
description={t('apiNotifications.errorCode', { error })}
actions={[
- { label: t('dashboard.reloadPage'), onClick: () => window.location.reload(), primary: true },
+ {
+ label: t('dashboard.reloadPage'),
+ onClick: () => window.location.reload(),
+ primary: true,
+ },
{ label: t('notFoundPage.support'), to: routes.contact },
]}
/>
@@ -450,7 +520,9 @@ const ProjectAlertsInner = ({ deferredData }: ProjectAlertsInnerProps) => {
<BellRingIcon className='mr-2 h-8 w-8' strokeWidth={1.5} />
<p className='text-3xl font-bold'>{t('dashboard.alerts')}</p>
</div>
- <p className='mt-2 text-sm whitespace-pre-wrap text-gray-100'>{t('dashboard.alertsDesc')}</p>
+ <p className='mt-2 text-sm whitespace-pre-wrap text-gray-100'>
+ {t('dashboard.alertsDesc')}
+ </p>
<Button
onClick={handleNewAlert}
className='mt-6 block max-w-max rounded-md border border-transparent bg-white px-3 py-2 text-sm font-medium text-gray-700 hover:bg-indigo-50 md:px-4'
@@ -500,7 +572,10 @@ const ProjectAlertsInner = ({ deferredData }: ProjectAlertsInnerProps) => {
/>
) : null}
</div>
- <PaidFeature isOpened={isPaidFeatureOpened} onClose={() => setIsPaidFeatureOpened(false)} />
+ <PaidFeature
+ isOpened={isPaidFeatureOpened}
+ onClose={() => setIsPaidFeatureOpened(false)}
+ />
</>
)
}
diff --git a/web/app/pages/Project/tabs/AskAI/AIChart.tsx b/web/app/pages/Project/tabs/AskAI/AIChart.tsx
index e5121d880..226c19eb2 100644
--- a/web/app/pages/Project/tabs/AskAI/AIChart.tsx
+++ b/web/app/pages/Project/tabs/AskAI/AIChart.tsx
@@ -36,8 +36,13 @@ const CHART_COLORS = [
'#db2777', // pink-600
]
-const calculateOptimalTicks = (data: number[], targetCount: number = 6): number[] => {
- const validData = data.filter((n) => n !== undefined && n !== null && Number.isFinite(n))
+const calculateOptimalTicks = (
+ data: number[],
+ targetCount: number = 6,
+): number[] => {
+ const validData = data.filter(
+ (n) => n !== undefined && n !== null && Number.isFinite(n),
+ )
if (validData.length === 0) {
return [0, 1]
@@ -108,14 +113,21 @@ const AIChart: React.FC<AIChartProps> = ({ chart }) => {
const isPieDonut = isPieOrDonutChart(chart.chartType)
if (isPieDonut) {
- if (_isEmpty(chart.data) || _isEmpty(chart.data.labels) || _isEmpty(chart.data.values)) {
+ if (
+ _isEmpty(chart.data) ||
+ _isEmpty(chart.data.labels) ||
+ _isEmpty(chart.data.values)
+ ) {
return {}
}
const labels = chart.data.labels as string[]
const values = chart.data.values as number[]
- const columns: any[] = labels.map((label, idx) => [label, values[idx] || 0])
+ const columns: any[] = labels.map((label, idx) => [
+ label,
+ values[idx] || 0,
+ ])
const colors: Record<string, string> = {}
labels.forEach((label, idx) => {
@@ -133,7 +145,8 @@ const AIChart: React.FC<AIChartProps> = ({ chart }) => {
? {
title: '',
label: {
- format: (_value: number, ratio: number) => `${(ratio * 100).toFixed(1)}%`,
+ format: (_value: number, ratio: number) =>
+ `${(ratio * 100).toFixed(1)}%`,
},
}
: undefined,
@@ -141,7 +154,8 @@ const AIChart: React.FC<AIChartProps> = ({ chart }) => {
chart.chartType === 'pie'
? {
label: {
- format: (_value: number, ratio: number) => `${(ratio * 100).toFixed(1)}%`,
+ format: (_value: number, ratio: number) =>
+ `${(ratio * 100).toFixed(1)}%`,
},
}
: undefined,
@@ -159,8 +173,10 @@ const AIChart: React.FC<AIChartProps> = ({ chart }) => {
format: {
value: (value: number, ratio: number) => {
const percentage = (ratio * 100).toFixed(1)
- if (value >= 1000000) return `${(value / 1000000).toFixed(2)}M (${percentage}%)`
- if (value >= 1000) return `${(value / 1000).toFixed(2)}K (${percentage}%)`
+ if (value >= 1000000)
+ return `${(value / 1000000).toFixed(2)}M (${percentage}%)`
+ if (value >= 1000)
+ return `${(value / 1000).toFixed(2)}K (${percentage}%)`
return `${value.toLocaleString()} (${percentage}%)`
},
},
@@ -176,11 +192,22 @@ const AIChart: React.FC<AIChartProps> = ({ chart }) => {
}
const xData = chart.data.x as string[]
- const seriesKeys = _filter(_keys(chart.data), (key) => key !== 'x' && key !== 'labels' && key !== 'values')
-
- const columns: any[] = [['x', ..._map(xData, (el) => (dayjs(el).isValid() ? dayjs(el).toDate() : el))]]
-
- const types: Record<string, ReturnType<typeof line | typeof bar | typeof area | typeof spline>> = {}
+ const seriesKeys = _filter(
+ _keys(chart.data),
+ (key) => key !== 'x' && key !== 'labels' && key !== 'values',
+ )
+
+ const columns: any[] = [
+ [
+ 'x',
+ ..._map(xData, (el) => (dayjs(el).isValid() ? dayjs(el).toDate() : el)),
+ ],
+ ]
+
+ const types: Record<
+ string,
+ ReturnType<typeof line | typeof bar | typeof area | typeof spline>
+ > = {}
const colors: Record<string, string> = {}
seriesKeys.forEach((key, idx) => {
@@ -201,7 +228,8 @@ const AIChart: React.FC<AIChartProps> = ({ chart }) => {
}
})
- const optimalTicks = allYValues.length > 0 ? calculateOptimalTicks(allYValues) : undefined
+ const optimalTicks =
+ allYValues.length > 0 ? calculateOptimalTicks(allYValues) : undefined
const isDateAxis = xData.length > 0 && dayjs(xData[0]).isValid()
@@ -298,7 +326,11 @@ const AIChart: React.FC<AIChartProps> = ({ chart }) => {
const isPieDonut = isPieOrDonutChart(chart.chartType)
if (isPieDonut) {
- if (_isEmpty(chart.data) || _isEmpty(chart.data.labels) || _isEmpty(chart.data.values)) {
+ if (
+ _isEmpty(chart.data) ||
+ _isEmpty(chart.data.labels) ||
+ _isEmpty(chart.data.values)
+ ) {
return null
}
} else {
@@ -310,7 +342,9 @@ const AIChart: React.FC<AIChartProps> = ({ chart }) => {
return (
<div className='rounded-lg border border-gray-200 bg-white p-3 dark:border-slate-600 dark:bg-slate-800'>
{chart.title ? (
- <h4 className='mb-2 text-sm font-medium text-gray-700 dark:text-gray-300'>{chart.title}</h4>
+ <h4 className='mb-2 text-sm font-medium text-gray-700 dark:text-gray-300'>
+ {chart.title}
+ </h4>
) : null}
<div className={isPieDonut ? 'h-[280px] w-full' : 'h-[200px] w-full'}>
<BillboardChart options={chartOptions} className='h-full w-full' />
diff --git a/web/app/pages/Project/tabs/AskAI/AskAIView.tsx b/web/app/pages/Project/tabs/AskAI/AskAIView.tsx
index 5c8463075..24b2742c6 100644
--- a/web/app/pages/Project/tabs/AskAI/AskAIView.tsx
+++ b/web/app/pages/Project/tabs/AskAI/AskAIView.tsx
@@ -142,19 +142,43 @@ const getToolInfo = (
toolName: string,
t: any,
): { label: string; icon: React.ComponentType<{ className?: string }> } => {
- const toolMap: Record<string, { label: string; icon: React.ComponentType<{ className?: string }> }> = {
- getProjectInfo: { label: t('project.askAi.tools.getProjectInfo'), icon: InfoIcon },
+ const toolMap: Record<
+ string,
+ { label: string; icon: React.ComponentType<{ className?: string }> }
+ > = {
+ getProjectInfo: {
+ label: t('project.askAi.tools.getProjectInfo'),
+ icon: InfoIcon,
+ },
getData: { label: t('project.askAi.tools.getData'), icon: BarChart3Icon },
- getGoalStats: { label: t('project.askAi.tools.getGoalStats'), icon: TargetIcon },
- getFunnelData: { label: t('project.askAi.tools.getFunnelData'), icon: GitBranchIcon },
+ getGoalStats: {
+ label: t('project.askAi.tools.getGoalStats'),
+ icon: TargetIcon,
+ },
+ getFunnelData: {
+ label: t('project.askAi.tools.getFunnelData'),
+ icon: GitBranchIcon,
+ },
}
return toolMap[toolName] || { label: toolName, icon: InfoIcon }
}
const getAvailableTools = (t: any) => [
- { id: 'getData', label: t('project.askAi.tools.queryData'), icon: BarChart3Icon },
- { id: 'getGoalStats', label: t('project.askAi.tools.goalStats'), icon: TargetIcon },
- { id: 'getFunnelData', label: t('project.askAi.tools.funnelData'), icon: GitBranchIcon },
+ {
+ id: 'getData',
+ label: t('project.askAi.tools.queryData'),
+ icon: BarChart3Icon,
+ },
+ {
+ id: 'getGoalStats',
+ label: t('project.askAi.tools.goalStats'),
+ icon: TargetIcon,
+ },
+ {
+ id: 'getFunnelData',
+ label: t('project.askAi.tools.funnelData'),
+ icon: GitBranchIcon,
+ },
]
const ToolsTooltip = () => {
@@ -193,36 +217,48 @@ const AICapabilitiesTooltip = () => {
return (
<div className='max-w-sm space-y-3 py-1 text-left'>
<div>
- <p className='mb-1.5 font-semibold text-white'>{t('project.askAi.capabilities.title')}</p>
+ <p className='mb-1.5 font-semibold text-white'>
+ {t('project.askAi.capabilities.title')}
+ </p>
<ul className='space-y-1 text-gray-300'>
<li className='flex items-start gap-1.5'>
<BarChart3Icon className='mt-0.5 h-3.5 w-3.5 shrink-0 text-green-400' />
<span>
- <strong className='text-white'>{t('project.askAi.capabilities.queryAnalytics')}</strong>
+ <strong className='text-white'>
+ {t('project.askAi.capabilities.queryAnalytics')}
+ </strong>
</span>
</li>
<li className='flex items-start gap-1.5'>
<TargetIcon className='mt-0.5 h-3.5 w-3.5 shrink-0 text-green-400' />
<span>
- <strong className='text-white'>{t('project.askAi.capabilities.goalStatistics')}</strong>
+ <strong className='text-white'>
+ {t('project.askAi.capabilities.goalStatistics')}
+ </strong>
</span>
</li>
<li className='flex items-start gap-1.5'>
<GitBranchIcon className='mt-0.5 h-3.5 w-3.5 shrink-0 text-green-400' />
<span>
- <strong className='text-white'>{t('project.askAi.capabilities.funnelAnalysis')}</strong>
+ <strong className='text-white'>
+ {t('project.askAi.capabilities.funnelAnalysis')}
+ </strong>
</span>
</li>
<li className='flex items-start gap-1.5'>
<BarChart3Icon className='mt-0.5 h-3.5 w-3.5 shrink-0 text-green-400' />
<span>
- <strong className='text-white'>{t('project.askAi.capabilities.performanceMetrics')}</strong>
+ <strong className='text-white'>
+ {t('project.askAi.capabilities.performanceMetrics')}
+ </strong>
</span>
</li>
<li className='flex items-start gap-1.5'>
<AlertCircleIcon className='mt-0.5 h-3.5 w-3.5 shrink-0 text-green-400' />
<span>
- <strong className='text-white'>{t('project.askAi.capabilities.errorTracking')}</strong>
+ <strong className='text-white'>
+ {t('project.askAi.capabilities.errorTracking')}
+ </strong>
</span>
</li>
<li className='flex items-start gap-1.5'>
@@ -232,7 +268,9 @@ const AICapabilitiesTooltip = () => {
</ul>
</div>
<div>
- <p className='mb-1.5 font-semibold text-white'>{t('project.askAi.capabilities.cannotTitle')}</p>
+ <p className='mb-1.5 font-semibold text-white'>
+ {t('project.askAi.capabilities.cannotTitle')}
+ </p>
<ul className='space-y-1 text-gray-300'>
<li className='flex items-start gap-1.5'>
<XIcon className='mt-0.5 h-3.5 w-3.5 shrink-0 text-red-400' />
@@ -295,14 +333,22 @@ const ThoughtProcess = ({
{isActivelyThinking ? (
<Loader2Icon className='h-3 w-3 animate-spin' />
) : (
- <svg className='h-3 w-3' viewBox='0 0 24 24' fill='none' stroke='currentColor' strokeWidth='2.5'>
+ <svg
+ className='h-3 w-3'
+ viewBox='0 0 24 24'
+ fill='none'
+ stroke='currentColor'
+ strokeWidth='2.5'
+ >
<circle cx='12' cy='12' r='10' />
<path d='M12 16v-4M12 8h.01' />
</svg>
)}
</span>
<span className='font-medium'>
- {isActivelyThinking ? t('project.askAi.thinking') : t('project.askAi.thought')}
+ {isActivelyThinking
+ ? t('project.askAi.thinking')
+ : t('project.askAi.thought')}
</span>
{!isActivelyThinking ? (
isExpanded ? (
@@ -321,7 +367,13 @@ const ThoughtProcess = ({
)
}
-const ToolCallBadge = ({ toolName, isLoading = false }: { toolName: string; isLoading?: boolean }) => {
+const ToolCallBadge = ({
+ toolName,
+ isLoading = false,
+}: {
+ toolName: string
+ isLoading?: boolean
+}) => {
const { t } = useTranslation('common')
const { label, icon: Icon } = getToolInfo(toolName, t)
@@ -339,7 +391,13 @@ const ToolCallBadge = ({ toolName, isLoading = false }: { toolName: string; isLo
)
}
-const MessageContent = ({ content, isStreaming }: { content: string; isStreaming?: boolean }) => {
+const MessageContent = ({
+ content,
+ isStreaming,
+}: {
+ content: string
+ isStreaming?: boolean
+}) => {
const { text, charts } = useMemo(() => parseCharts(content), [content])
return (
@@ -350,7 +408,9 @@ const MessageContent = ({ content, isStreaming }: { content: string; isStreaming
dangerouslySetInnerHTML={{ __html: renderMarkdown(text) }}
/>
) : null}
- {isStreaming && !text ? <span className='ml-1 inline-block h-4 w-0.5 animate-pulse bg-gray-400' /> : null}
+ {isStreaming && !text ? (
+ <span className='ml-1 inline-block h-4 w-0.5 animate-pulse bg-gray-400' />
+ ) : null}
{!_isEmpty(charts) ? (
<div className='mt-4 space-y-4'>
{_map(charts, (chart, idx) => (
@@ -362,12 +422,20 @@ const MessageContent = ({ content, isStreaming }: { content: string; isStreaming
)
}
-const AssistantMessage = ({ message, isStreaming }: { message: Message; isStreaming?: boolean }) => {
+const AssistantMessage = ({
+ message,
+ isStreaming,
+}: {
+ message: Message
+ isStreaming?: boolean
+}) => {
const [userToggled, setUserToggled] = useState(false)
const [userExpandedState, setUserExpandedState] = useState(false)
const hasContent = Boolean(message.content && message.content.trim())
- const isActivelyThinking = Boolean(isStreaming && message.reasoning && !hasContent)
+ const isActivelyThinking = Boolean(
+ isStreaming && message.reasoning && !hasContent,
+ )
const isThoughtExpanded = userToggled ? userExpandedState : isActivelyThinking
const handleToggle = () => {
@@ -385,7 +453,9 @@ const AssistantMessage = ({ message, isStreaming }: { message: Message; isStream
const part = message.parts[partIndex]
if (part.type !== 'toolCall') return false
// Check if there's any text content after this tool call
- const hasTextAfter = message.parts.slice(partIndex + 1).some((p) => p.type === 'text' && p.text?.trim())
+ const hasTextAfter = message.parts
+ .slice(partIndex + 1)
+ .some((p) => p.type === 'text' && p.text?.trim())
return isLastPart || !hasTextAfter
}
@@ -405,17 +475,25 @@ const AssistantMessage = ({ message, isStreaming }: { message: Message; isStream
if (part.type === 'text' && part.text) {
const isLastTextPart =
idx === message.parts!.length - 1 ||
- !message.parts!.slice(idx + 1).some((p) => p.type === 'text' && p.text?.trim())
+ !message
+ .parts!.slice(idx + 1)
+ .some((p) => p.type === 'text' && p.text?.trim())
return (
<div key={idx} className='mb-3'>
- <MessageContent content={part.text} isStreaming={isStreaming ? isLastTextPart : undefined} />
+ <MessageContent
+ content={part.text}
+ isStreaming={isStreaming ? isLastTextPart : undefined}
+ />
</div>
)
}
if (part.type === 'toolCall' && part.toolName) {
return (
<div key={idx} className='mb-3'>
- <ToolCallBadge toolName={part.toolName} isLoading={isToolCallLoading(idx)} />
+ <ToolCallBadge
+ toolName={part.toolName}
+ isLoading={isToolCallLoading(idx)}
+ />
</div>
)
}
@@ -428,7 +506,11 @@ const AssistantMessage = ({ message, isStreaming }: { message: Message; isStream
{message.toolCalls && message.toolCalls.length > 0 ? (
<div className='mb-3 flex flex-wrap gap-2'>
{_map(message.toolCalls, (call, idx) => (
- <ToolCallBadge key={idx} toolName={call.toolName} isLoading={Boolean(isStreaming && !hasContent)} />
+ <ToolCallBadge
+ key={idx}
+ toolName={call.toolName}
+ isLoading={Boolean(isStreaming && !hasContent)}
+ />
))}
</div>
) : null}
@@ -449,7 +531,13 @@ const UserMessage = ({ content }: { content: string }) => {
)
}
-const ScrollToBottomButton = ({ isAtBottom, scrollToBottom }: { isAtBottom: boolean; scrollToBottom: () => void }) => {
+const ScrollToBottomButton = ({
+ isAtBottom,
+ scrollToBottom,
+}: {
+ isAtBottom: boolean
+ scrollToBottom: () => void
+}) => {
const { t } = useTranslation('common')
if (isAtBottom) return null
@@ -513,18 +601,22 @@ const AskAIView = ({ projectId }: AskAIViewProps) => {
const isLoadingChats = allChatsFetcher.state !== 'idle'
- const { scrollRef, contentRef, isAtBottom, scrollToBottom } = useStickToBottom({
- resize: 'smooth',
- initial: 'smooth',
- })
+ const { scrollRef, contentRef, isAtBottom, scrollToBottom } =
+ useStickToBottom({
+ resize: 'smooth',
+ initial: 'smooth',
+ })
const streamingContentRef = useRef('')
const streamingReasoningRef = useRef('')
- const streamingToolCallsRef = useRef<Array<{ toolName: string; args: unknown }>>([])
+ const streamingToolCallsRef = useRef<
+ Array<{ toolName: string; args: unknown }>
+ >([])
const streamingPartsRef = useRef<MessagePart[]>([])
const currentTextPartRef = useRef('')
- const generateMessageId = () => `msg-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`
+ const generateMessageId = () =>
+ `msg-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`
const loadRecentChats = useCallback(() => {
if (recentChatsFetcher.state !== 'idle') return
@@ -562,12 +654,17 @@ const AskAIView = ({ projectId }: AskAIViewProps) => {
)
// Handle all chats fetcher response
- const [pendingAllChatsSkip, setPendingAllChatsSkip] = useState<number | null>(null)
+ const [pendingAllChatsSkip, setPendingAllChatsSkip] = useState<number | null>(
+ null,
+ )
useEffect(() => {
if (allChatsFetcher.state === 'idle' && allChatsFetcher.data) {
if (allChatsFetcher.data.success && allChatsFetcher.data.data) {
- const result = allChatsFetcher.data.data as { chats: AIChatSummary[]; total: number }
+ const result = allChatsFetcher.data.data as {
+ chats: AIChatSummary[]
+ total: number
+ }
if (pendingAllChatsSkip === 0) {
setAllChats(result.chats)
} else {
@@ -627,7 +724,12 @@ const AskAIView = ({ projectId }: AskAIViewProps) => {
setSearchParams(newParams)
}
}
- }, [loadChatFetcher.state, loadChatFetcher.data, searchParams, setSearchParams])
+ }, [
+ loadChatFetcher.state,
+ loadChatFetcher.data,
+ searchParams,
+ setSearchParams,
+ ])
const loadChatById = useCallback(
(chatId: string) => {
@@ -656,7 +758,14 @@ const AskAIView = ({ projectId }: AskAIViewProps) => {
console.error('Failed to save chat:', saveChatFetcher.data.error)
}
}
- }, [saveChatFetcher.state, saveChatFetcher.data, currentChatId, searchParams, setSearchParams, loadRecentChats])
+ }, [
+ saveChatFetcher.state,
+ saveChatFetcher.data,
+ currentChatId,
+ searchParams,
+ setSearchParams,
+ loadRecentChats,
+ ])
const saveChat = useCallback(
(messagesToSave: Message[]) => {
@@ -765,7 +874,11 @@ const AskAIView = ({ projectId }: AskAIViewProps) => {
if (!input.trim() || isLoading) return
setError(null)
- const userMessage: Message = { id: generateMessageId(), role: 'user', content: input.trim() }
+ const userMessage: Message = {
+ id: generateMessageId(),
+ role: 'user',
+ content: input.trim(),
+ }
const newMessages = [...messages, userMessage]
setMessages(newMessages)
setInput('')
@@ -783,7 +896,10 @@ const AskAIView = ({ projectId }: AskAIViewProps) => {
try {
const timezone = Intl.DateTimeFormat().resolvedOptions().timeZone
- const messagesToSend = _filter(newMessages, (msg) => msg.content.trim().length > 0).map((msg) => ({
+ const messagesToSend = _filter(
+ newMessages,
+ (msg) => msg.content.trim().length > 0,
+ ).map((msg) => ({
role: msg.role,
content: msg.content,
}))
@@ -801,7 +917,10 @@ const AskAIView = ({ projectId }: AskAIViewProps) => {
// Build current parts for display: completed parts + current text being streamed
const displayParts = [...streamingPartsRef.current]
if (currentTextPartRef.current) {
- displayParts.push({ type: 'text', text: currentTextPartRef.current })
+ displayParts.push({
+ type: 'text',
+ text: currentTextPartRef.current,
+ })
}
setStreamingMessage({
@@ -819,7 +938,10 @@ const AskAIView = ({ projectId }: AskAIViewProps) => {
// Save current accumulated text as a part before adding tool call
if (currentTextPartRef.current.trim()) {
- streamingPartsRef.current.push({ type: 'text', text: currentTextPartRef.current })
+ streamingPartsRef.current.push({
+ type: 'text',
+ text: currentTextPartRef.current,
+ })
currentTextPartRef.current = ''
}
// Add tool call as a part
@@ -827,7 +949,11 @@ const AskAIView = ({ projectId }: AskAIViewProps) => {
setStreamingMessage((prev) =>
prev
- ? { ...prev, toolCalls: [...streamingToolCallsRef.current], parts: [...streamingPartsRef.current] }
+ ? {
+ ...prev,
+ toolCalls: [...streamingToolCallsRef.current],
+ parts: [...streamingPartsRef.current],
+ }
: {
id: generateMessageId(),
role: 'assistant',
@@ -856,10 +982,16 @@ const AskAIView = ({ projectId }: AskAIViewProps) => {
// Finalize parts: add any remaining text
if (currentTextPartRef.current.trim()) {
- streamingPartsRef.current.push({ type: 'text', text: currentTextPartRef.current })
+ streamingPartsRef.current.push({
+ type: 'text',
+ text: currentTextPartRef.current,
+ })
}
- if (finalContent.trim() || streamingToolCallsRef.current.length > 0) {
+ if (
+ finalContent.trim() ||
+ streamingToolCallsRef.current.length > 0
+ ) {
const assistantMessage: Message = {
id: generateMessageId(),
role: 'assistant',
@@ -905,7 +1037,10 @@ const AskAIView = ({ projectId }: AskAIViewProps) => {
// Finalize parts: add any remaining text
if (currentTextPartRef.current.trim()) {
- streamingPartsRef.current.push({ type: 'text', text: currentTextPartRef.current })
+ streamingPartsRef.current.push({
+ type: 'text',
+ text: currentTextPartRef.current,
+ })
}
if (finalContent.trim() || streamingToolCallsRef.current.length > 0) {
@@ -966,9 +1101,12 @@ const AskAIView = ({ projectId }: AskAIViewProps) => {
const diffDays = Math.floor(diffMs / 86400000)
if (diffMins < 1) return t('project.askAi.timeFormat.justNow')
- if (diffMins < 60) return t('project.askAi.timeFormat.minutes', { count: diffMins })
- if (diffHours < 24) return t('project.askAi.timeFormat.hours', { count: diffHours })
- if (diffDays < 7) return t('project.askAi.timeFormat.days', { count: diffDays })
+ if (diffMins < 60)
+ return t('project.askAi.timeFormat.minutes', { count: diffMins })
+ if (diffHours < 24)
+ return t('project.askAi.timeFormat.hours', { count: diffHours })
+ if (diffDays < 7)
+ return t('project.askAi.timeFormat.days', { count: diffDays })
return date.toLocaleDateString()
}
@@ -1002,7 +1140,9 @@ const AskAIView = ({ projectId }: AskAIViewProps) => {
<div className='mx-auto w-full max-w-3xl px-4 pt-4'>
<div className='flex items-center gap-2 rounded-lg border border-red-200 bg-red-50 px-4 py-3 dark:border-red-800 dark:bg-red-900/20'>
<AlertCircleIcon className='h-5 w-5 shrink-0 text-red-500' />
- <p className='flex-1 text-sm text-red-700 dark:text-red-400'>{error}</p>
+ <p className='flex-1 text-sm text-red-700 dark:text-red-400'>
+ {error}
+ </p>
<button
type='button'
onClick={() => setError(null)}
@@ -1029,7 +1169,13 @@ const AskAIView = ({ projectId }: AskAIViewProps) => {
<SwetrixLogo />
</div>
- <Text as='h1' size='2xl' weight='semibold' colour='primary' className='mb-2'>
+ <Text
+ as='h1'
+ size='2xl'
+ weight='semibold'
+ colour='primary'
+ className='mb-2'
+ >
{t('project.askAi.welcomeTitle')}
</Text>
<Text as='p' size='base' colour='muted' className='mb-10'>
@@ -1104,12 +1250,17 @@ const AskAIView = ({ projectId }: AskAIViewProps) => {
<ThinkingIndicator />
</div>
) : null}
- {streamingMessage ? <AssistantMessage message={streamingMessage} isStreaming /> : null}
+ {streamingMessage ? (
+ <AssistantMessage message={streamingMessage} isStreaming />
+ ) : null}
</div>
)}
</div>
</div>
- <ScrollToBottomButton isAtBottom={isAtBottom} scrollToBottom={scrollToBottom} />
+ <ScrollToBottomButton
+ isAtBottom={isAtBottom}
+ scrollToBottom={scrollToBottom}
+ />
</div>
{!isEmpty ? (
@@ -1160,7 +1311,9 @@ const AskAIView = ({ projectId }: AskAIViewProps) => {
</div>
</form>
</div>
- <p className='mt-2 text-center text-xs text-gray-400 dark:text-gray-500'>{t('project.askAi.disclaimer')}</p>
+ <p className='mt-2 text-center text-xs text-gray-400 dark:text-gray-500'>
+ {t('project.askAi.disclaimer')}
+ </p>
</div>
</div>
) : null}
@@ -1190,10 +1343,22 @@ const AskAIView = ({ projectId }: AskAIViewProps) => {
onClick={() => handleOpenChat(chat.id)}
className='group flex w-full items-center justify-between text-left transition-colors'
>
- <Text as='span' size='sm' weight='medium' truncate className='group-hover:underline'>
+ <Text
+ as='span'
+ size='sm'
+ weight='medium'
+ truncate
+ className='group-hover:underline'
+ >
{chat.name || t('project.askAi.newChat')}
</Text>
- <Text as='span' size='sm' weight='medium' colour='muted' className='ml-4 shrink-0'>
+ <Text
+ as='span'
+ size='sm'
+ weight='medium'
+ colour='muted'
+ className='ml-4 shrink-0'
+ >
{formatRelativeTime(chat.updated)}
</Text>
</button>
@@ -1210,7 +1375,9 @@ const AskAIView = ({ projectId }: AskAIViewProps) => {
message={
<div className='mt-2 max-h-96 overflow-y-auto'>
{_isEmpty(allChats) && !isLoadingChats ? (
- <p className='py-8 text-center text-gray-500 dark:text-gray-400'>{t('project.askAi.noChats')}</p>
+ <p className='py-8 text-center text-gray-500 dark:text-gray-400'>
+ {t('project.askAi.noChats')}
+ </p>
) : (
<div className='space-y-2'>
{_map(allChats, (chat) => (
@@ -1253,7 +1420,9 @@ const AskAIView = ({ projectId }: AskAIViewProps) => {
disabled={isLoadingChats}
className='flex w-full items-center justify-center gap-2 rounded-lg border border-gray-200 bg-white px-4 py-2 text-sm font-medium text-gray-700 transition-colors hover:bg-gray-50 disabled:opacity-50 dark:border-slate-800/50 dark:bg-slate-800 dark:text-gray-200 hover:dark:bg-slate-700'
>
- {isLoadingChats ? <Loader2Icon className='h-4 w-4 animate-spin' /> : null}
+ {isLoadingChats ? (
+ <Loader2Icon className='h-4 w-4 animate-spin' />
+ ) : null}
{t('project.askAi.loadMore')}
</button>
) : null}
diff --git a/web/app/pages/Project/tabs/Captcha/CaptchaChart.tsx b/web/app/pages/Project/tabs/Captcha/CaptchaChart.tsx
index 909242770..f4f5a3fdf 100644
--- a/web/app/pages/Project/tabs/Captcha/CaptchaChart.tsx
+++ b/web/app/pages/Project/tabs/Captcha/CaptchaChart.tsx
@@ -30,7 +30,13 @@ export const CaptchaChart = ({
if (!chart) {
return {} as ChartOptions
}
- return getSettingsCaptcha(chart, timeBucket, timeFormat, rotateXAxis, chartType)
+ return getSettingsCaptcha(
+ chart,
+ timeBucket,
+ timeFormat,
+ rotateXAxis,
+ chartType,
+ )
}, [chart, timeBucket, timeFormat, rotateXAxis, chartType])
const deps = useMemo(
diff --git a/web/app/pages/Project/tabs/Captcha/CaptchaView.tsx b/web/app/pages/Project/tabs/Captcha/CaptchaView.tsx
index ee210a93f..671c6e349 100644
--- a/web/app/pages/Project/tabs/Captcha/CaptchaView.tsx
+++ b/web/app/pages/Project/tabs/Captcha/CaptchaView.tsx
@@ -3,14 +3,24 @@ import cx from 'clsx'
import _isEmpty from 'lodash/isEmpty'
import _keys from 'lodash/keys'
import _map from 'lodash/map'
-import { CompassIcon, MapPinIcon, MonitorCog, TabletSmartphoneIcon } from 'lucide-react'
+import {
+ CompassIcon,
+ MapPinIcon,
+ MonitorCog,
+ TabletSmartphoneIcon,
+} from 'lucide-react'
import { useState, useEffect, useMemo, useContext, useRef } from 'react'
import { useTranslation } from 'react-i18next'
import { useSearchParams } from 'react-router'
import { useCaptchaProxy } from '~/hooks/useAnalyticsProxy'
import useSize from '~/hooks/useSize'
-import { chartTypes, BROWSER_LOGO_MAP, OS_LOGO_MAP, OS_LOGO_MAP_DARK } from '~/lib/constants'
+import {
+ chartTypes,
+ BROWSER_LOGO_MAP,
+ OS_LOGO_MAP,
+ OS_LOGO_MAP_DARK,
+} from '~/lib/constants'
import { useCurrentProject } from '~/providers/CurrentProjectProvider'
import { useTheme } from '~/providers/ThemeProvider'
import Loader from '~/ui/Loader'
@@ -22,7 +32,10 @@ import Filters from '../../View/components/Filters'
import { Filter } from '../../View/interfaces/traffic'
import { Panel } from '../../View/Panels'
import { parseFilters } from '../../View/utils/filters'
-import { ViewProjectContext, RefreshTriggersContext } from '../../View/ViewProject'
+import {
+ ViewProjectContext,
+ RefreshTriggersContext,
+} from '../../View/ViewProject'
import { deviceIconMapping } from '../../View/ViewProject.helpers'
import { CaptchaChart } from './CaptchaChart'
@@ -54,7 +67,8 @@ const CaptchaView = ({ projectId }: CaptchaViewProps) => {
const { theme } = useTheme()
const { project } = useCurrentProject()
const { captchaRefreshTrigger } = useContext(RefreshTriggersContext)
- const { period, timeBucket, dateRange, timeFormat, size } = useContext(ViewProjectContext)
+ const { period, timeBucket, dateRange, timeFormat, size } =
+ useContext(ViewProjectContext)
const [searchParams] = useSearchParams()
const isEmbedded = searchParams.get('embedded') === 'true'
const isMountedRef = useRef(true)
@@ -66,7 +80,10 @@ const CaptchaView = ({ projectId }: CaptchaViewProps) => {
} = useTranslation('common')
const [panelsData, setPanelsData] = useState<any>({})
- const [chartData, setChartData] = useState<{ x: string[]; results: number[] } | null>(null)
+ const [chartData, setChartData] = useState<{
+ x: string[]
+ results: number[]
+ } | null>(null)
const [isPanelsDataEmpty, setIsPanelsDataEmpty] = useState(false)
const [analyticsLoading, setAnalyticsLoading] = useState(true)
const [dataLoading, setDataLoading] = useState(false)
@@ -177,7 +194,10 @@ const CaptchaView = ({ projectId }: CaptchaViewProps) => {
}, [captchaRefreshTrigger])
const getFilterLink = (column: string, value: string | null) => {
- const isFilterActive = filters.findIndex((filter) => filter.column === column && filter.filter === value) >= 0
+ const isFilterActive =
+ filters.findIndex(
+ (filter) => filter.column === column && filter.filter === value,
+ ) >= 0
const newSearchParams = new URLSearchParams(searchParams.toString())
if (isFilterActive) {
@@ -247,7 +267,9 @@ const CaptchaView = ({ projectId }: CaptchaViewProps) => {
const rowMapper = (entry: any) => {
const { name: entryName, cc } = entry
if (cc) {
- return <CCRow cc={cc} name={entryName} language={language} />
+ return (
+ <CCRow cc={cc} name={entryName} language={language} />
+ )
}
return <CCRow cc={entryName} language={language} />
}
@@ -275,7 +297,9 @@ const CaptchaView = ({ projectId }: CaptchaViewProps) => {
getFilterLink={getFilterLink}
name={panelName}
data={panelsData.data[type]}
- rowMapper={(entry: { name: keyof typeof deviceIconMapping }) => {
+ rowMapper={(entry: {
+ name: keyof typeof deviceIconMapping
+ }) => {
const { name: entryName } = entry
const icon = deviceIconMapping[entryName]
if (!icon) {
@@ -339,7 +363,8 @@ const CaptchaView = ({ projectId }: CaptchaViewProps) => {
const logoUrlLight = OS_LOGO_MAP[entryName]
// @ts-expect-error
const logoUrlDark = OS_LOGO_MAP_DARK[entryName]
- let logoUrl = theme === 'dark' ? logoUrlDark : logoUrlLight
+ let logoUrl =
+ theme === 'dark' ? logoUrlDark : logoUrlLight
logoUrl ||= logoUrlLight
if (!logoUrl) {
@@ -354,7 +379,11 @@ const CaptchaView = ({ projectId }: CaptchaViewProps) => {
return (
<>
- <img src={logoUrl} className='h-5 w-5 dark:fill-gray-50' alt='' />
+ <img
+ src={logoUrl}
+ className='h-5 w-5 dark:fill-gray-50'
+ alt=''
+ />
&nbsp;
{entryName}
</>
diff --git a/web/app/pages/Project/tabs/Captcha/NoCaptchaEvents.tsx b/web/app/pages/Project/tabs/Captcha/NoCaptchaEvents.tsx
index 6b639a62f..bd5406977 100644
--- a/web/app/pages/Project/tabs/Captcha/NoCaptchaEvents.tsx
+++ b/web/app/pages/Project/tabs/Captcha/NoCaptchaEvents.tsx
@@ -33,8 +33,15 @@ const NoCaptchaEvents = ({ filters }: NoCaptchaEventsProps) => {
<Text as='h3' size='xl' weight='medium' className='tracking-tight'>
{t('project.noEvTitle')}
</Text>
- <Text as='p' size='sm' colour='secondary' className='mx-auto mt-2 max-w-md'>
- {hasFilters ? t('project.noEventsFiltersDesc') : t('project.noEvContent')}
+ <Text
+ as='p'
+ size='sm'
+ colour='secondary'
+ className='mx-auto mt-2 max-w-md'
+ >
+ {hasFilters
+ ? t('project.noEventsFiltersDesc')
+ : t('project.noEvContent')}
</Text>
</div>
</>
diff --git a/web/app/pages/Project/tabs/Captcha/WaitingForCaptchaEvent.tsx b/web/app/pages/Project/tabs/Captcha/WaitingForCaptchaEvent.tsx
index 5cb02fa8b..7d5a3fb5c 100644
--- a/web/app/pages/Project/tabs/Captcha/WaitingForCaptchaEvent.tsx
+++ b/web/app/pages/Project/tabs/Captcha/WaitingForCaptchaEvent.tsx
@@ -6,7 +6,8 @@ import { Text } from '~/ui/Text'
import routes from '~/utils/routes'
const TROUBLESHOOTING_URL = 'https://docs.swetrix.com/troubleshooting'
-const CAPTCHA_INTEGRATION_GUIDE_URL = 'https://docs.swetrix.com/captcha/client-side-usage'
+const CAPTCHA_INTEGRATION_GUIDE_URL =
+ 'https://docs.swetrix.com/captcha/client-side-usage'
const WaitingForCaptchaEvent = () => {
const { t } = useTranslation('common')
@@ -19,7 +20,12 @@ const WaitingForCaptchaEvent = () => {
<Text as='h3' size='xl' weight='medium' className='tracking-tight'>
{t('project.waitingCaptcha.title')}
</Text>
- <Text as='p' size='sm' colour='secondary' className='mx-auto mt-2 max-w-md whitespace-pre-line'>
+ <Text
+ as='p'
+ size='sm'
+ colour='secondary'
+ className='mx-auto mt-2 max-w-md whitespace-pre-line'
+ >
<Trans
t={t}
i18nKey='project.waitingCaptcha.desc'
@@ -41,7 +47,10 @@ const WaitingForCaptchaEvent = () => {
/>
),
curl: (
- <Link to={routes.contact} className='font-medium text-indigo-600 hover:underline dark:text-indigo-400' />
+ <Link
+ to={routes.contact}
+ className='font-medium text-indigo-600 hover:underline dark:text-indigo-400'
+ />
),
}}
/>
diff --git a/web/app/pages/Project/tabs/Errors/ErrorChart.tsx b/web/app/pages/Project/tabs/Errors/ErrorChart.tsx
index 9399a9a28..771105386 100644
--- a/web/app/pages/Project/tabs/Errors/ErrorChart.tsx
+++ b/web/app/pages/Project/tabs/Errors/ErrorChart.tsx
@@ -44,12 +44,44 @@ export const ErrorChart = ({
}, [customDataNames, t])
const options: ChartOptions = useMemo(() => {
- return getSettingsError(chart, timeBucket as string, timeFormat, rotateXAxis, chartType, annotations, dataNames)
- }, [chart, timeBucket, timeFormat, rotateXAxis, chartType, annotations, dataNames])
+ return getSettingsError(
+ chart,
+ timeBucket as string,
+ timeFormat,
+ rotateXAxis,
+ chartType,
+ annotations,
+ dataNames,
+ )
+ }, [
+ chart,
+ timeBucket,
+ timeFormat,
+ rotateXAxis,
+ chartType,
+ annotations,
+ dataNames,
+ ])
const deps = useMemo(
- () => [chart, timeBucket, timeFormat, rotateXAxis, chartType, dataNames, annotations],
- [chart, timeBucket, timeFormat, rotateXAxis, chartType, dataNames, annotations],
+ () => [
+ chart,
+ timeBucket,
+ timeFormat,
+ rotateXAxis,
+ chartType,
+ dataNames,
+ annotations,
+ ],
+ [
+ chart,
+ timeBucket,
+ timeFormat,
+ rotateXAxis,
+ chartType,
+ dataNames,
+ annotations,
+ ],
)
return (
diff --git a/web/app/pages/Project/tabs/Errors/ErrorDetails.tsx b/web/app/pages/Project/tabs/Errors/ErrorDetails.tsx
index b0d8149d6..ad3a2e076 100644
--- a/web/app/pages/Project/tabs/Errors/ErrorDetails.tsx
+++ b/web/app/pages/Project/tabs/Errors/ErrorDetails.tsx
@@ -1,13 +1,32 @@
-import { ChevronDownIcon, ChevronUpIcon, ClipboardIcon, CheckIcon } from '@heroicons/react/24/outline'
+import {
+ ChevronDownIcon,
+ ChevronUpIcon,
+ ClipboardIcon,
+ CheckIcon,
+} from '@heroicons/react/24/outline'
import _map from 'lodash/map'
-import { FileCodeIcon, CalendarIcon, HashIcon, ExternalLinkIcon, UsersIcon, ActivityIcon } from 'lucide-react'
+import {
+ FileCodeIcon,
+ CalendarIcon,
+ HashIcon,
+ ExternalLinkIcon,
+ UsersIcon,
+ ActivityIcon,
+} from 'lucide-react'
import { useMemo, useState, useEffect, useCallback, useRef } from 'react'
import { useTranslation } from 'react-i18next'
import { Link, useLocation } from 'react-router'
-import type { ErrorAffectedSession, ErrorDetailsResponse } from '~/api/api.server'
+import type {
+ ErrorAffectedSession,
+ ErrorDetailsResponse,
+} from '~/api/api.server'
import { useErrorSessionsProxy } from '~/hooks/useAnalyticsProxy'
-import { BROWSER_LOGO_MAP, OS_LOGO_MAP, OS_LOGO_MAP_DARK } from '~/lib/constants'
+import {
+ BROWSER_LOGO_MAP,
+ OS_LOGO_MAP,
+ OS_LOGO_MAP_DARK,
+} from '~/lib/constants'
import { useCurrentProject } from '~/providers/CurrentProjectProvider'
import { useTheme } from '~/providers/ThemeProvider'
import { Badge } from '~/ui/Badge'
@@ -28,9 +47,22 @@ interface ErrorDetailsProps {
projectPassword?: string
}
-const StatItem = ({ icon, label, value }: { icon: React.ReactNode; label: string; value: string | number }) => (
+const StatItem = ({
+ icon,
+ label,
+ value,
+}: {
+ icon: React.ReactNode
+ label: string
+ value: string | number
+}) => (
<div className='flex flex-col gap-2 rounded-lg border border-gray-200 bg-white p-4 dark:border-slate-800/60 dark:bg-slate-800/25'>
- <Text size='xs' weight='medium' colour='muted' className='flex items-center gap-1.5 tracking-wide uppercase'>
+ <Text
+ size='xs'
+ weight='medium'
+ colour='muted'
+ className='flex items-center gap-1.5 tracking-wide uppercase'
+ >
{icon}
{label}
</Text>
@@ -93,16 +125,30 @@ const SessionRow = ({ session }: SessionRowProps) => {
>
<div className='flex min-w-0 flex-1 items-start gap-3'>
<div className='flex shrink-0 items-center gap-2 pt-0.5'>
- {session.cc ? <Flag className='rounded-xs' country={session.cc} size={16} alt='' aria-hidden='true' /> : null}
+ {session.cc ? (
+ <Flag
+ className='rounded-xs'
+ country={session.cc}
+ size={16}
+ alt=''
+ aria-hidden='true'
+ />
+ ) : null}
<BrowserIcon browser={session.br} />
<OSIcon os={session.os} theme={theme} />
</div>
<div className='flex min-w-0 flex-col gap-0.5'>
- <Text size='xs' weight='medium' truncate className='text-gray-900 dark:text-gray-200'>
+ <Text
+ size='xs'
+ weight='medium'
+ truncate
+ className='text-gray-900 dark:text-gray-200'
+ >
{session.profileId || t('project.unknownUser')}
</Text>
<Text size='xs' colour='muted' truncate>
- {lastErrorAt} · {session.errorCount} {t('project.occurrences').toLowerCase()}
+ {lastErrorAt} · {session.errorCount}{' '}
+ {t('project.occurrences').toLowerCase()}
</Text>
</div>
</div>
@@ -156,15 +202,16 @@ export const ErrorDetails = ({
return getRelativeDateIfPossible(details.last_seen, language)
}, [details.last_seen, language])
- const status: { label: string; colour: 'red' | 'yellow' | 'slate' } = useMemo(() => {
- if (details.status === 'active') {
- return { label: t('error.status.active'), colour: 'red' }
- }
- if (details.status === 'regressed') {
- return { label: t('error.status.regressed'), colour: 'yellow' }
- }
- return { label: t('error.status.resolved'), colour: 'slate' }
- }, [details.status, t])
+ const status: { label: string; colour: 'red' | 'yellow' | 'slate' } =
+ useMemo(() => {
+ if (details.status === 'active') {
+ return { label: t('error.status.active'), colour: 'red' }
+ }
+ if (details.status === 'regressed') {
+ return { label: t('error.status.regressed'), colour: 'yellow' }
+ }
+ return { label: t('error.status.resolved'), colour: 'slate' }
+ }, [details.status, t])
const stackTraceLines = useMemo(
() => (details.stackTrace ? details.stackTrace.split('\n') : []),
@@ -178,7 +225,8 @@ export const ErrorDetails = ({
}, [details.filename, details.lineno, details.colno])
useEffect(() => {
- const shouldExpand = stackTraceLines.length > 0 && stackTraceLines.length <= 8
+ const shouldExpand =
+ stackTraceLines.length > 0 && stackTraceLines.length <= 8
setIsStackTraceExpanded(shouldExpand)
setIsCopiedStack(false)
setIsCopiedEid(false)
@@ -258,7 +306,17 @@ export const ErrorDetails = ({
}
}
},
- [id, details.eid, timeBucket, period, from, to, sessionsLoading, sessionsSkip, fetchErrorSessions],
+ [
+ id,
+ details.eid,
+ timeBucket,
+ period,
+ from,
+ to,
+ sessionsLoading,
+ sessionsSkip,
+ fetchErrorSessions,
+ ],
)
useEffect(() => {
@@ -277,11 +335,15 @@ export const ErrorDetails = ({
return (
<p>
<span className='text-slate-500 dark:text-slate-400'>{prefix}</span>
- <span className='font-medium text-slate-700 dark:text-slate-300'>{funcName}</span>
+ <span className='font-medium text-slate-700 dark:text-slate-300'>
+ {funcName}
+ </span>
{location ? (
<>
<span className='text-slate-600 dark:text-slate-400'> (</span>
- <span className='text-slate-800 dark:text-slate-300'>{location}</span>
+ <span className='text-slate-800 dark:text-slate-300'>
+ {location}
+ </span>
<span className='text-slate-600 dark:text-slate-400'>)</span>
</>
) : null}
@@ -306,7 +368,10 @@ export const ErrorDetails = ({
}
const stackPreviewLines = stackTraceLines.slice(0, STACK_PREVIEW_LINES_COUNT)
- const stackHiddenCount = Math.max(0, stackTraceLines.length - STACK_PREVIEW_LINES_COUNT)
+ const stackHiddenCount = Math.max(
+ 0,
+ stackTraceLines.length - STACK_PREVIEW_LINES_COUNT,
+ )
return (
<div className='space-y-3'>
@@ -335,7 +400,9 @@ export const ErrorDetails = ({
</div>
<div>
- <h2 className='text-2xl font-bold wrap-break-word text-gray-900 dark:text-white'>{details.name}</h2>
+ <h2 className='text-2xl font-bold wrap-break-word text-gray-900 dark:text-white'>
+ {details.name}
+ </h2>
{details.message ? (
<p className='mt-1 font-mono text-sm wrap-break-word text-gray-600 dark:text-gray-400'>
{details.message}
@@ -348,7 +415,10 @@ export const ErrorDetails = ({
{details.filename ? (
<div className='flex items-center gap-2'>
<div className='flex items-center gap-2 rounded-md bg-gray-100 px-3 py-1.5 font-mono text-xs text-gray-600 dark:bg-slate-800 dark:text-gray-300'>
- <FileCodeIcon className='size-3.5 text-gray-500' strokeWidth={1.5} />
+ <FileCodeIcon
+ className='size-3.5 text-gray-500'
+ strokeWidth={1.5}
+ />
<span className='break-all'>{fileLocation}</span>
<button
type='button'
@@ -368,21 +438,40 @@ export const ErrorDetails = ({
</div>
<div className='grid grid-cols-2 gap-3 lg:grid-cols-4'>
- <StatItem icon={<HashIcon className='size-4' />} label={t('project.occurrences')} value={details.count || 0} />
- <StatItem icon={<UsersIcon className='size-4' />} label={t('dashboard.users')} value={details.users || 0} />
+ <StatItem
+ icon={<HashIcon className='size-4' />}
+ label={t('project.occurrences')}
+ value={details.count || 0}
+ />
+ <StatItem
+ icon={<UsersIcon className='size-4' />}
+ label={t('dashboard.users')}
+ value={details.users || 0}
+ />
<StatItem
icon={<CalendarIcon className='size-4' />}
label={t('dashboard.firstSeen')}
value={firstSeen || '-'}
/>
- <StatItem icon={<ActivityIcon className='size-4' />} label={t('dashboard.lastSeen')} value={lastSeen || '-'} />
+ <StatItem
+ icon={<ActivityIcon className='size-4' />}
+ label={t('dashboard.lastSeen')}
+ value={lastSeen || '-'}
+ />
</div>
<div className='space-y-3'>
{details.stackTrace ? (
<div className='rounded-lg border border-gray-200 bg-white p-5 dark:border-slate-800/60 dark:bg-slate-800/25'>
<div className='mb-3 flex items-center justify-between gap-3'>
- <Text as='h3' size='xs' weight='semibold' colour='primary' className='mb-2 uppercase' tracking='wide'>
+ <Text
+ as='h3'
+ size='xs'
+ weight='semibold'
+ colour='primary'
+ className='mb-2 uppercase'
+ tracking='wide'
+ >
{t('project.stackTraceXFrames', { x: stackTraceLines.length })}
</Text>
<div className='flex items-center gap-2'>
@@ -428,14 +517,23 @@ export const ErrorDetails = ({
</div>
<div className='rounded-lg border border-gray-100 bg-gray-50 dark:border-slate-700 dark:bg-slate-900/50'>
- <div className={isStackTraceExpanded ? 'max-h-80 overflow-auto p-3' : 'p-3'}>
+ <div
+ className={
+ isStackTraceExpanded ? 'max-h-80 overflow-auto p-3' : 'p-3'
+ }
+ >
<div className='space-y-0.5 font-mono text-xs leading-relaxed'>
- {(isStackTraceExpanded ? stackTraceLines : stackPreviewLines).map((line, index) => (
+ {(isStackTraceExpanded
+ ? stackTraceLines
+ : stackPreviewLines
+ ).map((line, index) => (
<div key={index} className='flex'>
<span className='mr-3 inline-block w-6 text-right text-gray-400 select-none dark:text-slate-500'>
{index + 1}
</span>
- <div className='min-w-0 flex-1'>{formatStackTraceLine(line)}</div>
+ <div className='min-w-0 flex-1'>
+ {formatStackTraceLine(line)}
+ </div>
</div>
))}
{!isStackTraceExpanded && stackHiddenCount > 0 ? (
@@ -450,8 +548,16 @@ export const ErrorDetails = ({
) : null}
<div className='rounded-lg border border-gray-200 bg-white p-5 dark:border-slate-800/60 dark:bg-slate-800/25'>
- <Text as='h3' size='xs' weight='semibold' colour='primary' className='mb-2 uppercase' tracking='wide'>
- {t('project.affectedSessionsList')} {sessionsTotal > 0 ? `(${sessionsTotal})` : ''}
+ <Text
+ as='h3'
+ size='xs'
+ weight='semibold'
+ colour='primary'
+ className='mb-2 uppercase'
+ tracking='wide'
+ >
+ {t('project.affectedSessionsList')}{' '}
+ {sessionsTotal > 0 ? `(${sessionsTotal})` : ''}
</Text>
{sessionsLoading && sessions.length === 0 ? (
diff --git a/web/app/pages/Project/tabs/Errors/ErrorsView.tsx b/web/app/pages/Project/tabs/Errors/ErrorsView.tsx
index dfe527e14..0b698771c 100644
--- a/web/app/pages/Project/tabs/Errors/ErrorsView.tsx
+++ b/web/app/pages/Project/tabs/Errors/ErrorsView.tsx
@@ -16,7 +16,16 @@ import {
AlertTriangleIcon,
UserIcon,
} from 'lucide-react'
-import { useState, useEffect, useMemo, useRef, useCallback, lazy, Suspense, use } from 'react'
+import {
+ useState,
+ useEffect,
+ useMemo,
+ useRef,
+ useCallback,
+ lazy,
+ Suspense,
+ use,
+} from 'react'
import { useTranslation } from 'react-i18next'
import {
Link,
@@ -31,7 +40,11 @@ import {
import { ClientOnly } from 'remix-utils/client-only'
import { toast } from 'sonner'
-import type { ErrorsResponse, ErrorDetailsResponse, ErrorOverviewResponse } from '~/api/api.server'
+import type {
+ ErrorsResponse,
+ ErrorDetailsResponse,
+ ErrorOverviewResponse,
+} from '~/api/api.server'
import { useErrorsProxy } from '~/hooks/useAnalyticsProxy'
import {
TimeFormat,
@@ -54,16 +67,25 @@ import Filters from '~/pages/Project/View/components/Filters'
import NoEvents from '~/pages/Project/View/components/NoEvents'
import { Panel, MetadataPanel } from '~/pages/Project/View/Panels'
import { ERROR_FILTERS_MAPPING } from '~/pages/Project/View/utils/filters'
-import { useViewProjectContext, useRefreshTriggers } from '~/pages/Project/View/ViewProject'
+import {
+ useViewProjectContext,
+ useRefreshTriggers,
+} from '~/pages/Project/View/ViewProject'
import {
getFormatDate,
typeNameMapping,
panelIconMapping,
getDeviceRowMapper,
} from '~/pages/Project/View/ViewProject.helpers'
-import { useCurrentProject, useProjectPassword } from '~/providers/CurrentProjectProvider'
+import {
+ useCurrentProject,
+ useProjectPassword,
+} from '~/providers/CurrentProjectProvider'
import { useTheme } from '~/providers/ThemeProvider'
-import type { ProjectViewActionData, ProjectLoaderData } from '~/routes/projects.$id'
+import type {
+ ProjectViewActionData,
+ ProjectLoaderData,
+} from '~/routes/projects.$id'
import { Badge } from '~/ui/Badge'
import BillboardChart from '~/ui/BillboardChart'
import Checkbox from '~/ui/Checkbox'
@@ -75,10 +97,17 @@ import Tooltip from '~/ui/Tooltip'
import { getRelativeDateIfPossible } from '~/utils/date'
import { getLocaleDisplayName, nFormatter } from '~/utils/generic'
-const InteractiveMap = lazy(() => import('~/pages/Project/View/components/InteractiveMap'))
+const InteractiveMap = lazy(
+ () => import('~/pages/Project/View/components/InteractiveMap'),
+)
-const calculateOptimalTicks = (data: number[], targetCount: number = 6): number[] => {
- const validData = data.filter((n) => n !== undefined && n !== null && Number.isFinite(n))
+const calculateOptimalTicks = (
+ data: number[],
+ targetCount: number = 6,
+): number[] => {
+ const validData = data.filter(
+ (n) => n !== undefined && n !== null && Number.isFinite(n),
+ )
if (validData.length === 0) {
return [0, 1]
@@ -137,11 +166,13 @@ const getErrorTrendsChartSettings = (
['affectedUsers', ...chartData.affectedUsers],
]
- const allYValues: number[] = [...chartData.occurrences, ...chartData.affectedUsers].filter(
- (n) => n !== undefined && n !== null,
- )
+ const allYValues: number[] = [
+ ...chartData.occurrences,
+ ...chartData.affectedUsers,
+ ].filter((n) => n !== undefined && n !== null)
- const optimalTicks = allYValues.length > 0 ? calculateOptimalTicks(allYValues) : undefined
+ const optimalTicks =
+ allYValues.length > 0 ? calculateOptimalTicks(allYValues) : undefined
return {
data: {
@@ -178,8 +209,14 @@ const getErrorTrendsChartSettings = (
format:
// @ts-expect-error
timeFormat === TimeFormat['24-hour']
- ? (x: string) => d3.timeFormat(tbsFormatMapper24h[timeBucket])(x as unknown as Date)
- : (x: string) => d3.timeFormat(tbsFormatMapper[timeBucket])(x as unknown as Date),
+ ? (x: string) =>
+ d3.timeFormat(tbsFormatMapper24h[timeBucket])(
+ x as unknown as Date,
+ )
+ : (x: string) =>
+ d3.timeFormat(tbsFormatMapper[timeBucket])(
+ x as unknown as Date,
+ ),
},
localtime: timeFormat === TimeFormat['24-hour'],
type: 'timeseries',
@@ -254,7 +291,9 @@ interface StatCardProps {
const StatCard = ({ icon, value, label }: StatCardProps) => (
<div className='relative overflow-hidden rounded-xl border border-gray-200 bg-white p-4 dark:border-slate-700 dark:bg-slate-800'>
- <div className='pointer-events-none absolute -bottom-5 -left-5 opacity-10 [&>svg]:size-24'>{icon}</div>
+ <div className='pointer-events-none absolute -bottom-5 -left-5 opacity-10 [&>svg]:size-24'>
+ {icon}
+ </div>
<div className='relative'>
<Text as='p' size='3xl' weight='bold' className='leading-tight'>
{value}
@@ -310,7 +349,10 @@ const ErrorItem = ({ error }: ErrorItemProps) => {
const maxNameLength = 80
const maxMessageLength = 150
- const displayName = error.name.length > maxNameLength ? `${error.name.slice(0, maxNameLength)}...` : error.name
+ const displayName =
+ error.name.length > maxNameLength
+ ? `${error.name.slice(0, maxNameLength)}...`
+ : error.name
const displayMessage =
error.message && error.message.length > maxMessageLength
? `${error.message.slice(0, maxMessageLength)}...`
@@ -332,10 +374,18 @@ const ErrorItem = ({ error }: ErrorItemProps) => {
/>
{error.filename ? (
<>
- <svg viewBox='0 0 2 2' className='h-0.5 w-0.5 flex-none self-center fill-gray-400'>
+ <svg
+ viewBox='0 0 2 2'
+ className='h-0.5 w-0.5 flex-none self-center fill-gray-400'
+ >
<circle cx={1} cy={1} r={1} />
</svg>
- <Text size='xs' weight='normal' colour='muted' className='mx-1 max-w-[200px] truncate'>
+ <Text
+ size='xs'
+ weight='normal'
+ colour='muted'
+ className='mx-1 max-w-[200px] truncate'
+ >
{error.filename}
</Text>
</>
@@ -345,16 +395,28 @@ const ErrorItem = ({ error }: ErrorItemProps) => {
<Tooltip
text={error.message}
tooltipNode={
- <Text as='p' size='sm' colour='muted' className='mt-1 flex text-left leading-5'>
+ <Text
+ as='p'
+ size='sm'
+ colour='muted'
+ className='mt-1 flex text-left leading-5'
+ >
{displayMessage}
</Text>
}
/>
) : null}
<p className='mt-1 flex items-center gap-x-2 text-sm leading-5 text-gray-500 dark:text-gray-300'>
- <Badge className='mr-2 sm:hidden' label={status.label} colour={status.colour} />
+ <Badge
+ className='mr-2 sm:hidden'
+ label={status.label}
+ colour={status.colour}
+ />
{lastSeen}
- <svg viewBox='0 0 2 2' className='h-0.5 w-0.5 flex-none fill-gray-400 sm:hidden'>
+ <svg
+ viewBox='0 0 2 2'
+ className='h-0.5 w-0.5 flex-none fill-gray-400 sm:hidden'
+ >
<circle cx={1} cy={1} r={1} />
</svg>
<span className='sm:hidden'>
@@ -364,11 +426,19 @@ const ErrorItem = ({ error }: ErrorItemProps) => {
</span>
</p>
<p className='mt-2 flex text-xs leading-5 text-gray-500 sm:hidden dark:text-gray-300'>
- <span className='mr-3 flex items-center' title={t('project.affectedUsers')}>
- <UserIcon className='mr-1 size-4' strokeWidth={1.5} /> {error.users}
+ <span
+ className='mr-3 flex items-center'
+ title={t('project.affectedUsers')}
+ >
+ <UserIcon className='mr-1 size-4' strokeWidth={1.5} />{' '}
+ {error.users}
</span>
- <span className='flex items-center' title={t('project.affectedSessions')}>
- <MonitorIcon className='mr-1 size-4' strokeWidth={1.5} /> {error.sessions}
+ <span
+ className='flex items-center'
+ title={t('project.affectedSessions')}
+ >
+ <MonitorIcon className='mr-1 size-4' strokeWidth={1.5} />{' '}
+ {error.sessions}
</span>
</p>
</div>
@@ -376,14 +446,26 @@ const ErrorItem = ({ error }: ErrorItemProps) => {
<div className='flex shrink-0 items-center gap-x-4'>
<div className='hidden gap-1 sm:flex sm:flex-col sm:items-end'>
<div className='flex items-center gap-x-3 text-sm leading-6 text-gray-900 dark:text-gray-50'>
- <span className='flex items-center' title={t('dashboard.xOccurrences', { x: error.count })}>
- <AlertTriangleIcon className='mr-1 size-4' strokeWidth={1.5} /> {error.count}
+ <span
+ className='flex items-center'
+ title={t('dashboard.xOccurrences', { x: error.count })}
+ >
+ <AlertTriangleIcon className='mr-1 size-4' strokeWidth={1.5} />{' '}
+ {error.count}
</span>
- <span className='flex items-center' title={t('project.xAffectedUsers', { x: error.users })}>
- <UserIcon className='mr-1 size-4' strokeWidth={1.5} /> {error.users}
+ <span
+ className='flex items-center'
+ title={t('project.xAffectedUsers', { x: error.users })}
+ >
+ <UserIcon className='mr-1 size-4' strokeWidth={1.5} />{' '}
+ {error.users}
</span>
- <span className='flex items-center' title={t('project.xAffectedSessions', { x: error.sessions })}>
- <MonitorIcon className='mr-1 size-4' strokeWidth={1.5} /> {error.sessions}
+ <span
+ className='flex items-center'
+ title={t('project.xAffectedSessions', { x: error.sessions })}
+ >
+ <MonitorIcon className='mr-1 size-4' strokeWidth={1.5} />{' '}
+ {error.sessions}
</span>
</div>
<Badge label={status.label} colour={status.colour} />
@@ -403,7 +485,11 @@ interface DeferredErrorsData {
errorOverview: ErrorOverviewResponse | null
}
-function ErrorsDataResolver({ children }: { children: (data: DeferredErrorsData) => React.ReactNode }) {
+function ErrorsDataResolver({
+ children,
+}: {
+ children: (data: DeferredErrorsData) => React.ReactNode
+}) {
const {
errorsData: errorsDataPromise,
errorDetails: errorDetailsPromise,
@@ -426,7 +512,9 @@ function ErrorsDataResolver({ children }: { children: (data: DeferredErrorsData)
function ErrorsViewWrapper() {
return (
<Suspense fallback={<Loader />}>
- <ErrorsDataResolver>{(deferredData) => <ErrorsViewInner deferredData={deferredData} />}</ErrorsDataResolver>
+ <ErrorsDataResolver>
+ {(deferredData) => <ErrorsViewInner deferredData={deferredData} />}
+ </ErrorsDataResolver>
</Suspense>
)
}
@@ -441,7 +529,8 @@ const ErrorsViewInner = ({ deferredData }: ErrorsViewInnerProps) => {
const revalidator = useRevalidator()
const errorsProxy = useErrorsProxy()
const { errorsRefreshTrigger } = useRefreshTriggers()
- const { timeBucket, timeFormat, period, dateRange, timezone, filters, size } = useViewProjectContext()
+ const { timeBucket, timeFormat, period, dateRange, timezone, filters, size } =
+ useViewProjectContext()
const {
t,
i18n: { language },
@@ -472,9 +561,15 @@ const ErrorsViewInner = ({ deferredData }: ErrorsViewInnerProps) => {
const isMountedRef = useRef(true)
- const [errorsLoading, setErrorsLoading] = useState<boolean | null>(() => (deferredData.errorsData ? false : null))
- const [errors, setErrors] = useState<SwetrixError[]>(() => deferredData.errorsData?.errors || [])
- const [errorsSkip, setErrorsSkip] = useState(() => deferredData.errorsData?.errors?.length || 0)
+ const [errorsLoading, setErrorsLoading] = useState<boolean | null>(() =>
+ deferredData.errorsData ? false : null,
+ )
+ const [errors, setErrors] = useState<SwetrixError[]>(
+ () => deferredData.errorsData?.errors || [],
+ )
+ const [errorsSkip, setErrorsSkip] = useState(
+ () => deferredData.errorsData?.errors?.length || 0,
+ )
const [canLoadMoreErrors, setCanLoadMoreErrors] = useState(
() => (deferredData.errorsData?.errors?.length || 0) >= ERRORS_TAKE,
)
@@ -573,7 +668,19 @@ const ErrorsViewInner = ({ deferredData }: ErrorsViewInnerProps) => {
skip: errorsSkip,
options: errorOptions,
})
- }, [id, timeBucket, period, from, to, timezone, filters, errorsSkip, errorOptions, errorsLoading, errorsProxy])
+ }, [
+ id,
+ timeBucket,
+ period,
+ from,
+ to,
+ timezone,
+ filters,
+ errorsSkip,
+ errorOptions,
+ errorsLoading,
+ errorsProxy,
+ ])
// Handle proxy response for pagination
useEffect(() => {
@@ -588,7 +695,12 @@ const ErrorsViewInner = ({ deferredData }: ErrorsViewInnerProps) => {
if (errorsProxy.error) {
toast.error(errorsProxy.error)
}
- }, [errorsProxy.data, errorsProxy.error, errorsProxy.isLoading, revalidator.state])
+ }, [
+ errorsProxy.data,
+ errorsProxy.error,
+ errorsProxy.isLoading,
+ revalidator.state,
+ ])
const updateStatusInErrors = useCallback(
(status: 'active' | 'resolved') => {
@@ -678,11 +790,18 @@ const ErrorsViewInner = ({ deferredData }: ErrorsViewInnerProps) => {
}, [errorsRefreshTrigger])
const chartOptions = useMemo(() => {
- if (!overview?.chart || !overview.chart.x || overview.chart.x.length === 0) return null
- return getErrorTrendsChartSettings(overview.chart, timeBucket, timeFormat, chartTypes.line, {
- occurrences: t('project.totalErrors'),
- affectedUsers: t('project.affectedUsers'),
- })
+ if (!overview?.chart || !overview.chart.x || overview.chart.x.length === 0)
+ return null
+ return getErrorTrendsChartSettings(
+ overview.chart,
+ timeBucket,
+ timeFormat,
+ chartTypes.line,
+ {
+ occurrences: t('project.totalErrors'),
+ affectedUsers: t('project.affectedUsers'),
+ },
+ )
}, [overview?.chart, timeBucket, timeFormat, t])
const hasErrorsRaw = !_isEmpty(errors) || overview?.stats?.totalErrors
@@ -699,7 +818,10 @@ const ErrorsViewInner = ({ deferredData }: ErrorsViewInnerProps) => {
const getFilterLink = useCallback(
(column: string, value: string | null): LinkProps['to'] => {
- const isFilterActive = filters.findIndex((filter) => filter.column === column && filter.filter === value) >= 0
+ const isFilterActive =
+ filters.findIndex(
+ (filter) => filter.column === column && filter.filter === value,
+ ) >= 0
const newSearchParams = new URLSearchParams(searchParams.toString())
if (isFilterActive) {
@@ -772,13 +894,18 @@ const ErrorsViewInner = ({ deferredData }: ErrorsViewInnerProps) => {
[t],
)
- if (typeof project?.isErrorDataExists === 'boolean' && !project.isErrorDataExists) {
+ if (
+ typeof project?.isErrorDataExists === 'boolean' &&
+ !project.isErrorDataExists
+ ) {
return <WaitingForAnError />
}
if (activeEID) {
const resolveButton =
- allowedToManage && activeError && activeError?.details?.status !== 'resolved' ? (
+ allowedToManage &&
+ activeError &&
+ activeError?.details?.status !== 'resolved' ? (
<button
type='button'
disabled={errorStatusUpdating}
@@ -786,14 +913,17 @@ const ErrorsViewInner = ({ deferredData }: ErrorsViewInnerProps) => {
className={cx(
'group relative rounded-md border border-transparent bg-transparent px-3 py-1.5 text-sm font-medium text-gray-700 transition-all ring-inset hover:border-gray-300 hover:bg-white focus:z-10 focus:ring-1 focus:ring-indigo-500 focus:outline-hidden dark:text-gray-50 hover:dark:border-slate-700/80 dark:hover:bg-slate-800 focus:dark:ring-gray-200',
{
- 'cursor-not-allowed opacity-50': errorLoading && !errorStatusUpdating,
+ 'cursor-not-allowed opacity-50':
+ errorLoading && !errorStatusUpdating,
'animate-pulse cursor-not-allowed': errorStatusUpdating,
},
)}
>
{t('project.resolve')}
</button>
- ) : allowedToManage && activeError && activeError?.details?.status === 'resolved' ? (
+ ) : allowedToManage &&
+ activeError &&
+ activeError?.details?.status === 'resolved' ? (
<button
type='button'
disabled={errorStatusUpdating}
@@ -801,7 +931,8 @@ const ErrorsViewInner = ({ deferredData }: ErrorsViewInnerProps) => {
className={cx(
'group relative rounded-md border border-transparent bg-transparent px-3 py-1.5 text-sm font-medium text-gray-700 transition-all ring-inset hover:border-gray-300 hover:bg-white focus:z-10 focus:ring-1 focus:ring-indigo-500 focus:outline-hidden dark:text-gray-50 hover:dark:border-slate-700/80 dark:hover:bg-slate-800 focus:dark:ring-gray-200',
{
- 'cursor-not-allowed opacity-50': errorLoading && !errorStatusUpdating,
+ 'cursor-not-allowed opacity-50':
+ errorLoading && !errorStatusUpdating,
'animate-pulse cursor-not-allowed': errorStatusUpdating,
},
)}
@@ -869,15 +1000,28 @@ const ErrorsViewInner = ({ deferredData }: ErrorsViewInnerProps) => {
return <CCRow cc={null} language={language} />
}
const entryNameArray = entryName.split('-')
- const displayName = getLocaleDisplayName(entryName, language)
+ const displayName = getLocaleDisplayName(
+ entryName,
+ language,
+ )
return (
- <CCRow cc={entryNameArray[entryNameArray.length - 1]} name={displayName} language={language} />
+ <CCRow
+ cc={entryNameArray[entryNameArray.length - 1]}
+ name={displayName}
+ language={language}
+ />
)
}
if (cc !== undefined) {
- return <CCRow cc={cc} name={entryName || undefined} language={language} />
+ return (
+ <CCRow
+ cc={cc}
+ name={entryName || undefined}
+ language={language}
+ />
+ )
}
return <CCRow cc={entryName} language={language} />
@@ -898,14 +1042,19 @@ const ErrorsViewInner = ({ deferredData }: ErrorsViewInnerProps) => {
})
}
activeTabId={errorsActiveTabs.location}
- data={activeError?.params?.[errorsActiveTabs.location] || []}
+ data={
+ activeError?.params?.[errorsActiveTabs.location] || []
+ }
rowMapper={rowMapper}
customRenderer={
errorsActiveTabs.location === 'map'
? () => {
const countryData = activeError?.params?.cc || []
const regionData = activeError?.params?.rg || []
- const total = countryData.reduce((acc, curr) => acc + curr.count, 0)
+ const total = countryData.reduce(
+ (acc, curr) => acc + curr.count,
+ 0,
+ )
return (
<Suspense
@@ -956,11 +1105,20 @@ const ErrorsViewInner = ({ deferredData }: ErrorsViewInnerProps) => {
name={t('project.devices')}
tabs={deviceTabs}
onTabChange={(tab) =>
- setErrorsActiveTabs({ ...errorsActiveTabs, device: tab as 'br' | 'os' | 'dv' })
+ setErrorsActiveTabs({
+ ...errorsActiveTabs,
+ device: tab as 'br' | 'os' | 'dv',
+ })
}
activeTabId={errorsActiveTabs.device}
- data={activeError?.params?.[errorsActiveTabs.device] || []}
- rowMapper={getDeviceRowMapper(errorsActiveTabs.device, theme, t)}
+ data={
+ activeError?.params?.[errorsActiveTabs.device] || []
+ }
+ rowMapper={getDeviceRowMapper(
+ errorsActiveTabs.device,
+ theme,
+ t,
+ )}
capitalize={errorsActiveTabs.device === 'dv'}
versionData={
errorsActiveTabs.device === 'br'
@@ -970,7 +1128,11 @@ const ErrorsViewInner = ({ deferredData }: ErrorsViewInnerProps) => {
: undefined
}
getVersionFilterLink={(parent, version) =>
- getVersionFilterLink(parent, version, errorsActiveTabs.device === 'br' ? 'br' : 'os')
+ getVersionFilterLink(
+ parent,
+ version,
+ errorsActiveTabs.device === 'br' ? 'br' : 'os',
+ )
}
valuesHeaderName={t('project.occurrences')}
highlightColour='red'
@@ -994,7 +1156,9 @@ const ErrorsViewInner = ({ deferredData }: ErrorsViewInnerProps) => {
if (!entryName) {
return (
<span className='italic'>
- {errorsActiveTabs.page === 'pg' ? t('common.notSet') : t('project.unknownHost')}
+ {errorsActiveTabs.page === 'pg'
+ ? t('common.notSet')
+ : t('project.unknownHost')}
</span>
)
}
@@ -1011,7 +1175,12 @@ const ErrorsViewInner = ({ deferredData }: ErrorsViewInnerProps) => {
}}
name={t('project.pages')}
tabs={pageTabs}
- onTabChange={(tab) => setErrorsActiveTabs({ ...errorsActiveTabs, page: tab as 'pg' | 'host' })}
+ onTabChange={(tab) =>
+ setErrorsActiveTabs({
+ ...errorsActiveTabs,
+ page: tab as 'pg' | 'host',
+ })
+ }
activeTabId={errorsActiveTabs.page}
data={activeError?.params?.[errorsActiveTabs.page] || []}
valuesHeaderName={t('project.occurrences')}
@@ -1023,7 +1192,9 @@ const ErrorsViewInner = ({ deferredData }: ErrorsViewInnerProps) => {
return null
})
: null}
- {activeError?.metadata ? <MetadataPanel metadata={activeError.metadata} /> : null}
+ {activeError?.metadata ? (
+ <MetadataPanel metadata={activeError.metadata} />
+ ) : null}
</div>
{_isEmpty(activeError) && errorLoading ? <Loader /> : null}
@@ -1034,7 +1205,11 @@ const ErrorsViewInner = ({ deferredData }: ErrorsViewInnerProps) => {
}
// List view - Initial loading state
- if ((overviewLoading === null || overviewLoading) && !overview && _isEmpty(errors)) {
+ if (
+ (overviewLoading === null || overviewLoading) &&
+ !overview &&
+ _isEmpty(errors)
+ ) {
return (
<div
className={cx('flex flex-col bg-gray-50 dark:bg-slate-900', {
@@ -1078,13 +1253,22 @@ const ErrorsViewInner = ({ deferredData }: ErrorsViewInnerProps) => {
return (
<div>
- <DashboardHeader showLiveVisitors showSearchButton={false} hideTimeBucket rightContent={filtersDropdown} />
-
- {(overviewLoading || errorsLoading) && (overview || !_isEmpty(errors)) ? <LoadingBar /> : null}
+ <DashboardHeader
+ showLiveVisitors
+ showSearchButton={false}
+ hideTimeBucket
+ rightContent={filtersDropdown}
+ />
+
+ {(overviewLoading || errorsLoading) && (overview || !_isEmpty(errors)) ? (
+ <LoadingBar />
+ ) : null}
{hasErrors ? <Filters className='mb-3' tnMapping={tnMapping} /> : null}
- {!hasErrors && errorsLoading === false && overviewLoading === false ? <NoEvents filters={filters} /> : null}
+ {!hasErrors && errorsLoading === false && overviewLoading === false ? (
+ <NoEvents filters={filters} />
+ ) : null}
{hasErrors ? (
<>
@@ -1102,7 +1286,9 @@ const ErrorsViewInner = ({ deferredData }: ErrorsViewInnerProps) => {
label={t('project.totalErrors')}
/>
<StatCard
- icon={<PercentIcon className='text-orange-600' strokeWidth={1.5} />}
+ icon={
+ <PercentIcon className='text-orange-600' strokeWidth={1.5} />
+ }
value={`${overview?.stats?.errorRate || 0}%`}
label={t('project.errorRate')}
/>
@@ -1112,7 +1298,9 @@ const ErrorsViewInner = ({ deferredData }: ErrorsViewInnerProps) => {
label={t('project.affectedUsers')}
/>
<StatCard
- icon={<MonitorIcon className='text-purple-600' strokeWidth={1.5} />}
+ icon={
+ <MonitorIcon className='text-purple-600' strokeWidth={1.5} />
+ }
value={nFormatter(overview?.stats?.affectedSessions || 0, 1)}
label={t('project.affectedSessions')}
/>
diff --git a/web/app/pages/Project/tabs/Errors/NoErrorDetails.tsx b/web/app/pages/Project/tabs/Errors/NoErrorDetails.tsx
index 8637822dd..24577b365 100644
--- a/web/app/pages/Project/tabs/Errors/NoErrorDetails.tsx
+++ b/web/app/pages/Project/tabs/Errors/NoErrorDetails.tsx
@@ -7,9 +7,14 @@ const NoErrorDetails = () => {
return (
<div className='mx-auto w-full max-w-2xl py-16 text-center text-gray-900 dark:text-gray-50'>
<div className='mx-auto mb-6 flex size-14 items-center justify-center rounded-xl bg-gray-100 dark:bg-slate-800'>
- <BugIcon className='size-7 text-gray-700 dark:text-gray-200' strokeWidth={1.5} />
+ <BugIcon
+ className='size-7 text-gray-700 dark:text-gray-200'
+ strokeWidth={1.5}
+ />
</div>
- <h3 className='text-xl font-medium tracking-tight'>{t('project.noErrorDetails')}</h3>
+ <h3 className='text-xl font-medium tracking-tight'>
+ {t('project.noErrorDetails')}
+ </h3>
<p className='mx-auto mt-2 max-w-md text-sm whitespace-pre-line text-gray-800 dark:text-gray-200'>
{t('project.noErrorDesc')}
</p>
diff --git a/web/app/pages/Project/tabs/Errors/WaitingForAnError.tsx b/web/app/pages/Project/tabs/Errors/WaitingForAnError.tsx
index 9e69a5e9a..56885d3d5 100644
--- a/web/app/pages/Project/tabs/Errors/WaitingForAnError.tsx
+++ b/web/app/pages/Project/tabs/Errors/WaitingForAnError.tsx
@@ -13,9 +13,14 @@ const WaitingForAnError = () => {
return (
<div className='mx-auto w-full max-w-2xl py-16 text-center text-gray-900 dark:text-gray-50'>
<div className='mx-auto mb-6 flex size-14 items-center justify-center rounded-xl bg-gray-100 dark:bg-slate-800'>
- <BugIcon className='size-7 text-gray-700 dark:text-gray-200' strokeWidth={1.5} />
+ <BugIcon
+ className='size-7 text-gray-700 dark:text-gray-200'
+ strokeWidth={1.5}
+ />
</div>
- <h3 className='text-xl font-medium tracking-tight'>{t('project.waitingError.title')}</h3>
+ <h3 className='text-xl font-medium tracking-tight'>
+ {t('project.waitingError.title')}
+ </h3>
<p className='mx-auto mt-2 max-w-md text-sm whitespace-pre-line text-gray-800 dark:text-gray-200'>
<Trans
t={t}
@@ -30,7 +35,10 @@ const WaitingForAnError = () => {
/>
),
curl: (
- <Link to={routes.contact} className='font-medium text-indigo-600 hover:underline dark:text-indigo-400' />
+ <Link
+ to={routes.contact}
+ className='font-medium text-indigo-600 hover:underline dark:text-indigo-400'
+ />
),
howto: (
<a
diff --git a/web/app/pages/Project/tabs/Experiments/ExperimentResults.tsx b/web/app/pages/Project/tabs/Experiments/ExperimentResults.tsx
index 0f1d87a21..dfacae603 100644
--- a/web/app/pages/Project/tabs/Experiments/ExperimentResults.tsx
+++ b/web/app/pages/Project/tabs/Experiments/ExperimentResults.tsx
@@ -29,7 +29,11 @@ import type {
ExperimentVariantResult,
Goal,
} from '~/api/api.server'
-import { useExperimentProxy, useExperimentResultsProxy, useGoalProxy } from '~/hooks/useAnalyticsProxy'
+import {
+ useExperimentProxy,
+ useExperimentResultsProxy,
+ useGoalProxy,
+} from '~/hooks/useAnalyticsProxy'
import {
TimeFormat,
tbsFormatMapper,
@@ -79,10 +83,17 @@ interface StatCardProps {
const StatCard = memo(({ icon, value, label, subValue }: StatCardProps) => (
<div className='relative overflow-hidden rounded-lg border border-gray-200 bg-white p-4 dark:border-slate-700 dark:bg-slate-800'>
- <div className='pointer-events-none absolute -bottom-5 -left-5 opacity-10 [&>svg]:size-24'>{icon}</div>
+ <div className='pointer-events-none absolute -bottom-5 -left-5 opacity-10 [&>svg]:size-24'>
+ {icon}
+ </div>
<div className='relative'>
<div className='flex items-baseline gap-1.5'>
- <Text as='p' size='3xl' weight='bold' className='leading-tight tabular-nums'>
+ <Text
+ as='p'
+ size='3xl'
+ weight='bold'
+ className='leading-tight tabular-nums'
+ >
{value}
</Text>
{subValue ? (
@@ -108,7 +119,9 @@ const getWinProbabilityChartSettings = (
): ChartOptions => {
const xAxisSize = _size(chartData.x)
- const columns: any[] = [['x', ..._map(chartData.x, (el) => dayjs(el).toDate())]]
+ const columns: any[] = [
+ ['x', ..._map(chartData.x, (el) => dayjs(el).toDate())],
+ ]
const types: Record<string, any> = {}
const colors: Record<string, string> = {}
@@ -153,8 +166,14 @@ const getWinProbabilityChartSettings = (
format:
// @ts-expect-error
timeFormat === TimeFormat['24-hour']
- ? (x: string) => d3.timeFormat(tbsFormatMapper24h[timeBucket])(x as unknown as Date)
- : (x: string) => d3.timeFormat(tbsFormatMapper[timeBucket])(x as unknown as Date),
+ ? (x: string) =>
+ d3.timeFormat(tbsFormatMapper24h[timeBucket])(
+ x as unknown as Date,
+ )
+ : (x: string) =>
+ d3.timeFormat(tbsFormatMapper[timeBucket])(
+ x as unknown as Date,
+ ),
},
localtime: timeFormat === TimeFormat['24-hour'],
type: 'timeseries',
@@ -229,8 +248,19 @@ const WinProbabilityChart = memo(
const { timeFormat } = useViewProjectContext()
const chartOptions = useMemo(() => {
- if (!chartData || !chartData.x || chartData.x.length === 0 || variants.length === 0) return null
- return getWinProbabilityChartSettings(chartData, variants, timeBucket, timeFormat)
+ if (
+ !chartData ||
+ !chartData.x ||
+ chartData.x.length === 0 ||
+ variants.length === 0
+ )
+ return null
+ return getWinProbabilityChartSettings(
+ chartData,
+ variants,
+ timeBucket,
+ timeFormat,
+ )
}, [chartData, variants, timeBucket, timeFormat])
if (!chartOptions) {
@@ -267,7 +297,10 @@ const ConfidenceBar = memo(
isControl: boolean
}) => {
const maxRange = 30
- const clampedImprovement = Math.max(-maxRange, Math.min(maxRange, improvement))
+ const clampedImprovement = Math.max(
+ -maxRange,
+ Math.min(maxRange, improvement),
+ )
const position = ((clampedImprovement + maxRange) / (maxRange * 2)) * 100
const isPositive = improvement > 0
@@ -295,8 +328,16 @@ const ConfidenceBar = memo(
<div className='absolute top-1/2 left-1/2 h-4 w-0.5 -translate-x-1/2 -translate-y-1/2 bg-gray-300 dark:bg-gray-600' />
- <div className='absolute top-1/2 -translate-x-1/2 -translate-y-1/2' style={{ left: `${position}%` }}>
- <div className={cx('size-3.5 rotate-45 rounded-sm shadow-sm', getColor())} />
+ <div
+ className='absolute top-1/2 -translate-x-1/2 -translate-y-1/2'
+ style={{ left: `${position}%` }}
+ >
+ <div
+ className={cx(
+ 'size-3.5 rotate-45 rounded-sm shadow-sm',
+ getColor(),
+ )}
+ />
</div>
</div>
)
@@ -305,7 +346,13 @@ const ConfidenceBar = memo(
ConfidenceBar.displayName = 'ConfidenceBar'
-const TableHeader = ({ children, className }: { children: React.ReactNode; className?: string }) => (
+const TableHeader = ({
+ children,
+ className,
+}: {
+ children: React.ReactNode
+ className?: string
+}) => (
<th
className={cx(
'px-4 py-3 text-left text-xs font-medium tracking-wider text-gray-500 uppercase dark:text-gray-400',
@@ -316,12 +363,22 @@ const TableHeader = ({ children, className }: { children: React.ReactNode; class
</th>
)
-const TableCell = ({ children, className }: { children: React.ReactNode; className?: string }) => (
- <td className={cx('px-4 py-4', className)}>{children}</td>
-)
+const TableCell = ({
+ children,
+ className,
+}: {
+ children: React.ReactNode
+ className?: string
+}) => <td className={cx('px-4 py-4', className)}>{children}</td>
const ExposuresTable = memo(
- ({ variants, totalExposures }: { variants: ExperimentVariantResult[]; totalExposures: number }) => {
+ ({
+ variants,
+ totalExposures,
+ }: {
+ variants: ExperimentVariantResult[]
+ totalExposures: number
+ }) => {
const { t } = useTranslation()
return (
@@ -342,9 +399,15 @@ const ExposuresTable = memo(
</thead>
<tbody className='divide-y divide-gray-200 dark:divide-slate-700'>
{_map(variants, (variant) => {
- const percentage = totalExposures > 0 ? ((variant.exposures / totalExposures) * 100).toFixed(1) : '0.0'
+ const percentage =
+ totalExposures > 0
+ ? ((variant.exposures / totalExposures) * 100).toFixed(1)
+ : '0.0'
return (
- <tr key={variant.key} className='hover:bg-gray-50 dark:hover:bg-slate-700/30'>
+ <tr
+ key={variant.key}
+ className='hover:bg-gray-50 dark:hover:bg-slate-700/30'
+ >
<TableCell>
<div className='flex items-center gap-2'>
<Text weight='medium' size='sm'>
@@ -429,7 +492,9 @@ const MetricsTable = memo(
<TableHeader>{t('experiments.variants')}</TableHeader>
<TableHeader>Value</TableHeader>
<TableHeader>{t('experiments.improvement')}</TableHeader>
- <TableHeader>{t('experiments.probabilityOfWinning')}</TableHeader>
+ <TableHeader>
+ {t('experiments.probabilityOfWinning')}
+ </TableHeader>
<TableHeader className='w-48'>
<div className='flex items-center justify-between text-[10px]'>
<span>-30%</span>
@@ -454,11 +519,22 @@ const MetricsTable = memo(
</TableCell>
<TableCell>
<div className='flex flex-col'>
- <Text as='p' weight='semibold' size='sm' className='tabular-nums'>
+ <Text
+ as='p'
+ weight='semibold'
+ size='sm'
+ className='tabular-nums'
+ >
{controlVariant.conversionRate}%
</Text>
- <Text as='p' size='xs' colour='muted' className='mt-0.5 tabular-nums'>
- {nFormatter(controlVariant.conversions, 1)} / {nFormatter(controlVariant.exposures, 1)}
+ <Text
+ as='p'
+ size='xs'
+ colour='muted'
+ className='mt-0.5 tabular-nums'
+ >
+ {nFormatter(controlVariant.conversions, 1)} /{' '}
+ {nFormatter(controlVariant.exposures, 1)}
</Text>
</div>
</TableCell>
@@ -475,7 +551,9 @@ const MetricsTable = memo(
<TableCell>
<ConfidenceBar
improvement={0}
- probabilityOfWinning={controlVariant.probabilityOfBeingBest}
+ probabilityOfWinning={
+ controlVariant.probabilityOfBeingBest
+ }
isControl
/>
</TableCell>
@@ -489,9 +567,12 @@ const MetricsTable = memo(
return (
<tr
key={variant.key}
- className={cx('hover:bg-gray-50 dark:hover:bg-slate-700/30', {
- 'bg-green-50/50 dark:bg-green-900/10': isWinner,
- })}
+ className={cx(
+ 'hover:bg-gray-50 dark:hover:bg-slate-700/30',
+ {
+ 'bg-green-50/50 dark:bg-green-900/10': isWinner,
+ },
+ )}
>
<TableCell>
<div className='flex items-center gap-2'>
@@ -508,21 +589,37 @@ const MetricsTable = memo(
</TableCell>
<TableCell>
<div className='flex flex-col'>
- <Text as='p' weight='semibold' size='sm' className='tabular-nums'>
+ <Text
+ as='p'
+ weight='semibold'
+ size='sm'
+ className='tabular-nums'
+ >
{variant.conversionRate}%
</Text>
- <Text as='p' size='xs' colour='muted' className='mt-0.5 tabular-nums'>
- {nFormatter(variant.conversions, 1)} / {nFormatter(variant.exposures, 1)}
+ <Text
+ as='p'
+ size='xs'
+ colour='muted'
+ className='mt-0.5 tabular-nums'
+ >
+ {nFormatter(variant.conversions, 1)} /{' '}
+ {nFormatter(variant.exposures, 1)}
</Text>
</div>
</TableCell>
<TableCell>
<div
- className={cx('flex items-center gap-1 text-sm font-medium', {
- 'text-green-600 dark:text-green-400': isPositive,
- 'text-red-600 dark:text-red-400': !isPositive && variant.improvement !== 0,
- 'text-gray-500 dark:text-gray-400': variant.improvement === 0,
- })}
+ className={cx(
+ 'flex items-center gap-1 text-sm font-medium',
+ {
+ 'text-green-600 dark:text-green-400': isPositive,
+ 'text-red-600 dark:text-red-400':
+ !isPositive && variant.improvement !== 0,
+ 'text-gray-500 dark:text-gray-400':
+ variant.improvement === 0,
+ },
+ )}
>
{variant.improvement !== 0 ? (
<>
@@ -543,9 +640,14 @@ const MetricsTable = memo(
<div className='flex items-center gap-2'>
<Text
size='sm'
- weight={variant.probabilityOfBeingBest >= 95 ? 'semibold' : 'normal'}
+ weight={
+ variant.probabilityOfBeingBest >= 95
+ ? 'semibold'
+ : 'normal'
+ }
className={cx('tabular-nums', {
- 'text-green-600 dark:text-green-400': variant.probabilityOfBeingBest >= 95,
+ 'text-green-600 dark:text-green-400':
+ variant.probabilityOfBeingBest >= 95,
})}
>
{variant.probabilityOfBeingBest}%
@@ -578,7 +680,15 @@ const MetricsTable = memo(
MetricsTable.displayName = 'MetricsTable'
const CollapsibleSection = memo(
- ({ title, children, defaultOpen = true }: { title: string; children: React.ReactNode; defaultOpen?: boolean }) => {
+ ({
+ title,
+ children,
+ defaultOpen = true,
+ }: {
+ title: string
+ children: React.ReactNode
+ defaultOpen?: boolean
+ }) => {
const [isOpen, setIsOpen] = useState(defaultOpen)
return (
@@ -597,7 +707,11 @@ const CollapsibleSection = memo(
<ChevronDownIcon className='size-4 text-gray-500' />
)}
</button>
- {isOpen ? <div className='border-t border-gray-200 px-4 py-4 dark:border-slate-700'>{children}</div> : null}
+ {isOpen ? (
+ <div className='border-t border-gray-200 px-4 py-4 dark:border-slate-700'>
+ {children}
+ </div>
+ ) : null}
</div>
)
},
@@ -647,7 +761,13 @@ const ExperimentResults = ({
try {
const [experimentData, resultsData] = await Promise.all([
experimentProxy.fetchExperiment(experimentId),
- resultsProxy.fetchResults(experimentId, { period, timeBucket, from, to, timezone }),
+ resultsProxy.fetchResults(experimentId, {
+ period,
+ timeBucket,
+ from,
+ to,
+ timezone,
+ }),
])
let goalData: Goal | null = null
@@ -677,11 +797,22 @@ const ExperimentResults = ({
loadData()
// eslint-disable-next-line react-hooks/exhaustive-deps
- }, [experimentId, period, timeBucket, from, to, timezone, reloadToken, refreshTrigger])
+ }, [
+ experimentId,
+ period,
+ timeBucket,
+ from,
+ to,
+ timezone,
+ reloadToken,
+ refreshTrigger,
+ ])
const overallConversionRate = useMemo(() => {
if (!results || results.totalExposures === 0) return 0
- return ((results.totalConversions / results.totalExposures) * 100).toFixed(2)
+ return ((results.totalConversions / results.totalExposures) * 100).toFixed(
+ 2,
+ )
}, [results])
const sortedVariants = useMemo(() => {
@@ -730,7 +861,9 @@ const ExperimentResults = ({
<Button
type='button'
onClick={() => setIsSettingsOpen(true)}
- disabled={results.status === 'running' || results.status === 'completed'}
+ disabled={
+ results.status === 'running' || results.status === 'completed'
+ }
ghost
small
>
@@ -742,24 +875,40 @@ const ExperimentResults = ({
}
leftContent={
<div className='flex items-center gap-2'>
- <FlaskConicalIcon className='size-5 text-purple-500' strokeWidth={1.5} />
+ <FlaskConicalIcon
+ className='size-5 text-purple-500'
+ strokeWidth={1.5}
+ />
<Text as='h2' size='xl' weight='bold' truncate>
{experiment.name}
</Text>
<div
- className={cx('inline-flex items-center rounded-full px-2 py-0.5 text-xs font-medium', {
- 'bg-gray-100 text-gray-600 dark:bg-gray-700 dark:text-gray-400': results.status === 'draft',
- 'bg-green-100 text-green-800 dark:bg-green-900/30 dark:text-green-400': results.status === 'running',
- 'bg-yellow-100 text-yellow-800 dark:bg-yellow-900/30 dark:text-yellow-400': results.status === 'paused',
- 'bg-blue-100 text-blue-800 dark:bg-blue-900/30 dark:text-blue-400': results.status === 'completed',
- })}
+ className={cx(
+ 'inline-flex items-center rounded-full px-2 py-0.5 text-xs font-medium',
+ {
+ 'bg-gray-100 text-gray-600 dark:bg-gray-700 dark:text-gray-400':
+ results.status === 'draft',
+ 'bg-green-100 text-green-800 dark:bg-green-900/30 dark:text-green-400':
+ results.status === 'running',
+ 'bg-yellow-100 text-yellow-800 dark:bg-yellow-900/30 dark:text-yellow-400':
+ results.status === 'paused',
+ 'bg-blue-100 text-blue-800 dark:bg-blue-900/30 dark:text-blue-400':
+ results.status === 'completed',
+ },
+ )}
>
{t(`experiments.status.${results.status}`)}
</div>
{goal?.name ? (
<div className='inline-flex max-w-[240px] items-center gap-1.5 rounded-full bg-indigo-50 px-2 py-0.5 text-xs font-medium text-indigo-700 dark:bg-indigo-900/20 dark:text-indigo-300'>
<TargetIcon className='size-3.5' strokeWidth={1.5} />
- <Text as='span' size='xs' weight='medium' colour='inherit' truncate>
+ <Text
+ as='span'
+ size='xs'
+ weight='medium'
+ colour='inherit'
+ truncate
+ >
{goal.name}
</Text>
</div>
@@ -781,12 +930,18 @@ const ExperimentResults = ({
<TrophyIcon className='size-6 text-green-600 dark:text-green-400' />
</div>
<div>
- <Text weight='bold' size='lg' className='text-green-800 dark:text-green-200'>
+ <Text
+ weight='bold'
+ size='lg'
+ className='text-green-800 dark:text-green-200'
+ >
{t('experiments.winnerFound')}
</Text>
<Text size='sm' className='text-green-700 dark:text-green-300'>
{t('experiments.winnerDescription', {
- variant: results.variants.find((v) => v.key === results.winnerKey)?.name || results.winnerKey,
+ variant:
+ results.variants.find((v) => v.key === results.winnerKey)
+ ?.name || results.winnerKey,
})}
</Text>
</div>
@@ -796,10 +951,18 @@ const ExperimentResults = ({
{results.totalExposures === 0 ? (
<div className='flex items-start gap-4 rounded-lg border border-yellow-300 bg-yellow-50 p-4 dark:border-yellow-700 dark:bg-yellow-900/20'>
<div className='flex size-12 shrink-0 items-center justify-center rounded-full bg-yellow-100 dark:bg-yellow-900/40'>
- <InfoIcon className='size-6 text-yellow-700 dark:text-yellow-300' strokeWidth={1.5} />
+ <InfoIcon
+ className='size-6 text-yellow-700 dark:text-yellow-300'
+ strokeWidth={1.5}
+ />
</div>
<div className='min-w-0 flex-1'>
- <Text as='p' weight='bold' size='lg' className='text-yellow-900 dark:text-yellow-100'>
+ <Text
+ as='p'
+ weight='bold'
+ size='lg'
+ className='text-yellow-900 dark:text-yellow-100'
+ >
{t('experiments.noDataYet')}
</Text>
<Text as='p' colour='muted' size='sm' className='mt-1'>
@@ -822,7 +985,11 @@ const ExperimentResults = ({
<div className='flex flex-col gap-3 lg:flex-row'>
<div className='w-full lg:w-[65%]'>
- <WinProbabilityChart chartData={results.chart} variants={sortedVariants} timeBucket={timeBucket} />
+ <WinProbabilityChart
+ chartData={results.chart}
+ variants={sortedVariants}
+ timeBucket={timeBucket}
+ />
</div>
<div className='grid w-full grid-cols-2 gap-3 lg:w-[35%]'>
@@ -838,21 +1005,35 @@ const ExperimentResults = ({
label={t('experiments.totalConversions')}
/>
<StatCard
- icon={<FlaskConicalIcon className='text-purple-600' strokeWidth={1.5} />}
+ icon={
+ <FlaskConicalIcon
+ className='text-purple-600'
+ strokeWidth={1.5}
+ />
+ }
value={results.variants.length}
label={t('experiments.variantsCount')}
/>
<StatCard
- icon={<PercentIcon className='text-amber-600' strokeWidth={1.5} />}
+ icon={
+ <PercentIcon className='text-amber-600' strokeWidth={1.5} />
+ }
value={`${results.confidenceLevel}%`}
label={t('experiments.confidenceLevel')}
/>
</div>
</div>
- <MetricsTable variants={sortedVariants} winnerKey={results.winnerKey} hasWinner={results.hasWinner} />
+ <MetricsTable
+ variants={sortedVariants}
+ winnerKey={results.winnerKey}
+ hasWinner={results.hasWinner}
+ />
- <ExposuresTable variants={sortedVariants} totalExposures={results.totalExposures} />
+ <ExposuresTable
+ variants={sortedVariants}
+ totalExposures={results.totalExposures}
+ />
{experiment.hypothesis ? (
<CollapsibleSection title={t('experiments.hypothesisLabel')}>
diff --git a/web/app/pages/Project/tabs/Experiments/ExperimentSettingsModal.tsx b/web/app/pages/Project/tabs/Experiments/ExperimentSettingsModal.tsx
index 40bc909b1..2d1eb1197 100644
--- a/web/app/pages/Project/tabs/Experiments/ExperimentSettingsModal.tsx
+++ b/web/app/pages/Project/tabs/Experiments/ExperimentSettingsModal.tsx
@@ -1,9 +1,20 @@
-import { Dialog, DialogBackdrop, DialogPanel, DialogTitle } from '@headlessui/react'
+import {
+ Dialog,
+ DialogBackdrop,
+ DialogPanel,
+ DialogTitle,
+} from '@headlessui/react'
import { XMarkIcon } from '@heroicons/react/24/outline'
import cx from 'clsx'
import _map from 'lodash/map'
import _sum from 'lodash/sum'
-import { PlusIcon, Trash2Icon, ChevronDownIcon, TrendingUpIcon, TrendingDownIcon } from 'lucide-react'
+import {
+ PlusIcon,
+ Trash2Icon,
+ ChevronDownIcon,
+ TrendingUpIcon,
+ TrendingDownIcon,
+} from 'lucide-react'
import { useState, useEffect, useMemo, useRef } from 'react'
import { useTranslation } from 'react-i18next'
import { useFetcher } from 'react-router'
@@ -17,7 +28,11 @@ import type {
MultipleVariantHandling,
FeatureFlagMode,
} from '~/api/api.server'
-import { useExperimentProxy, useProjectGoalsProxy, useProjectFeatureFlagsProxy } from '~/hooks/useAnalyticsProxy'
+import {
+ useExperimentProxy,
+ useProjectGoalsProxy,
+ useProjectFeatureFlagsProxy,
+} from '~/hooks/useAnalyticsProxy'
import type { ProjectViewActionData } from '~/routes/projects.$id'
import Button from '~/ui/Button'
import Input from '~/ui/Input'
@@ -72,10 +87,13 @@ const ExperimentSettingsModal = ({
const [variants, setVariants] = useState<ExperimentVariant[]>(defaultVariants)
const [showAdvanced, setShowAdvanced] = useState(false)
- const [exposureTrigger, setExposureTrigger] = useState<ExposureTrigger>('feature_flag')
+ const [exposureTrigger, setExposureTrigger] =
+ useState<ExposureTrigger>('feature_flag')
const [customEventName, setCustomEventName] = useState('')
- const [multipleVariantHandling, setMultipleVariantHandling] = useState<MultipleVariantHandling>('exclude')
- const [featureFlagMode, setFeatureFlagMode] = useState<FeatureFlagMode>('create')
+ const [multipleVariantHandling, setMultipleVariantHandling] =
+ useState<MultipleVariantHandling>('exclude')
+ const [featureFlagMode, setFeatureFlagMode] =
+ useState<FeatureFlagMode>('create')
const [existingFeatureFlagId, setExistingFeatureFlagId] = useState('')
const [errors, setErrors] = useState<Record<string, string>>({})
@@ -117,10 +135,14 @@ const ExperimentSettingsModal = ({
setDescription(experiment.description || '')
setFeatureFlagKey(experiment.featureFlagKey || '')
setGoalId(experiment.goalId || '')
- setVariants(experiment.variants.length > 0 ? experiment.variants : defaultVariants)
+ setVariants(
+ experiment.variants.length > 0 ? experiment.variants : defaultVariants,
+ )
setExposureTrigger(experiment.exposureTrigger || 'feature_flag')
setCustomEventName(experiment.customEventName || '')
- setMultipleVariantHandling(experiment.multipleVariantHandling || 'exclude')
+ setMultipleVariantHandling(
+ experiment.multipleVariantHandling || 'exclude',
+ )
setFeatureFlagMode(experiment.featureFlagMode || 'create')
setExistingFeatureFlagId(experiment.featureFlagId || '')
@@ -133,7 +155,9 @@ const ExperimentSettingsModal = ({
}
} catch (error) {
console.error('Failed to load experiment:', error)
- toast.error(typeof error === 'string' ? error : t('experiments.loadError'))
+ toast.error(
+ typeof error === 'string' ? error : t('experiments.loadError'),
+ )
onClose()
} finally {
setIsLoading(false)
@@ -157,7 +181,10 @@ const ExperimentSettingsModal = ({
const loadGoals = async () => {
setGoalsLoading(true)
try {
- const result = await goalsProxy.fetchGoals(projectId, { take: 100, skip: 0 })
+ const result = await goalsProxy.fetchGoals(projectId, {
+ take: 100,
+ skip: 0,
+ })
if (result) {
setGoals(result.results)
}
@@ -177,7 +204,10 @@ const ExperimentSettingsModal = ({
const loadFeatureFlags = async () => {
setFeatureFlagsLoading(true)
try {
- const result = await featureFlagsProxy.fetchFeatureFlags(projectId, { take: 100, skip: 0 })
+ const result = await featureFlagsProxy.fetchFeatureFlags(projectId, {
+ take: 100,
+ skip: 0,
+ })
if (result) {
setFeatureFlags(result.results)
}
@@ -274,15 +304,27 @@ const ExperimentSettingsModal = ({
const effectiveFlagKey = featureFlagKey.trim() || suggestedFlagKey
const formData = new FormData()
- formData.set('intent', isEditing ? 'update-experiment' : 'create-experiment')
+ formData.set(
+ 'intent',
+ isEditing ? 'update-experiment' : 'create-experiment',
+ )
formData.set('name', name.trim())
formData.set('description', description.trim())
formData.set('exposureTrigger', exposureTrigger)
- formData.set('customEventName', exposureTrigger === 'custom_event' ? customEventName.trim() : '')
+ formData.set(
+ 'customEventName',
+ exposureTrigger === 'custom_event' ? customEventName.trim() : '',
+ )
formData.set('multipleVariantHandling', multipleVariantHandling)
formData.set('featureFlagMode', featureFlagMode)
- formData.set('featureFlagKey', featureFlagMode === 'create' ? effectiveFlagKey : '')
- formData.set('existingFeatureFlagId', featureFlagMode === 'link' ? existingFeatureFlagId : '')
+ formData.set(
+ 'featureFlagKey',
+ featureFlagMode === 'create' ? effectiveFlagKey : '',
+ )
+ formData.set(
+ 'existingFeatureFlagId',
+ featureFlagMode === 'link' ? existingFeatureFlagId : '',
+ )
formData.set('goalId', goalId)
formData.set('variants', JSON.stringify(variants))
@@ -293,7 +335,9 @@ const ExperimentSettingsModal = ({
fetcher.submit(formData, { method: 'post' })
}
- const distributePercentages = (variantsList: ExperimentVariant[]): ExperimentVariant[] => {
+ const distributePercentages = (
+ variantsList: ExperimentVariant[],
+ ): ExperimentVariant[] => {
const count = variantsList.length
const basePercentage = Math.floor(100 / count)
const remainder = 100 - basePercentage * count
@@ -335,7 +379,11 @@ const ExperimentSettingsModal = ({
}
}
- const handleVariantChange = (index: number, field: keyof ExperimentVariant, value: string | number | boolean) => {
+ const handleVariantChange = (
+ index: number,
+ field: keyof ExperimentVariant,
+ value: string | number | boolean,
+ ) => {
const newVariants = [...variants]
if (field === 'isControl' && value === true) {
newVariants.forEach((v, i) => {
@@ -398,7 +446,9 @@ const ExperimentSettingsModal = ({
<div className='px-6 pt-5 pb-4'>
<div className='flex items-center justify-between'>
<DialogTitle className='text-lg font-semibold text-gray-900 dark:text-gray-50'>
- {isEditing ? t('experiments.edit') : t('experiments.create')}
+ {isEditing
+ ? t('experiments.edit')
+ : t('experiments.create')}
</DialogTitle>
<button
type='button'
@@ -445,22 +495,41 @@ const ExperimentSettingsModal = ({
{featureFlagMode === 'create' ? (
<div>
<div className='flex items-center gap-1.5'>
- <Text as='label' size='sm' weight='medium' className='text-gray-700 dark:text-gray-200'>
+ <Text
+ as='label'
+ size='sm'
+ weight='medium'
+ className='text-gray-700 dark:text-gray-200'
+ >
{t('experiments.featureFlagKey')}
</Text>
- <Tooltip text={t('experiments.featureFlagKeyHint')} className='flex items-center' />
+ <Tooltip
+ text={t('experiments.featureFlagKeyHint')}
+ className='flex items-center'
+ />
</div>
<input
type='text'
value={featureFlagKey}
- onChange={(e) => setFeatureFlagKey(e.target.value.toLowerCase().replace(/[^a-z0-9_-]/g, '_'))}
- placeholder={suggestedFlagKey || t('experiments.featureFlagKeyPlaceholder')}
+ onChange={(e) =>
+ setFeatureFlagKey(
+ e.target.value
+ .toLowerCase()
+ .replace(/[^a-z0-9_-]/g, '_'),
+ )
+ }
+ placeholder={
+ suggestedFlagKey ||
+ t('experiments.featureFlagKeyPlaceholder')
+ }
className='mt-1 w-full rounded-md border border-gray-300 bg-white px-3 py-2 font-mono text-sm text-gray-900 placeholder-gray-400 focus:border-indigo-500 focus:ring-1 focus:ring-indigo-500 focus:outline-none dark:border-slate-600 dark:bg-slate-800 dark:text-gray-100'
/>
{!featureFlagKey && suggestedFlagKey ? (
<Text size='xs' colour='muted' className='mt-1'>
Will use:{' '}
- <code className='rounded bg-gray-100 px-1 dark:bg-slate-700'>{suggestedFlagKey}</code>
+ <code className='rounded bg-gray-100 px-1 dark:bg-slate-700'>
+ {suggestedFlagKey}
+ </code>
</Text>
) : null}
</div>
@@ -469,7 +538,12 @@ const ExperimentSettingsModal = ({
<div>
<div className='mb-2 flex items-center justify-between'>
<div className='flex items-center gap-1.5'>
- <Text as='label' size='sm' weight='medium' className='text-gray-700 dark:text-gray-200'>
+ <Text
+ as='label'
+ size='sm'
+ weight='medium'
+ className='text-gray-700 dark:text-gray-200'
+ >
{t('experiments.variants')}
</Text>
<Tooltip
@@ -518,7 +592,13 @@ const ExperimentSettingsModal = ({
<input
type='text'
value={variant.name}
- onChange={(e) => handleVariantChange(index, 'name', e.target.value)}
+ onChange={(e) =>
+ handleVariantChange(
+ index,
+ 'name',
+ e.target.value,
+ )
+ }
placeholder='Name'
className='w-32 rounded-md border border-gray-300 bg-white px-2.5 py-1.5 text-sm dark:border-slate-600 dark:bg-slate-700'
/>
@@ -529,7 +609,9 @@ const ExperimentSettingsModal = ({
handleVariantChange(
index,
'key',
- e.target.value.toLowerCase().replace(/[^a-z0-9_]/g, '_'),
+ e.target.value
+ .toLowerCase()
+ .replace(/[^a-z0-9_]/g, '_'),
)
}
placeholder='key'
@@ -543,9 +625,16 @@ const ExperimentSettingsModal = ({
inputMode='numeric'
value={variant.rolloutPercentage}
onChange={(e) => {
- const val = e.target.value.replace(/[^0-9]/g, '')
+ const val = e.target.value.replace(
+ /[^0-9]/g,
+ '',
+ )
const num = parseInt(val, 10) || 0
- handleVariantChange(index, 'rolloutPercentage', Math.min(100, num))
+ handleVariantChange(
+ index,
+ 'rolloutPercentage',
+ Math.min(100, num),
+ )
}}
className='w-12 rounded-md border border-gray-300 bg-white px-2 py-1.5 text-center text-sm dark:border-slate-600 dark:bg-slate-700'
/>
@@ -559,7 +648,9 @@ const ExperimentSettingsModal = ({
type='radio'
name='controlVariant'
checked={variant.isControl}
- onChange={() => handleVariantChange(index, 'isControl', true)}
+ onChange={() =>
+ handleVariantChange(index, 'isControl', true)
+ }
className='size-3.5 text-indigo-600'
/>
<Text size='xs' colour='muted'>
@@ -593,7 +684,9 @@ const ExperimentSettingsModal = ({
size='sm'
weight='medium'
className={
- isPercentageValid ? 'text-green-600 dark:text-green-400' : 'text-red-600 dark:text-red-400'
+ isPercentageValid
+ ? 'text-green-600 dark:text-green-400'
+ : 'text-red-600 dark:text-red-400'
}
>
{totalPercentage}%
@@ -603,7 +696,12 @@ const ExperimentSettingsModal = ({
<div>
<div className='flex items-center gap-1.5'>
- <Text as='label' size='sm' weight='medium' className='text-gray-700 dark:text-gray-200'>
+ <Text
+ as='label'
+ size='sm'
+ weight='medium'
+ className='text-gray-700 dark:text-gray-200'
+ >
{t('experiments.goal')}
</Text>
<Tooltip
@@ -622,8 +720,13 @@ const ExperimentSettingsModal = ({
keyExtractor={(item) => item.value}
labelExtractor={(item) => item.label}
onSelect={(item) => setGoalId(item.value)}
- selectedItem={goalOptions.find((g) => g.value === goalId)}
- title={goalOptions.find((g) => g.value === goalId)?.label || t('experiments.noGoal')}
+ selectedItem={goalOptions.find(
+ (g) => g.value === goalId,
+ )}
+ title={
+ goalOptions.find((g) => g.value === goalId)
+ ?.label || t('experiments.noGoal')
+ }
capitalise
/>
</div>
@@ -682,7 +785,10 @@ const ExperimentSettingsModal = ({
Advanced settings
</Text>
<ChevronDownIcon
- className={cx('size-4 text-gray-400 transition-transform', showAdvanced && 'rotate-180')}
+ className={cx(
+ 'size-4 text-gray-400 transition-transform',
+ showAdvanced && 'rotate-180',
+ )}
/>
</button>
@@ -690,7 +796,12 @@ const ExperimentSettingsModal = ({
<div className='mt-4 space-y-4'>
<div>
<div className='flex items-center gap-1.5'>
- <Text as='label' size='sm' weight='medium' className='text-gray-700 dark:text-gray-200'>
+ <Text
+ as='label'
+ size='sm'
+ weight='medium'
+ className='text-gray-700 dark:text-gray-200'
+ >
Feature flag source
</Text>
<Tooltip
@@ -733,11 +844,16 @@ const ExperimentSettingsModal = ({
items={featureFlagOptions}
keyExtractor={(item) => item.value}
labelExtractor={(item) => item.label}
- onSelect={(item) => setExistingFeatureFlagId(item.value)}
- selectedItem={featureFlagOptions.find((f) => f.value === existingFeatureFlagId)}
+ onSelect={(item) =>
+ setExistingFeatureFlagId(item.value)
+ }
+ selectedItem={featureFlagOptions.find(
+ (f) => f.value === existingFeatureFlagId,
+ )}
title={
- featureFlagOptions.find((f) => f.value === existingFeatureFlagId)?.label ||
- t('experiments.selectFeatureFlag')
+ featureFlagOptions.find(
+ (f) => f.value === existingFeatureFlagId,
+ )?.label || t('experiments.selectFeatureFlag')
}
/>
{featureFlagsLoading ? (
@@ -755,7 +871,12 @@ const ExperimentSettingsModal = ({
<div>
<div className='flex items-center gap-1.5'>
- <Text as='label' size='sm' weight='medium' className='text-gray-700 dark:text-gray-200'>
+ <Text
+ as='label'
+ size='sm'
+ weight='medium'
+ className='text-gray-700 dark:text-gray-200'
+ >
Exposure tracking
</Text>
<Tooltip
@@ -766,7 +887,9 @@ const ExperimentSettingsModal = ({
<div className='mt-1.5 flex gap-2'>
<button
type='button'
- onClick={() => setExposureTrigger('feature_flag')}
+ onClick={() =>
+ setExposureTrigger('feature_flag')
+ }
className={cx(
'flex-1 rounded-md border px-3 py-2 text-sm transition-colors',
exposureTrigger === 'feature_flag'
@@ -778,7 +901,9 @@ const ExperimentSettingsModal = ({
</button>
<button
type='button'
- onClick={() => setExposureTrigger('custom_event')}
+ onClick={() =>
+ setExposureTrigger('custom_event')
+ }
className={cx(
'flex-1 rounded-md border px-3 py-2 text-sm transition-colors',
exposureTrigger === 'custom_event'
@@ -794,8 +919,12 @@ const ExperimentSettingsModal = ({
<Input
className='mt-2'
value={customEventName}
- onChange={(e) => setCustomEventName(e.target.value)}
- placeholder={t('experiments.exposureTrigger.eventNamePlaceholder')}
+ onChange={(e) =>
+ setCustomEventName(e.target.value)
+ }
+ placeholder={t(
+ 'experiments.exposureTrigger.eventNamePlaceholder',
+ )}
error={errors.customEvent}
/>
) : null}
@@ -803,18 +932,28 @@ const ExperimentSettingsModal = ({
<div>
<div className='flex items-center gap-1.5'>
- <Text as='label' size='sm' weight='medium' className='text-gray-700 dark:text-gray-200'>
+ <Text
+ as='label'
+ size='sm'
+ weight='medium'
+ className='text-gray-700 dark:text-gray-200'
+ >
Multi-exposure handling
</Text>
<Tooltip
text={
<div>
- <p className='font-medium'>What happens if a user sees multiple variants?</p>
+ <p className='font-medium'>
+ What happens if a user sees multiple
+ variants?
+ </p>
<p className='mt-1'>
- <strong>Exclude:</strong> Remove them from analysis (recommended)
+ <strong>Exclude:</strong> Remove them from
+ analysis (recommended)
</p>
<p className='mt-0.5'>
- <strong>First exposure:</strong> Only count their first variant
+ <strong>First exposure:</strong> Only
+ count their first variant
</p>
</div>
}
@@ -824,7 +963,9 @@ const ExperimentSettingsModal = ({
<div className='mt-1.5 flex gap-2'>
<button
type='button'
- onClick={() => setMultipleVariantHandling('exclude')}
+ onClick={() =>
+ setMultipleVariantHandling('exclude')
+ }
className={cx(
'flex-1 rounded-md border px-3 py-2 text-sm transition-colors',
multipleVariantHandling === 'exclude'
@@ -836,7 +977,9 @@ const ExperimentSettingsModal = ({
</button>
<button
type='button'
- onClick={() => setMultipleVariantHandling('first_exposure')}
+ onClick={() =>
+ setMultipleVariantHandling('first_exposure')
+ }
className={cx(
'flex-1 rounded-md border px-3 py-2 text-sm transition-colors',
multipleVariantHandling === 'first_exposure'
diff --git a/web/app/pages/Project/tabs/Experiments/ExperimentsView.tsx b/web/app/pages/Project/tabs/Experiments/ExperimentsView.tsx
index dbdb16adb..7763888c7 100644
--- a/web/app/pages/Project/tabs/Experiments/ExperimentsView.tsx
+++ b/web/app/pages/Project/tabs/Experiments/ExperimentsView.tsx
@@ -21,7 +21,10 @@ import { useSearchParams, useFetcher } from 'react-router'
import { toast } from 'sonner'
import DashboardHeader from '~/pages/Project/View/components/DashboardHeader'
-import { useViewProjectContext, useRefreshTriggers } from '~/pages/Project/View/ViewProject'
+import {
+ useViewProjectContext,
+ useRefreshTriggers,
+} from '~/pages/Project/View/ViewProject'
import { useCurrentProject } from '~/providers/CurrentProjectProvider'
import type { ProjectViewActionData } from '~/routes/projects.$id'
import Button from '~/ui/Button'
@@ -40,10 +43,22 @@ import ExperimentSettingsModal from './ExperimentSettingsModal'
dayjs.extend(relativeTime)
const STATUS_COLORS: Record<ExperimentStatus, { bg: string; text: string }> = {
- draft: { bg: 'bg-gray-100 dark:bg-gray-700', text: 'text-gray-600 dark:text-gray-400' },
- running: { bg: 'bg-green-100 dark:bg-green-900/30', text: 'text-green-800 dark:text-green-400' },
- paused: { bg: 'bg-yellow-100 dark:bg-yellow-900/30', text: 'text-yellow-800 dark:text-yellow-400' },
- completed: { bg: 'bg-blue-100 dark:bg-blue-900/30', text: 'text-blue-800 dark:text-blue-400' },
+ draft: {
+ bg: 'bg-gray-100 dark:bg-gray-700',
+ text: 'text-gray-600 dark:text-gray-400',
+ },
+ running: {
+ bg: 'bg-green-100 dark:bg-green-900/30',
+ text: 'text-green-800 dark:text-green-400',
+ },
+ paused: {
+ bg: 'bg-yellow-100 dark:bg-yellow-900/30',
+ text: 'text-yellow-800 dark:text-yellow-400',
+ },
+ completed: {
+ bg: 'bg-blue-100 dark:bg-blue-900/30',
+ text: 'text-blue-800 dark:text-blue-400',
+ },
}
const DEFAULT_EXPERIMENTS_TAKE = 20
@@ -114,7 +129,8 @@ const ExperimentRow = ({
const statusColors = STATUS_COLORS[experiment.status]
const variantsCount = experiment.variants?.length || 0
- const isEditDisabled = experiment.status === 'running' || experiment.status === 'completed'
+ const isEditDisabled =
+ experiment.status === 'running' || experiment.status === 'completed'
const handleStart = async () => {
setActionLoading(true)
@@ -151,8 +167,16 @@ const ExperimentRow = ({
<div className='flex min-w-0 gap-x-4'>
<div className='min-w-0 flex-auto'>
<div className='flex items-center gap-x-2'>
- <Text as='p' weight='semibold' truncate className='flex items-center gap-x-1.5'>
- <FlaskConicalIcon className='size-4 text-purple-500' strokeWidth={1.5} />
+ <Text
+ as='p'
+ weight='semibold'
+ truncate
+ className='flex items-center gap-x-1.5'
+ >
+ <FlaskConicalIcon
+ className='size-4 text-purple-500'
+ strokeWidth={1.5}
+ />
<span>{experiment.name}</span>
</Text>
{/* Status badge */}
@@ -184,12 +208,14 @@ const ExperimentRow = ({
<div className='mt-2 flex items-center gap-x-3 text-xs text-gray-500 dark:text-gray-400'>
{experiment.startedAt ? (
<span>
- {t('experiments.startedAt')}: {dayjs(experiment.startedAt).format('MMM D, YYYY')}
+ {t('experiments.startedAt')}:{' '}
+ {dayjs(experiment.startedAt).format('MMM D, YYYY')}
</span>
) : null}
{experiment.endedAt ? (
<span>
- {t('experiments.endedAt')}: {dayjs(experiment.endedAt).format('MMM D, YYYY')}
+ {t('experiments.endedAt')}:{' '}
+ {dayjs(experiment.endedAt).format('MMM D, YYYY')}
</span>
) : null}
</div>
@@ -201,17 +227,28 @@ const ExperimentRow = ({
<Button
onClick={handleStart}
disabled={actionLoading || !experiment.goalId}
- title={!experiment.goalId ? t('experiments.needGoal') : undefined}
+ title={
+ !experiment.goalId ? t('experiments.needGoal') : undefined
+ }
ghost
small
>
- {actionLoading ? <Spin className='size-4' /> : <PlayIcon className='mr-1 size-4' strokeWidth={1.5} />}
+ {actionLoading ? (
+ <Spin className='size-4' />
+ ) : (
+ <PlayIcon className='mr-1 size-4' strokeWidth={1.5} />
+ )}
{t('experiments.start')}
</Button>
) : null}
{experiment.status === 'running' ? (
<>
- <Button onClick={handlePause} disabled={actionLoading} ghost small>
+ <Button
+ onClick={handlePause}
+ disabled={actionLoading}
+ ghost
+ small
+ >
{actionLoading ? (
<Spin className='size-4' />
) : (
@@ -219,7 +256,11 @@ const ExperimentRow = ({
)}
{t('experiments.pause')}
</Button>
- <Button onClick={() => onViewResults(experiment.id)} ghost small>
+ <Button
+ onClick={() => onViewResults(experiment.id)}
+ ghost
+ small
+ >
<BarChart3Icon className='mr-1 size-4' strokeWidth={1.5} />
{t('experiments.results')}
</Button>
@@ -227,11 +268,25 @@ const ExperimentRow = ({
) : null}
{experiment.status === 'paused' ? (
<>
- <Button onClick={handleStart} disabled={actionLoading} ghost small>
- {actionLoading ? <Spin className='size-4' /> : <PlayIcon className='mr-1 size-4' strokeWidth={1.5} />}
+ <Button
+ onClick={handleStart}
+ disabled={actionLoading}
+ ghost
+ small
+ >
+ {actionLoading ? (
+ <Spin className='size-4' />
+ ) : (
+ <PlayIcon className='mr-1 size-4' strokeWidth={1.5} />
+ )}
{t('experiments.resume')}
</Button>
- <Button onClick={() => setShowCompleteModal(true)} disabled={actionLoading} ghost small>
+ <Button
+ onClick={() => setShowCompleteModal(true)}
+ disabled={actionLoading}
+ ghost
+ small
+ >
<CheckCircleIcon className='mr-1 size-4' strokeWidth={1.5} />
{t('experiments.complete')}
</Button>
@@ -248,7 +303,9 @@ const ExperimentRow = ({
<div className='flex items-center gap-1 border-l border-gray-200 pl-2 dark:border-slate-700'>
<button
type='button'
- onClick={() => (!isEditDisabled ? onEdit(experiment.id) : undefined)}
+ onClick={() =>
+ !isEditDisabled ? onEdit(experiment.id) : undefined
+ }
disabled={isEditDisabled}
aria-label={t('common.edit')}
title={
@@ -260,7 +317,8 @@ const ExperimentRow = ({
}
className={cx(
'rounded-md border border-transparent p-1.5 text-gray-800 transition-colors hover:border-gray-300 hover:bg-gray-50 hover:text-gray-900 dark:text-slate-400 hover:dark:border-slate-700/80 dark:hover:bg-slate-800 dark:hover:text-slate-300',
- isEditDisabled && 'cursor-not-allowed opacity-50 hover:border-transparent hover:bg-transparent',
+ isEditDisabled &&
+ 'cursor-not-allowed opacity-50 hover:border-transparent hover:bg-transparent',
)}
>
<PencilIcon className='size-4' strokeWidth={1.5} />
@@ -317,7 +375,12 @@ interface ExperimentsViewProps {
timezone?: string
}
-const ExperimentsView = ({ period, from = '', to = '', timezone }: ExperimentsViewProps) => {
+const ExperimentsView = ({
+ period,
+ from = '',
+ to = '',
+ timezone,
+}: ExperimentsViewProps) => {
const { id } = useCurrentProject()
const { experimentsRefreshTrigger } = useRefreshTriggers()
const { timeBucket } = useViewProjectContext()
@@ -338,12 +401,15 @@ const ExperimentsView = ({ period, from = '', to = '', timezone }: ExperimentsVi
// Modal state
const [isModalOpen, setIsModalOpen] = useState(false)
- const [editingExperimentId, setEditingExperimentId] = useState<string | null>(null)
+ const [editingExperimentId, setEditingExperimentId] = useState<string | null>(
+ null,
+ )
// Results view state
const [viewingResultsId, setViewingResultsId] = useState<string | null>(null)
const [resultsRefreshTrigger, setResultsRefreshTrigger] = useState(0)
- const [shouldRefreshListOnReturn, setShouldRefreshListOnReturn] = useState(false)
+ const [shouldRefreshListOnReturn, setShouldRefreshListOnReturn] =
+ useState(false)
// Cleanup on unmount
useEffect(() => {
@@ -381,7 +447,10 @@ const ExperimentsView = ({ period, from = '', to = '', timezone }: ExperimentsVi
if (isMountedRef.current) {
setIsLoading(false)
if (listFetcher.data.success && listFetcher.data.data) {
- const result = listFetcher.data.data as { results: Experiment[]; total: number }
+ const result = listFetcher.data.data as {
+ results: Experiment[]
+ total: number
+ }
setExperiments(result.results)
setTotal(result.total)
setError(null)
@@ -398,7 +467,8 @@ const ExperimentsView = ({ period, from = '', to = '', timezone }: ExperimentsVi
const { intent, success, error, data } = actionFetcher.data
const responseData = actionFetcher.data as Record<string, unknown>
- const uniqueSuffix = responseData.requestId ?? responseData.timestamp ?? actionFetcher.state
+ const uniqueSuffix =
+ responseData.requestId ?? responseData.timestamp ?? actionFetcher.state
const actionKey = `${intent}-${success ?? false}-${error ?? ''}-${uniqueSuffix}-${JSON.stringify(data)}`
if (processedActionRef.current === actionKey) return
processedActionRef.current = actionKey
@@ -406,33 +476,60 @@ const ExperimentsView = ({ period, from = '', to = '', timezone }: ExperimentsVi
if (actionFetcher.data.intent === 'delete-experiment') {
if (actionFetcher.data.success) {
toast.success(t('experiments.deleted'))
- loadExperiments(DEFAULT_EXPERIMENTS_TAKE, (page - 1) * DEFAULT_EXPERIMENTS_TAKE, true, filterQuery || undefined)
+ loadExperiments(
+ DEFAULT_EXPERIMENTS_TAKE,
+ (page - 1) * DEFAULT_EXPERIMENTS_TAKE,
+ true,
+ filterQuery || undefined,
+ )
} else if (actionFetcher.data.error) {
toast.error(actionFetcher.data.error)
}
} else if (actionFetcher.data.intent === 'start-experiment') {
if (actionFetcher.data.success) {
toast.success(t('experiments.started'))
- loadExperiments(DEFAULT_EXPERIMENTS_TAKE, (page - 1) * DEFAULT_EXPERIMENTS_TAKE, true, filterQuery || undefined)
+ loadExperiments(
+ DEFAULT_EXPERIMENTS_TAKE,
+ (page - 1) * DEFAULT_EXPERIMENTS_TAKE,
+ true,
+ filterQuery || undefined,
+ )
} else if (actionFetcher.data.error) {
toast.error(actionFetcher.data.error)
}
} else if (actionFetcher.data.intent === 'pause-experiment') {
if (actionFetcher.data.success) {
toast.success(t('experiments.paused'))
- loadExperiments(DEFAULT_EXPERIMENTS_TAKE, (page - 1) * DEFAULT_EXPERIMENTS_TAKE, true, filterQuery || undefined)
+ loadExperiments(
+ DEFAULT_EXPERIMENTS_TAKE,
+ (page - 1) * DEFAULT_EXPERIMENTS_TAKE,
+ true,
+ filterQuery || undefined,
+ )
} else if (actionFetcher.data.error) {
toast.error(actionFetcher.data.error)
}
} else if (actionFetcher.data.intent === 'complete-experiment') {
if (actionFetcher.data.success) {
toast.success(t('experiments.completed'))
- loadExperiments(DEFAULT_EXPERIMENTS_TAKE, (page - 1) * DEFAULT_EXPERIMENTS_TAKE, true, filterQuery || undefined)
+ loadExperiments(
+ DEFAULT_EXPERIMENTS_TAKE,
+ (page - 1) * DEFAULT_EXPERIMENTS_TAKE,
+ true,
+ filterQuery || undefined,
+ )
} else if (actionFetcher.data.error) {
toast.error(actionFetcher.data.error)
}
}
- }, [actionFetcher.data, actionFetcher.state, t, loadExperiments, page, filterQuery])
+ }, [
+ actionFetcher.data,
+ actionFetcher.state,
+ t,
+ loadExperiments,
+ page,
+ filterQuery,
+ ])
const debouncedLoadExperiments = useMemo(
() =>
@@ -459,7 +556,12 @@ const ExperimentsView = ({ period, from = '', to = '', timezone }: ExperimentsVi
}, [debouncedLoadExperiments])
useEffect(() => {
- loadExperiments(DEFAULT_EXPERIMENTS_TAKE, (page - 1) * DEFAULT_EXPERIMENTS_TAKE, true, filterQuery || undefined)
+ loadExperiments(
+ DEFAULT_EXPERIMENTS_TAKE,
+ (page - 1) * DEFAULT_EXPERIMENTS_TAKE,
+ true,
+ filterQuery || undefined,
+ )
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [page])
@@ -470,7 +572,12 @@ const ExperimentsView = ({ period, from = '', to = '', timezone }: ExperimentsVi
setShouldRefreshListOnReturn(true)
return
}
- loadExperiments(DEFAULT_EXPERIMENTS_TAKE, (page - 1) * DEFAULT_EXPERIMENTS_TAKE, true, filterQuery || undefined)
+ loadExperiments(
+ DEFAULT_EXPERIMENTS_TAKE,
+ (page - 1) * DEFAULT_EXPERIMENTS_TAKE,
+ true,
+ filterQuery || undefined,
+ )
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [experimentsRefreshTrigger, viewingResultsId, page])
@@ -478,7 +585,12 @@ const ExperimentsView = ({ period, from = '', to = '', timezone }: ExperimentsVi
useEffect(() => {
if (!viewingResultsId && shouldRefreshListOnReturn) {
setShouldRefreshListOnReturn(false)
- loadExperiments(DEFAULT_EXPERIMENTS_TAKE, (page - 1) * DEFAULT_EXPERIMENTS_TAKE, true, filterQuery || undefined)
+ loadExperiments(
+ DEFAULT_EXPERIMENTS_TAKE,
+ (page - 1) * DEFAULT_EXPERIMENTS_TAKE,
+ true,
+ filterQuery || undefined,
+ )
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [viewingResultsId, shouldRefreshListOnReturn, page])
@@ -499,13 +611,21 @@ const ExperimentsView = ({ period, from = '', to = '', timezone }: ExperimentsVi
}, [])
const handleModalSuccess = useCallback(() => {
- loadExperiments(DEFAULT_EXPERIMENTS_TAKE, (page - 1) * DEFAULT_EXPERIMENTS_TAKE, true, filterQuery || undefined)
+ loadExperiments(
+ DEFAULT_EXPERIMENTS_TAKE,
+ (page - 1) * DEFAULT_EXPERIMENTS_TAKE,
+ true,
+ filterQuery || undefined,
+ )
}, [page, filterQuery, loadExperiments])
const handleDeleteExperiment = useCallback(
(experimentId: string) => {
processedActionRef.current = null
- actionFetcher.submit({ intent: 'delete-experiment', experimentId }, { method: 'POST' })
+ actionFetcher.submit(
+ { intent: 'delete-experiment', experimentId },
+ { method: 'POST' },
+ )
},
[actionFetcher],
)
@@ -513,7 +633,10 @@ const ExperimentsView = ({ period, from = '', to = '', timezone }: ExperimentsVi
const handleStartExperiment = useCallback(
(experimentId: string) => {
processedActionRef.current = null
- actionFetcher.submit({ intent: 'start-experiment', experimentId }, { method: 'POST' })
+ actionFetcher.submit(
+ { intent: 'start-experiment', experimentId },
+ { method: 'POST' },
+ )
},
[actionFetcher],
)
@@ -521,7 +644,10 @@ const ExperimentsView = ({ period, from = '', to = '', timezone }: ExperimentsVi
const handlePauseExperiment = useCallback(
(experimentId: string) => {
processedActionRef.current = null
- actionFetcher.submit({ intent: 'pause-experiment', experimentId }, { method: 'POST' })
+ actionFetcher.submit(
+ { intent: 'pause-experiment', experimentId },
+ { method: 'POST' },
+ )
},
[actionFetcher],
)
@@ -529,7 +655,10 @@ const ExperimentsView = ({ period, from = '', to = '', timezone }: ExperimentsVi
const handleCompleteExperiment = useCallback(
(experimentId: string) => {
processedActionRef.current = null
- actionFetcher.submit({ intent: 'complete-experiment', experimentId }, { method: 'POST' })
+ actionFetcher.submit(
+ { intent: 'complete-experiment', experimentId },
+ { method: 'POST' },
+ )
},
[actionFetcher],
)
@@ -545,7 +674,11 @@ const ExperimentsView = ({ period, from = '', to = '', timezone }: ExperimentsVi
title={t('apiNotifications.somethingWentWrong')}
description={t('apiNotifications.errorCode', { error })}
actions={[
- { label: t('dashboard.reloadPage'), onClick: () => window.location.reload(), primary: true },
+ {
+ label: t('dashboard.reloadPage'),
+ onClick: () => window.location.reload(),
+ primary: true,
+ },
{ label: t('notFoundPage.support'), to: routes.contact },
]}
/>
@@ -591,7 +724,9 @@ const ExperimentsView = ({ period, from = '', to = '', timezone }: ExperimentsVi
<FlaskConicalIcon className='mr-2 h-8 w-8' strokeWidth={1.5} />
<p className='text-3xl font-bold'>{t('experiments.title')}</p>
</div>
- <p className='mt-2 text-sm whitespace-pre-wrap text-gray-100'>{t('experiments.description')}</p>
+ <p className='mt-2 text-sm whitespace-pre-wrap text-gray-100'>
+ {t('experiments.description')}
+ </p>
<Button
onClick={handleNewExperiment}
className='mt-6 block max-w-max rounded-md border border-transparent bg-white px-3 py-2 text-sm font-medium text-gray-700 hover:bg-indigo-50 md:px-4'
diff --git a/web/app/pages/Project/tabs/FeatureFlags/FeatureFlagSettingsModal.tsx b/web/app/pages/Project/tabs/FeatureFlags/FeatureFlagSettingsModal.tsx
index a8e60ebf1..7128eeb81 100644
--- a/web/app/pages/Project/tabs/FeatureFlags/FeatureFlagSettingsModal.tsx
+++ b/web/app/pages/Project/tabs/FeatureFlags/FeatureFlagSettingsModal.tsx
@@ -9,10 +9,21 @@ import {
ListboxOptions,
Transition,
} from '@headlessui/react'
-import { XMarkIcon, ClipboardIcon, CheckIcon as HeroCheckIcon } from '@heroicons/react/24/outline'
+import {
+ XMarkIcon,
+ ClipboardIcon,
+ CheckIcon as HeroCheckIcon,
+} from '@heroicons/react/24/outline'
import cx from 'clsx'
import _map from 'lodash/map'
-import { Trash2Icon, PlusIcon, CodeIcon, ChevronDownIcon, ChevronsUpDownIcon, CheckIcon } from 'lucide-react'
+import {
+ Trash2Icon,
+ PlusIcon,
+ CodeIcon,
+ ChevronDownIcon,
+ ChevronsUpDownIcon,
+ CheckIcon,
+} from 'lucide-react'
import { useState, useEffect, useCallback, Fragment, useRef } from 'react'
import { useTranslation } from 'react-i18next'
import { useFetcher } from 'react-router'
@@ -53,7 +64,13 @@ interface FeatureFlagSettingsModalProps {
flagId?: string | null
}
-const FeatureFlagSettingsModal = ({ isOpen, onClose, onSuccess, projectId, flagId }: FeatureFlagSettingsModalProps) => {
+const FeatureFlagSettingsModal = ({
+ isOpen,
+ onClose,
+ onSuccess,
+ projectId,
+ flagId,
+}: FeatureFlagSettingsModalProps) => {
const {
t,
i18n: { language },
@@ -69,7 +86,9 @@ const FeatureFlagSettingsModal = ({ isOpen, onClose, onSuccess, projectId, flagI
const [copiedCode, setCopiedCode] = useState<string | null>(null)
// Filter values cache for targeting rules
- const [filterValuesCache, setFilterValuesCache] = useState<Record<string, string[]>>({})
+ const [filterValuesCache, setFilterValuesCache] = useState<
+ Record<string, string[]>
+ >({})
const [loadingColumns, setLoadingColumns] = useState<Set<string>>(new Set())
// Form state
@@ -199,8 +218,12 @@ const FeatureFlagSettingsModal = ({ isOpen, onClose, onSuccess, projectId, flagI
key,
description: description || '',
flagType,
- rolloutPercentage: String(flagType === 'rollout' ? rolloutPercentage : 100),
- targetingRules: JSON.stringify(targetingRules.length > 0 ? targetingRules : []),
+ rolloutPercentage: String(
+ flagType === 'rollout' ? rolloutPercentage : 100,
+ ),
+ targetingRules: JSON.stringify(
+ targetingRules.length > 0 ? targetingRules : [],
+ ),
enabled: String(enabled),
},
{ method: 'POST' },
@@ -213,8 +236,12 @@ const FeatureFlagSettingsModal = ({ isOpen, onClose, onSuccess, projectId, flagI
key,
description: description || '',
flagType,
- rolloutPercentage: String(flagType === 'rollout' ? rolloutPercentage : 100),
- targetingRules: JSON.stringify(targetingRules.length > 0 ? targetingRules : []),
+ rolloutPercentage: String(
+ flagType === 'rollout' ? rolloutPercentage : 100,
+ ),
+ targetingRules: JSON.stringify(
+ targetingRules.length > 0 ? targetingRules : [],
+ ),
enabled: String(enabled),
},
{ method: 'POST' },
@@ -223,17 +250,32 @@ const FeatureFlagSettingsModal = ({ isOpen, onClose, onSuccess, projectId, flagI
}
const addTargetingRule = () => {
- setTargetingRules([...targetingRules, { column: 'cc', filter: '', isExclusive: false }])
+ setTargetingRules([
+ ...targetingRules,
+ { column: 'cc', filter: '', isExclusive: false },
+ ])
}
- const updateTargetingRule = (index: number, field: keyof TargetingRule, value: string | boolean) => {
+ const updateTargetingRule = (
+ index: number,
+ field: keyof TargetingRule,
+ value: string | boolean,
+ ) => {
const updated = [...targetingRules]
if (field === 'column') {
// Reset filter value when column changes
- updated[index] = { ...updated[index], column: value as string, filter: '' }
+ updated[index] = {
+ ...updated[index],
+ column: value as string,
+ filter: '',
+ }
// Fetch filter values for the new column if not already cached
const cacheKey = `${projectId}-${value as string}`
- if (value && !filterValuesCache[cacheKey] && !loadingColumns.has(value as string)) {
+ if (
+ value &&
+ !filterValuesCache[cacheKey] &&
+ !loadingColumns.has(value as string)
+ ) {
fetchFilterValues(value as string)
}
} else {
@@ -322,7 +364,9 @@ const { flags } = await response.json()
<div className='max-h-[70vh] overflow-y-auto px-6 pt-5 pb-4'>
<div className='flex items-center justify-between'>
<DialogTitle className='text-lg font-semibold text-gray-900 dark:text-gray-50'>
- {isNew ? t('featureFlags.createTitle') : t('featureFlags.editTitle')}
+ {isNew
+ ? t('featureFlags.createTitle')
+ : t('featureFlags.editTitle')}
</DialogTitle>
<button
type='button'
@@ -362,11 +406,18 @@ const { flags } = await response.json()
</label>
<Select
items={FLAG_TYPES}
- onSelect={(item) => setFlagType(item.value as 'boolean' | 'rollout')}
- title={FLAG_TYPES.find((t) => t.value === flagType)?.label || ''}
+ onSelect={(item) =>
+ setFlagType(item.value as 'boolean' | 'rollout')
+ }
+ title={
+ FLAG_TYPES.find((t) => t.value === flagType)?.label ||
+ ''
+ }
labelExtractor={(item) => item.label}
keyExtractor={(item) => item.value}
- selectedItem={FLAG_TYPES.find((t) => t.value === flagType)}
+ selectedItem={FLAG_TYPES.find(
+ (t) => t.value === flagType,
+ )}
capitalise
/>
</div>
@@ -374,14 +425,17 @@ const { flags } = await response.json()
{flagType === 'rollout' ? (
<div>
<label className='mb-1 block text-sm font-medium text-gray-700 dark:text-gray-300'>
- {t('featureFlags.rolloutPercentage')} ({rolloutPercentage}%)
+ {t('featureFlags.rolloutPercentage')} (
+ {rolloutPercentage}%)
</label>
<input
type='range'
min='0'
max='100'
value={rolloutPercentage}
- onChange={(e) => setRolloutPercentage(Number(e.target.value))}
+ onChange={(e) =>
+ setRolloutPercentage(Number(e.target.value))
+ }
className='w-full'
/>
<div className='mt-1 flex justify-between text-xs text-gray-500'>
@@ -410,19 +464,27 @@ const { flags } = await response.json()
{targetingRules.length > 0 ? (
<div className='space-y-3'>
{_map(targetingRules, (rule, index) => (
- <div key={index} className='flex items-center gap-2'>
+ <div
+ key={index}
+ className='flex items-center gap-2'
+ >
{/* Column Select */}
<Listbox
value={rule.column}
- onChange={(value) => updateTargetingRule(index, 'column', value)}
+ onChange={(value) =>
+ updateTargetingRule(index, 'column', value)
+ }
>
{({ open }) => (
<div className='relative w-36'>
<ListboxButton className='relative w-full rounded-md border border-gray-300 bg-white py-2 pr-8 pl-3 text-left text-sm transition-colors hover:bg-gray-50 focus:ring-2 focus:ring-indigo-500 focus:ring-offset-1 focus:outline-hidden dark:border-gray-700 dark:bg-slate-800 dark:text-gray-50 dark:hover:bg-slate-700'>
<span className='flex items-center gap-2 truncate'>
- {rule.column ? filterCategoryIcons[rule.column] : null}
- {TARGETING_COLUMNS.find((c) => c.value === rule.column)?.label ||
- t('common.select')}
+ {rule.column
+ ? filterCategoryIcons[rule.column]
+ : null}
+ {TARGETING_COLUMNS.find(
+ (c) => c.value === rule.column,
+ )?.label || t('common.select')}
</span>
<span className='pointer-events-none absolute inset-y-0 right-0 flex items-center pr-2'>
<ChevronsUpDownIcon className='h-4 w-4 text-gray-400' />
@@ -447,20 +509,34 @@ const { flags } = await response.json()
key={col.value}
value={col.value}
className={({ focus }) =>
- cx('relative cursor-pointer py-2 pr-4 pl-3 select-none', {
- 'bg-gray-100 dark:bg-slate-700': focus,
- 'text-gray-700 dark:text-gray-50': !focus,
- })
+ cx(
+ 'relative cursor-pointer py-2 pr-4 pl-3 select-none',
+ {
+ 'bg-gray-100 dark:bg-slate-700':
+ focus,
+ 'text-gray-700 dark:text-gray-50':
+ !focus,
+ },
+ )
}
>
{({ selected }) => (
<span
- className={cx('flex items-center gap-2', { 'font-medium': selected })}
+ className={cx(
+ 'flex items-center gap-2',
+ { 'font-medium': selected },
+ )}
>
<span className='shrink-0 text-gray-500 dark:text-gray-400'>
- {filterCategoryIcons[col.value]}
+ {
+ filterCategoryIcons[
+ col.value
+ ]
+ }
+ </span>
+ <span className='truncate'>
+ {col.label}
</span>
- <span className='truncate'>{col.label}</span>
{selected ? (
<CheckIcon className='ml-auto h-4 w-4 shrink-0 text-indigo-600 dark:text-indigo-400' />
) : null}
@@ -477,13 +553,21 @@ const { flags } = await response.json()
{/* Operator Select */}
<Listbox
value={rule.isExclusive ? 'exclude' : 'include'}
- onChange={(value) => updateTargetingRule(index, 'isExclusive', value === 'exclude')}
+ onChange={(value) =>
+ updateTargetingRule(
+ index,
+ 'isExclusive',
+ value === 'exclude',
+ )
+ }
>
{({ open }) => (
<div className='relative w-24'>
<ListboxButton className='relative w-full rounded-md border border-gray-300 bg-white py-2 pr-8 pl-3 text-left text-sm transition-colors hover:bg-gray-50 focus:ring-2 focus:ring-indigo-500 focus:ring-offset-1 focus:outline-hidden dark:border-gray-700 dark:bg-slate-800 dark:text-gray-50 dark:hover:bg-slate-700'>
<span className='block truncate'>
- {rule.isExclusive ? t('featureFlags.isNot') : t('featureFlags.is')}
+ {rule.isExclusive
+ ? t('featureFlags.isNot')
+ : t('featureFlags.is')}
</span>
<span className='pointer-events-none absolute inset-y-0 right-0 flex items-center pr-2'>
<ChevronsUpDownIcon className='h-4 w-4 text-gray-400' />
@@ -506,15 +590,25 @@ const { flags } = await response.json()
<ListboxOption
value='include'
className={({ focus }) =>
- cx('relative cursor-pointer py-2 pr-4 pl-8 select-none', {
- 'bg-gray-100 dark:bg-slate-700': focus,
- 'text-gray-700 dark:text-gray-50': !focus,
- })
+ cx(
+ 'relative cursor-pointer py-2 pr-4 pl-8 select-none',
+ {
+ 'bg-gray-100 dark:bg-slate-700':
+ focus,
+ 'text-gray-700 dark:text-gray-50':
+ !focus,
+ },
+ )
}
>
{({ selected }) => (
<>
- <span className={cx('block truncate', { 'font-medium': selected })}>
+ <span
+ className={cx(
+ 'block truncate',
+ { 'font-medium': selected },
+ )}
+ >
{t('featureFlags.is')}
</span>
{selected ? (
@@ -528,15 +622,25 @@ const { flags } = await response.json()
<ListboxOption
value='exclude'
className={({ focus }) =>
- cx('relative cursor-pointer py-2 pr-4 pl-8 select-none', {
- 'bg-gray-100 dark:bg-slate-700': focus,
- 'text-gray-700 dark:text-gray-50': !focus,
- })
+ cx(
+ 'relative cursor-pointer py-2 pr-4 pl-8 select-none',
+ {
+ 'bg-gray-100 dark:bg-slate-700':
+ focus,
+ 'text-gray-700 dark:text-gray-50':
+ !focus,
+ },
+ )
}
>
{({ selected }) => (
<>
- <span className={cx('block truncate', { 'font-medium': selected })}>
+ <span
+ className={cx(
+ 'block truncate',
+ { 'font-medium': selected },
+ )}
+ >
{t('featureFlags.isNot')}
</span>
{selected ? (
@@ -555,9 +659,15 @@ const { flags } = await response.json()
{/* Value Input with Autocomplete */}
<FilterValueInput
- items={filterValuesCache[`${projectId}-${rule.column}`] || []}
+ items={
+ filterValuesCache[
+ `${projectId}-${rule.column}`
+ ] || []
+ }
value={rule.filter}
- onChange={(value) => updateTargetingRule(index, 'filter', value)}
+ onChange={(value) =>
+ updateTargetingRule(index, 'filter', value)
+ }
placeholder={t('featureFlags.valuePlaceholder')}
column={rule.column}
language={language}
@@ -595,7 +705,9 @@ const { flags } = await response.json()
<div className='border-t border-gray-200 pt-4 dark:border-slate-700'>
<button
type='button'
- onClick={() => setShowImplementation(!showImplementation)}
+ onClick={() =>
+ setShowImplementation(!showImplementation)
+ }
className='flex w-full items-center justify-between text-left'
>
<div className='flex items-center gap-2'>
@@ -605,9 +717,12 @@ const { flags } = await response.json()
</Text>
</div>
<ChevronDownIcon
- className={cx('size-5 text-gray-500 transition-transform', {
- 'rotate-180': showImplementation,
- })}
+ className={cx(
+ 'size-5 text-gray-500 transition-transform',
+ {
+ 'rotate-180': showImplementation,
+ },
+ )}
/>
</button>
@@ -649,7 +764,12 @@ const { flags } = await response.json()
</Text>
<button
type='button'
- onClick={() => copyToClipboard(jsCodeWithAttributes, 'js-attr')}
+ onClick={() =>
+ copyToClipboard(
+ jsCodeWithAttributes,
+ 'js-attr',
+ )
+ }
className='flex items-center gap-1 text-xs text-gray-500 hover:text-gray-700'
>
{copiedCode === 'js-attr' ? (
@@ -673,7 +793,9 @@ const { flags } = await response.json()
</Text>
<button
type='button'
- onClick={() => copyToClipboard(fetchCode, 'fetch')}
+ onClick={() =>
+ copyToClipboard(fetchCode, 'fetch')
+ }
className='flex items-center gap-1 text-xs text-gray-500 hover:text-gray-700'
>
{copiedCode === 'fetch' ? (
diff --git a/web/app/pages/Project/tabs/FeatureFlags/FeatureFlagsView.tsx b/web/app/pages/Project/tabs/FeatureFlags/FeatureFlagsView.tsx
index a24bbb208..b32f49f7a 100644
--- a/web/app/pages/Project/tabs/FeatureFlags/FeatureFlagsView.tsx
+++ b/web/app/pages/Project/tabs/FeatureFlags/FeatureFlagsView.tsx
@@ -20,17 +20,45 @@ import {
CheckIcon,
XIcon,
} from 'lucide-react'
-import { useState, useEffect, useMemo, useRef, useCallback, Suspense, use } from 'react'
+import {
+ useState,
+ useEffect,
+ useMemo,
+ useRef,
+ useCallback,
+ Suspense,
+ use,
+} from 'react'
import { useTranslation } from 'react-i18next'
-import { Link, useLocation, useFetcher, useLoaderData, useRevalidator } from 'react-router'
+import {
+ Link,
+ useLocation,
+ useFetcher,
+ useLoaderData,
+ useRevalidator,
+} from 'react-router'
import { toast } from 'sonner'
-import type { FeatureFlagsResponse, ProjectFeatureFlag, FeatureFlagStats, FeatureFlagProfile } from '~/api/api.server'
-import { useFeatureFlagStatsProxy, useFeatureFlagProfilesProxy } from '~/hooks/useAnalyticsProxy'
+import type {
+ FeatureFlagsResponse,
+ ProjectFeatureFlag,
+ FeatureFlagStats,
+ FeatureFlagProfile,
+} from '~/api/api.server'
+import {
+ useFeatureFlagStatsProxy,
+ useFeatureFlagProfilesProxy,
+} from '~/hooks/useAnalyticsProxy'
import DashboardHeader from '~/pages/Project/View/components/DashboardHeader'
-import { useViewProjectContext, useRefreshTriggers } from '~/pages/Project/View/ViewProject'
+import {
+ useViewProjectContext,
+ useRefreshTriggers,
+} from '~/pages/Project/View/ViewProject'
import { useCurrentProject } from '~/providers/CurrentProjectProvider'
-import type { ProjectLoaderData, ProjectViewActionData } from '~/routes/projects.$id'
+import type {
+ ProjectLoaderData,
+ ProjectViewActionData,
+} from '~/routes/projects.$id'
import { Badge } from '~/ui/Badge'
import Button from '~/ui/Button'
import Spin from '~/ui/icons/Spin'
@@ -57,7 +85,10 @@ interface FeatureFlagProfileRowProps {
timeFormat: '12-hour' | '24-hour'
}
-const FeatureFlagProfileRow = ({ profile, timeFormat }: FeatureFlagProfileRowProps) => {
+const FeatureFlagProfileRow = ({
+ profile,
+ timeFormat,
+}: FeatureFlagProfileRowProps) => {
const {
t,
i18n: { language },
@@ -89,17 +120,28 @@ const FeatureFlagProfileRow = ({ profile, timeFormat }: FeatureFlagProfileRowPro
<li className='relative mb-2 flex cursor-pointer items-center justify-between gap-x-4 overflow-hidden rounded-lg border border-gray-200 bg-white px-3 py-2.5 transition-colors hover:bg-gray-100 dark:border-slate-700/50 dark:bg-slate-800/50 dark:hover:bg-slate-700/50'>
<div className='flex min-w-0 items-center gap-x-3'>
{/* Avatar */}
- <ProfileAvatar profileId={profile.profileId} size={32} className='shrink-0' />
+ <ProfileAvatar
+ profileId={profile.profileId}
+ size={32}
+ className='shrink-0'
+ />
<div className='min-w-0 flex-auto'>
<p className='flex items-center text-xs leading-5 font-semibold text-gray-900 dark:text-gray-50'>
<span className='truncate'>{displayName}</span>
{profile.isIdentified ? (
- <Badge label={t('project.identified')} colour='indigo' className='ml-1.5' />
+ <Badge
+ label={t('project.identified')}
+ colour='indigo'
+ className='ml-1.5'
+ />
) : null}
</p>
<p className='mt-0.5 text-xs text-gray-500 dark:text-gray-400'>
- {t('featureFlags.xEvaluations', { count: profile.evaluationCount })} · {lastEvaluatedText}
+ {t('featureFlags.xEvaluations', {
+ count: profile.evaluationCount,
+ })}{' '}
+ · {lastEvaluatedText}
</p>
</div>
</div>
@@ -177,8 +219,16 @@ const FeatureFlagRow = ({
<div className='flex min-w-0 gap-x-4'>
<div className='min-w-0 flex-auto'>
<div className='flex items-center gap-x-2'>
- <Text as='p' weight='semibold' truncate className='flex items-center gap-x-1.5'>
- <FlagIcon className='size-4 text-indigo-500' strokeWidth={1.5} />
+ <Text
+ as='p'
+ weight='semibold'
+ truncate
+ className='flex items-center gap-x-1.5'
+ >
+ <FlagIcon
+ className='size-4 text-indigo-500'
+ strokeWidth={1.5}
+ />
<span>{flag.key}</span>
</Text>
{/* Status badge */}
@@ -190,7 +240,9 @@ const FeatureFlagRow = ({
: 'bg-gray-100 text-gray-600 dark:bg-gray-700 dark:text-gray-400',
)}
>
- {flag.enabled ? t('featureFlags.enabled') : t('featureFlags.disabled')}
+ {flag.enabled
+ ? t('featureFlags.enabled')
+ : t('featureFlags.disabled')}
</span>
{/* Flag type badge */}
<span className='inline-flex items-center gap-1 rounded-full bg-blue-100 px-2 py-0.5 text-xs font-medium text-blue-800 dark:bg-blue-900/30 dark:text-blue-400'>
@@ -214,7 +266,9 @@ const FeatureFlagRow = ({
) : null}
{targetingRulesCount > 0 ? (
<Text className='mt-1' as='p' size='xs' colour='muted'>
- {t('featureFlags.targetingRulesCount', { count: targetingRulesCount })}
+ {t('featureFlags.targetingRulesCount', {
+ count: targetingRulesCount,
+ })}
</Text>
) : null}
{/* Mobile stats */}
@@ -227,7 +281,8 @@ const FeatureFlagRow = ({
<>
<span className='flex items-center gap-1'>
<ActivityIcon className='size-3' />
- {nFormatter(stats.evaluations, 1)} {t('featureFlags.evaluations').toLowerCase()}
+ {nFormatter(stats.evaluations, 1)}{' '}
+ {t('featureFlags.evaluations').toLowerCase()}
</span>
<span className='flex items-center gap-1'>
<UsersIcon className='size-3' />
@@ -268,7 +323,12 @@ const FeatureFlagRow = ({
</Text>
</div>
<div className='text-right'>
- <Text as='p' size='sm' weight='semibold' className='text-green-600 dark:text-green-400'>
+ <Text
+ as='p'
+ size='sm'
+ weight='semibold'
+ className='text-green-600 dark:text-green-400'
+ >
{stats.truePercentage}%
</Text>
<Text as='p' size='xs' colour='muted'>
@@ -291,7 +351,11 @@ const FeatureFlagRow = ({
e.stopPropagation()
onToggle(flag.id, !flag.enabled)
}}
- aria-label={flag.enabled ? t('featureFlags.disable') : t('featureFlags.enable')}
+ aria-label={
+ flag.enabled
+ ? t('featureFlags.disable')
+ : t('featureFlags.enable')
+ }
className={cx(
'rounded-md border border-transparent p-1.5 transition-colors',
flag.enabled
@@ -330,9 +394,12 @@ const FeatureFlagRow = ({
<Trash2Icon className='size-4' strokeWidth={1.5} />
</button>
<ChevronDownIcon
- className={cx('size-5 text-gray-500 transition-transform dark:text-gray-400', {
- 'rotate-180': isExpanded,
- })}
+ className={cx(
+ 'size-5 text-gray-500 transition-transform dark:text-gray-400',
+ {
+ 'rotate-180': isExpanded,
+ },
+ )}
strokeWidth={1.5}
/>
</div>
@@ -344,7 +411,10 @@ const FeatureFlagRow = ({
<div className='border-t border-gray-200 px-4 py-4 sm:px-6 dark:border-slate-700'>
{/* Result filter toggle */}
<div className='mb-3 flex items-center gap-2'>
- <Switch checked={resultFilter} onChange={(checked) => onResultFilterChange(flag.id, checked)} />
+ <Switch
+ checked={resultFilter}
+ onChange={(checked) => onResultFilterChange(flag.id, checked)}
+ />
<Text as='span' size='xs' colour='muted'>
{t('featureFlags.served')}
</Text>
@@ -364,7 +434,11 @@ const FeatureFlagRow = ({
<>
<ul>
{_map(profiles, (profile) => (
- <FeatureFlagProfileRow key={profile.profileId} profile={profile} timeFormat={timeFormat} />
+ <FeatureFlagProfileRow
+ key={profile.profileId}
+ profile={profile}
+ timeFormat={timeFormat}
+ />
))}
</ul>
{canLoadMoreProfiles ? (
@@ -386,7 +460,10 @@ const FeatureFlagRow = ({
{profilesLoading ? (
<Spin className='mr-2 size-5' />
) : (
- <DownloadIcon className='mr-2 h-5 w-5' strokeWidth={1.5} />
+ <DownloadIcon
+ className='mr-2 h-5 w-5'
+ strokeWidth={1.5}
+ />
)}
{t('featureFlags.loadMore')}
</button>
@@ -425,9 +502,16 @@ interface DeferredFeatureFlagsData {
featureFlagsData: FeatureFlagsResponse | null
}
-function FeatureFlagsDataResolver({ children }: { children: (data: DeferredFeatureFlagsData) => React.ReactNode }) {
- const { featureFlagsData: featureFlagsDataPromise } = useLoaderData<ProjectLoaderData>()
- const featureFlagsData = featureFlagsDataPromise ? use(featureFlagsDataPromise) : null
+function FeatureFlagsDataResolver({
+ children,
+}: {
+ children: (data: DeferredFeatureFlagsData) => React.ReactNode
+}) {
+ const { featureFlagsData: featureFlagsDataPromise } =
+ useLoaderData<ProjectLoaderData>()
+ const featureFlagsData = featureFlagsDataPromise
+ ? use(featureFlagsDataPromise)
+ : null
return <>{children({ featureFlagsData })}</>
}
@@ -435,7 +519,9 @@ function FeatureFlagsViewWrapper(props: FeatureFlagsViewProps) {
return (
<Suspense fallback={<Loader />}>
<FeatureFlagsDataResolver>
- {(deferredData) => <FeatureFlagsViewInner {...props} deferredData={deferredData} />}
+ {(deferredData) => (
+ <FeatureFlagsViewInner {...props} deferredData={deferredData} />
+ )}
</FeatureFlagsDataResolver>
</Suspense>
)
@@ -445,7 +531,13 @@ interface FeatureFlagsViewInnerProps extends FeatureFlagsViewProps {
deferredData: DeferredFeatureFlagsData
}
-const FeatureFlagsViewInner = ({ period, from = '', to = '', timezone, deferredData }: FeatureFlagsViewInnerProps) => {
+const FeatureFlagsViewInner = ({
+ period,
+ from = '',
+ to = '',
+ timezone,
+ deferredData,
+}: FeatureFlagsViewInnerProps) => {
const { id } = useCurrentProject()
const revalidator = useRevalidator()
const { featureFlagsRefreshTrigger } = useRefreshTriggers()
@@ -457,9 +549,15 @@ const FeatureFlagsViewInner = ({ period, from = '', to = '', timezone, deferredD
// Track if we're in search/pagination mode (not using loader data)
const [isSearchMode, setIsSearchMode] = useState(false)
- const [total, setTotal] = useState(() => deferredData.featureFlagsData?.total || 0)
- const [flags, setFlags] = useState<ProjectFeatureFlag[]>(() => deferredData.featureFlagsData?.results || [])
- const [flagStats, setFlagStats] = useState<Record<string, FeatureFlagStats | null>>({})
+ const [total, setTotal] = useState(
+ () => deferredData.featureFlagsData?.total || 0,
+ )
+ const [flags, setFlags] = useState<ProjectFeatureFlag[]>(
+ () => deferredData.featureFlagsData?.results || [],
+ )
+ const [flagStats, setFlagStats] = useState<
+ Record<string, FeatureFlagStats | null>
+ >({})
const [statsLoading, setStatsLoading] = useState<Record<string, boolean>>({})
const [page, setPage] = useState(1)
const [error, setError] = useState<string | null>(null)
@@ -470,16 +568,25 @@ const FeatureFlagsViewInner = ({ period, from = '', to = '', timezone, deferredD
// Expanded flag state
const [expandedFlagId, setExpandedFlagId] = useState<string | null>(null)
- const [flagProfiles, setFlagProfiles] = useState<Record<string, FeatureFlagProfile[]>>({})
- const [flagProfilesTotal, setFlagProfilesTotal] = useState<Record<string, number>>({})
- const [profilesLoading, setProfilesLoading] = useState<Record<string, boolean>>({})
- const [flagResultFilters, setFlagResultFilters] = useState<Record<string, boolean>>({})
+ const [flagProfiles, setFlagProfiles] = useState<
+ Record<string, FeatureFlagProfile[]>
+ >({})
+ const [flagProfilesTotal, setFlagProfilesTotal] = useState<
+ Record<string, number>
+ >({})
+ const [profilesLoading, setProfilesLoading] = useState<
+ Record<string, boolean>
+ >({})
+ const [flagResultFilters, setFlagResultFilters] = useState<
+ Record<string, boolean>
+ >({})
// Modal state
const [isModalOpen, setIsModalOpen] = useState(false)
const [editingFlagId, setEditingFlagId] = useState<string | null>(null)
- const isLoading = revalidator.state === 'loading' || listFetcher.state !== 'idle'
+ const isLoading =
+ revalidator.state === 'loading' || listFetcher.state !== 'idle'
// Cleanup on unmount
useEffect(() => {
@@ -491,7 +598,11 @@ const FeatureFlagsViewInner = ({ period, from = '', to = '', timezone, deferredD
// Sync state when loader provides new data
useEffect(() => {
- if (deferredData.featureFlagsData && revalidator.state === 'idle' && !isSearchMode) {
+ if (
+ deferredData.featureFlagsData &&
+ revalidator.state === 'idle' &&
+ !isSearchMode
+ ) {
setFlags(deferredData.featureFlagsData.results || [])
setTotal(deferredData.featureFlagsData.total || 0)
}
@@ -522,10 +633,16 @@ const FeatureFlagsViewInner = ({ period, from = '', to = '', timezone, deferredD
// Handle list fetcher response
useEffect(() => {
- if (listFetcher.data?.intent === 'get-project-feature-flags' && listFetcher.state === 'idle') {
+ if (
+ listFetcher.data?.intent === 'get-project-feature-flags' &&
+ listFetcher.state === 'idle'
+ ) {
if (isMountedRef.current) {
if (listFetcher.data.success && listFetcher.data.data) {
- const result = listFetcher.data.data as { results: ProjectFeatureFlag[]; total: number }
+ const result = listFetcher.data.data as {
+ results: ProjectFeatureFlag[]
+ total: number
+ }
setFlags(result.results)
setTotal(result.total)
} else if (listFetcher.data.error) {
@@ -550,7 +667,11 @@ const FeatureFlagsViewInner = ({ period, from = '', to = '', timezone, deferredD
setIsSearchMode(false)
revalidator.revalidate()
} else {
- loadFlags(DEFAULT_FEATURE_FLAGS_TAKE, (page - 1) * DEFAULT_FEATURE_FLAGS_TAKE, filterQuery || undefined)
+ loadFlags(
+ DEFAULT_FEATURE_FLAGS_TAKE,
+ (page - 1) * DEFAULT_FEATURE_FLAGS_TAKE,
+ filterQuery || undefined,
+ )
}
} else if (actionFetcher.data.error) {
toast.error(actionFetcher.data.error)
@@ -558,13 +679,25 @@ const FeatureFlagsViewInner = ({ period, from = '', to = '', timezone, deferredD
} else if (actionFetcher.data.intent === 'update-feature-flag') {
if (actionFetcher.data.success && actionFetcher.data.data) {
const updated = actionFetcher.data.data as ProjectFeatureFlag
- toast.success(updated.enabled ? t('featureFlags.flagEnabled') : t('featureFlags.flagDisabled'))
+ toast.success(
+ updated.enabled
+ ? t('featureFlags.flagEnabled')
+ : t('featureFlags.flagDisabled'),
+ )
setFlags((prev) => prev.map((f) => (f.id === updated.id ? updated : f)))
} else if (actionFetcher.data.error) {
toast.error(actionFetcher.data.error)
}
}
- }, [actionFetcher.data, actionFetcher.state, t, loadFlags, page, filterQuery, revalidator])
+ }, [
+ actionFetcher.data,
+ actionFetcher.state,
+ t,
+ loadFlags,
+ page,
+ filterQuery,
+ revalidator,
+ ])
// Debounced search to avoid excessive API calls
const debouncedLoadFlags = useMemo(
@@ -601,7 +734,12 @@ const FeatureFlagsViewInner = ({ period, from = '', to = '', timezone, deferredD
async (flagId: string) => {
setStatsLoading((prev) => ({ ...prev, [flagId]: true }))
try {
- const stats = await statsProxy.fetchStats(flagId, { period, from, to, timezone })
+ const stats = await statsProxy.fetchStats(flagId, {
+ period,
+ from,
+ to,
+ timezone,
+ })
if (isMountedRef.current) {
setFlagStats((prev) => ({ ...prev, [flagId]: stats }))
}
@@ -640,14 +778,19 @@ const FeatureFlagsViewInner = ({ period, from = '', to = '', timezone, deferredD
if (isMountedRef.current && result) {
setFlagProfiles((prev) => ({
...prev,
- [flagId]: append ? [...currentProfiles, ...result.profiles] : result.profiles,
+ [flagId]: append
+ ? [...currentProfiles, ...result.profiles]
+ : result.profiles,
}))
setFlagProfilesTotal((prev) => ({ ...prev, [flagId]: result.total }))
}
} catch (err) {
console.error('Failed to load flag profiles:', err)
if (isMountedRef.current) {
- setFlagProfiles((prev) => ({ ...prev, [flagId]: append ? currentProfiles : [] }))
+ setFlagProfiles((prev) => ({
+ ...prev,
+ [flagId]: append ? currentProfiles : [],
+ }))
setFlagProfilesTotal((prev) => ({ ...prev, [flagId]: 0 }))
}
} finally {
@@ -656,7 +799,15 @@ const FeatureFlagsViewInner = ({ period, from = '', to = '', timezone, deferredD
}
}
},
- [period, from, to, timezone, flagProfiles, flagResultFilters, profilesProxy],
+ [
+ period,
+ from,
+ to,
+ timezone,
+ flagProfiles,
+ flagResultFilters,
+ profilesProxy,
+ ],
)
const handleToggleExpand = useCallback(
@@ -693,7 +844,11 @@ const FeatureFlagsViewInner = ({ period, from = '', to = '', timezone, deferredD
// Handle page changes - use fetcher for pagination
useEffect(() => {
if (page > 1 || isSearchMode) {
- loadFlags(DEFAULT_FEATURE_FLAGS_TAKE, (page - 1) * DEFAULT_FEATURE_FLAGS_TAKE, filterQuery || undefined)
+ loadFlags(
+ DEFAULT_FEATURE_FLAGS_TAKE,
+ (page - 1) * DEFAULT_FEATURE_FLAGS_TAKE,
+ filterQuery || undefined,
+ )
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [page])
@@ -705,7 +860,11 @@ const FeatureFlagsViewInner = ({ period, from = '', to = '', timezone, deferredD
setIsSearchMode(false)
revalidator.revalidate()
} else {
- loadFlags(DEFAULT_FEATURE_FLAGS_TAKE, (page - 1) * DEFAULT_FEATURE_FLAGS_TAKE, filterQuery || undefined)
+ loadFlags(
+ DEFAULT_FEATURE_FLAGS_TAKE,
+ (page - 1) * DEFAULT_FEATURE_FLAGS_TAKE,
+ filterQuery || undefined,
+ )
}
setFlagStats({})
if (expandedFlagId) {
@@ -753,14 +912,21 @@ const FeatureFlagsViewInner = ({ period, from = '', to = '', timezone, deferredD
setIsSearchMode(false)
revalidator.revalidate()
} else {
- loadFlags(DEFAULT_FEATURE_FLAGS_TAKE, (page - 1) * DEFAULT_FEATURE_FLAGS_TAKE, filterQuery || undefined)
+ loadFlags(
+ DEFAULT_FEATURE_FLAGS_TAKE,
+ (page - 1) * DEFAULT_FEATURE_FLAGS_TAKE,
+ filterQuery || undefined,
+ )
}
}
const handleDeleteFlag = useCallback(
(flagId: string) => {
processedActionRef.current = null
- actionFetcher.submit({ intent: 'delete-feature-flag', flagId }, { method: 'POST' })
+ actionFetcher.submit(
+ { intent: 'delete-feature-flag', flagId },
+ { method: 'POST' },
+ )
},
[actionFetcher],
)
@@ -768,7 +934,10 @@ const FeatureFlagsViewInner = ({ period, from = '', to = '', timezone, deferredD
const handleToggleFlag = useCallback(
(flagId: string, enabled: boolean) => {
processedActionRef.current = null
- actionFetcher.submit({ intent: 'update-feature-flag', flagId, enabled: String(enabled) }, { method: 'POST' })
+ actionFetcher.submit(
+ { intent: 'update-feature-flag', flagId, enabled: String(enabled) },
+ { method: 'POST' },
+ )
},
[actionFetcher],
)
@@ -780,7 +949,11 @@ const FeatureFlagsViewInner = ({ period, from = '', to = '', timezone, deferredD
title={t('apiNotifications.somethingWentWrong')}
description={t('apiNotifications.errorCode', { error })}
actions={[
- { label: t('dashboard.reloadPage'), onClick: () => window.location.reload(), primary: true },
+ {
+ label: t('dashboard.reloadPage'),
+ onClick: () => window.location.reload(),
+ primary: true,
+ },
{ label: t('notFoundPage.support'), to: routes.contact },
]}
/>
@@ -798,7 +971,9 @@ const FeatureFlagsViewInner = ({ period, from = '', to = '', timezone, deferredD
<FlagIcon className='mr-2 h-8 w-8' strokeWidth={1.5} />
<p className='text-3xl font-bold'>{t('featureFlags.title')}</p>
</div>
- <p className='mt-2 text-sm whitespace-pre-wrap text-gray-100'>{t('featureFlags.description')}</p>
+ <p className='mt-2 text-sm whitespace-pre-wrap text-gray-100'>
+ {t('featureFlags.description')}
+ </p>
<Button
onClick={handleNewFlag}
className='mt-6 block max-w-max rounded-md border border-transparent bg-white px-3 py-2 text-sm font-medium text-gray-700 hover:bg-indigo-50 md:px-4'
diff --git a/web/app/pages/Project/tabs/Funnels/FunnelChart.tsx b/web/app/pages/Project/tabs/Funnels/FunnelChart.tsx
index 59356d2c2..95485563d 100644
--- a/web/app/pages/Project/tabs/Funnels/FunnelChart.tsx
+++ b/web/app/pages/Project/tabs/Funnels/FunnelChart.tsx
@@ -13,7 +13,12 @@ interface FunnelChartProps {
className?: string
}
-export const FunnelChart = ({ funnel, totalPageviews, t, className }: FunnelChartProps) => {
+export const FunnelChart = ({
+ funnel,
+ totalPageviews,
+ t,
+ className,
+}: FunnelChartProps) => {
const options: ChartOptions = useMemo(() => {
return getSettingsFunnels(funnel, totalPageviews, t)
}, [funnel, totalPageviews, t])
@@ -26,7 +31,18 @@ export const FunnelChart = ({ funnel, totalPageviews, t, className }: FunnelChar
[t],
)
- const deps = useMemo(() => [funnel, totalPageviews, t], [funnel, totalPageviews, t])
+ const deps = useMemo(
+ () => [funnel, totalPageviews, t],
+ [funnel, totalPageviews, t],
+ )
- return <MainChart chartId='funnel-chart' options={options} dataNames={dataNames} className={className} deps={deps} />
+ return (
+ <MainChart
+ chartId='funnel-chart'
+ options={options}
+ dataNames={dataNames}
+ className={className}
+ deps={deps}
+ />
+ )
}
diff --git a/web/app/pages/Project/tabs/Funnels/FunnelsList.tsx b/web/app/pages/Project/tabs/Funnels/FunnelsList.tsx
index 8799c4b84..fbac29573 100644
--- a/web/app/pages/Project/tabs/Funnels/FunnelsList.tsx
+++ b/web/app/pages/Project/tabs/Funnels/FunnelsList.tsx
@@ -29,7 +29,13 @@ interface AddFunnelProps {
openFunnelSettings: (funnel?: Funnel) => void
}
-const FunnelCard = ({ funnel, openFunnelSettings, deleteFunnel, loading, allowedToManage }: FunnelCardProps) => {
+const FunnelCard = ({
+ funnel,
+ openFunnelSettings,
+ deleteFunnel,
+ loading,
+ allowedToManage,
+}: FunnelCardProps) => {
const { t } = useTranslation()
const [searchParams] = useSearchParams()
@@ -107,7 +113,12 @@ const AddFunnel = ({ openFunnelSettings }: AddFunnelProps) => {
className='mx-auto h-12 w-12 text-gray-400 transition-colors group-hover:text-gray-500 dark:text-gray-200 group-hover:dark:text-gray-400'
strokeWidth={1}
/>
- <Text as='span' size='sm' weight='semibold' className='mt-2 block group-hover:dark:text-gray-400'>
+ <Text
+ as='span'
+ size='sm'
+ weight='semibold'
+ className='mt-2 block group-hover:dark:text-gray-400'
+ >
{t('dashboard.newFunnel')}
</Text>
</div>
@@ -115,7 +126,13 @@ const AddFunnel = ({ openFunnelSettings }: AddFunnelProps) => {
)
}
-const FunnelsList = ({ funnels, openFunnelSettings, deleteFunnel, loading, allowedToManage }: FunnelsListProps) => {
+const FunnelsList = ({
+ funnels,
+ openFunnelSettings,
+ deleteFunnel,
+ loading,
+ allowedToManage,
+}: FunnelsListProps) => {
const { isAuthenticated } = useAuth()
return (
@@ -130,7 +147,9 @@ const FunnelsList = ({ funnels, openFunnelSettings, deleteFunnel, loading, allow
allowedToManage={allowedToManage}
/>
))}
- {isAuthenticated && allowedToManage ? <AddFunnel openFunnelSettings={openFunnelSettings} /> : null}
+ {isAuthenticated && allowedToManage ? (
+ <AddFunnel openFunnelSettings={openFunnelSettings} />
+ ) : null}
</div>
)
}
diff --git a/web/app/pages/Project/tabs/Funnels/FunnelsView.tsx b/web/app/pages/Project/tabs/Funnels/FunnelsView.tsx
index 5d7c90040..5fac5595b 100644
--- a/web/app/pages/Project/tabs/Funnels/FunnelsView.tsx
+++ b/web/app/pages/Project/tabs/Funnels/FunnelsView.tsx
@@ -6,7 +6,13 @@ import _isEmpty from 'lodash/isEmpty'
import { FilterIcon } from 'lucide-react'
import { useState, useEffect, useMemo, useRef, Suspense, use } from 'react'
import { useTranslation } from 'react-i18next'
-import { Link, useSearchParams, useFetcher, useLoaderData, useRevalidator } from 'react-router'
+import {
+ Link,
+ useSearchParams,
+ useFetcher,
+ useLoaderData,
+ useRevalidator,
+} from 'react-router'
import { toast } from 'sonner'
import type { FunnelDataResponse } from '~/api/api.server'
@@ -16,10 +22,19 @@ import NewFunnel from '~/modals/NewFunnel'
import { FunnelChart } from '~/pages/Project/tabs/Funnels/FunnelChart'
import FunnelsList from '~/pages/Project/tabs/Funnels/FunnelsList'
import DashboardHeader from '~/pages/Project/View/components/DashboardHeader'
-import { useViewProjectContext, useRefreshTriggers } from '~/pages/Project/View/ViewProject'
+import {
+ useViewProjectContext,
+ useRefreshTriggers,
+} from '~/pages/Project/View/ViewProject'
import { useAuth } from '~/providers/AuthProvider'
-import { useCurrentProject, useProjectPassword } from '~/providers/CurrentProjectProvider'
-import type { ProjectLoaderData, ProjectViewActionData } from '~/routes/projects.$id'
+import {
+ useCurrentProject,
+ useProjectPassword,
+} from '~/providers/CurrentProjectProvider'
+import type {
+ ProjectLoaderData,
+ ProjectViewActionData,
+} from '~/routes/projects.$id'
import Loader from '~/ui/Loader'
import LoadingBar from '~/ui/LoadingBar'
import { Text } from '~/ui/Text'
@@ -30,7 +45,11 @@ interface DeferredFunnelData {
funnelData: FunnelDataResponse | null
}
-function FunnelDataResolver({ children }: { children: (data: DeferredFunnelData) => React.ReactNode }) {
+function FunnelDataResolver({
+ children,
+}: {
+ children: (data: DeferredFunnelData) => React.ReactNode
+}) {
const { funnelData: funnelDataPromise } = useLoaderData<ProjectLoaderData>()
const funnelData = funnelDataPromise ? use(funnelDataPromise) : null
return <>{children({ funnelData })}</>
@@ -39,7 +58,9 @@ function FunnelDataResolver({ children }: { children: (data: DeferredFunnelData)
function FunnelsViewWrapper() {
return (
<Suspense fallback={<Loader />}>
- <FunnelDataResolver>{(deferredData) => <FunnelsViewInner deferredData={deferredData} />}</FunnelDataResolver>
+ <FunnelDataResolver>
+ {(deferredData) => <FunnelsViewInner deferredData={deferredData} />}
+ </FunnelDataResolver>
</Suspense>
)
}
@@ -72,7 +93,9 @@ const FunnelsViewInner = ({ deferredData }: FunnelsViewInnerProps) => {
// Funnels state
const [isNewFunnelOpened, setIsNewFunnelOpened] = useState(false)
- const [funnelToEdit, setFunnelToEdit] = useState<Funnel | undefined>(undefined)
+ const [funnelToEdit, setFunnelToEdit] = useState<Funnel | undefined>(
+ undefined,
+ )
const [dataLoading, setDataLoading] = useState(false)
// Initialize funnelAnalytics from loader data
@@ -166,7 +189,17 @@ const FunnelsViewInner = ({ deferredData }: FunnelsViewInnerProps) => {
} else if (error) {
toast.error(error)
}
- }, [fetcher.state, fetcher.data, t, id, projectPassword, fetcher, mergeProject, activeFunnel?.id, revalidator])
+ }, [
+ fetcher.state,
+ fetcher.data,
+ t,
+ id,
+ projectPassword,
+ fetcher,
+ mergeProject,
+ activeFunnel?.id,
+ revalidator,
+ ])
const onFunnelCreate = (name: string, steps: string[]) => {
if (funnelActionLoading) return
@@ -189,7 +222,10 @@ const FunnelsViewInner = ({ deferredData }: FunnelsViewInnerProps) => {
const onFunnelDelete = (funnelId: string) => {
if (funnelActionLoading) return
- fetcher.submit({ intent: 'delete-funnel', funnelId }, { method: 'POST', action: `/projects/${id}` })
+ fetcher.submit(
+ { intent: 'delete-funnel', funnelId },
+ { method: 'POST', action: `/projects/${id}` },
+ )
}
// Sync funnelAnalytics when loader data changes
@@ -211,7 +247,9 @@ const FunnelsViewInner = ({ deferredData }: FunnelsViewInnerProps) => {
const stepsCount = funnelAnalytics.funnel.length
const startVisitors = funnelAnalytics.funnel[0]?.events || 0
const endVisitors = funnelAnalytics.funnel[stepsCount - 1]?.events || 0
- const conversionRate = Number(((endVisitors / Math.max(startVisitors, 1)) * 100).toFixed(2))
+ const conversionRate = Number(
+ ((endVisitors / Math.max(startVisitors, 1)) * 100).toFixed(2),
+ )
return {
stepsCount,
@@ -277,7 +315,12 @@ const FunnelsViewInner = ({ deferredData }: FunnelsViewInnerProps) => {
hideTimeBucket
timeBucketSelectorItems={timeBucketSelectorItems}
leftContent={
- <Text as='h2' size='xl' weight='bold' className='wrap-break-word break-all'>
+ <Text
+ as='h2'
+ size='xl'
+ weight='bold'
+ className='wrap-break-word break-all'
+ >
{activeFunnel?.name}
</Text>
}
@@ -294,14 +337,20 @@ const FunnelsViewInner = ({ deferredData }: FunnelsViewInnerProps) => {
{funnelSummary ? (
<>
<p className='font-medium text-gray-900 lg:text-left dark:text-gray-50'>
- {t('project.funnelSummary.xStepFunnel', { x: funnelSummary.stepsCount })}
+ {t('project.funnelSummary.xStepFunnel', {
+ x: funnelSummary.stepsCount,
+ })}
<span className='mx-2 text-gray-400'>•</span>
- {t('project.funnelSummary.conversionRateShort', { x: funnelSummary.conversionRate })}
+ {t('project.funnelSummary.conversionRateShort', {
+ x: funnelSummary.conversionRate,
+ })}
</p>
<p className='text-center text-gray-900 lg:text-left dark:text-gray-50'>
- {t('project.funnelSummary.startShort')}: {nLocaleFormatter(funnelSummary.startVisitors)}
+ {t('project.funnelSummary.startShort')}:{' '}
+ {nLocaleFormatter(funnelSummary.startVisitors)}
<span className='mx-1'>→</span>
- {t('project.funnelSummary.endShort')}: {nLocaleFormatter(funnelSummary.endVisitors)}
+ {t('project.funnelSummary.endShort')}:{' '}
+ {nLocaleFormatter(funnelSummary.endVisitors)}
</p>
</>
) : null}
@@ -385,7 +434,9 @@ const FunnelsViewInner = ({ deferredData }: FunnelsViewInnerProps) => {
<FilterIcon className='mr-2 h-8 w-8' strokeWidth={1.5} />
<p className='text-3xl font-bold'>{t('dashboard.funnels')}</p>
</div>
- <p className='mt-2 text-sm whitespace-pre-wrap text-gray-100'>{t('dashboard.funnelsDesc')}</p>
+ <p className='mt-2 text-sm whitespace-pre-wrap text-gray-100'>
+ {t('dashboard.funnelsDesc')}
+ </p>
{isAuthenticated ? (
<button
type='button'
diff --git a/web/app/pages/Project/tabs/Goals/GoalSettingsModal.tsx b/web/app/pages/Project/tabs/Goals/GoalSettingsModal.tsx
index 556aa6dc6..fd9dbe665 100644
--- a/web/app/pages/Project/tabs/Goals/GoalSettingsModal.tsx
+++ b/web/app/pages/Project/tabs/Goals/GoalSettingsModal.tsx
@@ -1,4 +1,9 @@
-import { Dialog, DialogBackdrop, DialogPanel, DialogTitle } from '@headlessui/react'
+import {
+ Dialog,
+ DialogBackdrop,
+ DialogPanel,
+ DialogTitle,
+} from '@headlessui/react'
import { XMarkIcon } from '@heroicons/react/24/outline'
import _map from 'lodash/map'
import { Trash2Icon, PlusIcon } from 'lucide-react'
@@ -32,7 +37,13 @@ interface GoalSettingsModalProps {
goalId?: string | null
}
-const GoalSettingsModal = ({ isOpen, onClose, onSuccess, projectId: _projectId, goalId }: GoalSettingsModalProps) => {
+const GoalSettingsModal = ({
+ isOpen,
+ onClose,
+ onSuccess,
+ projectId: _projectId,
+ goalId,
+}: GoalSettingsModalProps) => {
const { t } = useTranslation()
const fetcher = useFetcher<ProjectViewActionData>()
const processedRef = useRef<string | null>(null)
@@ -46,7 +57,9 @@ const GoalSettingsModal = ({ isOpen, onClose, onSuccess, projectId: _projectId,
const [type, setType] = useState<'pageview' | 'custom_event'>('pageview')
const [matchType, setMatchType] = useState<'exact' | 'contains'>('exact')
const [value, setValue] = useState('')
- const [metadataFilters, setMetadataFilters] = useState<{ key: string; value: string }[]>([])
+ const [metadataFilters, setMetadataFilters] = useState<
+ { key: string; value: string }[]
+ >([])
const isSaving = fetcher.state === 'submitting'
@@ -142,7 +155,11 @@ const GoalSettingsModal = ({ isOpen, onClose, onSuccess, projectId: _projectId,
setMetadataFilters([...metadataFilters, { key: '', value: '' }])
}
- const updateMetadataFilter = (index: number, field: 'key' | 'value', val: string) => {
+ const updateMetadataFilter = (
+ index: number,
+ field: 'key' | 'value',
+ val: string,
+ ) => {
const updated = [...metadataFilters]
updated[index][field] = val
setMetadataFilters(updated)
@@ -200,15 +217,21 @@ const GoalSettingsModal = ({ isOpen, onClose, onSuccess, projectId: _projectId,
</label>
<Select
items={GOAL_TYPES}
- onSelect={(item) => setType(item.value as 'pageview' | 'custom_event')}
- title={GOAL_TYPES.find((t) => t.value === type)?.label || ''}
+ onSelect={(item) =>
+ setType(item.value as 'pageview' | 'custom_event')
+ }
+ title={
+ GOAL_TYPES.find((t) => t.value === type)?.label || ''
+ }
labelExtractor={(item) => item.label}
keyExtractor={(item) => item.value}
selectedItem={GOAL_TYPES.find((t) => t.value === type)}
capitalise
/>
<p className='mt-1 text-xs text-gray-500 dark:text-gray-400'>
- {type === 'pageview' ? t('goals.typePageviewDesc') : t('goals.typeCustomEventDesc')}
+ {type === 'pageview'
+ ? t('goals.typePageviewDesc')
+ : t('goals.typeCustomEventDesc')}
</p>
</div>
@@ -218,17 +241,28 @@ const GoalSettingsModal = ({ isOpen, onClose, onSuccess, projectId: _projectId,
</label>
<Select
items={GOAL_MATCH_TYPES}
- onSelect={(item) => setMatchType(item.value as 'exact' | 'contains')}
- title={GOAL_MATCH_TYPES.find((t) => t.value === matchType)?.label || ''}
+ onSelect={(item) =>
+ setMatchType(item.value as 'exact' | 'contains')
+ }
+ title={
+ GOAL_MATCH_TYPES.find((t) => t.value === matchType)
+ ?.label || ''
+ }
labelExtractor={(item) => item.label}
keyExtractor={(item) => item.value}
- selectedItem={GOAL_MATCH_TYPES.find((t) => t.value === matchType)}
+ selectedItem={GOAL_MATCH_TYPES.find(
+ (t) => t.value === matchType,
+ )}
capitalise
/>
</div>
<Input
- label={type === 'pageview' ? t('goals.pagePath') : t('goals.eventName')}
+ label={
+ type === 'pageview'
+ ? t('goals.pagePath')
+ : t('goals.eventName')
+ }
value={value}
onChange={(e) => setValue(e.target.value)}
placeholder={
@@ -260,17 +294,32 @@ const GoalSettingsModal = ({ isOpen, onClose, onSuccess, projectId: _projectId,
{metadataFilters.length > 0 ? (
<div className='space-y-2'>
{_map(metadataFilters, (filter, index) => (
- <div key={index} className='flex items-center gap-2'>
+ <div
+ key={index}
+ className='flex items-center gap-2'
+ >
<Input
value={filter.key}
- onChange={(e) => updateMetadataFilter(index, 'key', e.target.value)}
+ onChange={(e) =>
+ updateMetadataFilter(
+ index,
+ 'key',
+ e.target.value,
+ )
+ }
placeholder={t('goals.filterKey')}
className='flex-1'
/>
<span className='text-gray-500'>=</span>
<Input
value={filter.value}
- onChange={(e) => updateMetadataFilter(index, 'value', e.target.value)}
+ onChange={(e) =>
+ updateMetadataFilter(
+ index,
+ 'value',
+ e.target.value,
+ )
+ }
placeholder={t('goals.filterValue')}
className='flex-1'
/>
@@ -285,7 +334,9 @@ const GoalSettingsModal = ({ isOpen, onClose, onSuccess, projectId: _projectId,
))}
</div>
) : (
- <p className='text-sm text-gray-500 dark:text-gray-400'>{t('goals.noMetadataFilters')}</p>
+ <p className='text-sm text-gray-500 dark:text-gray-400'>
+ {t('goals.noMetadataFilters')}
+ </p>
)}
</div>
</div>
diff --git a/web/app/pages/Project/tabs/Goals/GoalsView.tsx b/web/app/pages/Project/tabs/Goals/GoalsView.tsx
index 80cba11d5..e180c497e 100644
--- a/web/app/pages/Project/tabs/Goals/GoalsView.tsx
+++ b/web/app/pages/Project/tabs/Goals/GoalsView.tsx
@@ -17,12 +17,30 @@ import {
MousePointerClickIcon,
ChevronDownIcon,
} from 'lucide-react'
-import { useState, useEffect, useMemo, useRef, useCallback, Suspense, use } from 'react'
+import {
+ useState,
+ useEffect,
+ useMemo,
+ useRef,
+ useCallback,
+ Suspense,
+ use,
+} from 'react'
import { useTranslation } from 'react-i18next'
-import { useSearchParams, useFetcher, useLoaderData, useRevalidator } from 'react-router'
+import {
+ useSearchParams,
+ useFetcher,
+ useLoaderData,
+ useRevalidator,
+} from 'react-router'
import { toast } from 'sonner'
-import type { GoalsResponse, Goal, GoalStats, GoalChartData } from '~/api/api.server'
+import type {
+ GoalsResponse,
+ Goal,
+ GoalStats,
+ GoalChartData,
+} from '~/api/api.server'
import { useGoalStatsProxy, useGoalChartProxy } from '~/hooks/useAnalyticsProxy'
import {
TimeFormat,
@@ -33,9 +51,15 @@ import {
chartTypes,
} from '~/lib/constants'
import DashboardHeader from '~/pages/Project/View/components/DashboardHeader'
-import { useViewProjectContext, useRefreshTriggers } from '~/pages/Project/View/ViewProject'
+import {
+ useViewProjectContext,
+ useRefreshTriggers,
+} from '~/pages/Project/View/ViewProject'
import { useCurrentProject } from '~/providers/CurrentProjectProvider'
-import type { ProjectLoaderData, ProjectViewActionData } from '~/routes/projects.$id'
+import type {
+ ProjectLoaderData,
+ ProjectViewActionData,
+} from '~/routes/projects.$id'
import BillboardChart from '~/ui/BillboardChart'
import Button from '~/ui/Button'
import Spin from '~/ui/icons/Spin'
@@ -54,8 +78,13 @@ import GoalSettingsModal from './GoalSettingsModal'
const DEFAULT_GOALS_TAKE = 20
// Calculate optimal Y axis ticks
-const calculateOptimalTicks = (data: number[], targetCount: number = 6): number[] => {
- const validData = data.filter((n) => n !== undefined && n !== null && Number.isFinite(n))
+const calculateOptimalTicks = (
+ data: number[],
+ targetCount: number = 6,
+): number[] => {
+ const validData = data.filter(
+ (n) => n !== undefined && n !== null && Number.isFinite(n),
+ )
if (validData.length === 0) {
return [0, 1]
@@ -116,11 +145,13 @@ const getGoalChartSettings = (
]
// Calculate optimal Y axis ticks
- const allYValues: number[] = [...chartData.conversions, ...chartData.uniqueSessions].filter(
- (n) => n !== undefined && n !== null,
- )
+ const allYValues: number[] = [
+ ...chartData.conversions,
+ ...chartData.uniqueSessions,
+ ].filter((n) => n !== undefined && n !== null)
- const optimalTicks = allYValues.length > 0 ? calculateOptimalTicks(allYValues) : undefined
+ const optimalTicks =
+ allYValues.length > 0 ? calculateOptimalTicks(allYValues) : undefined
return {
data: {
@@ -157,8 +188,14 @@ const getGoalChartSettings = (
format:
// @ts-expect-error
timeFormat === TimeFormat['24-hour']
- ? (x: string) => d3.timeFormat(tbsFormatMapper24h[timeBucket])(x as unknown as Date)
- : (x: string) => d3.timeFormat(tbsFormatMapper[timeBucket])(x as unknown as Date),
+ ? (x: string) =>
+ d3.timeFormat(tbsFormatMapper24h[timeBucket])(
+ x as unknown as Date,
+ )
+ : (x: string) =>
+ d3.timeFormat(tbsFormatMapper[timeBucket])(
+ x as unknown as Date,
+ ),
},
localtime: timeFormat === TimeFormat['24-hour'],
type: 'timeseries',
@@ -257,16 +294,27 @@ const GoalRow = ({
const patternDisplay = useMemo(() => {
if (!goal.value) return null
- const matchPrefix = goal.matchType === 'exact' ? '= ' : goal.matchType === 'contains' ? '~ ' : ''
+ const matchPrefix =
+ goal.matchType === 'exact'
+ ? '= '
+ : goal.matchType === 'contains'
+ ? '~ '
+ : ''
return `${matchPrefix}${goal.value}`
}, [goal.value, goal.matchType])
const chartOptions = useMemo(() => {
if (!chartData || !chartData.x || chartData.x.length === 0) return null
- return getGoalChartSettings(chartData, timeBucket, timeFormat, chartTypes.line, {
- conversions: t('goals.conversions'),
- sessions: t('project.sessions'),
- })
+ return getGoalChartSettings(
+ chartData,
+ timeBucket,
+ timeFormat,
+ chartTypes.line,
+ {
+ conversions: t('goals.conversions'),
+ sessions: t('project.sessions'),
+ },
+ )
}, [chartData, timeBucket, timeFormat, t])
return (
@@ -279,16 +327,33 @@ const GoalRow = ({
>
<div className='flex min-w-0 gap-x-4'>
<div className='min-w-0 flex-auto'>
- <Text as='p' weight='semibold' truncate className='flex items-center gap-x-1.5'>
+ <Text
+ as='p'
+ weight='semibold'
+ truncate
+ className='flex items-center gap-x-1.5'
+ >
{goal.type === 'pageview' ? (
- <FileTextIcon className='size-4 text-blue-500' strokeWidth={1.5} />
+ <FileTextIcon
+ className='size-4 text-blue-500'
+ strokeWidth={1.5}
+ />
) : (
- <MousePointerClickIcon className='size-4 text-amber-500' strokeWidth={1.5} />
+ <MousePointerClickIcon
+ className='size-4 text-amber-500'
+ strokeWidth={1.5}
+ />
)}
<span>{goal.name}</span>
</Text>
{patternDisplay ? (
- <Text className='mt-1 max-w-max' as='p' size='xs' colour='secondary' code>
+ <Text
+ className='mt-1 max-w-max'
+ as='p'
+ size='xs'
+ colour='secondary'
+ code
+ >
{patternDisplay}
</Text>
) : null}
@@ -308,7 +373,11 @@ const GoalRow = ({
{t('goals.conversions').toLowerCase()}
</Text>
</span>
- <ProgressRing value={stats.conversionRate} size={36} strokeWidth={3} />
+ <ProgressRing
+ value={stats.conversionRate}
+ size={36}
+ strokeWidth={3}
+ />
</>
) : (
<Text as='p' size='xs' colour='muted'>
@@ -334,7 +403,11 @@ const GoalRow = ({
{t('goals.conversions').toLowerCase()}
</Text>
</p>
- <ProgressRing value={stats.conversionRate} size={44} strokeWidth={3.5} />
+ <ProgressRing
+ value={stats.conversionRate}
+ size={44}
+ strokeWidth={3.5}
+ />
</>
) : (
<Text as='p' size='sm' colour='muted'>
@@ -369,9 +442,12 @@ const GoalRow = ({
<Trash2Icon className='size-4' strokeWidth={1.5} />
</button>
<ChevronDownIcon
- className={cx('size-5 text-gray-500 transition-transform dark:text-gray-400', {
- 'rotate-180': isExpanded,
- })}
+ className={cx(
+ 'size-5 text-gray-500 transition-transform dark:text-gray-400',
+ {
+ 'rotate-180': isExpanded,
+ },
+ )}
strokeWidth={1.5}
/>
</div>
@@ -385,7 +461,10 @@ const GoalRow = ({
<div className='flex h-[200px] items-center justify-center'>
<Spin className='size-8' />
</div>
- ) : chartData && chartData.x && chartData.x.length > 0 && chartOptions ? (
+ ) : chartData &&
+ chartData.x &&
+ chartData.x.length > 0 &&
+ chartOptions ? (
<BillboardChart options={chartOptions} className='h-[200px]' />
) : (
<div className='flex h-[200px] items-center justify-center'>
@@ -426,7 +505,11 @@ interface DeferredGoalsData {
goalsData: GoalsResponse | null
}
-function GoalsDataResolver({ children }: { children: (data: DeferredGoalsData) => React.ReactNode }) {
+function GoalsDataResolver({
+ children,
+}: {
+ children: (data: DeferredGoalsData) => React.ReactNode
+}) {
const { goalsData: goalsDataPromise } = useLoaderData<ProjectLoaderData>()
const goalsData = goalsDataPromise ? use(goalsDataPromise) : null
return <>{children({ goalsData })}</>
@@ -436,7 +519,9 @@ function GoalsViewWrapper(props: GoalsViewProps) {
return (
<Suspense fallback={<Loader />}>
<GoalsDataResolver>
- {(deferredData) => <GoalsViewInner {...props} deferredData={deferredData} />}
+ {(deferredData) => (
+ <GoalsViewInner {...props} deferredData={deferredData} />
+ )}
</GoalsDataResolver>
</Suspense>
)
@@ -446,7 +531,13 @@ interface GoalsViewInnerProps extends GoalsViewProps {
deferredData: DeferredGoalsData
}
-const GoalsViewInner = ({ period, from = '', to = '', timezone, deferredData }: GoalsViewInnerProps) => {
+const GoalsViewInner = ({
+ period,
+ from = '',
+ to = '',
+ timezone,
+ deferredData,
+}: GoalsViewInnerProps) => {
const { id } = useCurrentProject()
const revalidator = useRevalidator()
const { goalsRefreshTrigger } = useRefreshTriggers()
@@ -459,8 +550,12 @@ const GoalsViewInner = ({ period, from = '', to = '', timezone, deferredData }:
const [isSearchMode, setIsSearchMode] = useState(false)
const isMountedRef = useRef(true)
const [total, setTotal] = useState(() => deferredData.goalsData?.total || 0)
- const [goals, setGoals] = useState<Goal[]>(() => deferredData.goalsData?.results || [])
- const [goalStats, setGoalStats] = useState<Record<string, GoalStats | null>>({})
+ const [goals, setGoals] = useState<Goal[]>(
+ () => deferredData.goalsData?.results || [],
+ )
+ const [goalStats, setGoalStats] = useState<Record<string, GoalStats | null>>(
+ {},
+ )
const [statsLoading, setStatsLoading] = useState<Record<string, boolean>>({})
const [page, setPage] = useState(1)
const [error, setError] = useState<string | null>(null)
@@ -469,7 +564,9 @@ const GoalsViewInner = ({ period, from = '', to = '', timezone, deferredData }:
// Expanded goal state
const [expandedGoalId, setExpandedGoalId] = useState<string | null>(null)
- const [goalChartData, setGoalChartData] = useState<Record<string, GoalChartData | null>>({})
+ const [goalChartData, setGoalChartData] = useState<
+ Record<string, GoalChartData | null>
+ >({})
const [chartLoading, setChartLoading] = useState<Record<string, boolean>>({})
// Modal state
@@ -488,7 +585,11 @@ const GoalsViewInner = ({ period, from = '', to = '', timezone, deferredData }:
// Sync state when loader provides new data
useEffect(() => {
- if (deferredData.goalsData && revalidator.state === 'idle' && !isSearchMode) {
+ if (
+ deferredData.goalsData &&
+ revalidator.state === 'idle' &&
+ !isSearchMode
+ ) {
setGoals(deferredData.goalsData.results || [])
setTotal(deferredData.goalsData.total || 0)
}
@@ -535,7 +636,10 @@ const GoalsViewInner = ({ period, from = '', to = '', timezone, deferredData }:
// Handle fetcher response for goals list
useEffect(() => {
- if (fetcher.data?.intent === 'get-project-goals' && fetcher.state === 'idle') {
+ if (
+ fetcher.data?.intent === 'get-project-goals' &&
+ fetcher.state === 'idle'
+ ) {
if (isMountedRef.current) {
if (fetcher.data.success && fetcher.data.data) {
const result = fetcher.data.data as { results: Goal[]; total: number }
@@ -556,7 +660,12 @@ const GoalsViewInner = ({ period, from = '', to = '', timezone, deferredData }:
const loadGoalStats = async (goalId: string) => {
setStatsLoading((prev) => ({ ...prev, [goalId]: true }))
try {
- const stats = await statsProxy.fetchStats(goalId, { period, from, to, timezone })
+ const stats = await statsProxy.fetchStats(goalId, {
+ period,
+ from,
+ to,
+ timezone,
+ })
if (isMountedRef.current) {
setGoalStats((prev) => ({ ...prev, [goalId]: stats }))
}
@@ -573,9 +682,18 @@ const GoalsViewInner = ({ period, from = '', to = '', timezone, deferredData }:
}
const loadGoalChartData = async (goalId: string, showLoading = true) => {
- setChartLoading((prev) => ({ ...prev, [goalId]: showLoading ? true : prev[goalId] }))
+ setChartLoading((prev) => ({
+ ...prev,
+ [goalId]: showLoading ? true : prev[goalId],
+ }))
try {
- const result = await chartProxy.fetchChart(goalId, { period, from, to, timeBucket, timezone })
+ const result = await chartProxy.fetchChart(goalId, {
+ period,
+ from,
+ to,
+ timeBucket,
+ timezone,
+ })
if (isMountedRef.current && result) {
setGoalChartData((prev) => ({ ...prev, [goalId]: result.chart }))
}
@@ -607,7 +725,11 @@ const GoalsViewInner = ({ period, from = '', to = '', timezone, deferredData }:
// Handle page/search changes - use fetcher for pagination
useEffect(() => {
if (page > 1 || debouncedSearch || isSearchMode) {
- loadGoals(DEFAULT_GOALS_TAKE, (page - 1) * DEFAULT_GOALS_TAKE, debouncedSearch || undefined)
+ loadGoals(
+ DEFAULT_GOALS_TAKE,
+ (page - 1) * DEFAULT_GOALS_TAKE,
+ debouncedSearch || undefined,
+ )
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [page, debouncedSearch])
@@ -637,7 +759,11 @@ const GoalsViewInner = ({ period, from = '', to = '', timezone, deferredData }:
setIsSearchMode(false)
revalidator.revalidate()
} else {
- loadGoals(DEFAULT_GOALS_TAKE, (page - 1) * DEFAULT_GOALS_TAKE, debouncedSearch || undefined)
+ loadGoals(
+ DEFAULT_GOALS_TAKE,
+ (page - 1) * DEFAULT_GOALS_TAKE,
+ debouncedSearch || undefined,
+ )
}
// Clear cached chart data for non-expanded goals, silently refresh expanded goal
if (expandedGoalId) {
@@ -670,7 +796,11 @@ const GoalsViewInner = ({ period, from = '', to = '', timezone, deferredData }:
setIsSearchMode(false)
revalidator.revalidate()
} else {
- loadGoals(DEFAULT_GOALS_TAKE, (page - 1) * DEFAULT_GOALS_TAKE, debouncedSearch || undefined)
+ loadGoals(
+ DEFAULT_GOALS_TAKE,
+ (page - 1) * DEFAULT_GOALS_TAKE,
+ debouncedSearch || undefined,
+ )
}
}
@@ -682,7 +812,11 @@ const GoalsViewInner = ({ period, from = '', to = '', timezone, deferredData }:
setIsSearchMode(false)
revalidator.revalidate()
} else {
- loadGoals(DEFAULT_GOALS_TAKE, (page - 1) * DEFAULT_GOALS_TAKE, debouncedSearch || undefined)
+ loadGoals(
+ DEFAULT_GOALS_TAKE,
+ (page - 1) * DEFAULT_GOALS_TAKE,
+ debouncedSearch || undefined,
+ )
}
} else if (fetcher.data?.error && fetcher.data?.intent === 'delete-goal') {
toast.error(fetcher.data.error)
@@ -703,7 +837,11 @@ const GoalsViewInner = ({ period, from = '', to = '', timezone, deferredData }:
title={t('apiNotifications.somethingWentWrong')}
description={t('apiNotifications.errorCode', { error })}
actions={[
- { label: t('dashboard.reloadPage'), onClick: () => window.location.reload(), primary: true },
+ {
+ label: t('dashboard.reloadPage'),
+ onClick: () => window.location.reload(),
+ primary: true,
+ },
{ label: t('notFoundPage.support'), to: routes.contact },
]}
/>
@@ -721,7 +859,9 @@ const GoalsViewInner = ({ period, from = '', to = '', timezone, deferredData }:
<TargetIcon className='mr-2 h-8 w-8' strokeWidth={1.5} />
<p className='text-3xl font-bold'>{t('goals.title')}</p>
</div>
- <p className='mt-2 text-sm whitespace-pre-wrap text-gray-100'>{t('goals.description')}</p>
+ <p className='mt-2 text-sm whitespace-pre-wrap text-gray-100'>
+ {t('goals.description')}
+ </p>
<Button
onClick={handleNewGoal}
className='mt-6 block max-w-max rounded-md border border-transparent bg-white px-3 py-2 text-sm font-medium text-gray-700 hover:bg-indigo-50 md:px-4'
diff --git a/web/app/pages/Project/tabs/Performance/PerformanceChart.tsx b/web/app/pages/Project/tabs/Performance/PerformanceChart.tsx
index 67130fdf0..3effbbe57 100644
--- a/web/app/pages/Project/tabs/Performance/PerformanceChart.tsx
+++ b/web/app/pages/Project/tabs/Performance/PerformanceChart.tsx
@@ -89,6 +89,12 @@ export const PerformanceChart = ({
)
return (
- <MainChart chartId='performance-chart' options={options} dataNames={dataNames} className={className} deps={deps} />
+ <MainChart
+ chartId='performance-chart'
+ options={options}
+ dataNames={dataNames}
+ className={className}
+ deps={deps}
+ />
)
}
diff --git a/web/app/pages/Project/tabs/Performance/PerformanceView.tsx b/web/app/pages/Project/tabs/Performance/PerformanceView.tsx
index 1ed461d86..a985f0a65 100644
--- a/web/app/pages/Project/tabs/Performance/PerformanceView.tsx
+++ b/web/app/pages/Project/tabs/Performance/PerformanceView.tsx
@@ -3,12 +3,28 @@ import _isEmpty from 'lodash/isEmpty'
import _keys from 'lodash/keys'
import _map from 'lodash/map'
import { EyeIcon, PercentIcon } from 'lucide-react'
-import { useState, useEffect, useMemo, useRef, lazy, Suspense, use } from 'react'
+import {
+ useState,
+ useEffect,
+ useMemo,
+ useRef,
+ lazy,
+ Suspense,
+ use,
+} from 'react'
import { createPortal } from 'react-dom'
import { useTranslation } from 'react-i18next'
-import { useNavigate, useSearchParams, useLoaderData, useRevalidator } from 'react-router'
-
-import type { PerformanceDataResponse, PerformanceOverallObject } from '~/api/api.server'
+import {
+ useNavigate,
+ useSearchParams,
+ useLoaderData,
+ useRevalidator,
+} from 'react-router'
+
+import type {
+ PerformanceDataResponse,
+ PerformanceOverallObject,
+} from '~/api/api.server'
import { useAnnotations } from '~/hooks/useAnnotations'
import { PERFORMANCE_PANELS_ORDER, chartTypes } from '~/lib/constants'
import { CountryEntry } from '~/lib/models/Entry'
@@ -23,7 +39,10 @@ import DashboardHeader from '~/pages/Project/View/components/DashboardHeader'
import Filters from '~/pages/Project/View/components/Filters'
import NoEvents from '~/pages/Project/View/components/NoEvents'
import { Panel } from '~/pages/Project/View/Panels'
-import { useViewProjectContext, useRefreshTriggers } from '~/pages/Project/View/ViewProject'
+import {
+ useViewProjectContext,
+ useRefreshTriggers,
+} from '~/pages/Project/View/ViewProject'
import {
panelIconMapping,
CHART_METRICS_MAPPING_PERF,
@@ -38,7 +57,9 @@ import Loader from '~/ui/Loader'
import LoadingBar from '~/ui/LoadingBar'
import { getStringFromTime, getTimeFromSeconds } from '~/utils/generic'
-const InteractiveMap = lazy(() => import('~/pages/Project/View/components/InteractiveMap'))
+const InteractiveMap = lazy(
+ () => import('~/pages/Project/View/components/InteractiveMap'),
+)
interface PerformanceViewProps {
tnMapping: Record<string, string>
@@ -49,11 +70,20 @@ interface DeferredPerfData {
perfOverallStats: Record<string, PerformanceOverallObject> | null
}
-function PerfDataResolver({ children }: { children: (data: DeferredPerfData) => React.ReactNode }) {
- const { perfData: perfDataPromise, perfOverallStats: perfOverallStatsPromise } = useLoaderData<ProjectLoaderData>()
+function PerfDataResolver({
+ children,
+}: {
+ children: (data: DeferredPerfData) => React.ReactNode
+}) {
+ const {
+ perfData: perfDataPromise,
+ perfOverallStats: perfOverallStatsPromise,
+ } = useLoaderData<ProjectLoaderData>()
const perfData = perfDataPromise ? use(perfDataPromise) : null
- const perfOverallStats = perfOverallStatsPromise ? use(perfOverallStatsPromise) : null
+ const perfOverallStats = perfOverallStatsPromise
+ ? use(perfOverallStatsPromise)
+ : null
return <>{children({ perfData, perfOverallStats })}</>
}
@@ -62,7 +92,9 @@ function PerformanceViewWrapper(props: PerformanceViewProps) {
return (
<Suspense fallback={<Loader />}>
<PerfDataResolver>
- {(deferredData) => <PerformanceViewInner {...props} deferredData={deferredData} />}
+ {(deferredData) => (
+ <PerformanceViewInner {...props} deferredData={deferredData} />
+ )}
</PerfDataResolver>
</Suspense>
)
@@ -72,7 +104,10 @@ interface PerformanceViewInnerProps extends PerformanceViewProps {
deferredData: DeferredPerfData
}
-const PerformanceViewInner = ({ tnMapping, deferredData }: PerformanceViewInnerProps) => {
+const PerformanceViewInner = ({
+ tnMapping,
+ deferredData,
+}: PerformanceViewInnerProps) => {
const { id, project, allowedToManage } = useCurrentProject()
const revalidator = useRevalidator()
const { performanceRefreshTrigger } = useRefreshTriggers()
@@ -132,13 +167,17 @@ const PerformanceViewInner = ({ tnMapping, deferredData }: PerformanceViewInnerP
}
return { data: {} }
})
- const [chartData, setChartData] = useState<any>(() => deferredData.perfData?.chart || {})
- const [overall, setOverall] = useState<Partial<OverallPerformanceObject>>(() => {
- if (deferredData.perfOverallStats && id) {
- return deferredData.perfOverallStats[id] || {}
- }
- return {}
- })
+ const [chartData, setChartData] = useState<any>(
+ () => deferredData.perfData?.chart || {},
+ )
+ const [overall, setOverall] = useState<Partial<OverallPerformanceObject>>(
+ () => {
+ if (deferredData.perfOverallStats && id) {
+ return deferredData.perfOverallStats[id] || {}
+ }
+ return {}
+ },
+ )
// Track if we've ever shown actual content to prevent NoEvents flash during exit animation
const hasShownContentRef = useRef(false)
@@ -172,8 +211,10 @@ const PerformanceViewInner = ({ tnMapping, deferredData }: PerformanceViewInnerP
}, [revalidator.state, deferredData, id])
// Get chart metrics and measure from URL params (SSR-friendly)
- const activeChartMetrics = searchParams.get('perfMetric') || CHART_METRICS_MAPPING_PERF.timing
- const activeMeasure = searchParams.get('measure') || CHART_MEASURES_MAPPING_PERF.median
+ const activeChartMetrics =
+ searchParams.get('perfMetric') || CHART_METRICS_MAPPING_PERF.timing
+ const activeMeasure =
+ searchParams.get('measure') || CHART_MEASURES_MAPPING_PERF.median
// Update URL when changing chart metrics or measure
const setActiveChartMetrics = (metric: string) => {
@@ -289,7 +330,9 @@ const PerformanceViewInner = ({ tnMapping, deferredData }: PerformanceViewInnerP
const createVersionDataMapping = useMemo(() => {
const browserDataSource = panelsData.data?.brv
- const browserVersions: { [key: string]: { name: string; count: number }[] } = {}
+ const browserVersions: {
+ [key: string]: { name: string; count: number }[]
+ } = {}
if (browserDataSource) {
browserDataSource.forEach((entry: any) => {
@@ -322,7 +365,13 @@ const PerformanceViewInner = ({ tnMapping, deferredData }: PerformanceViewInnerP
)
}
- const ChartTypeSwitcher = ({ type, onSwitch }: { type: string; onSwitch: (type: 'line' | 'bar') => void }) => {
+ const ChartTypeSwitcher = ({
+ type,
+ onSwitch,
+ }: {
+ type: string
+ onSwitch: (type: 'line' | 'bar') => void
+ }) => {
if (type === chartTypes.bar) {
return (
<button
@@ -376,7 +425,10 @@ const PerformanceViewInner = ({ tnMapping, deferredData }: PerformanceViewInnerP
if (isMapFullscreen && fullscreenMapRef.current) {
const countryData = panelsData.data?.cc || []
const regionData = panelsData.data?.rg || []
- const total = countryData.reduce((acc: number, curr: any) => acc + curr.count, 0)
+ const total = countryData.reduce(
+ (acc: number, curr: any) => acc + curr.count,
+ 0,
+ )
return createPortal(
<Suspense
@@ -384,7 +436,9 @@ const PerformanceViewInner = ({ tnMapping, deferredData }: PerformanceViewInnerP
<div className='flex h-full flex-1 items-center justify-center'>
<div className='flex flex-col items-center gap-2'>
<div className='h-8 w-8 animate-spin rounded-full border-2 border-indigo-400 border-t-transparent' />
- <span className='text-sm text-neutral-600 dark:text-neutral-300'>Loading map...</span>
+ <span className='text-sm text-neutral-600 dark:text-neutral-300'>
+ Loading map...
+ </span>
</div>
</div>
}
@@ -410,14 +464,22 @@ const PerformanceViewInner = ({ tnMapping, deferredData }: PerformanceViewInnerP
<DashboardHeader />
{dataLoading && !isPanelsDataEmpty ? <LoadingBar /> : null}
<div className={cx({ hidden: isPanelsDataEmpty })}>
- {!isPanelsDataEmpty ? <Filters className='mb-3' tnMapping={tnMapping} /> : null}
+ {!isPanelsDataEmpty ? (
+ <Filters className='mb-3' tnMapping={tnMapping} />
+ ) : null}
<div className='relative overflow-hidden rounded-lg border border-gray-200 bg-white p-4 dark:border-slate-800/60 dark:bg-slate-800/25'>
<div className='mb-3 flex w-full items-center justify-end gap-2 lg:absolute lg:top-2 lg:right-2 lg:mb-0 lg:w-auto lg:justify-normal'>
<Dropdown
items={chartMetrics}
className='xs:min-w-0'
header={t('main.metric')}
- title={[<EyeIcon key='eye-icon' aria-label={t('project.metricVis')} className='h-5 w-5' />]}
+ title={[
+ <EyeIcon
+ key='eye-icon'
+ aria-label={t('project.metricVis')}
+ className='h-5 w-5'
+ />,
+ ]}
labelExtractor={(pair) => pair.label}
keyExtractor={(pair) => pair.id}
onSelect={({ id: pairID }) => {
@@ -428,11 +490,19 @@ const PerformanceViewInner = ({ tnMapping, deferredData }: PerformanceViewInnerP
headless
/>
<Dropdown
- disabled={activeChartMetrics === CHART_METRICS_MAPPING_PERF.quantiles}
+ disabled={
+ activeChartMetrics === CHART_METRICS_MAPPING_PERF.quantiles
+ }
items={chartMeasures}
className='xs:min-w-0'
header={t('project.aggregation')}
- title={[<PercentIcon key='percent-icon' aria-label={t('project.aggregation')} className='h-5 w-5' />]}
+ title={[
+ <PercentIcon
+ key='percent-icon'
+ aria-label={t('project.aggregation')}
+ className='h-5 w-5'
+ />,
+ ]}
labelExtractor={(pair) => pair.label}
keyExtractor={(pair) => pair.id}
onSelect={({ id: pairID }) => {
@@ -442,7 +512,10 @@ const PerformanceViewInner = ({ tnMapping, deferredData }: PerformanceViewInnerP
chevron='mini'
headless
/>
- <ChartTypeSwitcher onSwitch={setChartTypeOnClick} type={chartType} />
+ <ChartTypeSwitcher
+ onSwitch={setChartTypeOnClick}
+ type={chartType}
+ />
</div>
{!_isEmpty(overall) ? (
@@ -453,7 +526,10 @@ const PerformanceViewInner = ({ tnMapping, deferredData }: PerformanceViewInnerP
/>
) : null}
{activeChartMetrics && !_isEmpty(chartData) ? (
- <div onContextMenu={(e) => handleChartContextMenu(e, chartData?.x)} className='relative'>
+ <div
+ onContextMenu={(e) => handleChartContextMenu(e, chartData?.x)}
+ className='relative'
+ >
<PerformanceChart
chart={chartData}
timeBucket={timeBucket}
@@ -486,7 +562,13 @@ const PerformanceViewInner = ({ tnMapping, deferredData }: PerformanceViewInnerP
const { name: entryName, cc } = entry
if (cc !== undefined) {
- return <CCRow cc={cc} name={entryName || undefined} language={language} />
+ return (
+ <CCRow
+ cc={cc}
+ name={entryName || undefined}
+ language={language}
+ />
+ )
}
return <CCRow cc={entryName} language={language} />
@@ -510,14 +592,19 @@ const PerformanceViewInner = ({ tnMapping, deferredData }: PerformanceViewInnerP
data={panelsData.data[activeTabs.location]}
rowMapper={rowMapper}
// @ts-expect-error
- valueMapper={(value) => getStringFromTime(getTimeFromSeconds(value), true)}
+ valueMapper={(value) =>
+ getStringFromTime(getTimeFromSeconds(value), true)
+ }
customRenderer={
activeTabs.location === 'map'
? () => {
const countryData = panelsData.data?.cc || []
const regionData = panelsData.data?.rg || []
// @ts-expect-error
- const total = countryData.reduce((acc, curr) => acc + curr.count, 0)
+ const total = countryData.reduce(
+ (acc, curr) => acc + curr.count,
+ 0,
+ )
return (
<Suspense
@@ -576,12 +663,24 @@ const PerformanceViewInner = ({ tnMapping, deferredData }: PerformanceViewInnerP
}
activeTabId={activeTabs.device}
data={panelsData.data[activeTabs.device]}
- rowMapper={getDeviceRowMapper(activeTabs.device, theme, t)}
+ rowMapper={getDeviceRowMapper(
+ activeTabs.device,
+ theme,
+ t,
+ )}
capitalize={activeTabs.device === 'dv'}
- versionData={activeTabs.device === 'br' ? createVersionDataMapping.browserVersions : undefined}
- getVersionFilterLink={(parent, version) => getVersionFilterLink(parent, version, 'br')}
+ versionData={
+ activeTabs.device === 'br'
+ ? createVersionDataMapping.browserVersions
+ : undefined
+ }
+ getVersionFilterLink={(parent, version) =>
+ getVersionFilterLink(parent, version, 'br')
+ }
// @ts-expect-error
- valueMapper={(value) => getStringFromTime(getTimeFromSeconds(value), true)}
+ valueMapper={(value) =>
+ getStringFromTime(getTimeFromSeconds(value), true)
+ }
valuesHeaderName={t('project.loadTime')}
highlightColour='orange'
/>
@@ -607,7 +706,9 @@ const PerformanceViewInner = ({ tnMapping, deferredData }: PerformanceViewInnerP
if (!entryName) {
return (
<span className='italic'>
- {activeTabs.page === 'pg' ? t('common.notSet') : t('project.unknownHost')}
+ {activeTabs.page === 'pg'
+ ? t('common.notSet')
+ : t('project.unknownHost')}
</span>
)
}
@@ -622,7 +723,12 @@ const PerformanceViewInner = ({ tnMapping, deferredData }: PerformanceViewInnerP
// For page paths (pg tab), show with clickable link
if (activeTabs.page === 'pg' && project?.websiteUrl) {
- return <PageLinkRow pagePath={decodedUri} websiteUrl={project.websiteUrl} />
+ return (
+ <PageLinkRow
+ pagePath={decodedUri}
+ websiteUrl={project.websiteUrl}
+ />
+ )
}
return decodedUri
@@ -638,7 +744,9 @@ const PerformanceViewInner = ({ tnMapping, deferredData }: PerformanceViewInnerP
activeTabId={activeTabs.page}
data={panelsData.data[activeTabs.page]}
// @ts-expect-error
- valueMapper={(value) => getStringFromTime(getTimeFromSeconds(value), true)}
+ valueMapper={(value) =>
+ getStringFromTime(getTimeFromSeconds(value), true)
+ }
valuesHeaderName={t('project.loadTime')}
highlightColour='orange'
/>
@@ -669,7 +777,11 @@ const PerformanceViewInner = ({ tnMapping, deferredData }: PerformanceViewInnerP
}}
onEditAnnotation={
contextMenu.annotation
- ? () => openAnnotationModal(contextMenu.annotation?.date, contextMenu.annotation!)
+ ? () =>
+ openAnnotationModal(
+ contextMenu.annotation?.date,
+ contextMenu.annotation!,
+ )
: undefined
}
onDeleteAnnotation={
diff --git a/web/app/pages/Project/tabs/Profiles/ProfileDetails.tsx b/web/app/pages/Project/tabs/Profiles/ProfileDetails.tsx
index 6cdeb9ca8..f0b0cc175 100644
--- a/web/app/pages/Project/tabs/Profiles/ProfileDetails.tsx
+++ b/web/app/pages/Project/tabs/Profiles/ProfileDetails.tsx
@@ -16,14 +16,26 @@ import {
import { useMemo } from 'react'
import { useTranslation } from 'react-i18next'
-import { BROWSER_LOGO_MAP, OS_LOGO_MAP, OS_LOGO_MAP_DARK } from '~/lib/constants'
-import { ProfileDetails as ProfileDetailsType, Session } from '~/lib/models/Project'
+import {
+ BROWSER_LOGO_MAP,
+ OS_LOGO_MAP,
+ OS_LOGO_MAP_DARK,
+} from '~/lib/constants'
+import {
+ ProfileDetails as ProfileDetailsType,
+ Session,
+} from '~/lib/models/Project'
import { useTheme } from '~/providers/ThemeProvider'
import Button from '~/ui/Button'
import Loader from '~/ui/Loader'
import { Text } from '~/ui/Text'
import Tooltip from '~/ui/Tooltip'
-import { cn, getLocaleDisplayName, getStringFromTime, getTimeFromSeconds } from '~/utils/generic'
+import {
+ cn,
+ getLocaleDisplayName,
+ getStringFromTime,
+ getTimeFromSeconds,
+} from '~/utils/generic'
import { getProfileDisplayName, ProfileAvatar } from '~/utils/profileAvatars'
import CCRow from '../../View/components/CCRow'
@@ -40,7 +52,11 @@ interface ProfileDetailsProps {
currency?: string
}
-const ActivityCalendar = ({ data }: { data: { date: string; count: number }[] }) => {
+const ActivityCalendar = ({
+ data,
+}: {
+ data: { date: string; count: number }[]
+}) => {
const { t } = useTranslation('common')
const countMap = useMemo(() => {
@@ -95,7 +111,11 @@ const ActivityCalendar = ({ data }: { data: { date: string; count: number }[] })
const dayLabels = ['S', 'M', 'T', 'W', 'T', 'F', 'S']
- const TooltipContent = ({ day }: { day: { date: string; count: number } }) => (
+ const TooltipContent = ({
+ day,
+ }: {
+ day: { date: string; count: number }
+ }) => (
<div className='text-center'>
<div className='font-medium'>{dayjs(day.date).format('MMM D, YYYY')}</div>
<div className='text-gray-300'>
@@ -106,9 +126,15 @@ const ActivityCalendar = ({ data }: { data: { date: string; count: number }[] })
return (
<div className='w-full'>
- <div className='mb-1 flex w-full gap-[2px]' style={{ paddingLeft: '18px' }}>
+ <div
+ className='mb-1 flex w-full gap-[2px]'
+ style={{ paddingLeft: '18px' }}
+ >
{weeks.map((_, weekIdx) => (
- <div key={weekIdx} className='relative flex-1 text-[10px] text-gray-400'>
+ <div
+ key={weekIdx}
+ className='relative flex-1 text-[10px] text-gray-400'
+ >
{monthLabels.find((m) => m.weekIndex === weekIdx)?.month}
</div>
))}
@@ -128,7 +154,14 @@ const ActivityCalendar = ({ data }: { data: { date: string; count: number }[] })
<Tooltip
key={dayIdx}
text={<TooltipContent day={day} />}
- tooltipNode={<div className={cn('h-3 w-full rounded-[2px]', getColor(day.count))} />}
+ tooltipNode={
+ <div
+ className={cn(
+ 'h-3 w-full rounded-[2px]',
+ getColor(day.count),
+ )}
+ />
+ }
delay={0}
disableHoverableContent
/>
@@ -141,9 +174,22 @@ const ActivityCalendar = ({ data }: { data: { date: string; count: number }[] })
)
}
-const StatItem = ({ icon, label, value }: { icon: React.ReactNode; label: string; value: string | number }) => (
+const StatItem = ({
+ icon,
+ label,
+ value,
+}: {
+ icon: React.ReactNode
+ label: string
+ value: string | number
+}) => (
<div>
- <Text size='xxs' weight='medium' colour='muted' className='mb-0.5 flex items-center gap-1.5 uppercase'>
+ <Text
+ size='xxs'
+ weight='medium'
+ colour='muted'
+ className='mb-0.5 flex items-center gap-1.5 uppercase'
+ >
{icon}
{label}
</Text>
@@ -153,12 +199,23 @@ const StatItem = ({ icon, label, value }: { icon: React.ReactNode; label: string
</div>
)
-const InfoRow = ({ label, value }: { label: string; value: React.ReactNode }) => (
+const InfoRow = ({
+ label,
+ value,
+}: {
+ label: string
+ value: React.ReactNode
+}) => (
<div className='flex items-center justify-between border-b border-gray-100 py-2 last:border-0 dark:border-slate-700/50'>
<Text size='sm' colour='muted'>
{label}
</Text>
- <Text size='sm' weight='medium' colour='primary' className='flex items-center gap-1'>
+ <Text
+ size='sm'
+ weight='medium'
+ colour='primary'
+ className='flex items-center gap-1'
+ >
{value}
</Text>
</div>
@@ -231,14 +288,20 @@ export const ProfileDetails = ({
if (!details) return <Loader />
- const avgDurationStr = details.avgDuration ? getStringFromTime(getTimeFromSeconds(details.avgDuration)) : 'N/A'
+ const avgDurationStr = details.avgDuration
+ ? getStringFromTime(getTimeFromSeconds(details.avgDuration))
+ : 'N/A'
return (
<div className='flex flex-col gap-3 lg:flex-row'>
<div className='space-y-3 lg:w-[380px]'>
<div className='rounded-lg border border-gray-300 bg-white px-4 py-5 dark:border-slate-800/60 dark:bg-slate-800/25'>
<div className='flex items-center gap-4'>
- <ProfileAvatar className='-mr-0.75 -mb-0.75' profileId={details.profileId} size={42} />
+ <ProfileAvatar
+ className='-mr-0.75 -mb-0.75'
+ profileId={details.profileId}
+ size={42}
+ />
<div className='flex flex-col gap-0.5'>
<Text size='base' weight='bold' colour='primary'>
{displayName}
@@ -294,18 +357,35 @@ export const ProfileDetails = ({
</div>
<div className='rounded-lg border border-gray-300 bg-white px-4 py-5 dark:border-slate-800/60 dark:bg-slate-800/25'>
- <Text as='h3' size='xs' weight='semibold' colour='primary' className='mb-2 uppercase' tracking='wide'>
+ <Text
+ as='h3'
+ size='xs'
+ weight='semibold'
+ colour='primary'
+ className='mb-2 uppercase'
+ tracking='wide'
+ >
{t('project.locationAndDevice')}
</Text>
<div>
<InfoRow
label={t('project.mapping.cc')}
- value={details.cc ? <CCRow size={16} cc={details.cc} language={language} /> : '-'}
+ value={
+ details.cc ? (
+ <CCRow size={16} cc={details.cc} language={language} />
+ ) : (
+ '-'
+ )
+ }
/>
- {details.rg ? <InfoRow label={t('project.mapping.rg')} value={details.rg} /> : null}
+ {details.rg ? (
+ <InfoRow label={t('project.mapping.rg')} value={details.rg} />
+ ) : null}
<InfoRow
label={t('project.mapping.lc')}
- value={details.lc ? getLocaleDisplayName(details.lc, language) : '-'}
+ value={
+ details.lc ? getLocaleDisplayName(details.lc, language) : '-'
+ }
/>
<InfoRow
label={t('project.mapping.dv')}
@@ -352,7 +432,14 @@ export const ProfileDetails = ({
</div>
<div className='rounded-lg border border-gray-300 bg-white px-4 py-5 dark:border-slate-800/60 dark:bg-slate-800/25'>
- <Text as='h3' size='xs' weight='semibold' colour='primary' className='mb-2 uppercase' tracking='wide'>
+ <Text
+ as='h3'
+ size='xs'
+ weight='semibold'
+ colour='primary'
+ className='mb-2 uppercase'
+ tracking='wide'
+ >
{t('project.activityCalendar')}
</Text>
<ActivityCalendar data={details.activityCalendar || []} />
@@ -362,7 +449,14 @@ export const ProfileDetails = ({
<div className='flex-1 space-y-3'>
{details.chart && !_isEmpty(details.chart.x) ? (
<div className='max-h-max rounded-lg border border-gray-300 bg-white px-4 py-5 dark:border-slate-800/60 dark:bg-slate-800/25'>
- <Text as='h3' size='xs' weight='semibold' colour='primary' className='mb-2 uppercase' tracking='wide'>
+ <Text
+ as='h3'
+ size='xs'
+ weight='semibold'
+ colour='primary'
+ className='mb-2 uppercase'
+ tracking='wide'
+ >
{t('dashboard.pageviews')}
</Text>
<SessionChart
@@ -377,13 +471,22 @@ export const ProfileDetails = ({
) : null}
<div className='rounded-lg border border-gray-300 bg-white px-4 py-5 dark:border-slate-800/60 dark:bg-slate-800/25'>
- <Text as='h3' size='xs' weight='semibold' colour='primary' className='mb-2 uppercase' tracking='wide'>
+ <Text
+ as='h3'
+ size='xs'
+ weight='semibold'
+ colour='primary'
+ className='mb-2 uppercase'
+ tracking='wide'
+ >
{t('project.userSessions')}
</Text>
{sessionsLoading && sessions.length === 0 ? (
<Loader />
) : sessions.length === 0 ? (
- <p className='py-4 text-center text-sm text-gray-400'>{t('project.noSessions')}</p>
+ <p className='py-4 text-center text-sm text-gray-400'>
+ {t('project.noSessions')}
+ </p>
) : (
<>
<Sessions
diff --git a/web/app/pages/Project/tabs/Profiles/Profiles.tsx b/web/app/pages/Project/tabs/Profiles/Profiles.tsx
index 9c417bc21..94491c2eb 100644
--- a/web/app/pages/Project/tabs/Profiles/Profiles.tsx
+++ b/web/app/pages/Project/tabs/Profiles/Profiles.tsx
@@ -3,7 +3,13 @@ import cx from 'clsx'
import dayjs from 'dayjs'
import relativeTime from 'dayjs/plugin/relativeTime'
import _map from 'lodash/map'
-import { BugIcon, FileTextIcon, MousePointerClickIcon, UsersIcon, CalendarIcon } from 'lucide-react'
+import {
+ BugIcon,
+ FileTextIcon,
+ MousePointerClickIcon,
+ UsersIcon,
+ CalendarIcon,
+} from 'lucide-react'
import React, { useMemo } from 'react'
import { useTranslation } from 'react-i18next'
import { Link, useLocation } from 'react-router'
@@ -80,9 +86,15 @@ const ProfileRow = ({ profile, timeFormat }: ProfileRowProps) => {
})
}, [profile.lastSeen, language, timeFormat])
- const onlineStatus = useMemo(() => getOnlineStatus(profile.lastSeen), [profile.lastSeen])
+ const onlineStatus = useMemo(
+ () => getOnlineStatus(profile.lastSeen),
+ [profile.lastSeen],
+ )
- const lastSeenAgo = useMemo(() => dayjs(profile.lastSeen).fromNow(), [profile.lastSeen])
+ const lastSeenAgo = useMemo(
+ () => dayjs(profile.lastSeen).fromNow(),
+ [profile.lastSeen],
+ )
const params = new URLSearchParams(location.search)
params.set('profileId', profile.profileId)
@@ -92,7 +104,11 @@ const ProfileRow = ({ profile, timeFormat }: ProfileRowProps) => {
<li className='relative mb-3 flex cursor-pointer justify-between gap-x-6 overflow-hidden rounded-lg border border-gray-200 bg-gray-50 px-4 py-4 transition-colors hover:bg-gray-200/70 sm:px-6 dark:border-slate-800/25 dark:bg-slate-800/70 dark:hover:bg-slate-700/60'>
<div className='flex min-w-0 gap-x-3'>
<div className='relative shrink-0'>
- <ProfileAvatar className='mt-1' profileId={profile.profileId} size={40} />
+ <ProfileAvatar
+ className='mt-1'
+ profileId={profile.profileId}
+ size={40}
+ />
{onlineStatus === 'offline' ? null : (
<Tooltip
text={t('project.lastSeenAgo', { time: lastSeenAgo })}
@@ -113,11 +129,21 @@ const ProfileRow = ({ profile, timeFormat }: ProfileRowProps) => {
<div className='min-w-0 flex-auto'>
<p className='flex items-center text-sm leading-6 font-semibold text-gray-900 dark:text-gray-50'>
<span className='truncate'>{displayName}</span>
- {profile.isIdentified ? <Badge label={t('project.identified')} colour='indigo' className='ml-2' /> : null}
+ {profile.isIdentified ? (
+ <Badge
+ label={t('project.identified')}
+ colour='indigo'
+ className='ml-2'
+ />
+ ) : null}
</p>
<p className='mt-1 flex flex-wrap items-center gap-x-2 text-xs leading-5 text-gray-500 dark:text-gray-300'>
<span className='flex items-center'>
- {profile.cc ? <CCRow size={18} cc={profile.cc} language={language} /> : t('project.unknownCountry')}
+ {profile.cc ? (
+ <CCRow size={18} cc={profile.cc} language={language} />
+ ) : (
+ t('project.unknownCountry')
+ )}
</span>
<Separator />
{profile.os || t('project.unknown')}
@@ -125,20 +151,39 @@ const ProfileRow = ({ profile, timeFormat }: ProfileRowProps) => {
{profile.br || t('project.unknown')}
</p>
<p className='mt-2 flex text-xs leading-5 text-gray-500 sm:hidden dark:text-gray-300'>
- <span className='mr-2 flex items-center' title={t('project.sessions')}>
- <UsersIcon className='mr-1 size-4' strokeWidth={1.5} /> {profile.sessionsCount}
+ <span
+ className='mr-2 flex items-center'
+ title={t('project.sessions')}
+ >
+ <UsersIcon className='mr-1 size-4' strokeWidth={1.5} />{' '}
+ {profile.sessionsCount}
</span>
- <span className='mr-2 flex items-center' title={t('dashboard.pageviews')}>
- <FileTextIcon className='mr-1 size-4' strokeWidth={1.5} /> {profile.pageviewsCount}
+ <span
+ className='mr-2 flex items-center'
+ title={t('dashboard.pageviews')}
+ >
+ <FileTextIcon className='mr-1 size-4' strokeWidth={1.5} />{' '}
+ {profile.pageviewsCount}
</span>
{profile.eventsCount > 0 ? (
- <span className='mr-2 flex items-center' title={t('dashboard.events')}>
- <MousePointerClickIcon className='mr-1 size-4' strokeWidth={1.5} /> {profile.eventsCount}
+ <span
+ className='mr-2 flex items-center'
+ title={t('dashboard.events')}
+ >
+ <MousePointerClickIcon
+ className='mr-1 size-4'
+ strokeWidth={1.5}
+ />{' '}
+ {profile.eventsCount}
</span>
) : null}
{profile.errorsCount > 0 ? (
- <span className='flex items-center text-red-400' title={t('dashboard.errors')}>
- <BugIcon className='mr-1 size-4' strokeWidth={1.5} /> {profile.errorsCount}
+ <span
+ className='flex items-center text-red-400'
+ title={t('dashboard.errors')}
+ >
+ <BugIcon className='mr-1 size-4' strokeWidth={1.5} />{' '}
+ {profile.errorsCount}
</span>
) : null}
</p>
@@ -147,15 +192,32 @@ const ProfileRow = ({ profile, timeFormat }: ProfileRowProps) => {
<div className='flex shrink-0 items-center gap-x-4'>
<div className='hidden sm:flex sm:flex-col sm:items-end'>
<div className='flex items-center gap-x-3 text-sm leading-6 text-gray-900 dark:text-gray-50'>
- <span className='flex items-center' title={t('project.xSessions', { x: profile.sessionsCount })}>
- <UsersIcon className='mr-1 size-5' strokeWidth={1.5} /> {profile.sessionsCount}
+ <span
+ className='flex items-center'
+ title={t('project.xSessions', { x: profile.sessionsCount })}
+ >
+ <UsersIcon className='mr-1 size-5' strokeWidth={1.5} />{' '}
+ {profile.sessionsCount}
</span>
- <span className='flex items-center' title={t('dashboard.xPageviews', { x: profile.pageviewsCount })}>
- <FileTextIcon className='mr-1 size-5' strokeWidth={1.5} /> {profile.pageviewsCount}
+ <span
+ className='flex items-center'
+ title={t('dashboard.xPageviews', { x: profile.pageviewsCount })}
+ >
+ <FileTextIcon className='mr-1 size-5' strokeWidth={1.5} />{' '}
+ {profile.pageviewsCount}
</span>
{profile.eventsCount > 0 ? (
- <span className='flex items-center' title={t('dashboard.xCustomEvents', { x: profile.eventsCount })}>
- <MousePointerClickIcon className='mr-1 size-5' strokeWidth={1.5} /> {profile.eventsCount}
+ <span
+ className='flex items-center'
+ title={t('dashboard.xCustomEvents', {
+ x: profile.eventsCount,
+ })}
+ >
+ <MousePointerClickIcon
+ className='mr-1 size-5'
+ strokeWidth={1.5}
+ />{' '}
+ {profile.eventsCount}
</span>
) : null}
{profile.errorsCount > 0 ? (
@@ -163,7 +225,8 @@ const ProfileRow = ({ profile, timeFormat }: ProfileRowProps) => {
className='flex items-center text-red-500'
title={t('dashboard.xErrors', { x: profile.errorsCount })}
>
- <BugIcon className='mr-1 size-5' strokeWidth={1.5} /> {profile.errorsCount}
+ <BugIcon className='mr-1 size-5' strokeWidth={1.5} />{' '}
+ {profile.errorsCount}
</span>
) : null}
</div>
@@ -172,7 +235,10 @@ const ProfileRow = ({ profile, timeFormat }: ProfileRowProps) => {
{lastSeenText}
</p>
</div>
- <ChevronRightIcon className='h-5 w-5 flex-none text-gray-400' aria-hidden='true' />
+ <ChevronRightIcon
+ className='h-5 w-5 flex-none text-gray-400'
+ aria-hidden='true'
+ />
</div>
</li>
</Link>
@@ -184,12 +250,15 @@ interface ProfilesFilterProps {
onProfileTypeChange: (type: 'all' | 'anonymous' | 'identified') => void
}
-export const ProfilesFilter: React.FC<ProfilesFilterProps> = ({ profileType, onProfileTypeChange }) => {
+export const ProfilesFilter: React.FC<ProfilesFilterProps> = ({
+ profileType,
+ onProfileTypeChange,
+}) => {
const { t } = useTranslation('common')
const filterButtonClass = (isActive: boolean) =>
cx(
- 'rounded-md px-3 py-1.5 text-sm font-medium transition-colors border',
+ 'rounded-md border px-3 py-1.5 text-sm font-medium transition-colors',
isActive
? 'border-slate-900 bg-slate-900 text-gray-50 dark:border-slate-700 dark:bg-slate-800'
: 'border-gray-200 bg-gray-50 text-gray-700 hover:border-gray-300 hover:bg-white dark:border-slate-700/50 dark:bg-slate-800/50 dark:text-gray-300 dark:hover:border-slate-600 dark:hover:bg-slate-700',
@@ -234,7 +303,11 @@ export const Profiles: React.FC<UsersProps> = ({ profiles, timeFormat }) => {
{() => (
<ul className='mt-4'>
{_map(profiles, (profile) => (
- <ProfileRow key={profile.profileId} profile={profile} timeFormat={timeFormat} />
+ <ProfileRow
+ key={profile.profileId}
+ profile={profile}
+ timeFormat={timeFormat}
+ />
))}
</ul>
)}
diff --git a/web/app/pages/Project/tabs/Profiles/ProfilesView.tsx b/web/app/pages/Project/tabs/Profiles/ProfilesView.tsx
index 52dc71be5..dad0b2eb1 100644
--- a/web/app/pages/Project/tabs/Profiles/ProfilesView.tsx
+++ b/web/app/pages/Project/tabs/Profiles/ProfilesView.tsx
@@ -6,15 +6,32 @@ import { useTranslation } from 'react-i18next'
import { useSearchParams } from 'react-router'
import { ApiProfile } from '~/api/api.server'
-import { useProfilesProxy, useProfileProxy, useProfileSessionsProxy } from '~/hooks/useAnalyticsProxy'
-import { Profile, ProfileDetails as ProfileDetailsType, Session } from '~/lib/models/Project'
+import {
+ useProfilesProxy,
+ useProfileProxy,
+ useProfileSessionsProxy,
+} from '~/hooks/useAnalyticsProxy'
+import {
+ Profile,
+ ProfileDetails as ProfileDetailsType,
+ Session,
+} from '~/lib/models/Project'
import NoProfiles from '~/pages/Project/tabs/Profiles/components/NoProfiles'
import { ProfileDetails } from '~/pages/Project/tabs/Profiles/ProfileDetails'
-import { Profiles, ProfilesFilter } from '~/pages/Project/tabs/Profiles/Profiles'
+import {
+ Profiles,
+ ProfilesFilter,
+} from '~/pages/Project/tabs/Profiles/Profiles'
import DashboardHeader from '~/pages/Project/View/components/DashboardHeader'
-import { useViewProjectContext, useRefreshTriggers } from '~/pages/Project/View/ViewProject'
+import {
+ useViewProjectContext,
+ useRefreshTriggers,
+} from '~/pages/Project/View/ViewProject'
import { getFormatDate } from '~/pages/Project/View/ViewProject.helpers'
-import { useCurrentProject, useProjectPassword } from '~/providers/CurrentProjectProvider'
+import {
+ useCurrentProject,
+ useProjectPassword,
+} from '~/providers/CurrentProjectProvider'
import Loader from '~/ui/Loader'
import LoadingBar from '~/ui/LoadingBar'
@@ -45,7 +62,8 @@ const ProfilesView = ({ tnMapping }: ProfilesViewProps) => {
const { id, project } = useCurrentProject()
const projectPassword = useProjectPassword(id)
const { profilesRefreshTrigger } = useRefreshTriggers()
- const { timezone, period, dateRange, filters, timeFormat } = useViewProjectContext()
+ const { timezone, period, dateRange, filters, timeFormat } =
+ useViewProjectContext()
const { t } = useTranslation('common')
const [searchParams] = useSearchParams()
const profilesProxy = useProfilesProxy()
@@ -57,13 +75,20 @@ const ProfilesView = ({ tnMapping }: ProfilesViewProps) => {
const [canLoadMoreProfiles, setCanLoadMoreProfiles] = useState(false)
const [profiles, setProfiles] = useState<Profile[]>([])
const [profilesLoading, setProfilesLoading] = useState<boolean | null>(null)
- const [activeProfile, setActiveProfile] = useState<ProfileDetailsType | null>(null)
+ const [activeProfile, setActiveProfile] = useState<ProfileDetailsType | null>(
+ null,
+ )
const [profileLoading, setProfileLoading] = useState(false)
const [profileSessions, setProfileSessions] = useState<Session[]>([])
- const [profileSessionsLoading, setProfileSessionsLoading] = useState<boolean | null>(null)
+ const [profileSessionsLoading, setProfileSessionsLoading] = useState<
+ boolean | null
+ >(null)
const [profileSessionsSkip, setProfileSessionsSkip] = useState(0)
- const [canLoadMoreProfileSessions, setCanLoadMoreProfileSessions] = useState(false)
- const [profileTypeFilter, setProfileTypeFilter] = useState<'all' | 'anonymous' | 'identified'>('all')
+ const [canLoadMoreProfileSessions, setCanLoadMoreProfileSessions] =
+ useState(false)
+ const [profileTypeFilter, setProfileTypeFilter] = useState<
+ 'all' | 'anonymous' | 'identified'
+ >('all')
const activeProfileId = useMemo(() => {
return searchParams.get('profileId')
@@ -114,7 +139,9 @@ const ProfilesView = ({ tnMapping }: ProfilesViewProps) => {
})
if (requestId === profilesRequestIdRef.current && isMountedRef.current) {
- const profilesList = (dataProfiles?.profiles || []).map(mapApiProfileToUI)
+ const profilesList = (dataProfiles?.profiles || []).map(
+ mapApiProfileToUI,
+ )
if (override) {
setProfiles(profilesList)
} else {
@@ -127,14 +154,20 @@ const ProfilesView = ({ tnMapping }: ProfilesViewProps) => {
return SESSIONS_TAKE + prev
})
- if (!dataProfiles?.profiles || dataProfiles.profiles.length < SESSIONS_TAKE) {
+ if (
+ !dataProfiles?.profiles ||
+ dataProfiles.profiles.length < SESSIONS_TAKE
+ ) {
setCanLoadMoreProfiles(false)
} else {
setCanLoadMoreProfiles(true)
}
}
} catch (reason) {
- console.error('[ERROR](loadProfiles) Loading profiles data failed:', reason)
+ console.error(
+ '[ERROR](loadProfiles) Loading profiles data failed:',
+ reason,
+ )
} finally {
if (requestId === profilesRequestIdRef.current && isMountedRef.current) {
setProfilesLoading(false)
@@ -144,7 +177,8 @@ const ProfilesView = ({ tnMapping }: ProfilesViewProps) => {
const loadProfile = async (profileId: string) => {
const requestId = ++profileRequestIdRef.current
- const hasExistingProfileData = !!activeProfile && activeProfile.profileId === profileId
+ const hasExistingProfileData =
+ !!activeProfile && activeProfile.profileId === profileId
setProfileLoading(true)
// Avoid flicker on refresh: keep currently displayed details/sessions while we refetch.
@@ -171,7 +205,11 @@ const ProfilesView = ({ tnMapping }: ProfilesViewProps) => {
timezone,
})
- if (requestId === profileRequestIdRef.current && isMountedRef.current && data) {
+ if (
+ requestId === profileRequestIdRef.current &&
+ isMountedRef.current &&
+ data
+ ) {
setActiveProfile(data as unknown as ProfileDetailsType)
// Load initial sessions for the profile (override existing on refresh)
loadProfileSessionsData(profileId, 0, true)
@@ -188,7 +226,11 @@ const ProfilesView = ({ tnMapping }: ProfilesViewProps) => {
}
}
- const loadProfileSessionsData = async (profileId: string, forcedSkip?: number, override?: boolean) => {
+ const loadProfileSessionsData = async (
+ profileId: string,
+ forcedSkip?: number,
+ override?: boolean,
+ ) => {
if (profileSessionsLoading) {
return
}
@@ -197,7 +239,8 @@ const ProfilesView = ({ tnMapping }: ProfilesViewProps) => {
setProfileSessionsLoading(true)
try {
- const skip = typeof forcedSkip === 'number' ? forcedSkip : profileSessionsSkip
+ const skip =
+ typeof forcedSkip === 'number' ? forcedSkip : profileSessionsSkip
let from = ''
let to = ''
@@ -206,18 +249,26 @@ const ProfilesView = ({ tnMapping }: ProfilesViewProps) => {
to = getFormatDate(dateRange[1])
}
- const dataSessions = await profileSessionsProxy.fetchProfileSessions(id, profileId, {
- period: period === 'custom' && dateRange ? '' : period,
- filters,
- from,
- to,
- take: SESSIONS_TAKE,
- skip,
- timezone,
- })
-
- if (requestId === profileSessionsRequestIdRef.current && isMountedRef.current) {
- const sessionsList = (dataSessions?.sessions || []) as unknown as Session[]
+ const dataSessions = await profileSessionsProxy.fetchProfileSessions(
+ id,
+ profileId,
+ {
+ period: period === 'custom' && dateRange ? '' : period,
+ filters,
+ from,
+ to,
+ take: SESSIONS_TAKE,
+ skip,
+ timezone,
+ },
+ )
+
+ if (
+ requestId === profileSessionsRequestIdRef.current &&
+ isMountedRef.current
+ ) {
+ const sessionsList = (dataSessions?.sessions ||
+ []) as unknown as Session[]
if (override) {
setProfileSessions(sessionsList)
} else {
@@ -230,16 +281,25 @@ const ProfilesView = ({ tnMapping }: ProfilesViewProps) => {
return SESSIONS_TAKE + prev
})
- if (!dataSessions?.sessions || dataSessions.sessions.length < SESSIONS_TAKE) {
+ if (
+ !dataSessions?.sessions ||
+ dataSessions.sessions.length < SESSIONS_TAKE
+ ) {
setCanLoadMoreProfileSessions(false)
} else {
setCanLoadMoreProfileSessions(true)
}
}
} catch (reason) {
- console.error('[ERROR](loadProfileSessions) Loading profile sessions failed:', reason)
+ console.error(
+ '[ERROR](loadProfileSessions) Loading profile sessions failed:',
+ reason,
+ )
} finally {
- if (requestId === profileSessionsRequestIdRef.current && isMountedRef.current) {
+ if (
+ requestId === profileSessionsRequestIdRef.current &&
+ isMountedRef.current
+ ) {
setProfileSessionsLoading(false)
}
}
@@ -260,7 +320,17 @@ const ProfilesView = ({ tnMapping }: ProfilesViewProps) => {
setProfilesSkip(0)
loadProfiles(0, true)
// eslint-disable-next-line react-hooks/exhaustive-deps
- }, [dateRange, filters, id, period, projectPassword, timezone, project, activeProfileId, profileTypeFilter])
+ }, [
+ dateRange,
+ filters,
+ id,
+ period,
+ projectPassword,
+ timezone,
+ project,
+ activeProfileId,
+ profileTypeFilter,
+ ])
// Load single profile when profileId is set
useEffect(() => {
@@ -340,7 +410,9 @@ const ProfilesView = ({ tnMapping }: ProfilesViewProps) => {
<>
<DashboardHeader showLiveVisitors />
{profilesLoading && !_isEmpty(profiles) ? <LoadingBar /> : null}
- {!_isEmpty(profiles) ? <Filters className='mb-3' tnMapping={tnMapping} /> : null}
+ {!_isEmpty(profiles) ? (
+ <Filters className='mb-3' tnMapping={tnMapping} />
+ ) : null}
<ProfilesFilter
profileType={profileTypeFilter}
onProfileTypeChange={(type) => {
@@ -348,8 +420,12 @@ const ProfilesView = ({ tnMapping }: ProfilesViewProps) => {
setProfilesSkip(0)
}}
/>
- {(profilesLoading === null || profilesLoading) && _isEmpty(profiles) ? <Loader /> : null}
- {typeof profilesLoading === 'boolean' && !profilesLoading && _isEmpty(profiles) ? (
+ {(profilesLoading === null || profilesLoading) && _isEmpty(profiles) ? (
+ <Loader />
+ ) : null}
+ {typeof profilesLoading === 'boolean' &&
+ !profilesLoading &&
+ _isEmpty(profiles) ? (
<NoProfiles filters={filters} />
) : null}
<Profiles profiles={profiles} timeFormat={timeFormat} />
@@ -361,7 +437,8 @@ const ProfilesView = ({ tnMapping }: ProfilesViewProps) => {
className={cx(
'relative mx-auto mt-2 flex items-center rounded-md border border-transparent p-2 text-sm font-medium text-gray-700 ring-inset hover:border-gray-300 hover:bg-white focus:z-10 focus:ring-1 focus:ring-indigo-500 focus:outline-hidden dark:bg-slate-900 dark:text-gray-50 hover:dark:border-slate-700/80 dark:hover:bg-slate-800 focus:dark:ring-gray-200',
{
- 'cursor-not-allowed opacity-50': profilesLoading || profilesLoading === null,
+ 'cursor-not-allowed opacity-50':
+ profilesLoading || profilesLoading === null,
hidden: profilesLoading && _isEmpty(profiles),
},
)}
diff --git a/web/app/pages/Project/tabs/Profiles/components/NoProfiles.tsx b/web/app/pages/Project/tabs/Profiles/components/NoProfiles.tsx
index f233b0897..b84352d35 100644
--- a/web/app/pages/Project/tabs/Profiles/components/NoProfiles.tsx
+++ b/web/app/pages/Project/tabs/Profiles/components/NoProfiles.tsx
@@ -32,8 +32,15 @@ const NoProfiles = ({ filters }: NoProfilesProps) => {
<Text as='h3' size='xl' weight='medium' className='tracking-tight'>
{t('project.noProfilesTitle')}
</Text>
- <Text as='p' size='sm' colour='secondary' className='mx-auto mt-2 max-w-md'>
- {hasFilters ? t('project.noProfilesFiltersDesc') : t('project.noProfilesContent')}
+ <Text
+ as='p'
+ size='sm'
+ colour='secondary'
+ className='mx-auto mt-2 max-w-md'
+ >
+ {hasFilters
+ ? t('project.noProfilesFiltersDesc')
+ : t('project.noProfilesContent')}
</Text>
</div>
</>
diff --git a/web/app/pages/Project/tabs/Sessions/NoSessionDetails.tsx b/web/app/pages/Project/tabs/Sessions/NoSessionDetails.tsx
index b6a39302f..b46cf073f 100644
--- a/web/app/pages/Project/tabs/Sessions/NoSessionDetails.tsx
+++ b/web/app/pages/Project/tabs/Sessions/NoSessionDetails.tsx
@@ -7,9 +7,14 @@ const NoSessionDetails = () => {
return (
<div className='mx-auto w-full max-w-2xl py-16 text-center text-gray-900 dark:text-gray-50'>
<div className='mx-auto mb-6 flex size-14 items-center justify-center rounded-xl bg-gray-100 dark:bg-slate-800'>
- <FaceFrownIcon className='size-7 text-gray-700 dark:text-gray-200' strokeWidth={1.5} />
+ <FaceFrownIcon
+ className='size-7 text-gray-700 dark:text-gray-200'
+ strokeWidth={1.5}
+ />
</div>
- <h3 className='text-xl font-medium tracking-tight'>{t('project.noSessionDetails')}</h3>
+ <h3 className='text-xl font-medium tracking-tight'>
+ {t('project.noSessionDetails')}
+ </h3>
<p className='mx-auto mt-2 max-w-md text-sm whitespace-pre-line text-gray-800 dark:text-gray-200'>
{t('project.noSessionDesc')}
</p>
diff --git a/web/app/pages/Project/tabs/Sessions/Pageflow.tsx b/web/app/pages/Project/tabs/Sessions/Pageflow.tsx
index 4af692855..494861f37 100644
--- a/web/app/pages/Project/tabs/Sessions/Pageflow.tsx
+++ b/web/app/pages/Project/tabs/Sessions/Pageflow.tsx
@@ -53,11 +53,19 @@ interface PageflowItemProps {
websiteUrl?: string | null
}
-const MetadataPanel = ({ metadata, t }: { metadata: Metadata[]; t: TFunction }) => {
+const MetadataPanel = ({
+ metadata,
+ t,
+}: {
+ metadata: Metadata[]
+ t: TFunction
+}) => {
const [showAll, setShowAll] = useState(false)
const INITIAL_SHOW_COUNT = 5
const hasMore = metadata.length > INITIAL_SHOW_COUNT
- const displayedMetadata = showAll ? metadata : metadata.slice(0, INITIAL_SHOW_COUNT)
+ const displayedMetadata = showAll
+ ? metadata
+ : metadata.slice(0, INITIAL_SHOW_COUNT)
const remainingCount = metadata.length - INITIAL_SHOW_COUNT
return (
@@ -73,7 +81,9 @@ const MetadataPanel = ({ metadata, t }: { metadata: Metadata[]; t: TFunction })
<div className='divide-y divide-slate-100 dark:divide-slate-800'>
{_map(displayedMetadata, ({ key, value }, index) => {
const needsTruncation = _size(value) > 60
- const displayValue = needsTruncation ? _truncate(value, { length: 60 }) : value
+ const displayValue = needsTruncation
+ ? _truncate(value, { length: 60 })
+ : value
return (
<div
@@ -81,7 +91,9 @@ const MetadataPanel = ({ metadata, t }: { metadata: Metadata[]; t: TFunction })
className='flex flex-col gap-1 px-3 py-2 transition-colors hover:bg-slate-50 sm:grid sm:grid-cols-[minmax(80px,auto)_1fr] sm:gap-3 dark:hover:bg-slate-800/30'
>
<div className='flex items-start'>
- <span className='font-mono text-[11px] font-medium text-slate-500 dark:text-slate-400'>{key}</span>
+ <span className='font-mono text-[11px] font-medium text-slate-500 dark:text-slate-400'>
+ {key}
+ </span>
</div>
<div className='flex items-start'>
<span
@@ -106,7 +118,9 @@ const MetadataPanel = ({ metadata, t }: { metadata: Metadata[]; t: TFunction })
onClick={() => setShowAll(!showAll)}
className='w-full border-t border-slate-200 bg-slate-50 px-3 py-1.5 text-[11px] font-medium text-slate-500 transition-colors hover:bg-slate-100 hover:text-slate-700 dark:border-slate-700 dark:bg-slate-800/50 dark:text-slate-400 dark:hover:bg-slate-700/50 dark:hover:text-slate-300'
>
- {showAll ? t('project.showLess') : t('project.showMore', { count: remainingCount })}
+ {showAll
+ ? t('project.showLess')
+ : t('project.showMore', { count: remainingCount })}
</button>
) : null}
</div>
@@ -165,37 +179,66 @@ const PageflowItem = ({
<div className='relative flex space-x-3'>
<div>
<span
- className={cn('flex h-8 w-8 items-center justify-center rounded-full', {
- 'bg-slate-400 dark:bg-slate-800': type === 'pageview' || type === 'event',
- 'bg-red-400 dark:bg-red-800': type === 'error',
- 'bg-green-500 dark:bg-green-700': type === 'sale',
- 'bg-orange-500 dark:bg-orange-700': type === 'refund',
- })}
+ className={cn(
+ 'flex h-8 w-8 items-center justify-center rounded-full',
+ {
+ 'bg-slate-400 dark:bg-slate-800':
+ type === 'pageview' || type === 'event',
+ 'bg-red-400 dark:bg-red-800': type === 'error',
+ 'bg-green-500 dark:bg-green-700': type === 'sale',
+ 'bg-orange-500 dark:bg-orange-700': type === 'refund',
+ },
+ )}
>
{type === 'pageview' ? (
- <FileTextIcon className='h-5 w-5 text-white' aria-hidden='true' strokeWidth={1.5} />
+ <FileTextIcon
+ className='h-5 w-5 text-white'
+ aria-hidden='true'
+ strokeWidth={1.5}
+ />
) : null}
{type === 'event' ? (
- <MousePointerClickIcon className='h-5 w-5 text-white' aria-hidden='true' strokeWidth={1.5} />
+ <MousePointerClickIcon
+ className='h-5 w-5 text-white'
+ aria-hidden='true'
+ strokeWidth={1.5}
+ />
) : null}
{type === 'error' ? (
- <BugIcon className='h-5 w-5 text-white' aria-hidden='true' strokeWidth={1.5} />
+ <BugIcon
+ className='h-5 w-5 text-white'
+ aria-hidden='true'
+ strokeWidth={1.5}
+ />
) : null}
{type === 'sale' ? (
- <DollarSignIcon className='h-5 w-5 text-white' aria-hidden='true' strokeWidth={1.5} />
+ <DollarSignIcon
+ className='h-5 w-5 text-white'
+ aria-hidden='true'
+ strokeWidth={1.5}
+ />
) : null}
{type === 'refund' ? (
- <RotateCcwIcon className='h-5 w-5 text-white' aria-hidden='true' strokeWidth={1.5} />
+ <RotateCcwIcon
+ className='h-5 w-5 text-white'
+ aria-hidden='true'
+ strokeWidth={1.5}
+ />
) : null}
</span>
</div>
<div className='flex min-w-0 flex-1 flex-col pt-1.5'>
<div className='flex flex-col gap-y-1 sm:flex-row sm:justify-between sm:space-x-4'>
<div
- className={cn('flex flex-wrap items-center gap-x-1 text-sm text-gray-700 dark:text-gray-300', {
- 'cursor-pointer': hasMetadata,
- })}
- onClick={hasMetadata ? () => setIsExpanded(!isExpanded) : undefined}
+ className={cn(
+ 'flex flex-wrap items-center gap-x-1 text-sm text-gray-700 dark:text-gray-300',
+ {
+ 'cursor-pointer': hasMetadata,
+ },
+ )}
+ onClick={
+ hasMetadata ? () => setIsExpanded(!isExpanded) : undefined
+ }
role={hasMetadata ? 'button' : undefined}
tabIndex={hasMetadata ? 0 : undefined}
onKeyDown={
@@ -214,7 +257,8 @@ const PageflowItem = ({
<span
className={cn('font-semibold', {
'text-green-600 dark:text-green-400': type === 'sale',
- 'text-orange-600 dark:text-orange-400': type === 'refund',
+ 'text-orange-600 dark:text-orange-400':
+ type === 'refund',
})}
>
{type === 'refund' ? '-' : ''}
@@ -223,13 +267,21 @@ const PageflowItem = ({
currency: currency || 'USD',
}).format(Math.abs(amount || 0))}
</span>
- {value ? <span className='ml-2 text-gray-500 dark:text-gray-400'>({value})</span> : null}
+ {value ? (
+ <span className='ml-2 text-gray-500 dark:text-gray-400'>
+ ({value})
+ </span>
+ ) : null}
</span>
) : (
<Trans
t={t}
i18nKey={
- type === 'pageview' ? 'project.pageviewX' : type === 'event' ? 'project.eventX' : 'project.errorX'
+ type === 'pageview'
+ ? 'project.pageviewX'
+ : type === 'event'
+ ? 'project.eventX'
+ : 'project.errorX'
}
components={{
value: fullPageUrl ? (
@@ -272,7 +324,9 @@ const PageflowItem = ({
</div>
{/* Collapsible metadata */}
- {hasMetadata && isExpanded ? <MetadataPanel metadata={metadata!} t={t} /> : null}
+ {hasMetadata && isExpanded ? (
+ <MetadataPanel metadata={metadata!} t={t} />
+ ) : null}
{/* Time duration to next step */}
{timeDuration !== null && timeDuration > 0 ? (
@@ -285,7 +339,11 @@ const PageflowItem = ({
xmlns='http://www.w3.org/2000/svg'
>
<circle cx='12' cy='12' r='10' strokeWidth='2' />
- <polyline points='12 6 12 12 16 14' strokeWidth='2' strokeLinecap='round' />
+ <polyline
+ points='12 6 12 12 16 14'
+ strokeWidth='2'
+ strokeLinecap='round'
+ />
</svg>
{formatDuration(timeDuration)}
</div>
@@ -297,7 +355,13 @@ const PageflowItem = ({
)
}
-export const Pageflow = ({ pages, timeFormat, zoomedTimeRange, sdur = 0, websiteUrl }: PageflowProps) => {
+export const Pageflow = ({
+ pages,
+ timeFormat,
+ zoomedTimeRange,
+ sdur = 0,
+ websiteUrl,
+}: PageflowProps) => {
const {
t,
i18n: { language },
@@ -314,7 +378,10 @@ export const Pageflow = ({ pages, timeFormat, zoomedTimeRange, sdur = 0, website
return pages.filter((page) => {
const pageTime = new Date(page.created).getTime()
- return pageTime >= zoomedTimeRange[0].getTime() && pageTime <= zoomedTimeRange[1].getTime()
+ return (
+ pageTime >= zoomedTimeRange[0].getTime() &&
+ pageTime <= zoomedTimeRange[1].getTime()
+ )
})
}, [pages, zoomedTimeRange])
@@ -341,8 +408,12 @@ export const Pageflow = ({ pages, timeFormat, zoomedTimeRange, sdur = 0, website
}
const firstEventTime = new Date(filteredPages[0].created).getTime()
- const lastEventTime = new Date(filteredPages[filteredPages.length - 1].created).getTime()
- const timeBetweenFirstAndLast = Math.round((lastEventTime - firstEventTime) / 1000)
+ const lastEventTime = new Date(
+ filteredPages[filteredPages.length - 1].created,
+ ).getTime()
+ const timeBetweenFirstAndLast = Math.round(
+ (lastEventTime - firstEventTime) / 1000,
+ )
const remaining = sdur - timeBetweenFirstAndLast
return remaining > 0 ? remaining : 0
@@ -359,42 +430,48 @@ export const Pageflow = ({ pages, timeFormat, zoomedTimeRange, sdur = 0, website
return (
<div className='flow-root'>
<ul className='-mb-8'>
- {_map(filteredPages, ({ value, created, type, metadata, amount, currency }, index) => {
- const displayCreated = new Date(created).toLocaleDateString(language, {
- day: 'numeric',
- month: 'short',
- hour: 'numeric',
- minute: 'numeric',
- second: 'numeric',
- hourCycle: timeFormat === '12-hour' ? 'h12' : 'h23',
- })
+ {_map(
+ filteredPages,
+ ({ value, created, type, metadata, amount, currency }, index) => {
+ const displayCreated = new Date(created).toLocaleDateString(
+ language,
+ {
+ day: 'numeric',
+ month: 'short',
+ hour: 'numeric',
+ minute: 'numeric',
+ second: 'numeric',
+ hourCycle: timeFormat === '12-hour' ? 'h12' : 'h23',
+ },
+ )
- const isLastEvent = index === filteredPages.length - 1
- // For the last event, show the remaining time (sdur - time between first and last event)
- // as "time spent on the last event" under the last item rather than under "End of session".
- const timeDuration = !isLastEvent
- ? timeBetweenEvents[index]
- : timeAfterLastEvent > 0
- ? timeAfterLastEvent
- : null
+ const isLastEvent = index === filteredPages.length - 1
+ // For the last event, show the remaining time (sdur - time between first and last event)
+ // as "time spent on the last event" under the last item rather than under "End of session".
+ const timeDuration = !isLastEvent
+ ? timeBetweenEvents[index]
+ : timeAfterLastEvent > 0
+ ? timeAfterLastEvent
+ : null
- return (
- <PageflowItem
- key={`${value}${created}${index}`}
- value={value}
- created={created}
- type={type}
- metadata={metadata}
- displayCreated={displayCreated}
- timeDuration={timeDuration}
- isLastEvent={isLastEvent}
- t={t}
- amount={amount}
- currency={currency}
- websiteUrl={websiteUrl}
- />
- )
- })}
+ return (
+ <PageflowItem
+ key={`${value}${created}${index}`}
+ value={value}
+ created={created}
+ type={type}
+ metadata={metadata}
+ displayCreated={displayCreated}
+ timeDuration={timeDuration}
+ isLastEvent={isLastEvent}
+ t={t}
+ amount={amount}
+ currency={currency}
+ websiteUrl={websiteUrl}
+ />
+ )
+ },
+ )}
{/* End of session marker */}
{filteredPages.length > 0 ? (
diff --git a/web/app/pages/Project/tabs/Sessions/SessionChart.tsx b/web/app/pages/Project/tabs/Sessions/SessionChart.tsx
index f1e6eb202..2d2eae136 100644
--- a/web/app/pages/Project/tabs/Sessions/SessionChart.tsx
+++ b/web/app/pages/Project/tabs/Sessions/SessionChart.tsx
@@ -33,7 +33,14 @@ export const SessionChart = ({
const options: ChartOptions = useMemo(() => {
// Session inspector chart is always rendered as a line/area chart,
// regardless of the user's global chart type preference.
- return getSettingsSession(chart, timeBucket as string, timeFormat, rotateXAxis, chartTypes.line, onZoom)
+ return getSettingsSession(
+ chart,
+ timeBucket as string,
+ timeFormat,
+ rotateXAxis,
+ chartTypes.line,
+ onZoom,
+ )
}, [chart, timeBucket, timeFormat, rotateXAxis, onZoom])
const deps = useMemo(
diff --git a/web/app/pages/Project/tabs/Sessions/SessionDetailView.tsx b/web/app/pages/Project/tabs/Sessions/SessionDetailView.tsx
index bc6855f75..179127757 100644
--- a/web/app/pages/Project/tabs/Sessions/SessionDetailView.tsx
+++ b/web/app/pages/Project/tabs/Sessions/SessionDetailView.tsx
@@ -3,19 +3,36 @@ import _capitalize from 'lodash/capitalize'
import _isEmpty from 'lodash/isEmpty'
import _size from 'lodash/size'
import _truncate from 'lodash/truncate'
-import { GlobeIcon, MonitorIcon, SmartphoneIcon, TabletIcon, ClockIcon, LinkIcon, UserIcon } from 'lucide-react'
+import {
+ GlobeIcon,
+ MonitorIcon,
+ SmartphoneIcon,
+ TabletIcon,
+ ClockIcon,
+ LinkIcon,
+ UserIcon,
+} from 'lucide-react'
import { useMemo, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { Link } from 'react-router'
-import { BROWSER_LOGO_MAP, OS_LOGO_MAP, OS_LOGO_MAP_DARK, PROJECT_TABS } from '~/lib/constants'
+import {
+ BROWSER_LOGO_MAP,
+ OS_LOGO_MAP,
+ OS_LOGO_MAP_DARK,
+ PROJECT_TABS,
+} from '~/lib/constants'
import { SessionDetails as SessionDetailsType } from '~/lib/models/Project'
import { useCurrentProject } from '~/providers/CurrentProjectProvider'
import { useTheme } from '~/providers/ThemeProvider'
import Loader from '~/ui/Loader'
import { Text } from '~/ui/Text'
import Tooltip from '~/ui/Tooltip'
-import { getLocaleDisplayName, getStringFromTime, getTimeFromSeconds } from '~/utils/generic'
+import {
+ getLocaleDisplayName,
+ getStringFromTime,
+ getTimeFromSeconds,
+} from '~/utils/generic'
import CCRow from '../../View/components/CCRow'
@@ -49,12 +66,23 @@ interface SessionDetailViewProps {
websiteUrl?: string | null
}
-const InfoRow = ({ label, value }: { label: string; value: React.ReactNode }) => (
+const InfoRow = ({
+ label,
+ value,
+}: {
+ label: string
+ value: React.ReactNode
+}) => (
<div className='flex items-center justify-between border-b border-gray-100 py-2 last:border-0 dark:border-slate-700/50'>
<Text size='sm' colour='muted'>
{label}
</Text>
- <Text size='sm' weight='medium' colour='primary' className='flex items-center gap-1'>
+ <Text
+ size='sm'
+ weight='medium'
+ colour='primary'
+ className='flex items-center gap-1'
+ >
{value}
</Text>
</div>
@@ -105,7 +133,9 @@ export const SessionDetailView = ({
} = useTranslation('common')
const { id: projectId } = useCurrentProject()
const { theme } = useTheme()
- const [zoomedTimeRange, setZoomedTimeRange] = useState<[Date, Date] | null>(null)
+ const [zoomedTimeRange, setZoomedTimeRange] = useState<[Date, Date] | null>(
+ null,
+ )
const sessionDuration = useMemo(() => {
if (!activeSession?.details) return 0
@@ -115,11 +145,16 @@ export const SessionDetailView = ({
}
if (!_isEmpty(activeSession.pages)) {
- const pageviews = activeSession.pages!.filter((p) => p.type === 'pageview')
+ const pageviews = activeSession.pages!.filter(
+ (p) => p.type === 'pageview',
+ )
if (pageviews.length >= 1) {
const firstPageview = pageviews[0]
const lastPageview = pageviews[pageviews.length - 1]
- const diffSeconds = dayjs(lastPageview.created).diff(dayjs(firstPageview.created), 'seconds')
+ const diffSeconds = dayjs(lastPageview.created).diff(
+ dayjs(firstPageview.created),
+ 'seconds',
+ )
if (diffSeconds > 0) {
return diffSeconds
}
@@ -137,7 +172,12 @@ export const SessionDetailView = ({
return <Loader />
}
- if (activeSession !== null && _isEmpty(activeSession?.chart) && _isEmpty(activeSession?.pages) && !sessionLoading) {
+ if (
+ activeSession !== null &&
+ _isEmpty(activeSession?.chart) &&
+ _isEmpty(activeSession?.pages) &&
+ !sessionLoading
+ ) {
return <NoSessionDetails />
}
@@ -152,7 +192,14 @@ export const SessionDetailView = ({
<div className='flex flex-col gap-3 lg:flex-row'>
<div className='space-y-4 lg:w-[380px]'>
<div className='rounded-lg border border-gray-200 bg-white px-4 py-5 dark:border-slate-800/60 dark:bg-slate-800/25'>
- <Text as='h3' size='xs' weight='semibold' colour='primary' className='mb-2 uppercase' tracking='wide'>
+ <Text
+ as='h3'
+ size='xs'
+ weight='semibold'
+ colour='primary'
+ className='mb-2 uppercase'
+ tracking='wide'
+ >
{t('project.sessionInfo')}
</Text>
<div>
@@ -183,7 +230,11 @@ export const SessionDetailView = ({
tooltipNode={
<div className='flex items-center gap-1'>
<LinkIcon className='h-4 w-4' />
- <span title={_size(details.ref) > 25 ? details.ref : undefined}>
+ <span
+ title={
+ _size(details.ref) > 25 ? details.ref : undefined
+ }
+ >
{_truncate(details.ref, { length: 25 })}
</span>
</div>
@@ -196,19 +247,38 @@ export const SessionDetailView = ({
/>
</div>
- <Text as='h3' size='xs' weight='semibold' colour='primary' className='mt-5 mb-2 uppercase' tracking='wide'>
+ <Text
+ as='h3'
+ size='xs'
+ weight='semibold'
+ colour='primary'
+ className='mt-5 mb-2 uppercase'
+ tracking='wide'
+ >
{t('project.locationAndDevice')}
</Text>
<div>
<InfoRow
label={t('project.mapping.cc')}
- value={details.cc ? <CCRow size={16} cc={details.cc} language={language} /> : '-'}
+ value={
+ details.cc ? (
+ <CCRow size={16} cc={details.cc} language={language} />
+ ) : (
+ '-'
+ )
+ }
/>
- {details.rg ? <InfoRow label={t('project.mapping.rg')} value={details.rg} /> : null}
- {details.ct ? <InfoRow label={t('project.mapping.ct')} value={details.ct} /> : null}
+ {details.rg ? (
+ <InfoRow label={t('project.mapping.rg')} value={details.rg} />
+ ) : null}
+ {details.ct ? (
+ <InfoRow label={t('project.mapping.ct')} value={details.ct} />
+ ) : null}
<InfoRow
label={t('project.mapping.lc')}
- value={details.lc ? getLocaleDisplayName(details.lc, language) : '-'}
+ value={
+ details.lc ? getLocaleDisplayName(details.lc, language) : '-'
+ }
/>
<InfoRow
label={t('project.mapping.dv')}
@@ -253,7 +323,11 @@ export const SessionDetailView = ({
/>
</div>
- {details.so || details.me || details.ca || details.te || details.co ? (
+ {details.so ||
+ details.me ||
+ details.ca ||
+ details.te ||
+ details.co ? (
<>
<Text
as='h3'
@@ -266,11 +340,36 @@ export const SessionDetailView = ({
{t('project.campaigns')}
</Text>
<div>
- {details.so ? <InfoRow label={t('project.mapping.so')} value={details.so} /> : null}
- {details.me ? <InfoRow label={t('project.mapping.me')} value={details.me} /> : null}
- {details.ca ? <InfoRow label={t('project.mapping.ca')} value={details.ca} /> : null}
- {details.te ? <InfoRow label={t('project.mapping.te')} value={details.te} /> : null}
- {details.co ? <InfoRow label={t('project.mapping.co')} value={details.co} /> : null}
+ {details.so ? (
+ <InfoRow
+ label={t('project.mapping.so')}
+ value={details.so}
+ />
+ ) : null}
+ {details.me ? (
+ <InfoRow
+ label={t('project.mapping.me')}
+ value={details.me}
+ />
+ ) : null}
+ {details.ca ? (
+ <InfoRow
+ label={t('project.mapping.ca')}
+ value={details.ca}
+ />
+ ) : null}
+ {details.te ? (
+ <InfoRow
+ label={t('project.mapping.te')}
+ value={details.te}
+ />
+ ) : null}
+ {details.co ? (
+ <InfoRow
+ label={t('project.mapping.co')}
+ value={details.co}
+ />
+ ) : null}
</div>
</>
) : null}
@@ -291,7 +390,14 @@ export const SessionDetailView = ({
{!_isEmpty(activeSession?.chart) ? (
<div className='rounded-lg border border-gray-200 bg-white px-4 py-5 dark:border-slate-800/60 dark:bg-slate-800/25'>
<div className='mb-2 flex items-center justify-between'>
- <Text as='h3' size='xs' weight='semibold' colour='primary' className='uppercase' tracking='wide'>
+ <Text
+ as='h3'
+ size='xs'
+ weight='semibold'
+ colour='primary'
+ className='uppercase'
+ tracking='wide'
+ >
{t('project.sessionActivity')}
</Text>
{zoomedTimeRange ? (
diff --git a/web/app/pages/Project/tabs/Sessions/Sessions.tsx b/web/app/pages/Project/tabs/Sessions/Sessions.tsx
index 26cc96db8..d43557b0b 100644
--- a/web/app/pages/Project/tabs/Sessions/Sessions.tsx
+++ b/web/app/pages/Project/tabs/Sessions/Sessions.tsx
@@ -4,7 +4,12 @@ import dayjs from 'dayjs'
import duration from 'dayjs/plugin/duration'
import relativeTime from 'dayjs/plugin/relativeTime'
import _map from 'lodash/map'
-import { FileTextIcon, BugIcon, MousePointerClickIcon, CalendarIcon } from 'lucide-react'
+import {
+ FileTextIcon,
+ BugIcon,
+ MousePointerClickIcon,
+ CalendarIcon,
+} from 'lucide-react'
import React, { useMemo } from 'react'
import { useTranslation } from 'react-i18next'
import { Link, useLocation } from 'react-router'
@@ -77,7 +82,13 @@ const Separator = () => (
</svg>
)
-const Session = ({ session, timeFormat, hideNewReturnBadge, hideUserDetails, currency }: SessionProps) => {
+const Session = ({
+ session,
+ timeFormat,
+ hideNewReturnBadge,
+ hideUserDetails,
+ currency,
+}: SessionProps) => {
const currencySymbol = getCurrencySymbol(currency)
const {
t,
@@ -90,11 +101,18 @@ const Session = ({ session, timeFormat, hideNewReturnBadge, hideUserDetails, cur
let sessionDurationString = ''
if (!session.isLive) {
if (session.sdur != null && session.sdur > 0) {
- sessionDurationString = getStringFromTime(getTimeFromSeconds(session.sdur))
+ sessionDurationString = getStringFromTime(
+ getTimeFromSeconds(session.sdur),
+ )
} else {
- const diffSeconds = dayjs(session.lastActivity).diff(sessionStartTime, 'seconds')
+ const diffSeconds = dayjs(session.lastActivity).diff(
+ sessionStartTime,
+ 'seconds',
+ )
if (diffSeconds > 0) {
- sessionDurationString = getStringFromTime(getTimeFromSeconds(diffSeconds))
+ sessionDurationString = getStringFromTime(
+ getTimeFromSeconds(diffSeconds),
+ )
}
}
}
@@ -103,18 +121,23 @@ const Session = ({ session, timeFormat, hideNewReturnBadge, hideUserDetails, cur
if (!session.profileId) {
return t('project.unknownUser')
}
- return getProfileDisplayName(session.profileId, Boolean(session.isIdentified))
+ return getProfileDisplayName(
+ session.profileId,
+ Boolean(session.isIdentified),
+ )
}, [session.profileId, session.isIdentified, t])
const dateLineString = useMemo(() => {
- const startDateTimeStr = sessionStartTime.toDate().toLocaleDateString(language, {
- day: 'numeric',
- month: 'short',
- year: 'numeric',
- hour: 'numeric',
- minute: 'numeric',
- hourCycle: timeFormat === '12-hour' ? 'h12' : 'h23',
- })
+ const startDateTimeStr = sessionStartTime
+ .toDate()
+ .toLocaleDateString(language, {
+ day: 'numeric',
+ month: 'short',
+ year: 'numeric',
+ hour: 'numeric',
+ minute: 'numeric',
+ hourCycle: timeFormat === '12-hour' ? 'h12' : 'h23',
+ })
if (session.isLive) {
return startDateTimeStr
@@ -133,13 +156,21 @@ const Session = ({ session, timeFormat, hideNewReturnBadge, hideUserDetails, cur
hourCycle: timeFormat === '12-hour' ? 'h12' : 'h23',
})
- const durationDisplay = sessionDurationString ? ` (${sessionDurationString})` : ''
+ const durationDisplay = sessionDurationString
+ ? ` (${sessionDurationString})`
+ : ''
return `${startDateTimeStr} - ${endTimeStr}${durationDisplay}`
}, [session, language, timeFormat, sessionDurationString, sessionStartTime])
- const onlineStatus = useMemo(() => getOnlineStatus(session.lastActivity), [session.lastActivity])
+ const onlineStatus = useMemo(
+ () => getOnlineStatus(session.lastActivity),
+ [session.lastActivity],
+ )
- const lastActivityAgo = useMemo(() => dayjs(session.lastActivity).fromNow(), [session.lastActivity])
+ const lastActivityAgo = useMemo(
+ () => dayjs(session.lastActivity).fromNow(),
+ [session.lastActivity],
+ )
const params = new URLSearchParams(location.search)
params.set('psid', session.psid)
@@ -152,10 +183,16 @@ const Session = ({ session, timeFormat, hideNewReturnBadge, hideUserDetails, cur
{hideUserDetails ? null : (
<div className='relative shrink-0'>
{session.profileId ? (
- <ProfileAvatar className='mt-1' profileId={session.profileId} size={40} />
+ <ProfileAvatar
+ className='mt-1'
+ profileId={session.profileId}
+ size={40}
+ />
) : (
<div className='flex h-10 w-10 items-center justify-center rounded-full bg-gray-200 dark:bg-slate-600'>
- <span className='text-sm font-medium text-gray-500 dark:text-gray-300'>?</span>
+ <span className='text-sm font-medium text-gray-500 dark:text-gray-300'>
+ ?
+ </span>
</div>
)}
{onlineStatus === 'offline' ? null : (
@@ -181,11 +218,19 @@ const Session = ({ session, timeFormat, hideNewReturnBadge, hideUserDetails, cur
<p className='flex items-center text-sm leading-6 font-semibold text-gray-900 dark:text-gray-50'>
<span className='truncate'>{displayName}</span>
{session.isIdentified ? (
- <Badge label={t('project.identified')} colour='indigo' className='ml-2' />
+ <Badge
+ label={t('project.identified')}
+ colour='indigo'
+ className='ml-2'
+ />
) : null}
{hideNewReturnBadge ? null : (
<Badge
- label={session.isFirstSession ? t('project.sessionNew') : t('project.sessionReturn')}
+ label={
+ session.isFirstSession
+ ? t('project.sessionNew')
+ : t('project.sessionReturn')
+ }
colour={session.isFirstSession ? 'green' : 'slate'}
className='ml-2'
/>
@@ -194,7 +239,11 @@ const Session = ({ session, timeFormat, hideNewReturnBadge, hideUserDetails, cur
)}
<p className='mt-1 flex flex-wrap items-center gap-x-2 text-xs leading-5 text-gray-500 dark:text-gray-300'>
<span className='flex items-center'>
- {session.cc ? <CCRow size={18} cc={session.cc} language={language} /> : t('project.unknownCountry')}
+ {session.cc ? (
+ <CCRow size={18} cc={session.cc} language={language} />
+ ) : (
+ t('project.unknownCountry')
+ )}
</span>
<Separator />
{session.os || t('project.unknown')}
@@ -202,8 +251,12 @@ const Session = ({ session, timeFormat, hideNewReturnBadge, hideUserDetails, cur
{session.br || t('project.unknown')}
</p>
<p className='mt-2 flex text-xs leading-5 text-gray-500 sm:hidden dark:text-gray-300'>
- <span className='mr-2 flex items-center' title={t('dashboard.pageviews')}>
- <FileTextIcon className='mr-1 size-4' strokeWidth={1.5} /> {session.pageviews}
+ <span
+ className='mr-2 flex items-center'
+ title={t('dashboard.pageviews')}
+ >
+ <FileTextIcon className='mr-1 size-4' strokeWidth={1.5} />{' '}
+ {session.pageviews}
</span>
{session.revenue != null && session.revenue !== 0 ? (
<span
@@ -219,13 +272,24 @@ const Session = ({ session, timeFormat, hideNewReturnBadge, hideUserDetails, cur
</span>
) : null}
{session.customEvents > 0 ? (
- <span className='mr-2 flex items-center' title={t('dashboard.events')}>
- <MousePointerClickIcon className='mr-1 size-4' strokeWidth={1.5} /> {session.customEvents}
+ <span
+ className='mr-2 flex items-center'
+ title={t('dashboard.events')}
+ >
+ <MousePointerClickIcon
+ className='mr-1 size-4'
+ strokeWidth={1.5}
+ />{' '}
+ {session.customEvents}
</span>
) : null}
{session.errors > 0 ? (
- <span className='flex items-center text-red-400' title={t('dashboard.errors')}>
- <BugIcon className='mr-1 size-4' strokeWidth={1.5} /> {session.errors}
+ <span
+ className='flex items-center text-red-400'
+ title={t('dashboard.errors')}
+ >
+ <BugIcon className='mr-1 size-4' strokeWidth={1.5} />{' '}
+ {session.errors}
</span>
) : null}
</p>
@@ -234,8 +298,12 @@ const Session = ({ session, timeFormat, hideNewReturnBadge, hideUserDetails, cur
<div className='flex shrink-0 items-center gap-x-4'>
<div className='hidden sm:flex sm:flex-col sm:items-end'>
<div className='flex items-center gap-x-3 text-sm leading-6 text-gray-900 dark:text-gray-50'>
- <span className='flex items-center' title={t('dashboard.xPageviews', { x: session.pageviews })}>
- <FileTextIcon className='mr-1 size-5' strokeWidth={1.5} /> {session.pageviews}
+ <span
+ className='flex items-center'
+ title={t('dashboard.xPageviews', { x: session.pageviews })}
+ >
+ <FileTextIcon className='mr-1 size-5' strokeWidth={1.5} />{' '}
+ {session.pageviews}
</span>
{session.revenue != null && session.revenue !== 0 ? (
<span
@@ -251,13 +319,26 @@ const Session = ({ session, timeFormat, hideNewReturnBadge, hideUserDetails, cur
</span>
) : null}
{session.customEvents > 0 ? (
- <span className='flex items-center' title={t('dashboard.xCustomEvents', { x: session.customEvents })}>
- <MousePointerClickIcon className='mr-1 size-5' strokeWidth={1.5} /> {session.customEvents}
+ <span
+ className='flex items-center'
+ title={t('dashboard.xCustomEvents', {
+ x: session.customEvents,
+ })}
+ >
+ <MousePointerClickIcon
+ className='mr-1 size-5'
+ strokeWidth={1.5}
+ />{' '}
+ {session.customEvents}
</span>
) : null}
{session.errors > 0 ? (
- <span className='flex items-center text-red-500' title={t('dashboard.xErrors', { x: session.errors })}>
- <BugIcon className='mr-1 size-5' strokeWidth={1.5} /> {session.errors}
+ <span
+ className='flex items-center text-red-500'
+ title={t('dashboard.xErrors', { x: session.errors })}
+ >
+ <BugIcon className='mr-1 size-5' strokeWidth={1.5} />{' '}
+ {session.errors}
</span>
) : null}
</div>
@@ -266,7 +347,10 @@ const Session = ({ session, timeFormat, hideNewReturnBadge, hideUserDetails, cur
{dateLineString}
</p>
</div>
- <ChevronRightIcon className='h-5 w-5 flex-none text-gray-400' aria-hidden='true' />
+ <ChevronRightIcon
+ className='h-5 w-5 flex-none text-gray-400'
+ aria-hidden='true'
+ />
</div>
</li>
</Link>
diff --git a/web/app/pages/Project/tabs/Sessions/SessionsView.tsx b/web/app/pages/Project/tabs/Sessions/SessionsView.tsx
index abc317e3d..ef7675939 100644
--- a/web/app/pages/Project/tabs/Sessions/SessionsView.tsx
+++ b/web/app/pages/Project/tabs/Sessions/SessionsView.tsx
@@ -1,20 +1,34 @@
import cx from 'clsx'
import _isEmpty from 'lodash/isEmpty'
import { DownloadIcon } from 'lucide-react'
-import { Component, useState, useEffect, useMemo, useRef, Suspense, use } from 'react'
+import {
+ Component,
+ useState,
+ useEffect,
+ useMemo,
+ useRef,
+ Suspense,
+ use,
+} from 'react'
import type { ReactNode } from 'react'
import { useTranslation } from 'react-i18next'
import { useSearchParams, useLoaderData, useRevalidator } from 'react-router'
import type { SessionsResponse, SessionDetailsResponse } from '~/api/api.server'
import { useSessionsProxy } from '~/hooks/useAnalyticsProxy'
-import { Session, SessionDetails as SessionDetailsType } from '~/lib/models/Project'
+import {
+ Session,
+ SessionDetails as SessionDetailsType,
+} from '~/lib/models/Project'
import NoSessions from '~/pages/Project/tabs/Sessions/components/NoSessions'
import { SessionDetailView } from '~/pages/Project/tabs/Sessions/SessionDetailView'
import { Sessions } from '~/pages/Project/tabs/Sessions/Sessions'
import DashboardHeader from '~/pages/Project/View/components/DashboardHeader'
import Filters from '~/pages/Project/View/components/Filters'
-import { useViewProjectContext, useRefreshTriggers } from '~/pages/Project/View/ViewProject'
+import {
+ useViewProjectContext,
+ useRefreshTriggers,
+} from '~/pages/Project/View/ViewProject'
import { getFormatDate } from '~/pages/Project/View/ViewProject.helpers'
import { useCurrentProject } from '~/providers/CurrentProjectProvider'
import type { ProjectLoaderData } from '~/routes/projects.$id'
@@ -29,7 +43,10 @@ interface SessionsErrorBoundaryState {
error: Error | null
}
-class SessionsErrorBoundary extends Component<{ children: ReactNode }, SessionsErrorBoundaryState> {
+class SessionsErrorBoundary extends Component<
+ { children: ReactNode },
+ SessionsErrorBoundaryState
+> {
constructor(props: { children: ReactNode }) {
super(props)
this.state = { hasError: false, error: null }
@@ -45,9 +62,15 @@ class SessionsErrorBoundary extends Component<{ children: ReactNode }, SessionsE
<StatusPage
type='error'
title='Failed to load sessions'
- description={this.state.error?.message || 'An unexpected error occurred'}
+ description={
+ this.state.error?.message || 'An unexpected error occurred'
+ }
actions={[
- { label: 'Reload page', onClick: () => window.location.reload(), primary: true },
+ {
+ label: 'Reload page',
+ onClick: () => window.location.reload(),
+ primary: true,
+ },
{ label: 'Support', to: routes.contact },
]}
/>
@@ -89,12 +112,20 @@ interface DeferredSessionsData {
sessionDetails: SessionDetailsResponse | null
}
-function SessionsDataResolver({ children }: { children: (data: DeferredSessionsData) => React.ReactNode }) {
- const { sessionsData: sessionsDataPromise, sessionDetails: sessionDetailsPromise } =
- useLoaderData<ProjectLoaderData>()
+function SessionsDataResolver({
+ children,
+}: {
+ children: (data: DeferredSessionsData) => React.ReactNode
+}) {
+ const {
+ sessionsData: sessionsDataPromise,
+ sessionDetails: sessionDetailsPromise,
+ } = useLoaderData<ProjectLoaderData>()
const sessionsData = sessionsDataPromise ? use(sessionsDataPromise) : null
- const sessionDetails = sessionDetailsPromise ? use(sessionDetailsPromise) : null
+ const sessionDetails = sessionDetailsPromise
+ ? use(sessionDetailsPromise)
+ : null
return <>{children({ sessionsData, sessionDetails })}</>
}
@@ -104,7 +135,9 @@ function SessionsViewWrapper(props: SessionsViewProps) {
<SessionsErrorBoundary>
<Suspense fallback={<Loader />}>
<SessionsDataResolver>
- {(deferredData) => <SessionsViewInner {...props} deferredData={deferredData} />}
+ {(deferredData) => (
+ <SessionsViewInner {...props} deferredData={deferredData} />
+ )}
</SessionsDataResolver>
</Suspense>
</SessionsErrorBoundary>
@@ -115,11 +148,16 @@ interface SessionsViewInnerProps extends SessionsViewProps {
deferredData: DeferredSessionsData
}
-const SessionsViewInner = ({ tnMapping, rotateXAxis, deferredData }: SessionsViewInnerProps) => {
+const SessionsViewInner = ({
+ tnMapping,
+ rotateXAxis,
+ deferredData,
+}: SessionsViewInnerProps) => {
const { id, project } = useCurrentProject()
const revalidator = useRevalidator()
const { sessionsRefreshTrigger } = useRefreshTriggers()
- const { timezone, period, dateRange, filters, timeFormat } = useViewProjectContext()
+ const { timezone, period, dateRange, filters, timeFormat } =
+ useViewProjectContext()
const { t } = useTranslation('common')
const [searchParams] = useSearchParams()
@@ -127,7 +165,9 @@ const SessionsViewInner = ({ tnMapping, rotateXAxis, deferredData }: SessionsVie
const sessionsProxy = useSessionsProxy()
// Session list state - derived from loader
- const [sessions, setSessions] = useState<Session[]>(() => deferredData.sessionsData?.sessions || [])
+ const [sessions, setSessions] = useState<Session[]>(
+ () => deferredData.sessionsData?.sessions || [],
+ )
const [sessionsSkip, setSessionsSkip] = useState(SESSIONS_TAKE)
const [canLoadMoreSessions, setCanLoadMoreSessions] = useState(
() => (deferredData.sessionsData?.sessions?.length || 0) >= SESSIONS_TAKE,
@@ -167,7 +207,8 @@ const SessionsViewInner = ({ tnMapping, rotateXAxis, deferredData }: SessionsVie
return null
}, [deferredData.sessionDetails])
- const sessionsLoading = revalidator.state === 'loading' || sessionsProxy.isLoading
+ const sessionsLoading =
+ revalidator.state === 'loading' || sessionsProxy.isLoading
const [error, setError] = useState<string | null>(null)
@@ -240,7 +281,9 @@ const SessionsViewInner = ({ tnMapping, rotateXAxis, deferredData }: SessionsVie
setSessions((prev) => {
// Deduplicate: only add sessions whose psid is not already present
const existingIds = new Set(prev.map((s) => s.psid))
- const uniqueNewSessions = newSessions.filter((s) => !existingIds.has(s.psid))
+ const uniqueNewSessions = newSessions.filter(
+ (s) => !existingIds.has(s.psid),
+ )
return [...prev, ...uniqueNewSessions]
})
setSessionsSkip((prev) => prev + SESSIONS_TAKE)
@@ -249,7 +292,12 @@ const SessionsViewInner = ({ tnMapping, rotateXAxis, deferredData }: SessionsVie
if (sessionsProxy.error) {
setError(sessionsProxy.error)
}
- }, [sessionsProxy.data, sessionsProxy.error, sessionsProxy.isLoading, revalidator.state])
+ }, [
+ sessionsProxy.data,
+ sessionsProxy.error,
+ sessionsProxy.isLoading,
+ revalidator.state,
+ ])
// Load more sessions via proxy
const loadMoreSessions = () => {
@@ -296,7 +344,11 @@ const SessionsViewInner = ({ tnMapping, rotateXAxis, deferredData }: SessionsVie
title={t('apiNotifications.somethingWentWrong')}
description={t('apiNotifications.errorCode', { error })}
actions={[
- { label: t('dashboard.reloadPage'), onClick: () => window.location.reload(), primary: true },
+ {
+ label: t('dashboard.reloadPage'),
+ onClick: () => window.location.reload(),
+ primary: true,
+ },
{ label: t('notFoundPage.support'), to: routes.contact },
]}
/>
@@ -330,12 +382,20 @@ const SessionsViewInner = ({ tnMapping, rotateXAxis, deferredData }: SessionsVie
<DashboardHeader showLiveVisitors />
{sessionsLoading && !_isEmpty(sessions) ? <LoadingBar /> : null}
<div>
- {!_isEmpty(sessions) ? <Filters className='mb-3' tnMapping={tnMapping} /> : null}
+ {!_isEmpty(sessions) ? (
+ <Filters className='mb-3' tnMapping={tnMapping} />
+ ) : null}
{sessionsLoading && _isEmpty(sessions) ? <Loader /> : null}
- {!sessionsLoading && _isEmpty(sessions) && !hasShownContentRef.current ? (
+ {!sessionsLoading &&
+ _isEmpty(sessions) &&
+ !hasShownContentRef.current ? (
<NoSessions filters={filters} />
) : null}
- <Sessions sessions={sessions} timeFormat={timeFormat} currency={project?.revenueCurrency} />
+ <Sessions
+ sessions={sessions}
+ timeFormat={timeFormat}
+ currency={project?.revenueCurrency}
+ />
{canLoadMoreSessions ? (
<button
type='button'
diff --git a/web/app/pages/Project/tabs/Sessions/components/NoSessions.tsx b/web/app/pages/Project/tabs/Sessions/components/NoSessions.tsx
index 54bca7a8a..1210e2b5e 100644
--- a/web/app/pages/Project/tabs/Sessions/components/NoSessions.tsx
+++ b/web/app/pages/Project/tabs/Sessions/components/NoSessions.tsx
@@ -31,8 +31,15 @@ const NoSessions = ({ filters }: NoSessionsProps) => {
<Text as='h3' size='xl' weight='medium' className='tracking-tight'>
{t('project.noSessionsTitle')}
</Text>
- <Text as='p' size='sm' colour='secondary' className='mx-auto mt-2 max-w-md'>
- {hasFilters ? t('project.noSessionsFiltersDesc') : t('project.noSessionsContent')}
+ <Text
+ as='p'
+ size='sm'
+ colour='secondary'
+ className='mx-auto mt-2 max-w-md'
+ >
+ {hasFilters
+ ? t('project.noSessionsFiltersDesc')
+ : t('project.noSessionsContent')}
</Text>
</div>
</>
diff --git a/web/app/pages/Project/tabs/Traffic/CustomEventsSubmenu.tsx b/web/app/pages/Project/tabs/Traffic/CustomEventsSubmenu.tsx
index 129210747..6b6a9d44f 100644
--- a/web/app/pages/Project/tabs/Traffic/CustomEventsSubmenu.tsx
+++ b/web/app/pages/Project/tabs/Traffic/CustomEventsSubmenu.tsx
@@ -13,7 +13,11 @@ const CUSTOM_EV_DROPDOWN_MAX_VISIBLE_LENGTH = 32
interface CustomEventsSubmenuProps {
label: string
- chartMetricsCustomEvents: Array<{ id: string; label: string; active: boolean }>
+ chartMetricsCustomEvents: Array<{
+ id: string
+ label: string
+ active: boolean
+ }>
switchCustomEventChart: (id: string) => void
}
@@ -27,7 +31,10 @@ const CustomEventsSubmenu: React.FC<CustomEventsSubmenuProps> = ({
const timeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null)
const submenuRef = useRef<HTMLDivElement>(null)
const triggerRef = useRef<HTMLDivElement>(null)
- const [coords, setCoords] = useState<{ top: number; left: number }>({ top: 0, left: 0 })
+ const [coords, setCoords] = useState<{ top: number; left: number }>({
+ top: 0,
+ left: 0,
+ })
const handleMouseEnter = () => {
if (timeoutRef.current) {
@@ -62,10 +69,13 @@ const CustomEventsSubmenu: React.FC<CustomEventsSubmenuProps> = ({
const spaceOnRight = viewportW - rect.right
const spaceOnLeft = rect.left
- const placeOnRight = spaceOnRight >= submenuWidth || spaceOnLeft < spaceOnRight
+ const placeOnRight =
+ spaceOnRight >= submenuWidth || spaceOnLeft < spaceOnRight
setIsOnRight(placeOnRight)
- let left = placeOnRight ? rect.right + padding : Math.max(padding, rect.left - submenuWidth - padding)
+ let left = placeOnRight
+ ? rect.right + padding
+ : Math.max(padding, rect.left - submenuWidth - padding)
// Try to keep submenu within viewport vertically
const estimatedHeight = submenuRef.current?.offsetHeight || 240
@@ -115,7 +125,12 @@ const CustomEventsSubmenu: React.FC<CustomEventsSubmenuProps> = ({
}, [isOpen])
return (
- <div ref={triggerRef} className='relative w-full' onMouseEnter={handleMouseEnter} onMouseLeave={handleMouseLeave}>
+ <div
+ ref={triggerRef}
+ className='relative w-full'
+ onMouseEnter={handleMouseEnter}
+ onMouseLeave={handleMouseLeave}
+ >
<div
className='w-full cursor-pointer rounded-md p-2 text-sm text-gray-700 hover:bg-gray-200 dark:text-gray-50 dark:hover:bg-slate-700'
onClick={handleClick}
@@ -145,7 +160,10 @@ const CustomEventsSubmenu: React.FC<CustomEventsSubmenuProps> = ({
className={cn(
'fixed z-50 w-80 max-w-sm rounded-md bg-gray-50 p-1 ring-1 ring-black/10 dark:bg-slate-800',
)}
- style={{ top: coords.top, left: isOnRight ? coords.left : Math.max(8, coords.left) }}
+ style={{
+ top: coords.top,
+ left: isOnRight ? coords.left : Math.max(8, coords.left),
+ }}
>
<div className='max-h-60 overflow-auto'>
{_map(chartMetricsCustomEvents, (event) => (
@@ -168,7 +186,8 @@ const CustomEventsSubmenu: React.FC<CustomEventsSubmenuProps> = ({
label: 'max-w-max',
}}
label={
- _size(event.label) > CUSTOM_EV_DROPDOWN_MAX_VISIBLE_LENGTH ? (
+ _size(event.label) >
+ CUSTOM_EV_DROPDOWN_MAX_VISIBLE_LENGTH ? (
<span title={event.label}>
{_truncate(event.label, {
length: CUSTOM_EV_DROPDOWN_MAX_VISIBLE_LENGTH,
diff --git a/web/app/pages/Project/tabs/Traffic/CustomMetrics.tsx b/web/app/pages/Project/tabs/Traffic/CustomMetrics.tsx
index 5040b9927..7e636c91e 100644
--- a/web/app/pages/Project/tabs/Traffic/CustomMetrics.tsx
+++ b/web/app/pages/Project/tabs/Traffic/CustomMetrics.tsx
@@ -58,7 +58,12 @@ const CustomMetric = ({ metric, onRemove }: CustomMetricProps) => {
title={t('project.removeFilter')}
aria-label={t('project.removeFilter')}
>
- <svg className='h-2 w-2' stroke='currentColor' fill='none' viewBox='0 0 8 8'>
+ <svg
+ className='h-2 w-2'
+ stroke='currentColor'
+ fill='none'
+ viewBox='0 0 8 8'
+ >
<path strokeLinecap='round' strokeWidth='1.5' d='M1 1l6 6m0-6L1 7' />
</svg>
</button>
@@ -72,7 +77,11 @@ interface FiltersProps {
resetMetrics: () => void
}
-const CustomMetrics = ({ metrics, onRemoveMetric, resetMetrics }: FiltersProps) => {
+const CustomMetrics = ({
+ metrics,
+ onRemoveMetric,
+ resetMetrics,
+}: FiltersProps) => {
if (_isEmpty(metrics)) {
return null
}
diff --git a/web/app/pages/Project/tabs/Traffic/MetricCards.tsx b/web/app/pages/Project/tabs/Traffic/MetricCards.tsx
index 64b41d6b2..2b73a4cb8 100644
--- a/web/app/pages/Project/tabs/Traffic/MetricCards.tsx
+++ b/web/app/pages/Project/tabs/Traffic/MetricCards.tsx
@@ -11,7 +11,11 @@ import { OverallObject, OverallPerformanceObject } from '~/lib/models/Project'
import { Badge } from '~/ui/Badge'
import OutsideClickHandler from '~/ui/OutsideClickHandler'
import { Text } from '~/ui/Text'
-import { nFormatter, getStringFromTime, getTimeFromSeconds } from '~/utils/generic'
+import {
+ nFormatter,
+ getStringFromTime,
+ getTimeFromSeconds,
+} from '~/utils/generic'
interface MetricCardProps {
label: string
@@ -27,37 +31,52 @@ interface MetricCardProps {
}
}
-const ChangeBadge = ({ change, type, goodChangeDirection, valueMapper }: Partial<MetricCardProps>) => {
+const ChangeBadge = ({
+ change,
+ type,
+ goodChangeDirection,
+ valueMapper,
+}: Partial<MetricCardProps>) => {
if (!_isNumber(change)) {
return null
}
if (change === 0) {
- const label = valueMapper ? valueMapper(change, 'badge') : `0${type === 'percent' ? '%' : ''}`
+ const label = valueMapper
+ ? valueMapper(change, 'badge')
+ : `0${type === 'percent' ? '%' : ''}`
return <Badge colour='slate' label={label} />
}
if (change < 0 && goodChangeDirection === 'up') {
- const label = valueMapper ? valueMapper(change, 'badge') : `${change}${type === 'percent' ? '%' : ''}`
+ const label = valueMapper
+ ? valueMapper(change, 'badge')
+ : `${change}${type === 'percent' ? '%' : ''}`
return <Badge colour='green' label={label} />
}
if (change < 0 && goodChangeDirection === 'down') {
- const label = valueMapper ? valueMapper(change, 'badge') : `${change}${type === 'percent' ? '%' : ''}`
+ const label = valueMapper
+ ? valueMapper(change, 'badge')
+ : `${change}${type === 'percent' ? '%' : ''}`
return <Badge colour='slate' label={label} />
}
if (change > 0 && goodChangeDirection === 'up') {
- const label = valueMapper ? valueMapper(change, 'badge') : `${change}${type === 'percent' ? '%' : ''}`
+ const label = valueMapper
+ ? valueMapper(change, 'badge')
+ : `${change}${type === 'percent' ? '%' : ''}`
return <Badge colour='slate' label={label} />
}
if (change > 0 && goodChangeDirection === 'down') {
- const label = valueMapper ? valueMapper(change, 'badge') : `${change}${type === 'percent' ? '%' : ''}`
+ const label = valueMapper
+ ? valueMapper(change, 'badge')
+ : `${change}${type === 'percent' ? '%' : ''}`
return <Badge colour='green' label={label} />
}
@@ -73,7 +92,11 @@ export const MetricCard: React.FC<MetricCardProps> = ({
classes,
}) => (
<div className={cx('flex flex-col', classes?.container)}>
- <Text size='4xl' weight='bold' className={cx('whitespace-nowrap', classes?.value)}>
+ <Text
+ size='4xl'
+ weight='bold'
+ className={cx('whitespace-nowrap', classes?.value)}
+ >
{valueMapper ? valueMapper(value, 'main') : value}
</Text>
<div
@@ -88,7 +111,12 @@ export const MetricCard: React.FC<MetricCardProps> = ({
<Text size='sm' weight='bold'>
{label}
</Text>
- <ChangeBadge change={change} type={type} goodChangeDirection={goodChangeDirection} valueMapper={valueMapper} />
+ <ChangeBadge
+ change={change}
+ type={type}
+ goodChangeDirection={goodChangeDirection}
+ valueMapper={valueMapper}
+ />
</div>
</div>
)
@@ -107,7 +135,12 @@ interface MetricCardSelectProps {
}
}
-export const MetricCardSelect = ({ values, valueMapper, selectLabel, classes }: MetricCardSelectProps) => {
+export const MetricCardSelect = ({
+ values,
+ valueMapper,
+ selectLabel,
+ classes,
+}: MetricCardSelectProps) => {
const [selected, setSelected] = useState(0)
const [show, setShow] = useState(false)
@@ -118,12 +151,21 @@ export const MetricCardSelect = ({ values, valueMapper, selectLabel, classes }:
return (
<div className={cx('flex flex-col', classes?.container)}>
- <Text size='4xl' weight='bold' className={cx('whitespace-nowrap', classes?.value)}>
- {valueMapper ? valueMapper(values[selected], selected) : values[selected].value}
+ <Text
+ size='4xl'
+ weight='bold'
+ className={cx('whitespace-nowrap', classes?.value)}
+ >
+ {valueMapper
+ ? valueMapper(values[selected], selected)
+ : values[selected].value}
</Text>
<div className='relative flex items-center whitespace-nowrap'>
<OutsideClickHandler onOutsideClick={() => setShow(false)}>
- <span className={cx('cursor-pointer', classes?.label)} onClick={() => setShow(!show)}>
+ <span
+ className={cx('cursor-pointer', classes?.label)}
+ onClick={() => setShow(!show)}
+ >
<Text size='sm' weight='bold'>
{values[selected].label}{' '}
<ChevronDownIcon
@@ -183,82 +225,105 @@ interface MetricCardsProps {
activePeriodCompare?: string
}
-export const MetricCards = memo(({ overall, overallCompare, activePeriodCompare }: MetricCardsProps) => {
- const { t } = useTranslation('common')
+export const MetricCards = memo(
+ ({ overall, overallCompare, activePeriodCompare }: MetricCardsProps) => {
+ const { t } = useTranslation('common')
- let uniqueChange = overall.uniqueChange
- let usersChange = overall.usersChange
- let allChange = overall.change
- let bounceRateChange = overall.bounceRateChange
- let sdurChange = overall.sdurChange
+ let uniqueChange = overall.uniqueChange
+ let usersChange = overall.usersChange
+ let allChange = overall.change
+ let bounceRateChange = overall.bounceRateChange
+ let sdurChange = overall.sdurChange
- if (!_isEmpty(overallCompare) && activePeriodCompare !== 'previous') {
- uniqueChange = (overall.current?.unique as number) - (overallCompare?.current?.unique as number)
- usersChange = (overall.current?.users as number) - (overallCompare?.current?.users as number)
- allChange = (overall.current?.all as number) - (overallCompare?.current?.all as number)
- bounceRateChange = ((overall.current?.bounceRate as number) - (overallCompare.current?.bounceRate as number)) * -1
- sdurChange = (overall.current?.sdur as number) - (overallCompare?.current?.sdur as number)
- }
+ if (!_isEmpty(overallCompare) && activePeriodCompare !== 'previous') {
+ uniqueChange =
+ (overall.current?.unique as number) -
+ (overallCompare?.current?.unique as number)
+ usersChange =
+ (overall.current?.users as number) -
+ (overallCompare?.current?.users as number)
+ allChange =
+ (overall.current?.all as number) -
+ (overallCompare?.current?.all as number)
+ bounceRateChange =
+ ((overall.current?.bounceRate as number) -
+ (overallCompare.current?.bounceRate as number)) *
+ -1
+ sdurChange =
+ (overall.current?.sdur as number) -
+ (overallCompare?.current?.sdur as number)
+ }
+
+ if (overall.customEVFilterApplied) {
+ return (
+ <MetricCard
+ label={t('project.events')}
+ value={overall.current?.all}
+ change={allChange}
+ type='percent'
+ goodChangeDirection='down'
+ valueMapper={(value, type) =>
+ `${type === 'badge' && value > 0 ? '+' : ''}${nFormatter(value, 1)}`
+ }
+ />
+ )
+ }
- if (overall.customEVFilterApplied) {
return (
- <MetricCard
- label={t('project.events')}
- value={overall.current?.all}
- change={allChange}
- type='percent'
- goodChangeDirection='down'
- valueMapper={(value, type) => `${type === 'badge' && value > 0 ? '+' : ''}${nFormatter(value, 1)}`}
- />
+ <>
+ <MetricCard
+ label={t('dashboard.users')}
+ value={overall.current?.users}
+ change={usersChange}
+ type='percent'
+ goodChangeDirection='down'
+ valueMapper={(value, type) =>
+ `${type === 'badge' && value > 0 ? '+' : ''}${nFormatter(value, 1)}`
+ }
+ />
+ <MetricCard
+ label={t('dashboard.sessions')}
+ value={overall.current?.unique}
+ change={uniqueChange}
+ type='percent'
+ goodChangeDirection='down'
+ valueMapper={(value, type) =>
+ `${type === 'badge' && value > 0 ? '+' : ''}${nFormatter(value, 1)}`
+ }
+ />
+ <MetricCard
+ label={t('dashboard.pageviews')}
+ value={overall.current?.all}
+ change={allChange}
+ type='percent'
+ goodChangeDirection='down'
+ valueMapper={(value, type) =>
+ `${type === 'badge' && value > 0 ? '+' : ''}${nFormatter(value, 1)}`
+ }
+ />
+ <MetricCard
+ label={t('dashboard.bounceRate')}
+ value={_round(overall.current?.bounceRate as number, 1)}
+ change={_round(bounceRateChange as number, 1)}
+ type='percent'
+ goodChangeDirection='up'
+ valueMapper={(value, type) =>
+ `${type === 'badge' && value > 0 ? '+' : ''}${value}%`
+ }
+ />
+ <MetricCard
+ label={t('dashboard.sessionDuration')}
+ value={overall.current?.sdur}
+ change={sdurChange}
+ goodChangeDirection='down'
+ valueMapper={(value, type) =>
+ `${type === 'badge' && value > 0 ? '+' : ''}${getStringFromTime(getTimeFromSeconds(value))}`
+ }
+ />
+ </>
)
- }
-
- return (
- <>
- <MetricCard
- label={t('dashboard.users')}
- value={overall.current?.users}
- change={usersChange}
- type='percent'
- goodChangeDirection='down'
- valueMapper={(value, type) => `${type === 'badge' && value > 0 ? '+' : ''}${nFormatter(value, 1)}`}
- />
- <MetricCard
- label={t('dashboard.sessions')}
- value={overall.current?.unique}
- change={uniqueChange}
- type='percent'
- goodChangeDirection='down'
- valueMapper={(value, type) => `${type === 'badge' && value > 0 ? '+' : ''}${nFormatter(value, 1)}`}
- />
- <MetricCard
- label={t('dashboard.pageviews')}
- value={overall.current?.all}
- change={allChange}
- type='percent'
- goodChangeDirection='down'
- valueMapper={(value, type) => `${type === 'badge' && value > 0 ? '+' : ''}${nFormatter(value, 1)}`}
- />
- <MetricCard
- label={t('dashboard.bounceRate')}
- value={_round(overall.current?.bounceRate as number, 1)}
- change={_round(bounceRateChange as number, 1)}
- type='percent'
- goodChangeDirection='up'
- valueMapper={(value, type) => `${type === 'badge' && value > 0 ? '+' : ''}${value}%`}
- />
- <MetricCard
- label={t('dashboard.sessionDuration')}
- value={overall.current?.sdur}
- change={sdurChange}
- goodChangeDirection='down'
- valueMapper={(value, type) =>
- `${type === 'badge' && value > 0 ? '+' : ''}${getStringFromTime(getTimeFromSeconds(value))}`
- }
- />
- </>
- )
-})
+ },
+)
interface PerformanceMetricCardsProps {
overall: Partial<OverallPerformanceObject>
@@ -267,7 +332,11 @@ interface PerformanceMetricCardsProps {
}
export const PerformanceMetricCards = memo(
- ({ overall, overallCompare, activePeriodCompare }: PerformanceMetricCardsProps) => {
+ ({
+ overall,
+ overallCompare,
+ activePeriodCompare,
+ }: PerformanceMetricCardsProps) => {
const { t } = useTranslation('common')
let frontendChange = overall.frontendChange
@@ -276,11 +345,14 @@ export const PerformanceMetricCards = memo(
if (!_isEmpty(overallCompare) && activePeriodCompare !== 'previous') {
// @ts-expect-error
- frontendChange = overall.current?.frontend - overallCompare?.current?.frontend
+ frontendChange =
+ overall.current?.frontend - overallCompare?.current?.frontend
// @ts-expect-error
- backendChange = overall.current?.backend - overallCompare?.current?.backend
+ backendChange =
+ overall.current?.backend - overallCompare?.current?.backend
// @ts-expect-error
- networkChange = overall.current?.network - overallCompare?.current?.network
+ networkChange =
+ overall.current?.network - overallCompare?.current?.network
}
return (
diff --git a/web/app/pages/Project/tabs/Traffic/PageLinkRow.tsx b/web/app/pages/Project/tabs/Traffic/PageLinkRow.tsx
index 5b5ec7587..68296d7fc 100644
--- a/web/app/pages/Project/tabs/Traffic/PageLinkRow.tsx
+++ b/web/app/pages/Project/tabs/Traffic/PageLinkRow.tsx
@@ -30,7 +30,9 @@ const PageLinkRow = ({ pagePath, websiteUrl }: PageLinkRowProps) => {
return (
<div className='scrollbar-thin hover-always-overflow flex min-w-0 items-center'>
- <span className='truncate text-sm text-gray-900 dark:text-gray-100'>{pagePath}</span>
+ <span className='truncate text-sm text-gray-900 dark:text-gray-100'>
+ {pagePath}
+ </span>
{fullUrl ? (
<a
href={fullUrl}
diff --git a/web/app/pages/Project/tabs/Traffic/RefRow.tsx b/web/app/pages/Project/tabs/Traffic/RefRow.tsx
index 07868d735..a06eafde9 100644
--- a/web/app/pages/Project/tabs/Traffic/RefRow.tsx
+++ b/web/app/pages/Project/tabs/Traffic/RefRow.tsx
@@ -8,7 +8,12 @@ const RefRow = ({ rowName }: { rowName: string | null }) => {
const { t } = useTranslation('common')
const { isUrl, faviconHost, displayRowName } = useMemo(() => {
- if (!rowName) return { isUrl: false, faviconHost: null as string | null, displayRowName: '' }
+ if (!rowName)
+ return {
+ isUrl: false,
+ faviconHost: null as string | null,
+ displayRowName: '',
+ }
let isUrl = false
try {
new URL(rowName)
@@ -17,7 +22,9 @@ const RefRow = ({ rowName }: { rowName: string | null }) => {
isUrl = false
}
- const displayRowName = rowName.replace(/^https?:\/\//, '').replace(/\/$/, '')
+ const displayRowName = rowName
+ .replace(/^https?:\/\//, '')
+ .replace(/\/$/, '')
return { isUrl, faviconHost: getFaviconHost(rowName), displayRowName }
}, [rowName])
@@ -42,7 +49,9 @@ const RefRow = ({ rowName }: { rowName: string | null }) => {
aria-hidden='true'
/>
) : null}
- <span className='truncate text-sm text-gray-900 dark:text-gray-100'>{displayRowName}</span>
+ <span className='truncate text-sm text-gray-900 dark:text-gray-100'>
+ {displayRowName}
+ </span>
{isUrl ? (
<a
href={rowName}
diff --git a/web/app/pages/Project/tabs/Traffic/TrafficChart.tsx b/web/app/pages/Project/tabs/Traffic/TrafficChart.tsx
index 1fc6839ec..2d61824e9 100644
--- a/web/app/pages/Project/tabs/Traffic/TrafficChart.tsx
+++ b/web/app/pages/Project/tabs/Traffic/TrafficChart.tsx
@@ -100,5 +100,13 @@ export const TrafficChart = ({
],
)
- return <MainChart chartId='traffic-chart' options={options} dataNames={dataNames} className={className} deps={deps} />
+ return (
+ <MainChart
+ chartId='traffic-chart'
+ options={options}
+ dataNames={dataNames}
+ className={className}
+ deps={deps}
+ />
+ )
}
diff --git a/web/app/pages/Project/tabs/Traffic/TrafficHeaderActions.tsx b/web/app/pages/Project/tabs/Traffic/TrafficHeaderActions.tsx
index 35408264c..b00f0bbc1 100644
--- a/web/app/pages/Project/tabs/Traffic/TrafficHeaderActions.tsx
+++ b/web/app/pages/Project/tabs/Traffic/TrafficHeaderActions.tsx
@@ -1,7 +1,12 @@
import cx from 'clsx'
import _filter from 'lodash/filter'
import _isEmpty from 'lodash/isEmpty'
-import { BookmarkIcon, DownloadIcon, PencilIcon, Trash2Icon } from 'lucide-react'
+import {
+ BookmarkIcon,
+ DownloadIcon,
+ PencilIcon,
+ Trash2Icon,
+} from 'lucide-react'
import React, { useEffect, useRef } from 'react'
import { useTranslation } from 'react-i18next'
import { useSearchParams, useFetcher } from 'react-router'
@@ -13,7 +18,11 @@ import { Text } from '~/ui/Text'
import { trackCustom } from '~/utils/analytics'
import { getFiltersUrlParams } from '../../View/components/SearchFilters'
-import { Filter, ProjectView, ProjectViewCustomEvent } from '../../View/interfaces/traffic'
+import {
+ Filter,
+ ProjectView,
+ ProjectViewCustomEvent,
+} from '../../View/interfaces/traffic'
interface ExportType {
label: string
@@ -134,7 +143,11 @@ const TrafficHeaderActions = ({
<PencilIcon className='size-3' />
</button>
<deleteFetcher.Form method='post' className='inline'>
- <input type='hidden' name='intent' value='delete-project-view' />
+ <input
+ type='hidden'
+ name='intent'
+ value='delete-project-view'
+ />
<input type='hidden' name='viewId' value={item.id} />
<button
type='submit'
@@ -170,7 +183,12 @@ const TrafficHeaderActions = ({
}
if (item.filters && !_isEmpty(item.filters)) {
- const newUrlParams = getFiltersUrlParams(filters, item.filters, true, searchParams)
+ const newUrlParams = getFiltersUrlParams(
+ filters,
+ item.filters,
+ true,
+ searchParams,
+ )
setSearchParams(newUrlParams)
}
diff --git a/web/app/pages/Project/tabs/Traffic/TrafficView.tsx b/web/app/pages/Project/tabs/Traffic/TrafficView.tsx
index cac8cac8e..cabfd4ea8 100644
--- a/web/app/pages/Project/tabs/Traffic/TrafficView.tsx
+++ b/web/app/pages/Project/tabs/Traffic/TrafficView.tsx
@@ -5,7 +5,12 @@ import _isEmpty from 'lodash/isEmpty'
import _keys from 'lodash/keys'
import _map from 'lodash/map'
import _some from 'lodash/some'
-import { BanIcon, ChartColumnBigIcon, ChartLineIcon, EyeIcon } from 'lucide-react'
+import {
+ BanIcon,
+ ChartColumnBigIcon,
+ ChartLineIcon,
+ EyeIcon,
+} from 'lucide-react'
import React, {
useState,
useEffect,
@@ -20,7 +25,13 @@ import React, {
} from 'react'
import { createPortal } from 'react-dom'
import { useTranslation } from 'react-i18next'
-import { useNavigate, Link, useSearchParams, useLoaderData, useRevalidator } from 'react-router'
+import {
+ useNavigate,
+ Link,
+ useSearchParams,
+ useLoaderData,
+ useRevalidator,
+} from 'react-router'
import { toast } from 'sonner'
import type {
@@ -40,7 +51,10 @@ import { OverallObject } from '~/lib/models/Project'
import AnnotationModal from '~/modals/AnnotationModal'
import CustomEventsSubmenu from '~/pages/Project/tabs/Traffic/CustomEventsSubmenu'
import CustomMetrics from '~/pages/Project/tabs/Traffic/CustomMetrics'
-import { MetricCard, MetricCards } from '~/pages/Project/tabs/Traffic/MetricCards'
+import {
+ MetricCard,
+ MetricCards,
+} from '~/pages/Project/tabs/Traffic/MetricCards'
import PageLinkRow from '~/pages/Project/tabs/Traffic/PageLinkRow'
import RefRow from '~/pages/Project/tabs/Traffic/RefRow'
import { TrafficChart } from '~/pages/Project/tabs/Traffic/TrafficChart'
@@ -60,9 +74,16 @@ import {
ProjectViewCustomEvent,
Properties,
} from '~/pages/Project/View/interfaces/traffic'
-import { Panel, CustomEvents, MetadataKeyPanel } from '~/pages/Project/View/Panels'
+import {
+ Panel,
+ CustomEvents,
+ MetadataKeyPanel,
+} from '~/pages/Project/View/Panels'
import { FILTER_CHART_METRICS_MAPPING_FOR_COMPARE } from '~/pages/Project/View/utils/filters'
-import { useViewProjectContext, useRefreshTriggers } from '~/pages/Project/View/ViewProject'
+import {
+ useViewProjectContext,
+ useRefreshTriggers,
+} from '~/pages/Project/View/ViewProject'
import {
getFormatDate,
panelIconMapping,
@@ -82,7 +103,9 @@ import { getLocaleDisplayName, nLocaleFormatter } from '~/utils/generic'
import { groupRefEntries } from '~/utils/referrers'
import routes from '~/utils/routes'
-const InteractiveMap = lazy(() => import('~/pages/Project/View/components/InteractiveMap'))
+const InteractiveMap = lazy(
+ () => import('~/pages/Project/View/components/InteractiveMap'),
+)
interface PanelsData {
types?: string[]
@@ -92,7 +115,11 @@ interface PanelsData {
meta?: TrafficMeta[]
}
-type KeywordEntry = Entry & { impressions: number; position: number; ctr: number }
+type KeywordEntry = Entry & {
+ impressions: number
+ position: number
+ ctr: number
+}
interface TrafficViewProps {
tnMapping: Record<string, string>
@@ -122,7 +149,10 @@ interface TrafficErrorBoundaryState {
error: Error | null
}
-class TrafficErrorBoundary extends Component<{ children: ReactNode }, TrafficErrorBoundaryState> {
+class TrafficErrorBoundary extends Component<
+ { children: ReactNode },
+ TrafficErrorBoundaryState
+> {
constructor(props: { children: ReactNode }) {
super(props)
this.state = { hasError: false, error: null }
@@ -140,7 +170,8 @@ class TrafficErrorBoundary extends Component<{ children: ReactNode }, TrafficErr
Failed to load traffic data
</p>
<p className='mt-2 text-center text-sm text-red-500 dark:text-red-300'>
- {this.state.error?.message || 'An unexpected error occurred. Please try again.'}
+ {this.state.error?.message ||
+ 'An unexpected error occurred. Please try again.'}
</p>
<button
type='button'
@@ -157,7 +188,11 @@ class TrafficErrorBoundary extends Component<{ children: ReactNode }, TrafficErr
}
}
-function TrafficDataResolver({ children }: { children: (data: DeferredTrafficData) => React.ReactNode }) {
+function TrafficDataResolver({
+ children,
+}: {
+ children: (data: DeferredTrafficData) => React.ReactNode
+}) {
const {
trafficData: trafficDataPromise,
overallStats: overallStatsPromise,
@@ -168,11 +203,25 @@ function TrafficDataResolver({ children }: { children: (data: DeferredTrafficDat
const trafficData = trafficDataPromise ? use(trafficDataPromise) : null
const overallStats = overallStatsPromise ? use(overallStatsPromise) : null
- const trafficCompareData = trafficComparePromise ? use(trafficComparePromise) : null
- const overallCompareStats = overallComparePromise ? use(overallComparePromise) : null
+ const trafficCompareData = trafficComparePromise
+ ? use(trafficComparePromise)
+ : null
+ const overallCompareStats = overallComparePromise
+ ? use(overallComparePromise)
+ : null
const customEventsData = customEventsPromise ? use(customEventsPromise) : null
- return <>{children({ trafficData, overallStats, trafficCompareData, overallCompareStats, customEventsData })}</>
+ return (
+ <>
+ {children({
+ trafficData,
+ overallStats,
+ trafficCompareData,
+ overallCompareStats,
+ customEventsData,
+ })}
+ </>
+ )
}
function TrafficViewWrapper(props: TrafficViewProps) {
@@ -180,7 +229,9 @@ function TrafficViewWrapper(props: TrafficViewProps) {
<TrafficErrorBoundary>
<Suspense fallback={<Loader />}>
<TrafficDataResolver>
- {(deferredData) => <TrafficViewInner {...props} deferredData={deferredData} />}
+ {(deferredData) => (
+ <TrafficViewInner {...props} deferredData={deferredData} />
+ )}
</TrafficDataResolver>
</Suspense>
</TrafficErrorBoundary>
@@ -207,7 +258,8 @@ const TrafficViewInner = ({
}: TrafficViewInnerProps) => {
const { id, project, allowedToManage } = useCurrentProject()
const revalidator = useRevalidator()
- const { fetchMetadata: fetchCustomEventsMetadata } = useCustomEventsMetadataProxy()
+ const { fetchMetadata: fetchCustomEventsMetadata } =
+ useCustomEventsMetadataProxy()
const { fetchMetadata: fetchPropertyMetadata } = usePropertyMetadataProxy()
const { fetchKeywords: fetchGSCKeywords } = useGSCKeywordsProxy()
const { fetchRevenueStatus, fetchRevenueData } = useRevenueProxy()
@@ -278,7 +330,10 @@ const TrafficViewInner = ({
return { data: {} }
}, [deferredData.trafficData])
- const baseChartData = useMemo(() => deferredData.trafficData?.chart || {}, [deferredData.trafficData])
+ const baseChartData = useMemo(
+ () => deferredData.trafficData?.chart || {},
+ [deferredData.trafficData],
+ )
const overall: Partial<OverallObject> = useMemo(() => {
if (deferredData.overallStats && id) {
@@ -304,13 +359,20 @@ const TrafficViewInner = ({
// Derive custom events data from loader
const customEventsChartData = useMemo(
- () => (deferredData.customEventsData?.chart?.events || {}) as Record<string, string[]>,
+ () =>
+ (deferredData.customEventsData?.chart?.events || {}) as Record<
+ string,
+ string[]
+ >,
[deferredData.customEventsData],
)
// Revenue state (still fetched client-side for now)
const [isRevenueConnected, setIsRevenueConnected] = useState(false)
- const [revenueOverlay, setRevenueOverlay] = useState<{ revenue: number[]; refundsAmount: number[] } | null>(null)
+ const [revenueOverlay, setRevenueOverlay] = useState<{
+ revenue: number[]
+ refundsAmount: number[]
+ } | null>(null)
// Merge base chart with revenue data
const chartData = useMemo(() => {
@@ -396,7 +458,10 @@ const TrafficViewInner = ({
setIsRevenueConnected(status.connected)
}
} catch (error) {
- console.error('[ERROR] (fetchRevenueStatus) Fetching revenue status failed', error)
+ console.error(
+ '[ERROR] (fetchRevenueStatus) Fetching revenue status failed',
+ error,
+ )
}
}
@@ -452,20 +517,29 @@ const TrafficViewInner = ({
id: CHART_METRICS_MAPPING.revenue,
label: t('dashboard.revenue'),
active: activeChartMetrics[CHART_METRICS_MAPPING.revenue],
- conflicts: [CHART_METRICS_MAPPING.bounce, CHART_METRICS_MAPPING.sessionDuration],
+ conflicts: [
+ CHART_METRICS_MAPPING.bounce,
+ CHART_METRICS_MAPPING.sessionDuration,
+ ],
}
: null,
{
id: CHART_METRICS_MAPPING.sessionDuration,
label: t('dashboard.sessionDuration'),
active: activeChartMetrics[CHART_METRICS_MAPPING.sessionDuration],
- conflicts: [CHART_METRICS_MAPPING.bounce, CHART_METRICS_MAPPING.revenue],
+ conflicts: [
+ CHART_METRICS_MAPPING.bounce,
+ CHART_METRICS_MAPPING.revenue,
+ ],
},
{
id: CHART_METRICS_MAPPING.bounce,
label: t('dashboard.bounceRate'),
active: activeChartMetrics[CHART_METRICS_MAPPING.bounce],
- conflicts: [CHART_METRICS_MAPPING.sessionDuration, CHART_METRICS_MAPPING.revenue],
+ conflicts: [
+ CHART_METRICS_MAPPING.sessionDuration,
+ CHART_METRICS_MAPPING.revenue,
+ ],
},
{
id: CHART_METRICS_MAPPING.viewsPerUnique,
@@ -530,14 +604,20 @@ const TrafficViewInner = ({
)
const checkIfAllMetricsAreDisabled = useMemo(
- () => !_some({ ...activeChartMetrics, ...activeChartMetricsCustomEvents }, (value) => value),
+ () =>
+ !_some(
+ { ...activeChartMetrics, ...activeChartMetricsCustomEvents },
+ (value) => value,
+ ),
[activeChartMetrics, activeChartMetricsCustomEvents],
)
const isConflicted = useCallback(
(conflicts: string[] | undefined) => {
if (!conflicts) return false
- return conflicts.some((id) => activeChartMetrics[id as keyof typeof activeChartMetrics])
+ return conflicts.some(
+ (id) => activeChartMetrics[id as keyof typeof activeChartMetrics],
+ )
},
[activeChartMetrics],
)
@@ -564,7 +644,8 @@ const TrafficViewInner = ({
const switchCustomEventChart = useCallback(
(eventId: string) => {
const newParams = new URLSearchParams(searchParams.toString())
- const currentEvents = newParams.get('customEvents')?.split(',').filter(Boolean) || []
+ const currentEvents =
+ newParams.get('customEvents')?.split(',').filter(Boolean) || []
let newEvents: string[]
if (currentEvents.includes(eventId)) {
@@ -592,7 +673,12 @@ const TrafficViewInner = ({
// Load revenue data (the only remaining client-side fetch)
const loadRevenueData = useCallback(async () => {
- if (!project || !activeChartMetrics.revenue || isSelfhosted || !isRevenueConnected) {
+ if (
+ !project ||
+ !activeChartMetrics.revenue ||
+ isSelfhosted ||
+ !isRevenueConnected
+ ) {
setRevenueOverlay(null)
return
}
@@ -641,7 +727,9 @@ const TrafficViewInner = ({
refundsByX.set(revX[i], Number(revRefunds[i] ?? 0))
}
revenueData = chart.x.map((x: string) => Number(byX.get(x) ?? 0))
- refundsData = chart.x.map((x: string) => Number(refundsByX.get(x) ?? 0))
+ refundsData = chart.x.map((x: string) =>
+ Number(refundsByX.get(x) ?? 0),
+ )
}
}
@@ -673,7 +761,11 @@ const TrafficViewInner = ({
timezone,
})
} else {
- result = await fetchCustomEventsMetadata(id, event, { timeBucket, period, timezone })
+ result = await fetchCustomEventsMetadata(id, event, {
+ timeBucket,
+ period,
+ timezone,
+ })
}
return result || { result: [] }
@@ -691,7 +783,12 @@ const TrafficViewInner = ({
timezone,
})
} else {
- result = await fetchPropertyMetadata(id, property, { timeBucket, period, filters, timezone })
+ result = await fetchPropertyMetadata(id, property, {
+ timeBucket,
+ period,
+ filters,
+ timezone,
+ })
}
return result || { result: [] }
@@ -766,7 +863,12 @@ const TrafficViewInner = ({
{
label: t('project.asCSV'),
onClick: () =>
- onCSVExportClick({ data: panelsData.data, types: panelsData.types || [] }, id, tnMapping, language),
+ onCSVExportClick(
+ { data: panelsData.data, types: panelsData.types || [] },
+ id,
+ tnMapping,
+ language,
+ ),
},
],
[t, panelsData, id, tnMapping, language],
@@ -803,7 +905,13 @@ const TrafficViewInner = ({
)
}
- const ChartTypeSwitcher = ({ type, onSwitch }: { type: string; onSwitch: (type: 'line' | 'bar') => void }) => {
+ const ChartTypeSwitcher = ({
+ type,
+ onSwitch,
+ }: {
+ type: string
+ onSwitch: (type: 'line' | 'bar') => void
+ }) => {
if (type === chartTypes.bar) {
return (
<button
@@ -833,7 +941,10 @@ const TrafficViewInner = ({
if (isMapFullscreen && fullscreenMapRef.current) {
const countryData = panelsData.data?.cc || []
const regionData = panelsData.data?.rg || []
- const total = countryData.reduce((acc: number, curr: any) => acc + curr.count, 0)
+ const total = countryData.reduce(
+ (acc: number, curr: any) => acc + curr.count,
+ 0,
+ )
return createPortal(
<Suspense
@@ -841,7 +952,9 @@ const TrafficViewInner = ({
<div className='flex h-full flex-1 items-center justify-center'>
<div className='flex flex-col items-center gap-2'>
<div className='h-8 w-8 animate-spin rounded-full border-2 border-indigo-400 border-t-transparent' />
- <span className='text-sm text-neutral-600 dark:text-neutral-300'>Loading map...</span>
+ <span className='text-sm text-neutral-600 dark:text-neutral-300'>
+ Loading map...
+ </span>
</div>
</div>
}
@@ -867,17 +980,33 @@ const TrafficViewInner = ({
<DashboardHeader rightContent={headerRightContent} />
{dataLoading && !isPanelsDataEmpty ? <LoadingBar /> : null}
<div className={cx({ hidden: isPanelsDataEmpty })}>
- {!isPanelsDataEmpty ? <Filters className='mb-3' tnMapping={tnMapping} /> : null}
+ {!isPanelsDataEmpty ? (
+ <Filters className='mb-3' tnMapping={tnMapping} />
+ ) : null}
<div className='relative overflow-hidden rounded-lg border border-gray-200 bg-white p-4 dark:border-slate-800/60 dark:bg-slate-800/25'>
<div className='mb-3 flex w-full items-center justify-end gap-2 lg:absolute lg:top-2 lg:right-2 lg:mb-0 lg:w-auto lg:justify-normal'>
<Dropdown
header={t('project.metricVis')}
items={
isActiveCompare
- ? _filter(chartMetrics, (el) => !!el && !_includes(FILTER_CHART_METRICS_MAPPING_FOR_COMPARE, el.id))
+ ? _filter(
+ chartMetrics,
+ (el) =>
+ !!el &&
+ !_includes(
+ FILTER_CHART_METRICS_MAPPING_FOR_COMPARE,
+ el.id,
+ ),
+ )
: chartMetrics
}
- title={[<EyeIcon key='eye-icon' aria-label={t('project.metricVis')} className='h-5 w-5' />]}
+ title={[
+ <EyeIcon
+ key='eye-icon'
+ aria-label={t('project.metricVis')}
+ className='h-5 w-5'
+ />,
+ ]}
labelExtractor={(pair) => {
if (!pair) return null
@@ -935,7 +1064,10 @@ const TrafficViewInner = ({
chevron='mini'
headless
/>
- <ChartTypeSwitcher onSwitch={setChartTypeOnClick} type={chartType} />
+ <ChartTypeSwitcher
+ onSwitch={setChartTypeOnClick}
+ type={chartType}
+ />
</div>
{!_isEmpty(overall) ? (
<div className='mb-5 flex flex-wrap justify-center gap-5 lg:justify-start'>
@@ -971,7 +1103,12 @@ const TrafficViewInner = ({
</div>
) : null}
{!checkIfAllMetricsAreDisabled && !_isEmpty(chartData) ? (
- <div onContextMenu={(e) => handleChartContextMenu(e, (chartData as any).x)} className='relative'>
+ <div
+ onContextMenu={(e) =>
+ handleChartContextMenu(e, (chartData as any).x)
+ }
+ className='relative'
+ >
<TrafficChart
chartData={chartData}
timeBucket={timeBucket}
@@ -1017,15 +1154,28 @@ const TrafficViewInner = ({
}
const entryNameArray = entryName.split('-')
- const displayName = getLocaleDisplayName(entryName, language)
+ const displayName = getLocaleDisplayName(
+ entryName,
+ language,
+ )
return (
- <CCRow cc={entryNameArray[entryNameArray.length - 1]} name={displayName} language={language} />
+ <CCRow
+ cc={entryNameArray[entryNameArray.length - 1]}
+ name={displayName}
+ language={language}
+ />
)
}
if (cc !== undefined) {
- return <CCRow cc={cc} name={entryName || undefined} language={language} />
+ return (
+ <CCRow
+ cc={cc}
+ name={entryName || undefined}
+ language={language}
+ />
+ )
}
return <CCRow cc={entryName} language={language} />
@@ -1048,7 +1198,10 @@ const TrafficViewInner = ({
? () => {
const countryData = panelsData.data?.cc || []
const regionData = panelsData.data?.rg || []
- const total = countryData.reduce((acc, curr) => acc + curr.count, 0)
+ const total = countryData.reduce(
+ (acc, curr) => acc + curr.count,
+ 0,
+ )
return (
<Suspense
@@ -1101,7 +1254,11 @@ const TrafficViewInner = ({
onTabChange={(tab) => setPanelTab('device', tab)}
activeTabId={panelsActiveTabs.device}
data={panelsData.data[panelsActiveTabs.device]}
- rowMapper={getDeviceRowMapper(panelsActiveTabs.device, theme, t)}
+ rowMapper={getDeviceRowMapper(
+ panelsActiveTabs.device,
+ theme,
+ t,
+ )}
capitalize={panelsActiveTabs.device === 'dv'}
versionData={
panelsActiveTabs.device === 'br'
@@ -1111,7 +1268,11 @@ const TrafficViewInner = ({
: undefined
}
getVersionFilterLink={(parent, version) =>
- getVersionFilterLink(parent, version, panelsActiveTabs.device === 'br' ? 'br' : 'os')
+ getVersionFilterLink(
+ parent,
+ version,
+ panelsActiveTabs.device === 'br' ? 'br' : 'os',
+ )
}
/>
)
@@ -1139,7 +1300,9 @@ const TrafficViewInner = ({
if (!entryName) {
return (
<span className='italic'>
- {panelsActiveTabs.page === 'host' ? t('project.unknownHost') : t('common.notSet')}
+ {panelsActiveTabs.page === 'host'
+ ? t('project.unknownHost')
+ : t('common.notSet')}
</span>
)
}
@@ -1153,8 +1316,16 @@ const TrafficViewInner = ({
}
// For page paths (pg tab), show with clickable link
- if (panelsActiveTabs.page === 'pg' && project?.websiteUrl) {
- return <PageLinkRow pagePath={decodedUri} websiteUrl={project.websiteUrl} />
+ if (
+ panelsActiveTabs.page === 'pg' &&
+ project?.websiteUrl
+ ) {
+ return (
+ <PageLinkRow
+ pagePath={decodedUri}
+ websiteUrl={project.websiteUrl}
+ />
+ )
}
return decodedUri
@@ -1166,7 +1337,12 @@ const TrafficViewInner = ({
data={panelsData.data[panelsActiveTabs.page]}
customRenderer={
panelsActiveTabs.page === 'userFlow'
- ? () => <UserFlow isReversed={false} setReversed={() => {}} />
+ ? () => (
+ <UserFlow
+ isReversed={false}
+ setReversed={() => {}}
+ />
+ )
: undefined
}
/>
@@ -1174,10 +1350,15 @@ const TrafficViewInner = ({
}
if (type === 'traffic-sources') {
- const hasRefNameFilter = filters.some((f) => f.column === 'refn')
+ const hasRefNameFilter = filters.some(
+ (f) => f.column === 'refn',
+ )
const trafficSourcesTabs = [
{ id: 'ref', label: t('project.mapping.ref') },
- !isSelfhosted && { id: 'keywords', label: t('project.mapping.keywords') },
+ !isSelfhosted && {
+ id: 'keywords',
+ label: t('project.mapping.keywords'),
+ },
[
{ id: 'so', label: t('project.mapping.so') },
{ id: 'me', label: t('project.mapping.me') },
@@ -1190,9 +1371,12 @@ const TrafficViewInner = ({
const getTrafficSourcesRowMapper = (activeTab: string) => {
if (activeTab === 'ref') {
// eslint-disable-next-line
- return ({ name: entryName }: any) => <RefRow rowName={entryName} />
+ return ({ name: entryName }: any) => (
+ <RefRow rowName={entryName} />
+ )
}
- return ({ name: entryName }: any) => decodeURIComponent(entryName)
+ return ({ name: entryName }: any) =>
+ decodeURIComponent(entryName)
}
return (
@@ -1203,7 +1387,10 @@ const TrafficViewInner = ({
getFilterLink={(column: string, value: string | null) => {
if (panelsActiveTabs.source === 'ref') {
// If grouped by name/domain (no refn filter active) -> filter by refn
- return getFilterLink(hasRefNameFilter || value === null ? 'ref' : 'refn', value)
+ return getFilterLink(
+ hasRefNameFilter || value === null ? 'ref' : 'refn',
+ value,
+ )
}
return getFilterLink(column, value)
}}
@@ -1219,14 +1406,26 @@ const TrafficViewInner = ({
const raw = panelsData.data?.ref || []
return hasRefNameFilter
? (raw as unknown as Entry[])
- : (groupRefEntries(raw as any) as unknown as Entry[])
+ : (groupRefEntries(
+ raw as any,
+ ) as unknown as Entry[])
})()
- : (panelsData.data[panelsActiveTabs.source] as unknown as Entry[])
+ : (panelsData.data[
+ panelsActiveTabs.source
+ ] as unknown as Entry[])
+ }
+ valuesHeaderName={
+ panelsActiveTabs.source === 'keywords'
+ ? t('project.clicks')
+ : undefined
}
- valuesHeaderName={panelsActiveTabs.source === 'keywords' ? t('project.clicks') : undefined}
- rowMapper={getTrafficSourcesRowMapper(panelsActiveTabs.source)}
+ rowMapper={getTrafficSourcesRowMapper(
+ panelsActiveTabs.source,
+ )}
disableRowClick={panelsActiveTabs.source === 'keywords'}
- hidePercentageInDetails={panelsActiveTabs.source === 'keywords'}
+ hidePercentageInDetails={
+ panelsActiveTabs.source === 'keywords'
+ }
detailsExtraColumns={
panelsActiveTabs.source === 'keywords'
? [
@@ -1234,19 +1433,22 @@ const TrafficViewInner = ({
header: t('project.impressions'),
render: (entry: any) => entry.impressions,
sortLabel: 'impressions',
- getSortValue: (entry: any) => Number(entry.impressions || 0),
+ getSortValue: (entry: any) =>
+ Number(entry.impressions || 0),
},
{
header: t('project.position'),
render: (entry: any) => entry.position,
sortLabel: 'position',
- getSortValue: (entry: any) => Number(entry.position || 0),
+ getSortValue: (entry: any) =>
+ Number(entry.position || 0),
},
{
header: t('project.ctr'),
render: (entry: any) => `${entry.ctr}%`,
sortLabel: 'ctr',
- getSortValue: (entry: any) => Number(entry.ctr || 0),
+ getSortValue: (entry: any) =>
+ Number(entry.ctr || 0),
},
]
: undefined
@@ -1259,11 +1461,15 @@ const TrafficViewInner = ({
? () => (
<div className='mt-4 text-center'>
<p className='text-sm text-gray-800 dark:text-gray-200'>
- {['owner', 'admin'].includes(project?.role || '')
+ {['owner', 'admin'].includes(
+ project?.role || '',
+ )
? t('project.connectGsc')
: t('project.gscConnectionRequired')}
</p>
- {['owner', 'admin'].includes(project?.role || '') ? (
+ {['owner', 'admin'].includes(
+ project?.role || '',
+ ) ? (
<Link
to={`${routes.project_settings.replace(':id', id)}?tab=integrations`}
className='mt-2 inline-flex items-center rounded-md border border-gray-300 bg-white px-3 py-1 text-sm text-gray-800 hover:bg-gray-50 dark:border-slate-700 dark:bg-slate-800 dark:text-gray-50 dark:hover:bg-slate-700'
@@ -1344,7 +1550,11 @@ const TrafficViewInner = ({
}}
onEditAnnotation={
contextMenu.annotation
- ? () => openAnnotationModal(contextMenu.annotation?.date, contextMenu.annotation!)
+ ? () =>
+ openAnnotationModal(
+ contextMenu.annotation?.date,
+ contextMenu.annotation!,
+ )
: undefined
}
onDeleteAnnotation={
diff --git a/web/app/pages/Project/tabs/Traffic/UserFlow.tsx b/web/app/pages/Project/tabs/Traffic/UserFlow.tsx
index b5ef771d2..ea4a0ac9a 100644
--- a/web/app/pages/Project/tabs/Traffic/UserFlow.tsx
+++ b/web/app/pages/Project/tabs/Traffic/UserFlow.tsx
@@ -18,7 +18,8 @@ interface UserFlowProps {
}
const UserFlow = ({ setReversed, isReversed }: UserFlowProps) => {
- const { dateRange, period, timeBucket, timezone, filters } = useViewProjectContext()
+ const { dateRange, period, timeBucket, timezone, filters } =
+ useViewProjectContext()
const { id } = useCurrentProject()
const { t } = useTranslation('common')
const [isLoading, setIsLoading] = useState<boolean | null>(null)
@@ -59,7 +60,11 @@ const UserFlow = ({ setReversed, isReversed }: UserFlowProps) => {
})
}
} catch (error: any) {
- toast.error(typeof error === 'string' ? error : t('apiNotifications.somethingWentWrong'))
+ toast.error(
+ typeof error === 'string'
+ ? error
+ : t('apiNotifications.somethingWentWrong'),
+ )
} finally {
setIsLoading(false)
}
@@ -76,8 +81,12 @@ const UserFlow = ({ setReversed, isReversed }: UserFlowProps) => {
if (
!isReversed
- ? _isEmpty(userFlow?.ascending) || _isEmpty(userFlow?.ascending?.nodes) || _isEmpty(userFlow?.ascending?.links)
- : _isEmpty(userFlow?.descending) || _isEmpty(userFlow?.descending?.links) || _isEmpty(userFlow?.descending?.nodes)
+ ? _isEmpty(userFlow?.ascending) ||
+ _isEmpty(userFlow?.ascending?.nodes) ||
+ _isEmpty(userFlow?.ascending?.links)
+ : _isEmpty(userFlow?.descending) ||
+ _isEmpty(userFlow?.descending?.links) ||
+ _isEmpty(userFlow?.descending?.nodes)
) {
return (
<>
diff --git a/web/app/pages/UserSettings/UserSettings.tsx b/web/app/pages/UserSettings/UserSettings.tsx
index c7b812249..df57a1613 100644
--- a/web/app/pages/UserSettings/UserSettings.tsx
+++ b/web/app/pages/UserSettings/UserSettings.tsx
@@ -1,4 +1,8 @@
-import { EnvelopeIcon, ExclamationTriangleIcon, ChevronDownIcon } from '@heroicons/react/24/outline'
+import {
+ EnvelopeIcon,
+ ExclamationTriangleIcon,
+ ChevronDownIcon,
+} from '@heroicons/react/24/outline'
import cx from 'clsx'
import dayjs from 'dayjs'
import utc from 'dayjs/plugin/utc'
@@ -15,7 +19,13 @@ import { useTranslation } from 'react-i18next'
import { useNavigate, useFetcher } from 'react-router'
import { toast } from 'sonner'
-import { reportFrequencies, DEFAULT_TIMEZONE, CONFIRMATION_TIMEOUT, TimeFormat, isSelfhosted } from '~/lib/constants'
+import {
+ reportFrequencies,
+ DEFAULT_TIMEZONE,
+ CONFIRMATION_TIMEOUT,
+ TimeFormat,
+ isSelfhosted,
+} from '~/lib/constants'
import { User } from '~/lib/models/User'
import PaidFeature from '~/modals/PaidFeature'
import { useAuth } from '~/providers/AuthProvider'
@@ -30,7 +40,11 @@ import Textarea from '~/ui/Textarea'
import TimezonePicker from '~/ui/TimezonePicker'
import { getCookie, setCookie } from '~/utils/cookie'
import routes from '~/utils/routes'
-import { isValidEmail, isValidPassword, MIN_PASSWORD_CHARS } from '~/utils/validator'
+import {
+ isValidEmail,
+ isValidPassword,
+ MIN_PASSWORD_CHARS,
+} from '~/utils/validator'
import Integrations from './components/Integrations'
import NoOrganisations from './components/NoOrganisations'
@@ -106,15 +120,26 @@ const UserSettings = () => {
timeFormat: user?.timeFormat || TimeFormat['12-hour'],
}))
const [showPasswordFields, setShowPasswordFields] = useState(false)
- const [timezone, setTimezone] = useState(() => user?.timezone || DEFAULT_TIMEZONE)
+ const [timezone, setTimezone] = useState(
+ () => user?.timezone || DEFAULT_TIMEZONE,
+ )
const [isPaidFeatureOpened, setIsPaidFeatureOpened] = useState(false)
- const [isPasswordChangeModalOpened, setIsPasswordChangeModalOpened] = useState(false)
- const [reportFrequency, setReportFrequency] = useState(() => user?.reportFrequency)
+ const [isPasswordChangeModalOpened, setIsPasswordChangeModalOpened] =
+ useState(false)
+ const [reportFrequency, setReportFrequency] = useState(
+ () => user?.reportFrequency,
+ )
const [beenSubmitted, setBeenSubmitted] = useState(false)
const [showModal, setShowModal] = useState(false)
const [showAPIDeleteModal, setShowAPIDeleteModal] = useState(false)
- const translatedFrequencies = useMemo(() => _map(reportFrequencies, (key) => t(`profileSettings.${key}`)), [t])
- const translatedTimeFormat = useMemo(() => _map(TimeFormat, (key) => t(`profileSettings.${key}`)), [t])
+ const translatedFrequencies = useMemo(
+ () => _map(reportFrequencies, (key) => t(`profileSettings.${key}`)),
+ [t],
+ )
+ const translatedTimeFormat = useMemo(
+ () => _map(TimeFormat, (key) => t(`profileSettings.${key}`)),
+ [t],
+ )
const [deletionFeedback, setDeletionFeedback] = useState('')
const lastHandledData = useRef<UserSettingsActionData | null>(null)
@@ -124,7 +149,10 @@ const UserSettings = () => {
const isSubmitting = fetcher.state === 'submitting'
const tabs = getTabs(t)
- const activeTabLabel = useMemo(() => _find(tabs, (tab) => tab.id === activeTab)?.label, [tabs, activeTab])
+ const activeTabLabel = useMemo(
+ () => _find(tabs, (tab) => tab.id === activeTab)?.label,
+ [tabs, activeTab],
+ )
useEffect(() => {
if (fetcher.state !== 'idle' || !fetcher.data) return
@@ -166,11 +194,17 @@ const UserSettings = () => {
}
} else if (fetcher.data?.error) {
if (pendingToggles.current.has('live-visitors')) {
- mergeUser({ showLiveVisitorsInTitle: pendingToggles.current.get('live-visitors') })
+ mergeUser({
+ showLiveVisitorsInTitle: pendingToggles.current.get('live-visitors'),
+ })
pendingToggles.current.delete('live-visitors')
}
if (pendingToggles.current.has('login-notifications')) {
- mergeUser({ receiveLoginNotifications: pendingToggles.current.get('login-notifications') })
+ mergeUser({
+ receiveLoginNotifications: pendingToggles.current.get(
+ 'login-notifications',
+ ),
+ })
pendingToggles.current.delete('login-notifications')
}
toast.error(fetcher.data.error)
@@ -219,17 +253,25 @@ const UserSettings = () => {
if (form.email) formData.set('email', form.email)
if (form.password) formData.set('password', form.password)
if (form.repeat) formData.set('repeat', form.repeat)
- if (additionalData?.timezone) formData.set('timezone', additionalData.timezone as string)
+ if (additionalData?.timezone)
+ formData.set('timezone', additionalData.timezone as string)
if (additionalData?.timeFormat || form.timeFormat) {
- formData.set('timeFormat', (additionalData?.timeFormat || form.timeFormat) as string)
+ formData.set(
+ 'timeFormat',
+ (additionalData?.timeFormat || form.timeFormat) as string,
+ )
}
- if (additionalData?.reportFrequency) formData.set('reportFrequency', additionalData.reportFrequency as string)
+ if (additionalData?.reportFrequency)
+ formData.set('reportFrequency', additionalData.reportFrequency as string)
passwordChangedRef.current = !!form.password
fetcher.submit(formData, { method: 'post' })
}
- const handleSubmit = (e: React.FormEvent<HTMLFormElement> | null, force?: boolean) => {
+ const handleSubmit = (
+ e: React.FormEvent<HTMLFormElement> | null,
+ force?: boolean,
+ ) => {
if (e) {
e.preventDefault()
e.stopPropagation()
@@ -254,7 +296,10 @@ const UserSettings = () => {
const handleShowLiveVisitorsSave = (checked: boolean) => {
if (pendingToggles.current.has('live-visitors')) return
- pendingToggles.current.set('live-visitors', user?.showLiveVisitorsInTitle ?? false)
+ pendingToggles.current.set(
+ 'live-visitors',
+ user?.showLiveVisitorsInTitle ?? false,
+ )
const formData = new FormData()
formData.set('intent', 'toggle-live-visitors')
formData.set('show', checked.toString())
@@ -266,7 +311,10 @@ const UserSettings = () => {
const handleReceiveLoginNotifications = (checked: boolean) => {
if (pendingToggles.current.has('login-notifications')) return
- pendingToggles.current.set('login-notifications', user?.receiveLoginNotifications ?? false)
+ pendingToggles.current.set(
+ 'login-notifications',
+ user?.receiveLoginNotifications ?? false,
+ )
const formData = new FormData()
formData.set('intent', 'toggle-login-notifications')
formData.set('receiveLoginNotifications', checked.toString())
@@ -275,7 +323,10 @@ const UserSettings = () => {
mergeUser({ receiveLoginNotifications: checked })
}
- const handleIntegrationSave = (data: Record<string, unknown>, callback: (isSuccess: boolean) => void = () => {}) => {
+ const handleIntegrationSave = (
+ data: Record<string, unknown>,
+ callback: (isSuccess: boolean) => void = () => {},
+ ) => {
setBeenSubmitted(true)
if (validated) {
@@ -384,7 +435,10 @@ const UserSettings = () => {
return (
<div className='flex min-h-min-footer flex-col bg-gray-50 dark:bg-slate-900'>
- <form className='mx-auto w-full max-w-7xl px-4 py-6 sm:px-6 lg:px-8' onSubmit={handleSubmit}>
+ <form
+ className='mx-auto w-full max-w-7xl px-4 py-6 sm:px-6 lg:px-8'
+ onSubmit={handleSubmit}
+ >
<Text as='h2' size='3xl' weight='bold' className='mt-2'>
{t('titles.profileSettings')}
</Text>
@@ -422,7 +476,8 @@ const UserSettings = () => {
className={cx(
'group flex items-center rounded-md px-3 py-2 text-left text-sm text-gray-900 transition-colors',
{
- 'bg-gray-200 font-semibold dark:bg-slate-800 dark:text-gray-50': isCurrent,
+ 'bg-gray-200 font-semibold dark:bg-slate-800 dark:text-gray-50':
+ isCurrent,
'hover:bg-gray-200 dark:text-gray-200 dark:hover:bg-slate-800 dark:hover:text-gray-50':
!isCurrent,
},
@@ -473,7 +528,9 @@ const UserSettings = () => {
name='password'
type='password'
label={t('auth.common.password')}
- hint={t('auth.common.hint', { amount: MIN_PASSWORD_CHARS })}
+ hint={t('auth.common.hint', {
+ amount: MIN_PASSWORD_CHARS,
+ })}
value={form.password}
placeholder={t('auth.common.password')}
className='sm:col-span-3'
@@ -522,11 +579,21 @@ const UserSettings = () => {
</p>
)}
{user?.apiKey ? (
- <Button className='mt-4' onClick={() => setShowAPIDeleteModal(true)} danger large>
+ <Button
+ className='mt-4'
+ onClick={() => setShowAPIDeleteModal(true)}
+ danger
+ large
+ >
{t('profileSettings.deleteApiKeyBtn')}
</Button>
) : (
- <Button className='mt-4' onClick={onApiKeyGenerate} primary large>
+ <Button
+ className='mt-4'
+ onClick={onApiKeyGenerate}
+ primary
+ large
+ >
{t('profileSettings.addApiKeyBtn')}
</Button>
)}
@@ -573,7 +640,9 @@ const UserSettings = () => {
scope='col'
className='px-4 py-3 text-left text-xs font-bold tracking-wider text-gray-900 uppercase dark:text-white'
>
- {t('profileSettings.organisationsTable.organisation')}
+ {t(
+ 'profileSettings.organisationsTable.organisation',
+ )}
</th>
<th
scope='col'
@@ -585,15 +654,23 @@ const UserSettings = () => {
scope='col'
className='px-4 py-3 text-left text-xs font-bold tracking-wider text-gray-900 uppercase dark:text-white'
>
- {t('profileSettings.organisationsTable.joinedOn')}
+ {t(
+ 'profileSettings.organisationsTable.joinedOn',
+ )}
</th>
<th scope='col' />
</tr>
</thead>
<tbody className='divide-y divide-gray-200 bg-white dark:divide-slate-700 dark:bg-slate-900'>
- {_map(user?.organisationMemberships, (membership) => (
- <Organisations key={membership.id} membership={membership} />
- ))}
+ {_map(
+ user?.organisationMemberships,
+ (membership) => (
+ <Organisations
+ key={membership.id}
+ membership={membership}
+ />
+ ),
+ )}
</tbody>
</table>
</div>
@@ -628,7 +705,11 @@ const UserSettings = () => {
{t('profileSettings.logoutAll')}
</>
</Button>
- <Button onClick={() => setShowModal(true)} semiSmall semiDanger>
+ <Button
+ onClick={() => setShowModal(true)}
+ semiSmall
+ semiDanger
+ >
<>
<ExclamationTriangleIcon className='mr-1 h-5 w-5' />
{t('profileSettings.delete')}
@@ -648,7 +729,12 @@ const UserSettings = () => {
<TimezonePicker value={timezone} onChange={setTimezone} />
</div>
</div>
- <Button className='mt-4' onClick={handleTimezoneSave} primary large>
+ <Button
+ className='mt-4'
+ onClick={handleTimezoneSave}
+ primary
+ large
+ >
{t('common.save')}
</Button>
{/* Timeformat selector (12 / 24 hour format) */}
@@ -666,17 +752,33 @@ const UserSettings = () => {
onSelect={(f) =>
setForm((prev) => ({
...prev,
- timeFormat: timeFormatArray[_findIndex(translatedTimeFormat, (freq) => freq === f)],
+ timeFormat:
+ timeFormatArray[
+ _findIndex(
+ translatedTimeFormat,
+ (freq) => freq === f,
+ )
+ ],
}))
}
capitalise
selectedItem={
- translatedTimeFormat[_findIndex(timeFormatArray, (freq) => freq === form.timeFormat)]
+ translatedTimeFormat[
+ _findIndex(
+ timeFormatArray,
+ (freq) => freq === form.timeFormat,
+ )
+ ]
}
/>
</div>
</div>
- <Button className='mt-4' onClick={setAsyncTimeFormat} primary large>
+ <Button
+ className='mt-4'
+ onClick={setAsyncTimeFormat}
+ primary
+ large
+ >
{t('common.save')}
</Button>
@@ -688,7 +790,9 @@ const UserSettings = () => {
<Checkbox
checked={user?.showLiveVisitorsInTitle}
onChange={handleShowLiveVisitorsSave}
- disabled={fetcher.formData?.get('intent') === 'toggle-live-visitors'}
+ disabled={
+ fetcher.formData?.get('intent') === 'toggle-live-visitors'
+ }
name='active'
classes={{
label: 'mt-4',
@@ -701,7 +805,9 @@ const UserSettings = () => {
{activeTab === TAB_MAPPING.COMMUNICATIONS && !isSelfhosted ? (
<>
{/* Email reports frequency selector (e.g. monthly, weekly, etc.) */}
- <h3 className='text-lg font-bold text-gray-900 dark:text-gray-50'>{t('profileSettings.email')}</h3>
+ <h3 className='text-lg font-bold text-gray-900 dark:text-gray-50'>
+ {t('profileSettings.email')}
+ </h3>
<div className='mt-4 grid grid-cols-1 gap-x-4 gap-y-6 lg:grid-cols-2'>
<div>
<Select
@@ -710,16 +816,33 @@ const UserSettings = () => {
className='w-full'
items={translatedFrequencies}
onSelect={(f) =>
- setReportFrequency(reportFrequencies[_findIndex(translatedFrequencies, (freq) => freq === f)])
+ setReportFrequency(
+ reportFrequencies[
+ _findIndex(
+ translatedFrequencies,
+ (freq) => freq === f,
+ )
+ ],
+ )
}
capitalise
selectedItem={
- translatedFrequencies[_findIndex(reportFrequencies, (freq) => freq === reportFrequency)]
+ translatedFrequencies[
+ _findIndex(
+ reportFrequencies,
+ (freq) => freq === reportFrequency,
+ )
+ ]
}
/>
</div>
</div>
- <Button className='mt-4' onClick={handleReportSave} primary large>
+ <Button
+ className='mt-4'
+ onClick={handleReportSave}
+ primary
+ large
+ >
{t('common.save')}
</Button>
@@ -736,7 +859,10 @@ const UserSettings = () => {
<Checkbox
checked={user?.receiveLoginNotifications}
onChange={handleReceiveLoginNotifications}
- disabled={fetcher.formData?.get('intent') === 'toggle-login-notifications'}
+ disabled={
+ fetcher.formData?.get('intent') ===
+ 'toggle-login-notifications'
+ }
name='receiveLoginNotifications'
classes={{
label: 'mt-4',
@@ -750,7 +876,10 @@ const UserSettings = () => {
</div>
</form>
- <PaidFeature isOpened={isPaidFeatureOpened} onClose={() => setIsPaidFeatureOpened(false)} />
+ <PaidFeature
+ isOpened={isPaidFeatureOpened}
+ onClose={() => setIsPaidFeatureOpened(false)}
+ />
<Modal
onClose={() => {
setDeletionFeedback('')
diff --git a/web/app/pages/UserSettings/components/Integrations.tsx b/web/app/pages/UserSettings/components/Integrations.tsx
index 967b53401..439337f1e 100644
--- a/web/app/pages/UserSettings/components/Integrations.tsx
+++ b/web/app/pages/UserSettings/components/Integrations.tsx
@@ -1,4 +1,8 @@
-import { CheckCircleIcon, XCircleIcon, ClockIcon } from '@heroicons/react/24/solid'
+import {
+ CheckCircleIcon,
+ XCircleIcon,
+ ClockIcon,
+} from '@heroicons/react/24/solid'
import type i18next from 'i18next'
import _map from 'lodash/map'
import React, { useState, memo, useEffect } from 'react'
@@ -49,10 +53,14 @@ const TG_BOT_URL = 'https://t.me/swetrixbot'
const TG_BOT_USERNAME = '@swetrixbot'
const SLACK_WEBHOOKS_HELP = 'https://api.slack.com/messaging/webhooks'
-const DISCORD_WEBHOOKS_HELP = 'https://support.discord.com/hc/en-us/articles/228383668-Intro-to-Webhooks'
+const DISCORD_WEBHOOKS_HELP =
+ 'https://support.discord.com/hc/en-us/articles/228383668-Intro-to-Webhooks'
interface IntegrationsProps {
- handleIntegrationSave: (data: Partial<User>, cb: (isSuccess: boolean) => void) => void
+ handleIntegrationSave: (
+ data: Partial<User>,
+ cb: (isSuccess: boolean) => void,
+ ) => void
}
interface IntegrationStatus {
@@ -66,7 +74,9 @@ const Integrations = ({ handleIntegrationSave }: IntegrationsProps) => {
const { t } = useTranslation('common')
const available = getAvailableIntegrations(t)
- const [integrationConfigurating, setIntegrationConfigurating] = useState<string | null>(null)
+ const [integrationConfigurating, setIntegrationConfigurating] = useState<
+ string | null
+ >(null)
const [integrationInput, setIntegrationInput] = useState<string | null>(null)
const [isIntegrationLoading, setIsIntegrationLoading] = useState(false)
const [isRemovalLoading, setIsRemovalLoading] = useState(false)
@@ -194,7 +204,10 @@ const Integrations = ({ handleIntegrationSave }: IntegrationsProps) => {
return
}
- fetcher.submit({ intent: 'remove-tg-integration', tgID: user.telegramChatId }, { method: 'POST' })
+ fetcher.submit(
+ { intent: 'remove-tg-integration', tgID: user.telegramChatId },
+ { method: 'POST' },
+ )
return
}
@@ -406,7 +419,9 @@ const Integrations = ({ handleIntegrationSave }: IntegrationsProps) => {
return (
<>
- <p className='max-w-prose text-base text-gray-900 dark:text-gray-50'>{t('profileSettings.integrationsDesc')}</p>
+ <p className='max-w-prose text-base text-gray-900 dark:text-gray-50'>
+ {t('profileSettings.integrationsDesc')}
+ </p>
<div className='mt-2 overflow-hidden rounded-lg border border-gray-200 bg-white dark:border-slate-700 dark:bg-slate-900'>
<table className='min-w-full divide-y divide-gray-200 dark:divide-slate-700'>
<thead className='bg-gray-50 dark:bg-slate-800'>
@@ -435,10 +450,17 @@ const Integrations = ({ handleIntegrationSave }: IntegrationsProps) => {
<tbody className='divide-y divide-gray-200 bg-white dark:divide-slate-700 dark:bg-slate-900'>
{_map(available, ({ name, key, description, Icon }) => {
const { connected, confirmed, id } = getIntegrationStatus(key)
- const status = connected ? (confirmed ? 'connected' : 'pending') : 'notConnected'
+ const status = connected
+ ? confirmed
+ ? 'connected'
+ : 'pending'
+ : 'notConnected'
return (
- <tr key={key} className='hover:bg-gray-50 dark:hover:bg-slate-800/50'>
+ <tr
+ key={key}
+ className='hover:bg-gray-50 dark:hover:bg-slate-800/50'
+ >
<td className='px-4 py-3 text-sm text-gray-900 dark:text-gray-100'>
<div className='flex items-center gap-2'>
<div className='hidden shrink-0 sm:block'>
@@ -467,13 +489,22 @@ const Integrations = ({ handleIntegrationSave }: IntegrationsProps) => {
<td className='px-4 py-3 text-sm text-gray-700 dark:text-gray-300'>
<div className='flex items-center'>
{status === 'notConnected' ? (
- <XCircleIcon className='mr-1.5 h-5 w-5 shrink-0 text-red-400' aria-hidden='true' />
+ <XCircleIcon
+ className='mr-1.5 h-5 w-5 shrink-0 text-red-400'
+ aria-hidden='true'
+ />
) : null}
{status === 'pending' ? (
- <ClockIcon className='mr-1.5 h-5 w-5 shrink-0 text-yellow-400' aria-hidden='true' />
+ <ClockIcon
+ className='mr-1.5 h-5 w-5 shrink-0 text-yellow-400'
+ aria-hidden='true'
+ />
) : null}
{status === 'connected' ? (
- <CheckCircleIcon className='mr-1.5 h-5 w-5 shrink-0 text-green-400' aria-hidden='true' />
+ <CheckCircleIcon
+ className='mr-1.5 h-5 w-5 shrink-0 text-green-400'
+ aria-hidden='true'
+ />
) : null}
{t(`common.${status}`)}
</div>
@@ -481,7 +512,11 @@ const Integrations = ({ handleIntegrationSave }: IntegrationsProps) => {
<td className='px-4 py-3 text-right text-sm whitespace-nowrap'>
<div className='flex items-center justify-end gap-2'>
{connected ? (
- <Button onClick={() => removeIntegration(key)} small danger>
+ <Button
+ onClick={() => removeIntegration(key)}
+ small
+ danger
+ >
{t('profileSettings.removeIntegration')}
</Button>
) : (
diff --git a/web/app/pages/UserSettings/components/Organisations.tsx b/web/app/pages/UserSettings/components/Organisations.tsx
index 4f2ef0b47..b6b5a8543 100644
--- a/web/app/pages/UserSettings/components/Organisations.tsx
+++ b/web/app/pages/UserSettings/components/Organisations.tsx
@@ -48,12 +48,15 @@ const Organisations = ({ membership }: OrganisationsProps) => {
if (fetcher.data?.intent === 'accept-organisation-invitation') {
if (fetcher.data.success) {
mergeUser({
- organisationMemberships: _map(user?.organisationMemberships, (item) => {
- if (item.id === membership.id) {
- return { ...item, confirmed: true }
- }
- return item
- }),
+ organisationMemberships: _map(
+ user?.organisationMemberships,
+ (item) => {
+ if (item.id === membership.id) {
+ return { ...item, confirmed: true }
+ }
+ return item
+ },
+ ),
})
toast.success(t('apiNotifications.acceptInvitation'))
} else if (fetcher.data.error) {
@@ -63,16 +66,24 @@ const Organisations = ({ membership }: OrganisationsProps) => {
}, [fetcher.data, mergeUser, membership.id, t, user?.organisationMemberships])
const onQuit = () => {
- fetcher.submit({ intent: 'reject-organisation-invitation', membershipId: membership.id }, { method: 'POST' })
+ fetcher.submit(
+ { intent: 'reject-organisation-invitation', membershipId: membership.id },
+ { method: 'POST' },
+ )
}
const onAccept = () => {
- fetcher.submit({ intent: 'accept-organisation-invitation', membershipId: membership.id }, { method: 'POST' })
+ fetcher.submit(
+ { intent: 'accept-organisation-invitation', membershipId: membership.id },
+ { method: 'POST' },
+ )
}
return (
<tr className='bg-white hover:bg-gray-50 dark:bg-slate-900 dark:hover:bg-slate-800/50'>
- <td className='px-4 py-3 text-sm whitespace-nowrap text-gray-900 dark:text-gray-100'>{organisation.name}</td>
+ <td className='px-4 py-3 text-sm whitespace-nowrap text-gray-900 dark:text-gray-100'>
+ {organisation.name}
+ </td>
<td className='px-4 py-3 text-sm whitespace-nowrap text-gray-900 dark:text-gray-100'>
{t(`organisations.role.${role}.name`)}
</td>
@@ -92,7 +103,12 @@ const Organisations = ({ membership }: OrganisationsProps) => {
</Button>
) : (
<>
- <Button className='mr-2' onClick={() => setShowDeleteModal(true)} primary small>
+ <Button
+ className='mr-2'
+ onClick={() => setShowDeleteModal(true)}
+ primary
+ small
+ >
{t('common.reject')}
</Button>
<Button onClick={onAccept} loading={isLoading} primary small>
diff --git a/web/app/pages/UserSettings/components/ProjectList.tsx b/web/app/pages/UserSettings/components/ProjectList.tsx
index 784165033..5a0445d0c 100644
--- a/web/app/pages/UserSettings/components/ProjectList.tsx
+++ b/web/app/pages/UserSettings/components/ProjectList.tsx
@@ -33,7 +33,10 @@ const ProjectList = ({ item }: ProjectListProps) => {
if (fetcher.data?.intent === 'reject-project-share') {
if (fetcher.data.success) {
mergeUser({
- sharedProjects: _filter(user?.sharedProjects, (share) => share.id !== item.id),
+ sharedProjects: _filter(
+ user?.sharedProjects,
+ (share) => share.id !== item.id,
+ ),
})
toast.success(t('apiNotifications.quitProject'))
} else if (fetcher.data.error) {
@@ -59,16 +62,24 @@ const ProjectList = ({ item }: ProjectListProps) => {
}, [fetcher.data, id, item.id, mergeUser, t, user?.sharedProjects])
const onQuit = () => {
- fetcher.submit({ intent: 'reject-project-share', shareId: item.id }, { method: 'post', action: '/user-settings' })
+ fetcher.submit(
+ { intent: 'reject-project-share', shareId: item.id },
+ { method: 'post', action: '/user-settings' },
+ )
}
const onAccept = () => {
- fetcher.submit({ intent: 'accept-project-share', shareId: id }, { method: 'post', action: '/user-settings' })
+ fetcher.submit(
+ { intent: 'accept-project-share', shareId: id },
+ { method: 'post', action: '/user-settings' },
+ )
}
return (
<tr className='bg-white hover:bg-gray-50 dark:bg-slate-900 dark:hover:bg-slate-800/50'>
- <td className='px-4 py-3 text-sm whitespace-nowrap text-gray-900 dark:text-gray-100'>{project.name}</td>
+ <td className='px-4 py-3 text-sm whitespace-nowrap text-gray-900 dark:text-gray-100'>
+ {project.name}
+ </td>
<td className='px-4 py-3 text-sm whitespace-nowrap text-gray-900 dark:text-gray-100'>
{t(`project.settings.roles.${role}.name`)}
</td>
@@ -79,12 +90,23 @@ const ProjectList = ({ item }: ProjectListProps) => {
</td>
<td className='px-4 py-3 text-right text-sm whitespace-nowrap'>
{confirmed ? (
- <Button onClick={() => setShowDeleteModal(true)} danger small loading={isPending}>
+ <Button
+ onClick={() => setShowDeleteModal(true)}
+ danger
+ small
+ loading={isPending}
+ >
{t('common.quit')}
</Button>
) : (
<>
- <Button className='mr-2' onClick={() => setShowDeleteModal(true)} primary small loading={isPending}>
+ <Button
+ className='mr-2'
+ onClick={() => setShowDeleteModal(true)}
+ primary
+ small
+ loading={isPending}
+ >
{t('common.reject')}
</Button>
<Button onClick={onAccept} primary small loading={isPending}>
diff --git a/web/app/pages/UserSettings/components/Socialisations.tsx b/web/app/pages/UserSettings/components/Socialisations.tsx
index a6070668d..43c0e6a87 100644
--- a/web/app/pages/UserSettings/components/Socialisations.tsx
+++ b/web/app/pages/UserSettings/components/Socialisations.tsx
@@ -92,7 +92,11 @@ const Socialisations = () => {
}
try {
- const { uuid, auth_url: authUrl, expires_in: expiresIn } = await generateSSOAuthURL(provider)
+ const {
+ uuid,
+ auth_url: authUrl,
+ expires_in: expiresIn,
+ } = await generateSSOAuthURL(provider)
const safeAuthUrl = (() => {
try {
@@ -101,8 +105,16 @@ const Socialisations = () => {
// Only allow expected OAuth endpoints here (no OIDC option in this UI today, but keep it future-proof).
if (parsed.protocol !== 'https:') return null
- if (provider === SSO_PROVIDERS.GOOGLE && parsed.hostname !== 'accounts.google.com') return null
- if (provider === SSO_PROVIDERS.GITHUB && parsed.hostname !== 'github.com') return null
+ if (
+ provider === SSO_PROVIDERS.GOOGLE &&
+ parsed.hostname !== 'accounts.google.com'
+ )
+ return null
+ if (
+ provider === SSO_PROVIDERS.GITHUB &&
+ parsed.hostname !== 'github.com'
+ )
+ return null
return parsed.toString()
} catch {
@@ -145,7 +157,11 @@ const Socialisations = () => {
}
}
} catch (reason) {
- toast.error(typeof reason === 'string' ? reason : t('apiNotifications.socialisationGenericError'))
+ toast.error(
+ typeof reason === 'string'
+ ? reason
+ : t('apiNotifications.socialisationGenericError'),
+ )
setIsLoading(false)
return
}
@@ -157,7 +173,9 @@ const Socialisations = () => {
return (
<>
- <p className='max-w-prose text-base text-gray-900 dark:text-gray-50'>{t('profileSettings.socialisationsDesc')}</p>
+ <p className='max-w-prose text-base text-gray-900 dark:text-gray-50'>
+ {t('profileSettings.socialisationsDesc')}
+ </p>
<div className='mt-2 overflow-hidden rounded-lg border border-gray-200 bg-white dark:border-slate-700 dark:bg-slate-900'>
<table className='min-w-full divide-y divide-gray-200 dark:divide-slate-700'>
<thead className='bg-gray-50 dark:bg-slate-800'>
@@ -184,7 +202,10 @@ const Socialisations = () => {
const status = connected ? 'connected' : 'notConnected'
return (
- <tr key={key} className='hover:bg-gray-50 dark:hover:bg-slate-800/50'>
+ <tr
+ key={key}
+ className='hover:bg-gray-50 dark:hover:bg-slate-800/50'
+ >
<td className='px-4 py-3 text-sm text-gray-900 dark:text-gray-100'>
<div className='flex items-center gap-3'>
<div className='hidden shrink-0 sm:block'>
@@ -200,10 +221,16 @@ const Socialisations = () => {
<td className='px-4 py-3 text-sm text-gray-700 dark:text-gray-300'>
<div className='flex items-center'>
{status === 'notConnected' ? (
- <XCircleIcon className='mr-1.5 h-5 w-5 shrink-0 text-red-400' aria-hidden='true' />
+ <XCircleIcon
+ className='mr-1.5 h-5 w-5 shrink-0 text-red-400'
+ aria-hidden='true'
+ />
) : null}
{status === 'connected' ? (
- <CheckCircleIcon className='mr-1.5 h-5 w-5 shrink-0 text-green-400' aria-hidden='true' />
+ <CheckCircleIcon
+ className='mr-1.5 h-5 w-5 shrink-0 text-green-400'
+ aria-hidden='true'
+ />
) : null}
{t(`common.${status}`)}
</div>
@@ -211,19 +238,37 @@ const Socialisations = () => {
<td className='px-4 py-3 text-right text-sm whitespace-nowrap'>
<div className='flex items-center justify-end gap-2'>
{connected && !unlinkable ? (
- <Button onClick={() => toast.error(t('profileSettings.cantUnlinkSocialisation'))} small danger>
+ <Button
+ onClick={() =>
+ toast.error(
+ t('profileSettings.cantUnlinkSocialisation'),
+ )
+ }
+ small
+ danger
+ >
{t('common.unlink')}
</Button>
) : null}
{connected && unlinkable ? (
- <Button onClick={() => onUnlinkSSO(key)} loading={isUnlinking} small danger>
+ <Button
+ onClick={() => onUnlinkSSO(key)}
+ loading={isUnlinking}
+ small
+ danger
+ >
{t('common.unlink')}
</Button>
) : null}
{!connected ? (
- <Button onClick={() => linkSSO(key)} loading={isLoading} small primary>
+ <Button
+ onClick={() => linkSSO(key)}
+ loading={isLoading}
+ small
+ primary
+ >
{t('common.link')}
</Button>
) : null}
diff --git a/web/app/pages/UserSettings/components/TwoFA.tsx b/web/app/pages/UserSettings/components/TwoFA.tsx
index b91e05f22..e28e308f2 100644
--- a/web/app/pages/UserSettings/components/TwoFA.tsx
+++ b/web/app/pages/UserSettings/components/TwoFA.tsx
@@ -27,7 +27,8 @@ const TwoFA = () => {
const [twoFARecovery, setTwoFARecovery] = useState<string | null>(null)
const { isTwoFactorAuthenticationEnabled } = user || {}
- const isLoading = fetcher.state === 'submitting' || fetcher.state === 'loading'
+ const isLoading =
+ fetcher.state === 'submitting' || fetcher.state === 'loading'
// Handle fetcher responses
useEffect(() => {
@@ -37,7 +38,10 @@ const TwoFA = () => {
if (intent === 'generate-2fa' && twoFAData) {
setTimeout(() => {
setTwoFAConfigurating(true)
- setTwoFAConfigData({ secret: twoFAData.secret, otpauthUrl: twoFAData.otpauthUrl })
+ setTwoFAConfigData({
+ secret: twoFAData.secret,
+ otpauthUrl: twoFAData.otpauthUrl,
+ })
}, 0)
} else if (intent === 'enable-2fa' && twoFAData?.twoFactorRecoveryCode) {
mergeUser({ isTwoFactorAuthenticationEnabled: true })
@@ -117,7 +121,9 @@ const TwoFA = () => {
if (twoFARecovery) {
return (
<div className='max-w-prose'>
- <p className='text-base text-gray-900 dark:text-gray-50'>{t('profileSettings.2faRecoveryNote')}</p>
+ <p className='text-base text-gray-900 dark:text-gray-50'>
+ {t('profileSettings.2faRecoveryNote')}
+ </p>
<Input className='mt-4' value={twoFARecovery} />
<Button onClick={recoverySaved} primary large>
{t('profileSettings.2faRecoverySaved')}
@@ -130,7 +136,9 @@ const TwoFA = () => {
if (twoFADisabling) {
return (
<>
- <p className='max-w-prose text-base text-gray-900 dark:text-gray-50'>{t('profileSettings.2faDisableHint')}</p>
+ <p className='max-w-prose text-base text-gray-900 dark:text-gray-50'>
+ {t('profileSettings.2faDisableHint')}
+ </p>
<div className='mt-4 flex items-center'>
<Input
label={t('profileSettings.enter2faToDisable')}
@@ -161,8 +169,15 @@ const TwoFA = () => {
return (
<>
- <p className='max-w-prose text-base text-gray-900 dark:text-gray-50'>{t('profileSettings.2faEnabled')}</p>
- <Button className='mt-4' onClick={() => setTwoFADisabling(true)} danger large>
+ <p className='max-w-prose text-base text-gray-900 dark:text-gray-50'>
+ {t('profileSettings.2faEnabled')}
+ </p>
+ <Button
+ className='mt-4'
+ onClick={() => setTwoFADisabling(true)}
+ danger
+ large
+ >
{t('profileSettings.2faDisableBtn')}
</Button>
</>
@@ -172,12 +187,16 @@ const TwoFA = () => {
if (twoFAConfigurating) {
return (
<>
- <p className='max-w-prose text-base text-gray-900 dark:text-gray-50'>{t('profileSettings.2faDesc')}</p>
+ <p className='max-w-prose text-base text-gray-900 dark:text-gray-50'>
+ {t('profileSettings.2faDesc')}
+ </p>
<div className='mt-4 w-max bg-white p-4'>
<QRCode value={twoFAConfigData?.otpauthUrl || ''} />
</div>
<p className='mt-2 text-base whitespace-pre-line text-gray-900 dark:text-gray-50'>
- {t('profileSettings.2faQRAlt', { key: twoFAConfigData?.secret || '' })}
+ {t('profileSettings.2faQRAlt', {
+ key: twoFAConfigData?.secret || '',
+ })}
</p>
<div className='mt-4 flex items-center'>
<Input
@@ -209,8 +228,16 @@ const TwoFA = () => {
return (
<>
- <p className='max-w-prose text-base text-gray-900 dark:text-gray-50'>{t('profileSettings.2faEnable')}</p>
- <Button className='mt-4' onClick={_generate2FA} loading={isLoading} primary large>
+ <p className='max-w-prose text-base text-gray-900 dark:text-gray-50'>
+ {t('profileSettings.2faEnable')}
+ </p>
+ <Button
+ className='mt-4'
+ onClick={_generate2FA}
+ loading={isLoading}
+ primary
+ large
+ >
{t('profileSettings.2faEnableBtn')}
</Button>
</>
diff --git a/web/app/providers/AuthProvider.tsx b/web/app/providers/AuthProvider.tsx
index c82e5c4ff..af7ef35e7 100644
--- a/web/app/providers/AuthProvider.tsx
+++ b/web/app/providers/AuthProvider.tsx
@@ -1,4 +1,11 @@
-import { createContext, useCallback, useContext, useEffect, useRef, useState } from 'react'
+import {
+ createContext,
+ useCallback,
+ useContext,
+ useEffect,
+ useRef,
+ useState,
+} from 'react'
import { useAuthProxy } from '~/hooks/useAuthProxy'
import { User } from '~/lib/models/User'
@@ -34,10 +41,14 @@ export const AuthProvider = ({
}: AuthProviderProps) => {
const { authMe } = useAuthProxy()
- const [isAuthenticated, setIsAuthenticated] = useState(initialIsAuthenticated || !!initialUser)
+ const [isAuthenticated, setIsAuthenticated] = useState(
+ initialIsAuthenticated || !!initialUser,
+ )
const [user, setUserState] = useState<User | null>(initialUser || null)
// TODO: @deprecated
- const [totalMonthlyEvents, setTotalMonthlyEvents] = useState(initialTotalMonthlyEvents || 0)
+ const [totalMonthlyEvents, setTotalMonthlyEvents] = useState(
+ initialTotalMonthlyEvents || 0,
+ )
// Track whether this is the initial mount
const isInitialMount = useRef(true)
@@ -72,7 +83,9 @@ export const AuthProvider = ({
clearLocalStorageOnLogout()
// Navigate to server-side logout route which handles cookie cleanup
- const logoutUrl = invalidateAllSessions ? '/logout?logoutAll=true' : '/logout'
+ const logoutUrl = invalidateAllSessions
+ ? '/logout?logoutAll=true'
+ : '/logout'
window.location.href = logoutUrl
}, [])
diff --git a/web/app/providers/CurrentProjectProvider.tsx b/web/app/providers/CurrentProjectProvider.tsx
index 10d9a28ad..bf8d31cb2 100644
--- a/web/app/providers/CurrentProjectProvider.tsx
+++ b/web/app/providers/CurrentProjectProvider.tsx
@@ -1,16 +1,41 @@
-import { createContext, useCallback, useContext, useEffect, useMemo, useRef, useState } from 'react'
+import {
+ createContext,
+ useCallback,
+ useContext,
+ useEffect,
+ useMemo,
+ useRef,
+ useState,
+} from 'react'
import { useTranslation } from 'react-i18next'
-import { useNavigate, useSearchParams, useFetcher, useLoaderData } from 'react-router'
+import {
+ useNavigate,
+ useSearchParams,
+ useFetcher,
+ useLoaderData,
+} from 'react-router'
import { toast } from 'sonner'
import { useLiveVisitorsProxy } from '~/hooks/useAnalyticsProxy'
-import { LIVE_VISITORS_UPDATE_INTERVAL, LS_PROJECTS_PROTECTED_KEY, Period, TimeBucket } from '~/lib/constants'
+import {
+ LIVE_VISITORS_UPDATE_INTERVAL,
+ LS_PROJECTS_PROTECTED_KEY,
+ Period,
+ TimeBucket,
+} from '~/lib/constants'
import { type Project } from '~/lib/models/Project'
-import type { ProjectLoaderData, ProjectViewActionData } from '~/routes/projects.$id'
+import type {
+ ProjectLoaderData,
+ ProjectViewActionData,
+} from '~/routes/projects.$id'
import { getItemJSON } from '~/utils/localstorage'
import routes from '~/utils/routes'
-import { getProjectPreferences, setProjectPassword, setProjectPreferences } from '../pages/Project/View/utils/cache'
+import {
+ getProjectPreferences,
+ setProjectPassword,
+ setProjectPreferences,
+} from '../pages/Project/View/utils/cache'
import { CHART_METRICS_MAPPING } from '../pages/Project/View/ViewProject.helpers'
interface CurrentProjectContextType {
@@ -23,10 +48,14 @@ interface CurrentProjectContextType {
liveVisitors: number
updateLiveVisitors: () => Promise<void>
isPasswordRequired: boolean
- submitPassword: (password: string) => Promise<{ success: boolean; error?: string }>
+ submitPassword: (
+ password: string,
+ ) => Promise<{ success: boolean; error?: string }>
}
-const CurrentProjectContext = createContext<CurrentProjectContextType | undefined>(undefined)
+const CurrentProjectContext = createContext<
+ CurrentProjectContextType | undefined
+>(undefined)
interface CurrentProjectProviderProps {
id: string
@@ -37,7 +66,10 @@ export const useProjectPassword = (id?: string) => {
const [searchParams] = useSearchParams()
const projectPassword = useMemo(
- () => searchParams.get('password') || getItemJSON(LS_PROJECTS_PROTECTED_KEY)?.[id || ''] || '',
+ () =>
+ searchParams.get('password') ||
+ getItemJSON(LS_PROJECTS_PROTECTED_KEY)?.[id || ''] ||
+ '',
[id, searchParams],
)
@@ -51,17 +83,27 @@ const useProject = (id: string) => {
const storedPassword = useProjectPassword(id)
// Use loader data only for initial state (SSR hydration)
- const [project, setProject] = useState<Project | null>(() => loaderData?.project || null)
- const [isPasswordRequired, setIsPasswordRequired] = useState(() => loaderData?.isPasswordRequired || false)
+ const [project, setProject] = useState<Project | null>(
+ () => loaderData?.project || null,
+ )
+ const [isPasswordRequired, setIsPasswordRequired] = useState(
+ () => loaderData?.isPasswordRequired || false,
+ )
const passwordFetcher = useFetcher<ProjectViewActionData>()
const lastHandledFetcherData = useRef<ProjectViewActionData | null>(null)
const hasTriedStoredPassword = useRef(false)
- const passwordResolverRef = useRef<((value: { success: boolean; error?: string }) => void) | null>(null)
+ const passwordResolverRef = useRef<
+ ((value: { success: boolean; error?: string }) => void) | null
+ >(null)
const lastSubmittedPasswordRef = useRef<string | null>(null)
useEffect(() => {
- if (loaderData?.error && !loaderData.project && !loaderData.isPasswordRequired) {
+ if (
+ loaderData?.error &&
+ !loaderData.project &&
+ !loaderData.isPasswordRequired
+ ) {
console.error('[ERROR] (getProject)', loaderData.error)
toast.error(t('project.noExist'))
navigate(routes.dashboard)
@@ -112,7 +154,10 @@ const useProject = (id: string) => {
lastSubmittedPasswordRef.current = null
if (passwordResolverRef.current) {
- passwordResolverRef.current({ success: false, error: passwordFetcher.data.error })
+ passwordResolverRef.current({
+ success: false,
+ error: passwordFetcher.data.error,
+ })
passwordResolverRef.current = null
}
}
@@ -123,7 +168,10 @@ const useProject = (id: string) => {
return new Promise((resolve) => {
passwordResolverRef.current = resolve
lastSubmittedPasswordRef.current = password
- passwordFetcher.submit({ intent: 'get-project', password }, { method: 'POST', action: `/projects/${id}` })
+ passwordFetcher.submit(
+ { intent: 'get-project', password },
+ { method: 'POST', action: `/projects/${id}` },
+ )
})
},
[id, passwordFetcher],
@@ -151,7 +199,9 @@ export type ProjectPreferences = {
}
const useProjectPreferences = (id: string) => {
- const [preferences, setPreferences] = useState<ProjectPreferences>(getProjectPreferences(id) as ProjectPreferences)
+ const [preferences, setPreferences] = useState<ProjectPreferences>(
+ getProjectPreferences(id) as ProjectPreferences,
+ )
const updatePreferences = useCallback(
(prefs: ProjectPreferences) => {
@@ -207,8 +257,12 @@ const useLiveVisitors = (project: Project | null) => {
return { liveVisitors, updateLiveVisitors }
}
-export const CurrentProjectProvider = ({ children, id }: CurrentProjectProviderProps) => {
- const { project, mergeProject, isPasswordRequired, submitPassword } = useProject(id)
+export const CurrentProjectProvider = ({
+ children,
+ id,
+}: CurrentProjectProviderProps) => {
+ const { project, mergeProject, isPasswordRequired, submitPassword } =
+ useProject(id)
const { preferences, updatePreferences } = useProjectPreferences(id)
const { liveVisitors, updateLiveVisitors } = useLiveVisitors(project)
@@ -236,7 +290,9 @@ export const useCurrentProject = () => {
const context = useContext(CurrentProjectContext)
if (context === undefined) {
- throw new Error('useCurrentProject must be used within a CurrentProjectProvider')
+ throw new Error(
+ 'useCurrentProject must be used within a CurrentProjectProvider',
+ )
}
return context
diff --git a/web/app/providers/ThemeProvider.tsx b/web/app/providers/ThemeProvider.tsx
index 83febb2a1..096ec7413 100644
--- a/web/app/providers/ThemeProvider.tsx
+++ b/web/app/providers/ThemeProvider.tsx
@@ -15,7 +15,10 @@ interface ThemeProviderProps {
initialTheme: ThemeType
}
-export const ThemeProvider = ({ children, initialTheme }: ThemeProviderProps) => {
+export const ThemeProvider = ({
+ children,
+ initialTheme,
+}: ThemeProviderProps) => {
const [theme, setTheme] = useState(initialTheme)
const _setTheme = useCallback((theme: ThemeType) => {
@@ -23,7 +26,11 @@ export const ThemeProvider = ({ children, initialTheme }: ThemeProviderProps) =>
setCookie(LS_THEME_SETTING, theme, 3600 * 24 * 90)
}, [])
- return <ThemeContext.Provider value={{ theme, setTheme: _setTheme }}>{children}</ThemeContext.Provider>
+ return (
+ <ThemeContext.Provider value={{ theme, setTheme: _setTheme }}>
+ {children}
+ </ThemeContext.Provider>
+ )
}
export const useTheme = () => {
diff --git a/web/app/referrers.map.json b/web/app/referrers.map.json
index 52fc54c32..eaded6200 100644
--- a/web/app/referrers.map.json
+++ b/web/app/referrers.map.json
@@ -4,13 +4,31 @@
{ "name": "Wikipedia", "patterns": ["wikipedia.org"] },
{
"name": "Yandex",
- "patterns": ["yandex.ru", "yandex.com", "yandex.kz", "yandex.by", "ya.ru", "yandex.eu", "yandex.fr"]
+ "patterns": [
+ "yandex.ru",
+ "yandex.com",
+ "yandex.kz",
+ "yandex.by",
+ "ya.ru",
+ "yandex.eu",
+ "yandex.fr"
+ ]
},
{ "name": "GitHub", "patterns": ["github.com"] },
- { "name": "Google", "patterns": ["google.com", "doubleclick.net", "android-app://com.google.android.gm/"] },
+ {
+ "name": "Google",
+ "patterns": [
+ "google.com",
+ "doubleclick.net",
+ "android-app://com.google.android.gm/"
+ ]
+ },
{ "name": "Bing", "patterns": ["bing.com", "ntp.msn.com"] },
{ "name": "DuckDuckGo", "patterns": ["duckduckgo.com", "ddg.gg"] },
- { "name": "Reddit", "patterns": ["reddit.com", "android-app://com.reddit.frontpage/"] },
+ {
+ "name": "Reddit",
+ "patterns": ["reddit.com", "android-app://com.reddit.frontpage/"]
+ },
{ "name": "YouTube", "patterns": ["youtube.com", "youtu.be"] },
{ "name": "Stack Overflow", "patterns": ["stackoverflow.com"] },
{ "name": "Hacker News", "patterns": ["news.ycombinator.com"] },
@@ -19,7 +37,10 @@
{ "name": "Facebook", "patterns": ["facebook.com"] },
{ "name": "LinkedIn", "patterns": ["linkedin.com"] },
{ "name": "Product Hunt", "patterns": ["producthunt.com"] },
- { "name": "Microsoft Teams", "patterns": ["teams.microsoft.com", "statics.teams.cdn.office.net"] },
+ {
+ "name": "Microsoft Teams",
+ "patterns": ["teams.microsoft.com", "statics.teams.cdn.office.net"]
+ },
{ "name": "ChatGPT", "patterns": ["chatgpt.com"] },
{ "name": "Claude", "patterns": ["claude.ai"] },
{ "name": "Telegram", "patterns": ["telegram.org", "t.me"] },
diff --git a/web/app/root.tsx b/web/app/root.tsx
index 64253b9bf..adb30336a 100644
--- a/web/app/root.tsx
+++ b/web/app/root.tsx
@@ -1,10 +1,18 @@
-import { ExclamationTriangleIcon, ChevronDownIcon, ChevronUpIcon } from '@heroicons/react/24/outline'
+import {
+ ExclamationTriangleIcon,
+ ChevronDownIcon,
+ ChevronUpIcon,
+} from '@heroicons/react/24/outline'
import BillboardCss from 'billboard.js/dist/billboard.min.css?url'
import cx from 'clsx'
import _replace from 'lodash/replace'
import { useEffect, useState } from 'react'
import { useTranslation } from 'react-i18next'
-import type { LinksFunction, LoaderFunctionArgs, HeadersFunction } from 'react-router'
+import type {
+ LinksFunction,
+ LoaderFunctionArgs,
+ HeadersFunction,
+} from 'react-router'
import {
data,
redirect,
@@ -24,7 +32,13 @@ import { getAuthenticatedUser } from '~/api/api.server'
import { LocaleLinks } from '~/components/LocaleLinks'
import SelfhostedApiUrlBanner from '~/components/SelfhostedApiUrlBanner'
import { SEO } from '~/components/SEO'
-import { CONTACT_EMAIL, LS_THEME_SETTING, isSelfhosted, I18N_CACHE_BREAKER, isDevelopment } from '~/lib/constants'
+import {
+ CONTACT_EMAIL,
+ LS_THEME_SETTING,
+ isSelfhosted,
+ I18N_CACHE_BREAKER,
+ isDevelopment,
+} from '~/lib/constants'
import mainCss from '~/styles/index.css?url'
import tailwindCss from '~/styles/tailwind.css?url'
import { trackViews, trackErrors, trackError } from '~/utils/analytics'
@@ -72,7 +86,8 @@ export const headers: HeadersFunction = () => ({
'Accept-CH': 'Sec-CH-Prefers-Color-Scheme',
Vary: 'Sec-CH-Prefers-Color-Scheme, Cookie',
'Critical-CH': 'Sec-CH-Prefers-Color-Scheme',
- 'Cache-Control': 'no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0',
+ 'Cache-Control':
+ 'no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0',
Pragma: 'no-cache',
Expires: '0',
})
@@ -80,7 +95,10 @@ export const headers: HeadersFunction = () => ({
// Fix for "You made a POST request to ... but did not provide an `action`" error
// caused by bots probing endpoints that don't support POST requests.
export async function action() {
- return data(null, { status: 405, statusText: 'Method Not Allowed - non existent endpoint' })
+ return data(null, {
+ status: 405,
+ statusText: 'Method Not Allowed - non existent endpoint',
+ })
}
export function ErrorBoundary() {
@@ -115,14 +133,19 @@ export function ErrorBoundary() {
</head>
<body>
{/* Using style because for some reason min-h-screen doesn't work */}
- <div style={{ minHeight: '100vh' }} className='flex flex-col bg-gray-50 pt-16 pb-12 dark:bg-slate-900'>
+ <div
+ style={{ minHeight: '100vh' }}
+ className='flex flex-col bg-gray-50 pt-16 pb-12 dark:bg-slate-900'
+ >
<div className='mx-auto flex w-full max-w-7xl flex-grow flex-col justify-center px-4 sm:px-6 lg:px-8'>
<div className='flex shrink-0 justify-center'>
<ExclamationTriangleIcon className='h-24 w-auto text-yellow-400 dark:text-yellow-600' />
</div>
<div className='py-8'>
<div className='text-center'>
- <h1 className='text-4xl font-extrabold text-gray-900 sm:text-5xl dark:text-gray-50'>Uh-oh..</h1>
+ <h1 className='text-4xl font-extrabold text-gray-900 sm:text-5xl dark:text-gray-50'>
+ Uh-oh..
+ </h1>
<p className='mt-2 text-base font-medium text-gray-800 dark:text-gray-300'>
The app has crashed. We are sorry about that :(
<br />
@@ -254,9 +277,18 @@ const Body = () => {
const { theme } = useTheme()
return (
- <body className={cx(theme, { 'bg-gray-50': theme === 'light', 'bg-slate-900': theme === 'dark' })}>
+ <body
+ className={cx(theme, {
+ 'bg-gray-50': theme === 'light',
+ 'bg-slate-900': theme === 'dark',
+ })}
+ >
<SelfhostedApiUrlBanner />
- <AuthProvider initialIsAuthenticated={isAuthed} initialUser={user} initialTotalMonthlyEvents={totalMonthlyEvents}>
+ <AuthProvider
+ initialIsAuthenticated={isAuthed}
+ initialUser={user}
+ initialTotalMonthlyEvents={totalMonthlyEvents}
+ >
<AppWrapper />
</AuthProvider>
<ScrollRestoration />
@@ -279,13 +311,23 @@ export default function App() {
const isEmbedded = searchParams.get('embedded') === 'true'
return (
- <html className={cx('font-sans antialiased', { 'scrollbar-thin': isEmbedded })} lang={locale} dir={i18n.dir()}>
+ <html
+ className={cx('font-sans antialiased', { 'scrollbar-thin': isEmbedded })}
+ lang={locale}
+ dir={i18n.dir()}
+ >
<head>
<meta charSet='utf-8' />
<SEO />
<meta name='google' content='notranslate' />
- <link rel='icon' type='image/x-icon' href={isSelfhosted ? '/favicon-ce.ico' : '/favicon.ico'} />
- {isDevelopment ? <script src='https://unpkg.com/[email protected]/dist/auto.global.js' /> : null}
+ <link
+ rel='icon'
+ type='image/x-icon'
+ href={isSelfhosted ? '/favicon-ce.ico' : '/favicon.ico'}
+ />
+ {isDevelopment ? (
+ <script src='https://unpkg.com/[email protected]/dist/auto.global.js' />
+ ) : null}
<Meta />
<meta name='viewport' content='width=device-width,initial-scale=1' />
<Links />
diff --git a/web/app/routes/$.tsx b/web/app/routes/$.tsx
index d2096681f..5b70e489c 100644
--- a/web/app/routes/$.tsx
+++ b/web/app/routes/$.tsx
@@ -10,7 +10,10 @@ import { getDescription, getPreviewImage, getTitle } from '~/utils/seo'
export const meta: MetaFunction = (loaderData: any) => {
if (!loaderData?.data) {
- return [...getTitle('Page Not Found'), ...getDescription('The page you are looking for does not exist.')]
+ return [
+ ...getTitle('Page Not Found'),
+ ...getDescription('The page you are looking for does not exist.'),
+ ]
}
const ogImageUrl = getOgImageUrl(loaderData?.data?.title)
diff --git a/web/app/routes/3rd-party-unsubscribe.$token.tsx b/web/app/routes/3rd-party-unsubscribe.$token.tsx
index cd98e7f6a..aa4b691ae 100644
--- a/web/app/routes/3rd-party-unsubscribe.$token.tsx
+++ b/web/app/routes/3rd-party-unsubscribe.$token.tsx
@@ -16,7 +16,10 @@ export interface UnsubscribeLoaderData {
error?: string
}
-export async function loader({ request, params }: LoaderFunctionArgs): Promise<UnsubscribeLoaderData | Response> {
+export async function loader({
+ request,
+ params,
+}: LoaderFunctionArgs): Promise<UnsubscribeLoaderData | Response> {
if (isSelfhosted) {
return redirect('/login', 302)
}
@@ -32,7 +35,8 @@ export async function loader({ request, params }: LoaderFunctionArgs): Promise<U
})
if (result.error) {
- const errorMessage = typeof result.error === 'string' ? result.error : 'Failed to unsubscribe'
+ const errorMessage =
+ typeof result.error === 'string' ? result.error : 'Failed to unsubscribe'
return { success: false, error: errorMessage }
}
diff --git a/web/app/routes/_index.tsx b/web/app/routes/_index.tsx
index ec52a49c9..ac5398b53 100644
--- a/web/app/routes/_index.tsx
+++ b/web/app/routes/_index.tsx
@@ -45,7 +45,10 @@ import {
} from '~/lib/constants'
import { DEFAULT_METAINFO, Metainfo } from '~/lib/models/Metainfo'
import { Stats } from '~/lib/models/Stats'
-import { MetricCard, MetricCardSelect } from '~/pages/Project/tabs/Traffic/MetricCards'
+import {
+ MetricCard,
+ MetricCardSelect,
+} from '~/pages/Project/tabs/Traffic/MetricCards'
import CCRow from '~/pages/Project/View/components/CCRow'
import { useTheme } from '~/providers/ThemeProvider'
import Flag from '~/ui/Flag'
@@ -99,7 +102,9 @@ interface FeedbackHighlightProps {
}
const FeedbackHighlight = ({ children }: FeedbackHighlightProps) => (
- <span className='bg-yellow-100/80 font-medium dark:bg-yellow-400/40'>&nbsp;{children}&nbsp;</span>
+ <span className='bg-yellow-100/80 font-medium dark:bg-yellow-400/40'>
+ &nbsp;{children}&nbsp;
+ </span>
)
const FeedbackDual = () => {
@@ -112,15 +117,23 @@ const FeedbackDual = () => {
<div className='flex flex-col pb-10 sm:pb-16 lg:pr-8 lg:pb-0 xl:pr-20'>
<img
alt='Casterlabs'
- src={theme === 'dark' ? '/assets/users/casterlabs-dark.svg' : '/assets/users/casterlabs-light.svg'}
+ src={
+ theme === 'dark'
+ ? '/assets/users/casterlabs-dark.svg'
+ : '/assets/users/casterlabs-light.svg'
+ }
className='h-12 self-start'
/>
<figure className='mt-10 flex flex-auto flex-col justify-between'>
<blockquote className='text-lg/8 text-gray-900 dark:text-gray-100'>
<p>
- "Swetrix has been a<FeedbackHighlight>game changer for our analytics.</FeedbackHighlight> They've
- always been on top of feature requests and bug reports and have been friendly every step of the way. I
- can't recommend them enough."
+ "Swetrix has been a
+ <FeedbackHighlight>
+ game changer for our analytics.
+ </FeedbackHighlight>{' '}
+ They've always been on top of feature requests and bug reports
+ and have been friendly every step of the way. I can't
+ recommend them enough."
</p>
</blockquote>
<figcaption className='mt-10 flex items-center gap-x-6'>
@@ -130,8 +143,12 @@ const FeedbackDual = () => {
className='size-14 rounded-full bg-gray-50 dark:bg-gray-800'
/>
<div className='text-base'>
- <div className='font-semibold text-gray-900 dark:text-gray-100'>Alex Bowles</div>
- <div className='mt-1 text-gray-500 dark:text-gray-400'>Co-founder of Casterlabs</div>
+ <div className='font-semibold text-gray-900 dark:text-gray-100'>
+ Alex Bowles
+ </div>
+ <div className='mt-1 text-gray-500 dark:text-gray-400'>
+ Co-founder of Casterlabs
+ </div>
</div>
</figcaption>
</figure>
@@ -139,18 +156,24 @@ const FeedbackDual = () => {
<div className='flex flex-col border-t border-gray-900/10 pt-10 sm:pt-16 lg:border-t-0 lg:border-l lg:pt-0 lg:pl-8 xl:pl-20 dark:border-gray-100/10'>
<img
alt='Phalcode'
- src={theme === 'dark' ? '/assets/users/phalcode-dark.svg' : '/assets/users/phalcode-light.svg'}
+ src={
+ theme === 'dark'
+ ? '/assets/users/phalcode-dark.svg'
+ : '/assets/users/phalcode-light.svg'
+ }
className='h-8 self-start'
/>
<figure className='mt-10 flex flex-auto flex-col justify-between'>
<blockquote className='text-lg/8 text-gray-900 dark:text-gray-100'>
<p>
- "I was confused by Google Analytics so much that I was getting zero actionable insights. Swetrix
- changed everything -
+ "I was confused by Google Analytics so much that I was getting
+ zero actionable insights. Swetrix changed everything -
<FeedbackHighlight>
- clean dashboard, instant understanding of user behavior, and features that actually matter.
+ clean dashboard, instant understanding of user behavior, and
+ features that actually matter.
</FeedbackHighlight>
- Finally, analytics that help me make better decisions instead of irritating me."
+ Finally, analytics that help me make better decisions instead
+ of irritating me."
</p>
</blockquote>
<figcaption className='mt-10 flex items-center gap-x-6'>
@@ -160,8 +183,12 @@ const FeedbackDual = () => {
className='size-14 rounded-full bg-gray-50 dark:bg-gray-800'
/>
<div className='text-base'>
- <div className='font-semibold text-gray-900 dark:text-gray-100'>Alper Alkan</div>
- <div className='mt-1 text-gray-500 dark:text-gray-400'>Co-founder of Phalcode</div>
+ <div className='font-semibold text-gray-900 dark:text-gray-100'>
+ Alper Alkan
+ </div>
+ <div className='mt-1 text-gray-500 dark:text-gray-400'>
+ Co-founder of Phalcode
+ </div>
</div>
</figcaption>
</figure>
@@ -195,18 +222,35 @@ const REVIEWERS = [
},
]
-const Testimonials = ({ className, stats }: { className?: string; stats: Stats | null }) => {
+const Testimonials = ({
+ className,
+ stats,
+}: {
+ className?: string
+ stats: Stats | null
+}) => {
const { t } = useTranslation('common')
return (
- <div className={cn('flex flex-col items-center justify-center gap-3 md:flex-row', className)}>
+ <div
+ className={cn(
+ 'flex flex-col items-center justify-center gap-3 md:flex-row',
+ className,
+ )}
+ >
<div className='flex -space-x-5 overflow-hidden'>
{_map(REVIEWERS, ({ name, image }) => (
<div
key={`${name}${image}`}
className='relative inline-flex size-12 overflow-hidden rounded-full border-4 border-gray-50 dark:border-slate-800/90'
>
- <img alt={name} width='400' height='400' style={{ color: 'transparent' }} src={image} />
+ <img
+ alt={name}
+ width='400'
+ height='400'
+ style={{ color: 'transparent' }}
+ src={image}
+ />
</div>
))}
</div>
@@ -247,7 +291,11 @@ const LiveDemoPreview = () => {
return (
<div className='relative z-20 mx-auto mt-10 overflow-hidden rounded-xl ring-2 ring-gray-900/10 dark:ring-white/10'>
<img
- src={theme === 'dark' ? '/assets/screenshot_dark.png' : '/assets/screenshot_light.png'}
+ src={
+ theme === 'dark'
+ ? '/assets/screenshot_dark.png'
+ : '/assets/screenshot_light.png'
+ }
className='relative w-full'
width='100%'
height='auto'
@@ -314,7 +362,9 @@ const Hero = () => {
<h1 className='max-w-5xl text-left text-5xl font-semibold tracking-tight text-pretty text-slate-900 sm:leading-none lg:mt-6 lg:text-6xl xl:text-7xl dark:text-white'>
{t('main.slogan')}
</h1>
- <p className='mt-4 max-w-2xl text-left text-lg text-slate-900 dark:text-gray-50'>{t('main.description')}</p>
+ <p className='mt-4 max-w-2xl text-left text-lg text-slate-900 dark:text-gray-50'>
+ {t('main.description')}
+ </p>
<div className='mt-8 flex flex-col items-stretch sm:flex-row sm:items-center'>
<Link
to={routesPath.signup}
@@ -371,12 +421,24 @@ const Hero = () => {
)
}
-const FeatureCard = ({ title, description, media }: { title: string; description: string; media: React.ReactNode }) => (
+const FeatureCard = ({
+ title,
+ description,
+ media,
+}: {
+ title: string
+ description: string
+ media: React.ReactNode
+}) => (
<div className='flex h-full flex-col overflow-hidden rounded-xl bg-white ring-1 ring-black/5 dark:bg-slate-800 dark:ring-white/10'>
<div className='relative h-60 overflow-hidden'>{media}</div>
<div className='p-6'>
- <h3 className='text-lg font-semibold text-gray-950 dark:text-white'>{title}</h3>
- <p className='mt-1 text-sm text-gray-700 dark:text-gray-300'>{description}</p>
+ <h3 className='text-lg font-semibold text-gray-950 dark:text-white'>
+ {title}
+ </h3>
+ <p className='mt-1 text-sm text-gray-700 dark:text-gray-300'>
+ {description}
+ </p>
</div>
</div>
)
@@ -393,8 +455,12 @@ const LargeFeatureCard = ({
<div className='flex h-full flex-col overflow-hidden rounded-2xl bg-white ring-1 ring-black/5 dark:bg-slate-800 dark:ring-white/10'>
<div className='relative h-60 overflow-hidden'>{media}</div>
<div className='p-6'>
- <h3 className='text-xl font-semibold text-gray-950 dark:text-white'>{title}</h3>
- <div className='mt-1 text-sm text-gray-700 dark:text-gray-300'>{description}</div>
+ <h3 className='text-xl font-semibold text-gray-950 dark:text-white'>
+ {title}
+ </h3>
+ <div className='mt-1 text-sm text-gray-700 dark:text-gray-300'>
+ {description}
+ </div>
</div>
</div>
)
@@ -415,7 +481,8 @@ const SdurMetric = () => {
<MetricCard
classes={{
value: 'max-md:text-xl md:text-3xl',
- container: 'rounded-md bg-gray-50 dark:bg-slate-700/60 py-1 px-2 max-w-max',
+ container:
+ 'rounded-md bg-gray-50 dark:bg-slate-700/60 py-1 px-2 max-w-max',
}}
label={t('dashboard.sessionDuration')}
value={duration}
@@ -426,18 +493,26 @@ const SdurMetric = () => {
const AnalyticsLivePreview = () => {
const { t } = useTranslation('common')
- const [points, setPoints] = useState<number[]>(() => Array.from({ length: 32 }, () => 2 + Math.random() * 10))
+ const [points, setPoints] = useState<number[]>(() =>
+ Array.from({ length: 32 }, () => 2 + Math.random() * 10),
+ )
const [live, setLive] = useState(18)
useEffect(() => {
const intervalId = setInterval(() => {
setPoints((prev) => {
const next = prev.slice(1)
- next.push(Math.max(1, Math.min(14, prev[prev.length - 1] + (Math.random() - 0.5) * 3)))
+ next.push(
+ Math.max(
+ 1,
+ Math.min(14, prev[prev.length - 1] + (Math.random() - 0.5) * 3),
+ ),
+ )
return next
})
setLive((v) => {
- const n = v + (Math.random() > 0.5 ? 1 : -1) * (Math.random() > 0.6 ? 2 : 1)
+ const n =
+ v + (Math.random() > 0.5 ? 1 : -1) * (Math.random() > 0.6 ? 2 : 1)
return Math.max(8, Math.min(28, n))
})
}, 2000)
@@ -577,23 +652,63 @@ const randomEvent = (): EventItem => {
const metas = [
{
text: 'United States • Chrome • iOS',
- flag: <Flag className='rounded-xs' country='US' size={16} alt='' aria-hidden='true' />,
+ flag: (
+ <Flag
+ className='rounded-xs'
+ country='US'
+ size={16}
+ alt=''
+ aria-hidden='true'
+ />
+ ),
},
{
text: 'France • Edge • Windows',
- flag: <Flag className='rounded-xs' country='FR' size={16} alt='' aria-hidden='true' />,
+ flag: (
+ <Flag
+ className='rounded-xs'
+ country='FR'
+ size={16}
+ alt=''
+ aria-hidden='true'
+ />
+ ),
},
{
text: 'United Kingdom • Safari • macOS',
- flag: <Flag className='rounded-xs' country='GB' size={16} alt='' aria-hidden='true' />,
+ flag: (
+ <Flag
+ className='rounded-xs'
+ country='GB'
+ size={16}
+ alt=''
+ aria-hidden='true'
+ />
+ ),
},
{
text: 'Germany • Firefox • Linux',
- flag: <Flag className='rounded-xs' country='DE' size={16} alt='' aria-hidden='true' />,
+ flag: (
+ <Flag
+ className='rounded-xs'
+ country='DE'
+ size={16}
+ alt=''
+ aria-hidden='true'
+ />
+ ),
},
{
text: 'Ukraine • Chrome • macOS',
- flag: <Flag className='rounded-xs' country='UA' size={16} alt='' aria-hidden='true' />,
+ flag: (
+ <Flag
+ className='rounded-xs'
+ country='UA'
+ size={16}
+ alt=''
+ aria-hidden='true'
+ />
+ ),
},
]
const pick = (arr: any[]) => arr[Math.floor(Math.random() * arr.length)]
@@ -612,8 +727,17 @@ const randomEvent = (): EventItem => {
}
const CustomEventsPreview = () => {
- const [items, setItems] = useState<EventItem[]>(() => Array.from({ length: 5 }, randomEvent))
- const agos = ['just now', '5 sec ago', '12 sec ago', '18 sec ago', '25 sec ago', '32 sec ago']
+ const [items, setItems] = useState<EventItem[]>(() =>
+ Array.from({ length: 5 }, randomEvent),
+ )
+ const agos = [
+ 'just now',
+ '5 sec ago',
+ '12 sec ago',
+ '18 sec ago',
+ '25 sec ago',
+ '32 sec ago',
+ ]
useEffect(() => {
const id = setInterval(() => {
@@ -653,11 +777,17 @@ const CustomEventsPreview = () => {
)}
</span>
<div>
- <div className='font-medium text-slate-900 dark:text-gray-50'>{ev.name}</div>
- <div className='text-xs text-slate-600 dark:text-gray-400'>{ev.meta}</div>
+ <div className='font-medium text-slate-900 dark:text-gray-50'>
+ {ev.name}
+ </div>
+ <div className='text-xs text-slate-600 dark:text-gray-400'>
+ {ev.meta}
+ </div>
</div>
</div>
- <div className='text-xs whitespace-nowrap text-slate-500 dark:text-gray-400'>{agos[index]}</div>
+ <div className='text-xs whitespace-nowrap text-slate-500 dark:text-gray-400'>
+ {agos[index]}
+ </div>
</motion.li>
))}
</AnimatePresence>
@@ -684,12 +814,32 @@ const PerformancePreview = () => {
const height = 120
const init = (base: number, amp: number) =>
- Array.from({ length: POINTS }, (_, i) => Math.max(0, base + (Math.sin(i / 3) + (Math.random() - 0.5)) * amp))
+ Array.from({ length: POINTS }, (_, i) =>
+ Math.max(0, base + (Math.sin(i / 3) + (Math.random() - 0.5)) * amp),
+ )
const [series, setSeries] = useState<Series[]>([
- { id: 'frontend', color: '#709775', base: 0.5, amp: 0.15, values: init(0.5, 0.15) },
- { id: 'backend', color: '#00A8E8', base: 0.14, amp: 0.06, values: init(0.14, 0.06) },
- { id: 'network', color: '#F7A265', base: 0.06, amp: 0.03, values: init(0.06, 0.03) },
+ {
+ id: 'frontend',
+ color: '#709775',
+ base: 0.5,
+ amp: 0.15,
+ values: init(0.5, 0.15),
+ },
+ {
+ id: 'backend',
+ color: '#00A8E8',
+ base: 0.14,
+ amp: 0.06,
+ values: init(0.14, 0.06),
+ },
+ {
+ id: 'network',
+ color: '#F7A265',
+ base: 0.06,
+ amp: 0.03,
+ values: init(0.06, 0.03),
+ },
])
useEffect(() => {
@@ -722,8 +872,10 @@ const PerformancePreview = () => {
}
const label = (id: SeriesId) => t(`dashboard.${id}`)
- const last = (id: SeriesId) => series.find((s) => s.id === id)!.values[POINTS - 1]
- const prev = (id: SeriesId) => series.find((s) => s.id === id)!.values[POINTS - 2]
+ const last = (id: SeriesId) =>
+ series.find((s) => s.id === id)!.values[POINTS - 1]
+ const prev = (id: SeriesId) =>
+ series.find((s) => s.id === id)!.values[POINTS - 2]
const fmt = (v: number) => `${v.toFixed(2)}s`
@@ -738,7 +890,10 @@ const PerformancePreview = () => {
<ul className='flex flex-wrap items-center justify-center gap-x-3 gap-y-1 text-[10px] text-slate-600 dark:text-gray-300'>
{series.map((s) => (
<li key={s.id} className='inline-flex items-center gap-1'>
- <span className='inline-block size-2 rounded-[2px]' style={{ backgroundColor: s.color }} />
+ <span
+ className='inline-block size-2 rounded-[2px]'
+ style={{ backgroundColor: s.color }}
+ />
{label(s.id)}
</li>
))}
@@ -747,12 +902,17 @@ const PerformancePreview = () => {
const metric = (label: string, value: number, prevValue: number) => {
const isUp = value >= prevValue
- const pct = prevValue > 0 ? Math.abs(Math.round(((value - prevValue) / prevValue) * 100)) : 0
+ const pct =
+ prevValue > 0
+ ? Math.abs(Math.round(((value - prevValue) / prevValue) * 100))
+ : 0
return (
<div className='min-w-0 flex-1 rounded-md bg-white px-2.5 py-1.5 text-[11px] text-slate-900 ring-1 ring-black/5 dark:bg-slate-900 dark:text-gray-50 dark:ring-white/10'>
<div className='text-lg font-bold'>{fmt(value)}</div>
<div className='mt-0.5 flex items-center justify-between'>
- <div className='text-[10px] text-slate-600 dark:text-gray-300'>{label}</div>
+ <div className='text-[10px] text-slate-600 dark:text-gray-300'>
+ {label}
+ </div>
<div
className={cn('flex items-center gap-1 text-[10px]', {
'text-emerald-600 dark:text-emerald-400': isUp,
@@ -795,7 +955,15 @@ const PerformancePreview = () => {
</linearGradient>
</defs>
{[0.5].map((r) => (
- <line key={r} x1={0} x2={width} y1={height * r} y2={height * r} stroke='url(#gridfade)' strokeWidth={1} />
+ <line
+ key={r}
+ x1={0}
+ x2={width}
+ y1={height * r}
+ y2={height * r}
+ stroke='url(#gridfade)'
+ strokeWidth={1}
+ />
))}
{series.map((s) => (
<g key={s.id}>
@@ -830,11 +998,23 @@ const randomLog = (): LogItem => {
}
const ErrorsPreview = () => {
- const [logs, setLogs] = useState<LogItem[]>(() => Array.from({ length: 5 }, () => randomLog()))
- const agos = ['just now', '5 sec ago', '12 sec ago', '18 sec ago', '25 sec ago', '32 sec ago']
+ const [logs, setLogs] = useState<LogItem[]>(() =>
+ Array.from({ length: 5 }, () => randomLog()),
+ )
+ const agos = [
+ 'just now',
+ '5 sec ago',
+ '12 sec ago',
+ '18 sec ago',
+ '25 sec ago',
+ '32 sec ago',
+ ]
useEffect(() => {
- const id = setInterval(() => setLogs((prev) => [randomLog(), ...prev].slice(0, 6)), 4800)
+ const id = setInterval(
+ () => setLogs((prev) => [randomLog(), ...prev].slice(0, 6)),
+ 4800,
+ )
return () => clearInterval(id)
}, [])
@@ -853,9 +1033,13 @@ const ErrorsPreview = () => {
>
<div className='flex items-start gap-2'>
<span className='mt-0.5 inline-block size-2.5 flex-shrink-0 rounded-full bg-rose-500' />
- <div className='text-rose-700 dark:text-rose-200'>{log.message}</div>
+ <div className='text-rose-700 dark:text-rose-200'>
+ {log.message}
+ </div>
+ </div>
+ <div className='text-xs whitespace-nowrap text-rose-600 dark:text-rose-300'>
+ {agos[index]}
</div>
- <div className='text-xs whitespace-nowrap text-rose-600 dark:text-rose-300'>{agos[index]}</div>
</motion.li>
))}
</AnimatePresence>
@@ -930,8 +1114,12 @@ const FunnelsPreview = () => {
return (
<div className='h-full w-full bg-gradient-to-b from-white to-slate-50 p-4 dark:from-slate-800 dark:to-slate-900'>
<div className='mb-2 flex items-center justify-between'>
- <div className='text-xs font-medium text-slate-700 dark:text-gray-300'>Sample funnel</div>
- <div className='text-[11px] text-slate-700 dark:text-gray-300'>% of previous step</div>
+ <div className='text-xs font-medium text-slate-700 dark:text-gray-300'>
+ Sample funnel
+ </div>
+ <div className='text-[11px] text-slate-700 dark:text-gray-300'>
+ % of previous step
+ </div>
</div>
<div className='relative'>
<svg viewBox={`0 0 ${width} ${height}`} className='h-36 w-full'>
@@ -970,7 +1158,10 @@ const FunnelsPreview = () => {
<div className='pointer-events-none absolute inset-0 flex items-center justify-between px-3'>
{midLabels.slice(0, -1).map((p, idx) => (
- <div key={idx} className='rounded-md bg-gray-200 p-1 text-xs font-semibold text-slate-900'>
+ <div
+ key={idx}
+ className='rounded-md bg-gray-200 p-1 text-xs font-semibold text-slate-900'
+ >
{p.v.toFixed(0)}%
</div>
))}
@@ -1000,12 +1191,17 @@ const randomChatItem = (): ChatItem => {
}
const AlertsPreview = () => {
- const [items, setItems] = useState<ChatItem[]>(() => Array.from({ length: 3 }, () => randomChatItem()))
+ const [items, setItems] = useState<ChatItem[]>(() =>
+ Array.from({ length: 3 }, () => randomChatItem()),
+ )
const agos = ['just now', '7 sec ago', '52 sec ago', '2 min ago', '6 min ago']
useEffect(() => {
- const id = setInterval(() => setItems((prev) => [randomChatItem(), ...prev].slice(0, 5)), 5140)
+ const id = setInterval(
+ () => setItems((prev) => [randomChatItem(), ...prev].slice(0, 5)),
+ 5140,
+ )
return () => clearInterval(id)
}, [])
@@ -1016,15 +1212,21 @@ const AlertsPreview = () => {
<div className='mb-1 flex items-center gap-2 text-slate-900 dark:text-white'>
<BugIcon className='size-4 text-rose-600 dark:text-rose-400' />
<span className='text-sm'>
- Error alert <span className='font-semibold'>Unique error</span> triggered!
+ Error alert <span className='font-semibold'>Unique error</span>{' '}
+ triggered!
</span>
</div>
<div className='text-sm leading-5 wrap-break-word whitespace-pre-wrap text-slate-800 dark:text-gray-200'>
Project: <span className='font-mono'>Demo</span>
<br />
- Error: <span className='font-mono'>NetworkError: Failed to fetch /api/data</span>
+ Error:{' '}
+ <span className='font-mono'>
+ NetworkError: Failed to fetch /api/data
+ </span>
+ </div>
+ <div className='mt-2 text-xs whitespace-nowrap text-slate-500 dark:text-gray-400'>
+ {agos[index]}
</div>
- <div className='mt-2 text-xs whitespace-nowrap text-slate-500 dark:text-gray-400'>{agos[index]}</div>
</div>
)
}
@@ -1037,13 +1239,17 @@ const AlertsPreview = () => {
<div className='mb-1 flex items-center gap-2 text-slate-900 dark:text-white'>
<BellRingIcon className='size-4 text-amber-600 dark:text-amber-400' />
<span className='text-sm'>
- Alert <span className='font-semibold'>Online &gt;= 10</span> got triggered!
+ Alert <span className='font-semibold'>Online &gt;= 10</span> got
+ triggered!
</span>
</div>
<div className='text-sm leading-5 text-slate-800 dark:text-gray-200'>
- Your project <span className='font-semibold'>Example</span> has {online} online users right now!
+ Your project <span className='font-semibold'>Example</span> has{' '}
+ {online} online users right now!
+ </div>
+ <div className='mt-2 text-xs whitespace-nowrap text-slate-500 dark:text-gray-400'>
+ {agos[index]}
</div>
- <div className='mt-2 text-xs whitespace-nowrap text-slate-500 dark:text-gray-400'>{agos[index]}</div>
</div>
)
}
@@ -1053,13 +1259,17 @@ const AlertsPreview = () => {
<div className='mb-1 flex items-center gap-2 text-slate-900 dark:text-white'>
<BellRingIcon className='size-4 text-amber-600 dark:text-amber-400' />
<span className='text-sm'>
- Alert <span className='font-semibold'>No traffic</span> got triggered!
+ Alert <span className='font-semibold'>No traffic</span> got
+ triggered!
</span>
</div>
<div className='text-sm leading-5 text-slate-800 dark:text-gray-200'>
- Your project <span className='font-semibold'>Demo</span> has had no traffic for the last 24 hours!
+ Your project <span className='font-semibold'>Demo</span> has had no
+ traffic for the last 24 hours!
+ </div>
+ <div className='mt-2 text-xs whitespace-nowrap text-slate-500 dark:text-gray-400'>
+ {agos[index]}
</div>
- <div className='mt-2 text-xs whitespace-nowrap text-slate-500 dark:text-gray-400'>{agos[index]}</div>
</div>
)
}
@@ -1139,11 +1349,19 @@ const RevenuePreview = () => {
<div key={source.name} className='space-y-2'>
<div className='flex items-center justify-between text-[11px]'>
<div className='flex items-center gap-2'>
- <div className='size-2 rounded-full' style={{ backgroundColor: source.color }} />
- <span className='font-medium text-slate-700 dark:text-gray-300'>{source.name}</span>
+ <div
+ className='size-2 rounded-full'
+ style={{ backgroundColor: source.color }}
+ />
+ <span className='font-medium text-slate-700 dark:text-gray-300'>
+ {source.name}
+ </span>
</div>
<span className='font-semibold text-slate-900 tabular-nums dark:text-white'>
- ${source.amount.toLocaleString(undefined, { maximumFractionDigits: 0 })}
+ $
+ {source.amount.toLocaleString(undefined, {
+ maximumFractionDigits: 0,
+ })}
</span>
</div>
<div className='relative h-1.5 w-full overflow-hidden rounded-full bg-slate-100 dark:bg-slate-800'>
@@ -1173,9 +1391,30 @@ type FlagItem = {
const FeatureFlagsPreview = () => {
const [flags, setFlags] = useState<FlagItem[]>([
- { id: '1', name: 'dark-mode', enabled: true, type: 'boolean', value: 100, evaluations: 1247 },
- { id: '2', name: 'new-checkout', enabled: true, type: 'percentage', value: 75, evaluations: 892 },
- { id: '3', name: 'beta-features', enabled: false, type: 'boolean', value: 0, evaluations: 156 },
+ {
+ id: '1',
+ name: 'dark-mode',
+ enabled: true,
+ type: 'boolean',
+ value: 100,
+ evaluations: 1247,
+ },
+ {
+ id: '2',
+ name: 'new-checkout',
+ enabled: true,
+ type: 'percentage',
+ value: 75,
+ evaluations: 892,
+ },
+ {
+ id: '3',
+ name: 'beta-features',
+ enabled: false,
+ type: 'boolean',
+ value: 0,
+ evaluations: 156,
+ },
])
useEffect(() => {
@@ -1214,7 +1453,9 @@ const FeatureFlagsPreview = () => {
</div>
<div>
<div className='flex items-center gap-2'>
- <span className='font-medium text-slate-900 dark:text-gray-50'>{flag.name}</span>
+ <span className='font-medium text-slate-900 dark:text-gray-50'>
+ {flag.name}
+ </span>
<span
className={cn(
'rounded px-1.5 py-0.5 text-[10px] font-medium',
@@ -1272,7 +1513,9 @@ const ExperimentsPreview = () => {
<div className='mb-3 flex items-center justify-between'>
<div className='flex items-center gap-2'>
<FlaskConicalIcon className='size-4 text-indigo-600 dark:text-indigo-400' />
- <span className='text-sm font-medium text-slate-900 dark:text-white'>Checkout Flow Test</span>
+ <span className='text-sm font-medium text-slate-900 dark:text-white'>
+ Checkout Flow Test
+ </span>
<span className='rounded-full bg-emerald-100 px-2 py-0.5 text-[10px] font-medium text-emerald-700 dark:bg-emerald-900/40 dark:text-emerald-400'>
Running
</span>
@@ -1283,7 +1526,9 @@ const ExperimentsPreview = () => {
</div>
<div className='rounded-lg bg-white p-3 ring-1 ring-black/5 dark:bg-slate-900 dark:ring-white/10'>
- <div className='mb-2 text-[10px] font-medium text-slate-600 dark:text-gray-300'>Probability of winning</div>
+ <div className='mb-2 text-[10px] font-medium text-slate-600 dark:text-gray-300'>
+ Probability of winning
+ </div>
<div className='relative h-6 overflow-hidden rounded-full bg-slate-100 dark:bg-slate-800'>
<motion.div
className='absolute top-0 left-0 h-full bg-blue-500'
@@ -1315,8 +1560,12 @@ const ExperimentsPreview = () => {
)}
>
<div className='flex items-center justify-between'>
- <span className='font-medium text-slate-900 dark:text-white'>{v.name}</span>
- {i === winnerIdx ? <TrendingUpIcon className='size-3 text-emerald-600 dark:text-emerald-400' /> : null}
+ <span className='font-medium text-slate-900 dark:text-white'>
+ {v.name}
+ </span>
+ {i === winnerIdx ? (
+ <TrendingUpIcon className='size-3 text-emerald-600 dark:text-emerald-400' />
+ ) : null}
</div>
<div className='mt-1 text-slate-600 dark:text-gray-300'>
<span className='font-semibold text-slate-900 dark:text-white'>
@@ -1383,12 +1632,18 @@ const FeaturesShowcase = () => {
<>
{t('main.web.description')}
<ul className='mt-2 grid grid-cols-1 gap-2 text-gray-900 sm:grid-cols-2 dark:text-gray-50'>
- {_map(t('main.web.features', { returnObjects: true }), (feature: string) => (
- <li className='flex items-center gap-2 text-sm text-gray-900 dark:text-gray-50' key={feature}>
- <CheckIcon className='h-4 w-4' strokeWidth={1.5} />
- <span>{feature}</span>
- </li>
- ))}
+ {_map(
+ t('main.web.features', { returnObjects: true }),
+ (feature: string) => (
+ <li
+ className='flex items-center gap-2 text-sm text-gray-900 dark:text-gray-50'
+ key={feature}
+ >
+ <CheckIcon className='h-4 w-4' strokeWidth={1.5} />
+ <span>{feature}</span>
+ </li>
+ ),
+ )}
</ul>
</>
}
@@ -1408,12 +1663,18 @@ const FeaturesShowcase = () => {
<>
{t('main.sessions.description')}
<ul className='mt-2 grid grid-cols-1 gap-2 text-gray-900 sm:grid-cols-2 dark:text-gray-50'>
- {_map(t('main.sessions.features', { returnObjects: true }), (feature: string) => (
- <li className='flex items-center gap-2 text-sm text-gray-900 dark:text-gray-50' key={feature}>
- <CheckIcon className='h-4 w-4' strokeWidth={1.5} />
- <span>{feature}</span>
- </li>
- ))}
+ {_map(
+ t('main.sessions.features', { returnObjects: true }),
+ (feature: string) => (
+ <li
+ className='flex items-center gap-2 text-sm text-gray-900 dark:text-gray-50'
+ key={feature}
+ >
+ <CheckIcon className='h-4 w-4' strokeWidth={1.5} />
+ <span>{feature}</span>
+ </li>
+ ),
+ )}
</ul>
</>
}
@@ -1424,7 +1685,8 @@ const FeaturesShowcase = () => {
<MetricCardSelect
classes={{
value: 'max-md:text-xl md:text-2xl',
- container: 'rounded-md bg-gray-50 dark:bg-slate-700/60 py-1 px-2 max-w-max',
+ container:
+ 'rounded-md bg-gray-50 dark:bg-slate-700/60 py-1 px-2 max-w-max',
}}
values={geoOptions}
selectLabel={t('project.geo')}
@@ -1450,13 +1712,15 @@ const FeaturesShowcase = () => {
<MetricCard
classes={{
value: 'max-md:text-xl md:text-3xl',
- container: 'rounded-md bg-gray-50 dark:bg-slate-700/60 py-1 px-2 max-w-max',
+ container:
+ 'rounded-md bg-gray-50 dark:bg-slate-700/60 py-1 px-2 max-w-max',
}}
label={t('project.mapping.os')}
value={deviceInfo.os}
valueMapper={(value: keyof typeof OS_LOGO_MAP) => {
const logoUrlLight = OS_LOGO_MAP[value]
- const logoUrlDark = OS_LOGO_MAP_DARK[value as keyof typeof OS_LOGO_MAP_DARK]
+ const logoUrlDark =
+ OS_LOGO_MAP_DARK[value as keyof typeof OS_LOGO_MAP_DARK]
let logoUrl = theme === 'dark' ? logoUrlDark : logoUrlLight
logoUrl ||= logoUrlLight
@@ -1473,7 +1737,11 @@ const FeaturesShowcase = () => {
return (
<div className='flex items-center'>
- <img src={logoUrl} className='size-6 dark:fill-gray-50' alt='' />
+ <img
+ src={logoUrl}
+ className='size-6 dark:fill-gray-50'
+ alt=''
+ />
&nbsp;
{value}
</div>
@@ -1484,7 +1752,8 @@ const FeaturesShowcase = () => {
<MetricCard
classes={{
value: 'max-md:text-xl md:text-3xl',
- container: 'rounded-md bg-gray-50 dark:bg-slate-700/60 py-1 px-2 max-w-max',
+ container:
+ 'rounded-md bg-gray-50 dark:bg-slate-700/60 py-1 px-2 max-w-max',
}}
label={t('project.mapping.br')}
value={deviceInfo.browser}
@@ -1503,7 +1772,11 @@ const FeaturesShowcase = () => {
return (
<div className='flex items-center'>
- <img src={logoUrl} className='size-6 dark:fill-gray-50' alt='' />
+ <img
+ src={logoUrl}
+ className='size-6 dark:fill-gray-50'
+ alt=''
+ />
&nbsp;
{value}
</div>
@@ -1526,7 +1799,11 @@ const FeaturesShowcase = () => {
<div>
<span className='flex h-8 w-8 items-center justify-center rounded-full bg-slate-400 dark:bg-slate-800'>
{path.startsWith('/') ? (
- <FileTextIcon className='h-5 w-5 text-white' aria-hidden='true' strokeWidth={1.5} />
+ <FileTextIcon
+ className='h-5 w-5 text-white'
+ aria-hidden='true'
+ strokeWidth={1.5}
+ />
) : (
<MousePointerClickIcon
className='h-5 w-5 text-white'
@@ -1539,9 +1816,15 @@ const FeaturesShowcase = () => {
<p className='pt-1.5 text-sm text-gray-700 dark:text-gray-300'>
<Trans
t={t}
- i18nKey={path.startsWith('/') ? 'project.pageviewX' : 'project.eventX'}
+ i18nKey={
+ path.startsWith('/')
+ ? 'project.pageviewX'
+ : 'project.eventX'
+ }
components={{
- value: <span className='font-medium text-gray-900 dark:text-gray-50' />,
+ value: (
+ <span className='font-medium text-gray-900 dark:text-gray-50' />
+ ),
span: <span />,
}}
values={{
@@ -1626,7 +1909,13 @@ const FeaturesShowcase = () => {
<FeatureCard
title={t('main.cookies.title')}
description={t('main.cookies.description')}
- media={<img src='/assets/say-no-to-cookies.png' alt='' className='h-full w-full object-cover' />}
+ media={
+ <img
+ src='/assets/say-no-to-cookies.png'
+ alt=''
+ className='h-full w-full object-cover'
+ />
+ }
/>
</div>
diff --git a/web/app/routes/api.ai.ts b/web/app/routes/api.ai.ts
index bb7413ec2..f10feec4f 100644
--- a/web/app/routes/api.ai.ts
+++ b/web/app/routes/api.ai.ts
@@ -1,4 +1,8 @@
-import { type ActionFunctionArgs, type LoaderFunctionArgs, data } from 'react-router'
+import {
+ type ActionFunctionArgs,
+ type LoaderFunctionArgs,
+ data,
+} from 'react-router'
import { streamingServerFetch } from '~/api/api.server'
@@ -18,7 +22,12 @@ export async function action({ request }: ActionFunctionArgs) {
if (!response.ok) {
const errorData = await response.json().catch(() => ({}))
- return data({ error: errorData.message || `HTTP error! status: ${response.status}` }, { status: response.status })
+ return data(
+ {
+ error: errorData.message || `HTTP error! status: ${response.status}`,
+ },
+ { status: response.status },
+ )
}
// Stream the response back to the client
@@ -31,7 +40,10 @@ export async function action({ request }: ActionFunctionArgs) {
})
} catch (error) {
console.error('[api.ai] Proxy request failed:', error)
- return data({ error: error instanceof Error ? error.message : 'Unknown error' }, { status: 500 })
+ return data(
+ { error: error instanceof Error ? error.message : 'Unknown error' },
+ { status: 500 },
+ )
}
}
diff --git a/web/app/routes/api.analytics.ts b/web/app/routes/api.analytics.ts
index 68838aae9..c07d0d75e 100644
--- a/web/app/routes/api.analytics.ts
+++ b/web/app/routes/api.analytics.ts
@@ -1,4 +1,8 @@
-import { type ActionFunctionArgs, type LoaderFunctionArgs, data } from 'react-router'
+import {
+ type ActionFunctionArgs,
+ type LoaderFunctionArgs,
+ data,
+} from 'react-router'
import {
getSessionsServer,
@@ -137,7 +141,11 @@ export async function action({ request }: ActionFunctionArgs) {
const password = getProjectPasswordCookie(request, projectId)
- const analyticsParams: AnalyticsParams & { take?: number; skip?: number; options?: Record<string, unknown> } = {
+ const analyticsParams: AnalyticsParams & {
+ take?: number
+ skip?: number
+ options?: Record<string, unknown>
+ } = {
timeBucket: params.timeBucket || 'day',
period: params.period || '7d',
from: params.from,
@@ -152,10 +160,18 @@ export async function action({ request }: ActionFunctionArgs) {
try {
switch (action) {
case 'getSessions': {
- const result = await getSessionsServer(request, projectId, analyticsParams)
+ const result = await getSessionsServer(
+ request,
+ projectId,
+ analyticsParams,
+ )
return data<ProxyResponse<SessionsResponse>>({
data: result.data,
- error: result.error ? (Array.isArray(result.error) ? result.error.join(', ') : result.error) : null,
+ error: result.error
+ ? Array.isArray(result.error)
+ ? result.error.join(', ')
+ : result.error
+ : null,
})
}
@@ -164,13 +180,20 @@ export async function action({ request }: ActionFunctionArgs) {
const result = await getErrorsServer(request, projectId, errorsParams)
return data<ProxyResponse<ErrorsResponse>>({
data: result.data,
- error: result.error ? (Array.isArray(result.error) ? result.error.join(', ') : result.error) : null,
+ error: result.error
+ ? Array.isArray(result.error)
+ ? result.error.join(', ')
+ : result.error
+ : null,
})
}
case 'getFeatureFlagStats': {
if (!body.flagId) {
- return data<ProxyResponse<null>>({ data: null, error: 'flagId is required' }, { status: 400 })
+ return data<ProxyResponse<null>>(
+ { data: null, error: 'flagId is required' },
+ { status: 400 },
+ )
}
const result = await getFeatureFlagStatsServer(
request,
@@ -182,13 +205,20 @@ export async function action({ request }: ActionFunctionArgs) {
)
return data<ProxyResponse<FeatureFlagStats>>({
data: result.data,
- error: result.error ? (Array.isArray(result.error) ? result.error.join(', ') : result.error) : null,
+ error: result.error
+ ? Array.isArray(result.error)
+ ? result.error.join(', ')
+ : result.error
+ : null,
})
}
case 'getFeatureFlagProfiles': {
if (!body.flagId) {
- return data<ProxyResponse<null>>({ data: null, error: 'flagId is required' }, { status: 400 })
+ return data<ProxyResponse<null>>(
+ { data: null, error: 'flagId is required' },
+ { status: 400 },
+ )
}
const result = await getFeatureFlagProfilesServer(
request,
@@ -203,13 +233,20 @@ export async function action({ request }: ActionFunctionArgs) {
)
return data<ProxyResponse<FeatureFlagProfilesResponse>>({
data: result.data,
- error: result.error ? (Array.isArray(result.error) ? result.error.join(', ') : result.error) : null,
+ error: result.error
+ ? Array.isArray(result.error)
+ ? result.error.join(', ')
+ : result.error
+ : null,
})
}
case 'getGoalStats': {
if (!body.goalId) {
- return data<ProxyResponse<null>>({ data: null, error: 'goalId is required' }, { status: 400 })
+ return data<ProxyResponse<null>>(
+ { data: null, error: 'goalId is required' },
+ { status: 400 },
+ )
}
const result = await getGoalStatsServer(
request,
@@ -221,13 +258,20 @@ export async function action({ request }: ActionFunctionArgs) {
)
return data<ProxyResponse<GoalStats>>({
data: result.data,
- error: result.error ? (Array.isArray(result.error) ? result.error.join(', ') : result.error) : null,
+ error: result.error
+ ? Array.isArray(result.error)
+ ? result.error.join(', ')
+ : result.error
+ : null,
})
}
case 'getGoalChart': {
if (!body.goalId) {
- return data<ProxyResponse<null>>({ data: null, error: 'goalId is required' }, { status: 400 })
+ return data<ProxyResponse<null>>(
+ { data: null, error: 'goalId is required' },
+ { status: 400 },
+ )
}
const result = await getGoalChartServer(
request,
@@ -240,7 +284,11 @@ export async function action({ request }: ActionFunctionArgs) {
)
return data<ProxyResponse<{ chart: GoalChartData }>>({
data: result.data,
- error: result.error ? (Array.isArray(result.error) ? result.error.join(', ') : result.error) : null,
+ error: result.error
+ ? Array.isArray(result.error)
+ ? result.error.join(', ')
+ : result.error
+ : null,
})
}
@@ -257,13 +305,20 @@ export async function action({ request }: ActionFunctionArgs) {
)
return data<ProxyResponse<CaptchaDataResponse>>({
data: result.data,
- error: result.error ? (Array.isArray(result.error) ? result.error.join(', ') : result.error) : null,
+ error: result.error
+ ? Array.isArray(result.error)
+ ? result.error.join(', ')
+ : result.error
+ : null,
})
}
case 'getExperimentResults': {
if (!body.experimentId) {
- return data<ProxyResponse<null>>({ data: null, error: 'experimentId is required' }, { status: 400 })
+ return data<ProxyResponse<null>>(
+ { data: null, error: 'experimentId is required' },
+ { status: 400 },
+ )
}
const result = await getExperimentResultsServer(
request,
@@ -276,29 +331,47 @@ export async function action({ request }: ActionFunctionArgs) {
)
return data<ProxyResponse<ExperimentResults>>({
data: result.data,
- error: result.error ? (Array.isArray(result.error) ? result.error.join(', ') : result.error) : null,
+ error: result.error
+ ? Array.isArray(result.error)
+ ? result.error.join(', ')
+ : result.error
+ : null,
})
}
case 'getExperiment': {
if (!body.experimentId) {
- return data<ProxyResponse<null>>({ data: null, error: 'experimentId is required' }, { status: 400 })
+ return data<ProxyResponse<null>>(
+ { data: null, error: 'experimentId is required' },
+ { status: 400 },
+ )
}
const result = await getExperimentServer(request, body.experimentId)
return data<ProxyResponse<Experiment>>({
data: result.data,
- error: result.error ? (Array.isArray(result.error) ? result.error.join(', ') : result.error) : null,
+ error: result.error
+ ? Array.isArray(result.error)
+ ? result.error.join(', ')
+ : result.error
+ : null,
})
}
case 'getGoal': {
if (!body.goalId) {
- return data<ProxyResponse<null>>({ data: null, error: 'goalId is required' }, { status: 400 })
+ return data<ProxyResponse<null>>(
+ { data: null, error: 'goalId is required' },
+ { status: 400 },
+ )
}
const result = await getGoalServer(request, body.goalId)
return data<ProxyResponse<Goal>>({
data: result.data,
- error: result.error ? (Array.isArray(result.error) ? result.error.join(', ') : result.error) : null,
+ error: result.error
+ ? Array.isArray(result.error)
+ ? result.error.join(', ')
+ : result.error
+ : null,
})
}
@@ -312,7 +385,11 @@ export async function action({ request }: ActionFunctionArgs) {
)
return data<ProxyResponse<GoalsResponse>>({
data: result.data,
- error: result.error ? (Array.isArray(result.error) ? result.error.join(', ') : result.error) : null,
+ error: result.error
+ ? Array.isArray(result.error)
+ ? result.error.join(', ')
+ : result.error
+ : null,
})
}
@@ -326,7 +403,11 @@ export async function action({ request }: ActionFunctionArgs) {
)
return data<ProxyResponse<FeatureFlagsResponse>>({
data: result.data,
- error: result.error ? (Array.isArray(result.error) ? result.error.join(', ') : result.error) : null,
+ error: result.error
+ ? Array.isArray(result.error)
+ ? result.error.join(', ')
+ : result.error
+ : null,
})
}
@@ -346,13 +427,20 @@ export async function action({ request }: ActionFunctionArgs) {
)
return data<ProxyResponse<ProfilesResponse>>({
data: result.data,
- error: result.error ? (Array.isArray(result.error) ? result.error.join(', ') : result.error) : null,
+ error: result.error
+ ? Array.isArray(result.error)
+ ? result.error.join(', ')
+ : result.error
+ : null,
})
}
case 'getProfile': {
if (!body.profileId) {
- return data<ProxyResponse<null>>({ data: null, error: 'profileId is required' }, { status: 400 })
+ return data<ProxyResponse<null>>(
+ { data: null, error: 'profileId is required' },
+ { status: 400 },
+ )
}
const result = await getProfileServer(
request,
@@ -366,13 +454,20 @@ export async function action({ request }: ActionFunctionArgs) {
)
return data<ProxyResponse<ProfileDetailsResponse>>({
data: result.data,
- error: result.error ? (Array.isArray(result.error) ? result.error.join(', ') : result.error) : null,
+ error: result.error
+ ? Array.isArray(result.error)
+ ? result.error.join(', ')
+ : result.error
+ : null,
})
}
case 'getProfileSessions': {
if (!body.profileId) {
- return data<ProxyResponse<null>>({ data: null, error: 'profileId is required' }, { status: 400 })
+ return data<ProxyResponse<null>>(
+ { data: null, error: 'profileId is required' },
+ { status: 400 },
+ )
}
const result = await getProfileSessionsServer(
request,
@@ -389,37 +484,73 @@ export async function action({ request }: ActionFunctionArgs) {
)
return data<ProxyResponse<ProfileSessionsResponse>>({
data: result.data,
- error: result.error ? (Array.isArray(result.error) ? result.error.join(', ') : result.error) : null,
+ error: result.error
+ ? Array.isArray(result.error)
+ ? result.error.join(', ')
+ : result.error
+ : null,
})
}
case 'getProject': {
- const result = await getProjectServer(request, projectId, password || undefined)
+ const result = await getProjectServer(
+ request,
+ projectId,
+ password || undefined,
+ )
return data<ProxyResponse<Project>>({
data: result.data,
- error: result.error ? (Array.isArray(result.error) ? result.error.join(', ') : result.error) : null,
+ error: result.error
+ ? Array.isArray(result.error)
+ ? result.error.join(', ')
+ : result.error
+ : null,
})
}
case 'getFilters': {
if (!body.filterType) {
- return data<ProxyResponse<null>>({ data: null, error: 'filterType is required' }, { status: 400 })
+ return data<ProxyResponse<null>>(
+ { data: null, error: 'filterType is required' },
+ { status: 400 },
+ )
}
- const result = await getFiltersServer(request, projectId, body.filterType, password || undefined)
+ const result = await getFiltersServer(
+ request,
+ projectId,
+ body.filterType,
+ password || undefined,
+ )
return data<ProxyResponse<string[]>>({
data: result.data,
- error: result.error ? (Array.isArray(result.error) ? result.error.join(', ') : result.error) : null,
+ error: result.error
+ ? Array.isArray(result.error)
+ ? result.error.join(', ')
+ : result.error
+ : null,
})
}
case 'getErrorsFilters': {
if (!body.filterType) {
- return data<ProxyResponse<null>>({ data: null, error: 'filterType is required' }, { status: 400 })
+ return data<ProxyResponse<null>>(
+ { data: null, error: 'filterType is required' },
+ { status: 400 },
+ )
}
- const result = await getErrorsFiltersServer(request, projectId, body.filterType, password || undefined)
+ const result = await getErrorsFiltersServer(
+ request,
+ projectId,
+ body.filterType,
+ password || undefined,
+ )
return data<ProxyResponse<string[]>>({
data: result.data,
- error: result.error ? (Array.isArray(result.error) ? result.error.join(', ') : result.error) : null,
+ error: result.error
+ ? Array.isArray(result.error)
+ ? result.error.join(', ')
+ : result.error
+ : null,
})
}
@@ -439,97 +570,161 @@ export async function action({ request }: ActionFunctionArgs) {
)
return data<ProxyResponse<VersionFilter[]>>({
data: result.data,
- error: result.error ? (Array.isArray(result.error) ? result.error.join(', ') : result.error) : null,
+ error: result.error
+ ? Array.isArray(result.error)
+ ? result.error.join(', ')
+ : result.error
+ : null,
})
}
case 'getCustomEventsMetadata': {
if (!body.event) {
- return data<ProxyResponse<null>>({ data: null, error: 'event is required' }, { status: 400 })
+ return data<ProxyResponse<null>>(
+ { data: null, error: 'event is required' },
+ { status: 400 },
+ )
}
- const result = await getCustomEventsMetadataServer(request, projectId, body.event, {
- timeBucket: params.timeBucket,
- period: params.period,
- from: params.from,
- to: params.to,
- timezone: params.timezone,
- password: password || undefined,
- })
+ const result = await getCustomEventsMetadataServer(
+ request,
+ projectId,
+ body.event,
+ {
+ timeBucket: params.timeBucket,
+ period: params.period,
+ from: params.from,
+ to: params.to,
+ timezone: params.timezone,
+ password: password || undefined,
+ },
+ )
return data<ProxyResponse<CustomEventsMetadataResponse>>({
data: result.data,
- error: result.error ? (Array.isArray(result.error) ? result.error.join(', ') : result.error) : null,
+ error: result.error
+ ? Array.isArray(result.error)
+ ? result.error.join(', ')
+ : result.error
+ : null,
})
}
case 'getPropertyMetadata': {
if (!body.property) {
- return data<ProxyResponse<null>>({ data: null, error: 'property is required' }, { status: 400 })
+ return data<ProxyResponse<null>>(
+ { data: null, error: 'property is required' },
+ { status: 400 },
+ )
}
- const result = await getPropertyMetadataServer(request, projectId, body.property, {
- timeBucket: params.timeBucket,
- period: params.period,
- from: params.from,
- to: params.to,
- filters: params.filters,
- timezone: params.timezone,
- password: password || undefined,
- })
+ const result = await getPropertyMetadataServer(
+ request,
+ projectId,
+ body.property,
+ {
+ timeBucket: params.timeBucket,
+ period: params.period,
+ from: params.from,
+ to: params.to,
+ filters: params.filters,
+ timezone: params.timezone,
+ password: password || undefined,
+ },
+ )
return data<ProxyResponse<PropertyMetadataResponse>>({
data: result.data,
- error: result.error ? (Array.isArray(result.error) ? result.error.join(', ') : result.error) : null,
+ error: result.error
+ ? Array.isArray(result.error)
+ ? result.error.join(', ')
+ : result.error
+ : null,
})
}
case 'getErrorSessions': {
if (!body.errorId) {
- return data<ProxyResponse<null>>({ data: null, error: 'errorId is required' }, { status: 400 })
+ return data<ProxyResponse<null>>(
+ { data: null, error: 'errorId is required' },
+ { status: 400 },
+ )
}
- const result = await getErrorSessionsServer(request, projectId, body.errorId, {
- timeBucket: params.timeBucket,
- period: params.period,
- from: params.from,
- to: params.to,
- take: params.take,
- skip: params.skip,
- password: password || undefined,
- })
+ const result = await getErrorSessionsServer(
+ request,
+ projectId,
+ body.errorId,
+ {
+ timeBucket: params.timeBucket,
+ period: params.period,
+ from: params.from,
+ to: params.to,
+ take: params.take,
+ skip: params.skip,
+ password: password || undefined,
+ },
+ )
return data<ProxyResponse<ErrorSessionsResponse>>({
data: result.data,
- error: result.error ? (Array.isArray(result.error) ? result.error.join(', ') : result.error) : null,
+ error: result.error
+ ? Array.isArray(result.error)
+ ? result.error.join(', ')
+ : result.error
+ : null,
})
}
case 'getLiveVisitors': {
const pids = body.pids || [projectId]
- const result = await getLiveVisitorsServer(request, pids, password || undefined)
+ const result = await getLiveVisitorsServer(
+ request,
+ pids,
+ password || undefined,
+ )
return data<ProxyResponse<LiveStats>>({
data: result.data,
- error: result.error ? (Array.isArray(result.error) ? result.error.join(', ') : result.error) : null,
+ error: result.error
+ ? Array.isArray(result.error)
+ ? result.error.join(', ')
+ : result.error
+ : null,
})
}
case 'getLiveVisitorsInfo': {
- const result = await getLiveVisitorsInfoServer(request, projectId, password || undefined)
+ const result = await getLiveVisitorsInfoServer(
+ request,
+ projectId,
+ password || undefined,
+ )
return data<ProxyResponse<LiveVisitorInfo[]>>({
data: result.data,
- error: result.error ? (Array.isArray(result.error) ? result.error.join(', ') : result.error) : null,
+ error: result.error
+ ? Array.isArray(result.error)
+ ? result.error.join(', ')
+ : result.error
+ : null,
})
}
case 'getProjectDataCustomEvents': {
- const result = await getProjectDataCustomEventsServer(request, projectId, {
- timeBucket: params.timeBucket,
- period: params.period,
- filters: params.filters,
- from: params.from,
- to: params.to,
- timezone: params.timezone,
- customEvents: body.customEvents,
- password: password || undefined,
- })
+ const result = await getProjectDataCustomEventsServer(
+ request,
+ projectId,
+ {
+ timeBucket: params.timeBucket,
+ period: params.period,
+ filters: params.filters,
+ from: params.from,
+ to: params.to,
+ timezone: params.timezone,
+ customEvents: body.customEvents,
+ password: password || undefined,
+ },
+ )
return data<ProxyResponse<ProjectDataCustomEventsResponse>>({
data: result.data,
- error: result.error ? (Array.isArray(result.error) ? result.error.join(', ') : result.error) : null,
+ error: result.error
+ ? Array.isArray(result.error)
+ ? result.error.join(', ')
+ : result.error
+ : null,
})
}
@@ -545,7 +740,11 @@ export async function action({ request }: ActionFunctionArgs) {
})
return data<ProxyResponse<UserFlowResponse>>({
data: result.data,
- error: result.error ? (Array.isArray(result.error) ? result.error.join(', ') : result.error) : null,
+ error: result.error
+ ? Array.isArray(result.error)
+ ? result.error.join(', ')
+ : result.error
+ : null,
})
}
@@ -559,7 +758,11 @@ export async function action({ request }: ActionFunctionArgs) {
})
return data<ProxyResponse<GSCKeywordsResponse>>({
data: result.data,
- error: result.error ? (Array.isArray(result.error) ? result.error.join(', ') : result.error) : null,
+ error: result.error
+ ? Array.isArray(result.error)
+ ? result.error.join(', ')
+ : result.error
+ : null,
})
}
@@ -567,7 +770,11 @@ export async function action({ request }: ActionFunctionArgs) {
const result = await getRevenueStatusServer(request, projectId)
return data<ProxyResponse<RevenueStatus>>({
data: result.data,
- error: result.error ? (Array.isArray(result.error) ? result.error.join(', ') : result.error) : null,
+ error: result.error
+ ? Array.isArray(result.error)
+ ? result.error.join(', ')
+ : result.error
+ : null,
})
}
@@ -581,13 +788,20 @@ export async function action({ request }: ActionFunctionArgs) {
})
return data<ProxyResponse<RevenueDataResponse>>({
data: result.data,
- error: result.error ? (Array.isArray(result.error) ? result.error.join(', ') : result.error) : null,
+ error: result.error
+ ? Array.isArray(result.error)
+ ? result.error.join(', ')
+ : result.error
+ : null,
})
}
case 'getOverallStats': {
if (!pids || pids.length === 0) {
- return data<ProxyResponse<null>>({ data: null, error: 'pids is required' }, { status: 400 })
+ return data<ProxyResponse<null>>(
+ { data: null, error: 'pids is required' },
+ { status: 400 },
+ )
}
const result = await getOverallStatsServer(request, pids, {
timeBucket: params.timeBucket || 'day',
@@ -600,17 +814,27 @@ export async function action({ request }: ActionFunctionArgs) {
})
return data<ProxyResponse<Record<string, OverallObject>>>({
data: result.data,
- error: result.error ? (Array.isArray(result.error) ? result.error.join(', ') : result.error) : null,
+ error: result.error
+ ? Array.isArray(result.error)
+ ? result.error.join(', ')
+ : result.error
+ : null,
})
}
default:
- return data<ProxyResponse<null>>({ data: null, error: `Unknown action: ${action}` }, { status: 400 })
+ return data<ProxyResponse<null>>(
+ { data: null, error: `Unknown action: ${action}` },
+ { status: 400 },
+ )
}
} catch (error) {
console.error('[api.analytics] Proxy request failed:', error)
return data<ProxyResponse<null>>(
- { data: null, error: error instanceof Error ? error.message : 'Unknown error' },
+ {
+ data: null,
+ error: error instanceof Error ? error.message : 'Unknown error',
+ },
{ status: 500 },
)
}
diff --git a/web/app/routes/api.auth.ts b/web/app/routes/api.auth.ts
index fffd0e44c..9e824c3e1 100644
--- a/web/app/routes/api.auth.ts
+++ b/web/app/routes/api.auth.ts
@@ -1,4 +1,8 @@
-import { type ActionFunctionArgs, type LoaderFunctionArgs, data } from 'react-router'
+import {
+ type ActionFunctionArgs,
+ type LoaderFunctionArgs,
+ data,
+} from 'react-router'
import {
generateSSOAuthURLServer,
@@ -46,24 +50,45 @@ export async function action({ request }: ActionFunctionArgs) {
switch (action) {
case 'generateSSOAuthURL': {
if (!body.provider) {
- return data<ProxyResponse<null>>({ data: null, error: 'provider is required' }, { status: 400 })
+ return data<ProxyResponse<null>>(
+ { data: null, error: 'provider is required' },
+ { status: 400 },
+ )
}
- const result = await generateSSOAuthURLServer(request, body.provider, body.redirectUrl)
+ const result = await generateSSOAuthURLServer(
+ request,
+ body.provider,
+ body.redirectUrl,
+ )
return data<ProxyResponse<SSOAuthURLResponse>>({
data: result.data,
- error: result.error ? (Array.isArray(result.error) ? result.error.join(', ') : result.error) : null,
+ error: result.error
+ ? Array.isArray(result.error)
+ ? result.error.join(', ')
+ : result.error
+ : null,
})
}
case 'getJWTBySSOHash': {
if (!body.hash || !body.provider) {
- return data<ProxyResponse<null>>({ data: null, error: 'hash and provider are required' }, { status: 400 })
+ return data<ProxyResponse<null>>(
+ { data: null, error: 'hash and provider are required' },
+ { status: 400 },
+ )
}
- const result = await getJWTBySSOHashServer(request, body.hash, body.provider)
+ const result = await getJWTBySSOHashServer(
+ request,
+ body.hash,
+ body.provider,
+ )
if (result.data) {
const { accessToken, refreshToken } = result.data
- const cookies = createAuthCookies({ accessToken, refreshToken }, body.remember ?? false)
+ const cookies = createAuthCookies(
+ { accessToken, refreshToken },
+ body.remember ?? false,
+ )
return data<ProxyResponse<SSOHashResponse>>(
{
@@ -71,14 +96,21 @@ export async function action({ request }: ActionFunctionArgs) {
error: null,
},
{
- headers: cookies.map((cookie) => ['Set-Cookie', cookie]) as [string, string][],
+ headers: cookies.map((cookie) => ['Set-Cookie', cookie]) as [
+ string,
+ string,
+ ][],
},
)
}
return data<ProxyResponse<SSOHashResponse>>({
data: result.data,
- error: result.error ? (Array.isArray(result.error) ? result.error.join(', ') : result.error) : null,
+ error: result.error
+ ? Array.isArray(result.error)
+ ? result.error.join(', ')
+ : result.error
+ : null,
})
}
@@ -89,43 +121,85 @@ export async function action({ request }: ActionFunctionArgs) {
{ status: 400 },
)
}
- const result = await processSSOTokenCommunityEditionServer(request, body.code, body.hash, body.redirectUrl)
+ const result = await processSSOTokenCommunityEditionServer(
+ request,
+ body.code,
+ body.hash,
+ body.redirectUrl,
+ )
return data<ProxyResponse<unknown>>({
data: result.data,
- error: result.error ? (Array.isArray(result.error) ? result.error.join(', ') : result.error) : null,
+ error: result.error
+ ? Array.isArray(result.error)
+ ? result.error.join(', ')
+ : result.error
+ : null,
})
}
case 'linkBySSOHash': {
if (!body.hash || !body.provider) {
- return data<ProxyResponse<null>>({ data: null, error: 'hash and provider are required' }, { status: 400 })
+ return data<ProxyResponse<null>>(
+ { data: null, error: 'hash and provider are required' },
+ { status: 400 },
+ )
}
- const result = await linkBySSOHashServer(request, body.hash, body.provider)
+ const result = await linkBySSOHashServer(
+ request,
+ body.hash,
+ body.provider,
+ )
return data<ProxyResponse<unknown>>({
data: result.data,
- error: result.error ? (Array.isArray(result.error) ? result.error.join(', ') : result.error) : null,
+ error: result.error
+ ? Array.isArray(result.error)
+ ? result.error.join(', ')
+ : result.error
+ : null,
})
}
case 'processSSOToken': {
if (!body.token || !body.hash) {
- return data<ProxyResponse<null>>({ data: null, error: 'token and hash are required' }, { status: 400 })
+ return data<ProxyResponse<null>>(
+ { data: null, error: 'token and hash are required' },
+ { status: 400 },
+ )
}
- const result = await processSSOTokenServer(request, body.token, body.hash)
+ const result = await processSSOTokenServer(
+ request,
+ body.token,
+ body.hash,
+ )
return data<ProxyResponse<unknown>>({
data: result.data,
- error: result.error ? (Array.isArray(result.error) ? result.error.join(', ') : result.error) : null,
+ error: result.error
+ ? Array.isArray(result.error)
+ ? result.error.join(', ')
+ : result.error
+ : null,
})
}
case 'processGSCToken': {
if (!body.code || !body.state) {
- return data<ProxyResponse<null>>({ data: null, error: 'code and state are required' }, { status: 400 })
+ return data<ProxyResponse<null>>(
+ { data: null, error: 'code and state are required' },
+ { status: 400 },
+ )
}
- const result = await processGSCTokenServer(request, body.code, body.state)
+ const result = await processGSCTokenServer(
+ request,
+ body.code,
+ body.state,
+ )
return data<ProxyResponse<{ pid: string }>>({
data: result.data,
- error: result.error ? (Array.isArray(result.error) ? result.error.join(', ') : result.error) : null,
+ error: result.error
+ ? Array.isArray(result.error)
+ ? result.error.join(', ')
+ : result.error
+ : null,
})
}
@@ -133,17 +207,27 @@ export async function action({ request }: ActionFunctionArgs) {
const result = await authMeServer(request)
return data<ProxyResponse<AuthMeResponse>>({
data: result.data,
- error: result.error ? (Array.isArray(result.error) ? result.error.join(', ') : result.error) : null,
+ error: result.error
+ ? Array.isArray(result.error)
+ ? result.error.join(', ')
+ : result.error
+ : null,
})
}
default:
- return data<ProxyResponse<null>>({ data: null, error: `Unknown action: ${action}` }, { status: 400 })
+ return data<ProxyResponse<null>>(
+ { data: null, error: `Unknown action: ${action}` },
+ { status: 400 },
+ )
}
} catch (error) {
console.error('[api.auth] Proxy request failed:', error)
return data<ProxyResponse<null>>(
- { data: null, error: error instanceof Error ? error.message : 'Unknown error' },
+ {
+ data: null,
+ error: error instanceof Error ? error.message : 'Unknown error',
+ },
{ status: 500 },
)
}
diff --git a/web/app/routes/billing.tsx b/web/app/routes/billing.tsx
index d4dc1b75a..6ed3c08d5 100644
--- a/web/app/routes/billing.tsx
+++ b/web/app/routes/billing.tsx
@@ -1,4 +1,9 @@
-import { type ActionFunctionArgs, type LoaderFunctionArgs, redirect, data } from 'react-router'
+import {
+ type ActionFunctionArgs,
+ type LoaderFunctionArgs,
+ redirect,
+ data,
+} from 'react-router'
import type { SitemapFunction } from 'remix-sitemap'
import { serverFetch } from '~/api/api.server'
@@ -6,7 +11,10 @@ import { isSelfhosted } from '~/lib/constants'
import { Metainfo } from '~/lib/models/Metainfo'
import { UsageInfo } from '~/lib/models/Usageinfo'
import Billing from '~/pages/Billing'
-import { redirectIfNotAuthenticated, createHeadersWithCookies } from '~/utils/session.server'
+import {
+ redirectIfNotAuthenticated,
+ createHeadersWithCookies,
+} from '~/utils/session.server'
export const sitemap: SitemapFunction = () => ({
exclude: true,
@@ -63,7 +71,10 @@ export async function action({ request }: ActionFunctionArgs) {
})
if (result.error) {
- return data<BillingActionData>({ intent, error: result.error as string }, { status: 400 })
+ return data<BillingActionData>(
+ { intent, error: result.error as string },
+ { status: 400 },
+ )
}
return data<BillingActionData>(
@@ -81,7 +92,10 @@ export async function action({ request }: ActionFunctionArgs) {
})
if (result.error) {
- return data<BillingActionData>({ intent, error: result.error as string }, { status: 400 })
+ return data<BillingActionData>(
+ { intent, error: result.error as string },
+ { status: 400 },
+ )
}
return data<BillingActionData>(
@@ -94,7 +108,10 @@ export async function action({ request }: ActionFunctionArgs) {
const result = await serverFetch<Metainfo>(request, 'user/metainfo')
if (result.error) {
- return data<BillingActionData>({ intent, error: result.error as string }, { status: 400 })
+ return data<BillingActionData>(
+ { intent, error: result.error as string },
+ { status: 400 },
+ )
}
return data<BillingActionData>(
@@ -104,7 +121,10 @@ export async function action({ request }: ActionFunctionArgs) {
}
default:
- return data<BillingActionData>({ error: 'Unknown action' }, { status: 400 })
+ return data<BillingActionData>(
+ { error: 'Unknown action' },
+ { status: 400 },
+ )
}
}
diff --git a/web/app/routes/blog.$category.$slug.tsx b/web/app/routes/blog.$category.$slug.tsx
index 024061dcf..7e20cf15a 100644
--- a/web/app/routes/blog.$category.$slug.tsx
+++ b/web/app/routes/blog.$category.$slug.tsx
@@ -1,7 +1,11 @@
import type { LoaderFunctionArgs, MetaFunction } from 'react-router'
import { redirect, data } from 'react-router'
-import { isSelfhosted, getOgImageUrl, isDisableMarketingPages } from '~/lib/constants'
+import {
+ isSelfhosted,
+ getOgImageUrl,
+ isDisableMarketingPages,
+} from '~/lib/constants'
import Post from '~/pages/Blog/Post'
import { getPost } from '~/utils/getPosts.server'
import { getDescription, getPreviewImage, getTitle } from '~/utils/seo'
diff --git a/web/app/routes/blog.$slug.tsx b/web/app/routes/blog.$slug.tsx
index e30b9204e..7e6f1b8ad 100644
--- a/web/app/routes/blog.$slug.tsx
+++ b/web/app/routes/blog.$slug.tsx
@@ -5,7 +5,12 @@ import { redirect, data } from 'react-router'
import type { LoaderFunctionArgs, MetaFunction } from 'react-router'
import type { SitemapFunction } from 'remix-sitemap'
-import { isSelfhosted, getOgImageUrl, isDisableMarketingPages, API_URL } from '~/lib/constants'
+import {
+ isSelfhosted,
+ getOgImageUrl,
+ isDisableMarketingPages,
+ API_URL,
+} from '~/lib/constants'
import Post from '~/pages/Blog/Post'
import { getSlugFromFilename, getDateFromFilename } from '~/utils/blog'
import { getPost } from '~/utils/getPosts.server'
diff --git a/web/app/routes/blog._index.tsx b/web/app/routes/blog._index.tsx
index 5393e7834..6c8ef899a 100644
--- a/web/app/routes/blog._index.tsx
+++ b/web/app/routes/blog._index.tsx
@@ -33,7 +33,9 @@ export default function Posts() {
if (_filter(posts, (post) => !post.hidden).length === 0) {
return (
<div className='flex min-h-min-footer items-center justify-center'>
- <h1 className='text-3xl font-bold text-slate-900 dark:text-slate-200'>No posts found</h1>
+ <h1 className='text-3xl font-bold text-slate-900 dark:text-slate-200'>
+ No posts found
+ </h1>
</div>
)
}
diff --git a/web/app/routes/change-email.$id.tsx b/web/app/routes/change-email.$id.tsx
index ff4c12181..990d0f15b 100644
--- a/web/app/routes/change-email.$id.tsx
+++ b/web/app/routes/change-email.$id.tsx
@@ -21,7 +21,10 @@ export interface ChangeEmailLoaderData {
error?: string
}
-export async function loader({ request, params }: LoaderFunctionArgs): Promise<ChangeEmailLoaderData | Response> {
+export async function loader({
+ request,
+ params,
+}: LoaderFunctionArgs): Promise<ChangeEmailLoaderData | Response> {
if (isSelfhosted) {
return redirect('/login', 302)
}
@@ -32,12 +35,17 @@ export async function loader({ request, params }: LoaderFunctionArgs): Promise<C
return { success: false, error: 'Invalid verification link' }
}
- const result = await serverFetch(request, `v1/auth/change-email/confirm/${id}`, {
- skipAuth: true,
- })
+ const result = await serverFetch(
+ request,
+ `v1/auth/change-email/confirm/${id}`,
+ {
+ skipAuth: true,
+ },
+ )
if (result.error) {
- const errorMessage = typeof result.error === 'string' ? result.error : 'Verification failed'
+ const errorMessage =
+ typeof result.error === 'string' ? result.error : 'Verification failed'
return { success: false, error: errorMessage }
}
diff --git a/web/app/routes/dashboard.tsx b/web/app/routes/dashboard.tsx
index dcc727e54..f3d3b35e1 100644
--- a/web/app/routes/dashboard.tsx
+++ b/web/app/routes/dashboard.tsx
@@ -5,7 +5,10 @@ import type { SitemapFunction } from 'remix-sitemap'
import { serverFetch } from '~/api/api.server'
import { Project } from '~/lib/models/Project'
import Dashboard from '~/pages/Dashboard'
-import { redirectIfNotAuthenticated, createHeadersWithCookies } from '~/utils/session.server'
+import {
+ redirectIfNotAuthenticated,
+ createHeadersWithCookies,
+} from '~/utils/session.server'
export const sitemap: SitemapFunction = () => ({
exclude: true,
@@ -43,17 +46,25 @@ export async function action({ request }: ActionFunctionArgs) {
const organisationId = formData.get('organisationId')?.toString()
if (!name.trim()) {
- return data<DashboardActionData>({ intent, fieldErrors: { name: 'Project name is required' } }, { status: 400 })
+ return data<DashboardActionData>(
+ { intent, fieldErrors: { name: 'Project name is required' } },
+ { status: 400 },
+ )
}
if (name.length > 50) {
return data<DashboardActionData>(
- { intent, fieldErrors: { name: 'Project name must be 50 characters or less' } },
+ {
+ intent,
+ fieldErrors: { name: 'Project name must be 50 characters or less' },
+ },
{ status: 400 },
)
}
- const body: { name: string; organisationId?: string } = { name: name.trim() }
+ const body: { name: string; organisationId?: string } = {
+ name: name.trim(),
+ }
if (organisationId) body.organisationId = organisationId
const result = await serverFetch<Project>(request, 'project', {
@@ -62,7 +73,10 @@ export async function action({ request }: ActionFunctionArgs) {
})
if (result.error) {
- return data<DashboardActionData>({ intent, error: result.error as string }, { status: 400 })
+ return data<DashboardActionData>(
+ { intent, error: result.error as string },
+ { status: 400 },
+ )
}
return data<DashboardActionData>(
@@ -75,7 +89,10 @@ export async function action({ request }: ActionFunctionArgs) {
const projectId = formData.get('projectId')?.toString()
if (!projectId) {
- return data<DashboardActionData>({ intent, error: 'Project ID is required' }, { status: 400 })
+ return data<DashboardActionData>(
+ { intent, error: 'Project ID is required' },
+ { status: 400 },
+ )
}
const result = await serverFetch(request, `project/${projectId}/pin`, {
@@ -83,7 +100,10 @@ export async function action({ request }: ActionFunctionArgs) {
})
if (result.error) {
- return data<DashboardActionData>({ intent, error: result.error as string }, { status: 400 })
+ return data<DashboardActionData>(
+ { intent, error: result.error as string },
+ { status: 400 },
+ )
}
return data<DashboardActionData>(
@@ -96,7 +116,10 @@ export async function action({ request }: ActionFunctionArgs) {
const projectId = formData.get('projectId')?.toString()
if (!projectId) {
- return data<DashboardActionData>({ intent, error: 'Project ID is required' }, { status: 400 })
+ return data<DashboardActionData>(
+ { intent, error: 'Project ID is required' },
+ { status: 400 },
+ )
}
const result = await serverFetch(request, `project/${projectId}/pin`, {
@@ -104,7 +127,10 @@ export async function action({ request }: ActionFunctionArgs) {
})
if (result.error) {
- return data<DashboardActionData>({ intent, error: result.error as string }, { status: 400 })
+ return data<DashboardActionData>(
+ { intent, error: result.error as string },
+ { status: 400 },
+ )
}
return data<DashboardActionData>(
@@ -117,7 +143,10 @@ export async function action({ request }: ActionFunctionArgs) {
const shareId = formData.get('shareId')?.toString()
if (!shareId) {
- return data<DashboardActionData>({ intent, error: 'Share ID is required' }, { status: 400 })
+ return data<DashboardActionData>(
+ { intent, error: 'Share ID is required' },
+ { status: 400 },
+ )
}
const result = await serverFetch(request, `user/share/${shareId}`, {
@@ -125,14 +154,23 @@ export async function action({ request }: ActionFunctionArgs) {
})
if (result.error) {
- return data<DashboardActionData>({ intent, error: result.error as string }, { status: 400 })
+ return data<DashboardActionData>(
+ { intent, error: result.error as string },
+ { status: 400 },
+ )
}
- return data<DashboardActionData>({ intent, success: true }, { headers: createHeadersWithCookies(result.cookies) })
+ return data<DashboardActionData>(
+ { intent, success: true },
+ { headers: createHeadersWithCookies(result.cookies) },
+ )
}
default:
- return data<DashboardActionData>({ error: 'Unknown action' }, { status: 400 })
+ return data<DashboardActionData>(
+ { error: 'Unknown action' },
+ { status: 400 },
+ )
}
}
@@ -149,13 +187,19 @@ export async function loader({ request }: LoaderFunctionArgs) {
const skip = (page - 1) * pageSize
const cookieHeader = request.headers.get('Cookie')
- const viewMode = (cookieHeader?.match(/(?<=dashboard_view=)[^;]*/)?.[0] as 'grid' | 'list') || 'grid'
+ const viewMode =
+ (cookieHeader?.match(/(?<=dashboard_view=)[^;]*/)?.[0] as
+ | 'grid'
+ | 'list') || 'grid'
const projectsResult = await serverFetch<{
results: Project[]
total: number
page_total: number
- }>(request, `/project?take=${pageSize}&skip=${skip}&search=${search}&period=${period}&sort=${sort}`)
+ }>(
+ request,
+ `/project?take=${pageSize}&skip=${skip}&search=${search}&period=${period}&sort=${sort}`,
+ )
const loaderData: DashboardLoaderData = {
viewMode,
diff --git a/web/app/routes/gsc-connected.tsx b/web/app/routes/gsc-connected.tsx
index 04d79c0fb..544b89668 100644
--- a/web/app/routes/gsc-connected.tsx
+++ b/web/app/routes/gsc-connected.tsx
@@ -19,7 +19,9 @@ export interface GscConnectedLoaderData {
useClientFallback?: boolean
}
-export async function loader({ request }: LoaderFunctionArgs): Promise<GscConnectedLoaderData | Response> {
+export async function loader({
+ request,
+}: LoaderFunctionArgs): Promise<GscConnectedLoaderData | Response> {
if (isSelfhosted) {
return redirect('/login', 302)
}
@@ -36,10 +38,14 @@ export async function loader({ request }: LoaderFunctionArgs): Promise<GscConnec
return { useClientFallback: true }
}
- const result = await serverFetch<{ pid: string }>(request, 'v1/project/gsc/process-token', {
- method: 'POST',
- body: { code, state },
- })
+ const result = await serverFetch<{ pid: string }>(
+ request,
+ 'v1/project/gsc/process-token',
+ {
+ method: 'POST',
+ body: { code, state },
+ },
+ )
// If auth fails (401/403), fall back to client-side which has localStorage tokens
if (result.status === 401 || result.status === 403) {
@@ -84,7 +90,11 @@ function GscHashHandler() {
const [{ state, code }] = useState(() => {
if (typeof window === 'undefined') return { state: null, code: null }
// Fix Google's hash URL redirect (sometimes Google uses # instead of ?)
- const _location = _replace(window.location.href, `${routes.gsc_connected}#`, `${routes.gsc_connected}?`)
+ const _location = _replace(
+ window.location.href,
+ `${routes.gsc_connected}#`,
+ `${routes.gsc_connected}?`,
+ )
const { searchParams } = new URL(_location)
return {
state: searchParams.get('state'),
@@ -112,7 +122,9 @@ function GscHashHandler() {
.catch((reason) => {
sessionStorage.removeItem(processedKey)
setError(String(reason))
- console.error(`[ERROR] Error while processing GSC integration: ${reason}`)
+ console.error(
+ `[ERROR] Error while processing GSC integration: ${reason}`,
+ )
})
}, [navigate, state, code, processGSCToken])
diff --git a/web/app/routes/login.tsx b/web/app/routes/login.tsx
index dc53a4e2d..4f00e3c29 100644
--- a/web/app/routes/login.tsx
+++ b/web/app/routes/login.tsx
@@ -1,9 +1,16 @@
-import type { ActionFunctionArgs, HeadersFunction, LoaderFunctionArgs } from 'react-router'
+import type {
+ ActionFunctionArgs,
+ HeadersFunction,
+ LoaderFunctionArgs,
+} from 'react-router'
import { redirect, data } from 'react-router'
import { getAuthenticatedUser, loginUser, serverFetch } from '~/api/api.server'
import Signin from '~/pages/Auth/Signin'
-import { createHeadersWithCookies, createAuthCookies } from '~/utils/session.server'
+import {
+ createHeadersWithCookies,
+ createAuthCookies,
+} from '~/utils/session.server'
export const headers: HeadersFunction = ({ parentHeaders }) => {
parentHeaders.set('X-Frame-Options', 'DENY')
@@ -41,12 +48,19 @@ export async function action({ request }: ActionFunctionArgs) {
// Handle 2FA submission
if (intent === 'submit-2fa') {
- const twoFactorAuthenticationCode = formData.get('twoFACode')?.toString() || ''
+ const twoFactorAuthenticationCode =
+ formData.get('twoFACode')?.toString() || ''
const dontRemember = formData.get('dontRemember') === 'true'
- if (!twoFactorAuthenticationCode || twoFactorAuthenticationCode.length !== 6) {
+ if (
+ !twoFactorAuthenticationCode ||
+ twoFactorAuthenticationCode.length !== 6
+ ) {
return data<LoginActionData>(
- { fieldErrors: { twoFACode: 'Please enter a valid 6-digit code' }, timestamp: Date.now() },
+ {
+ fieldErrors: { twoFACode: 'Please enter a valid 6-digit code' },
+ timestamp: Date.now(),
+ },
{ status: 400 },
)
}
@@ -62,15 +76,23 @@ export async function action({ request }: ActionFunctionArgs) {
if (result.error) {
return data<LoginActionData>(
- { fieldErrors: { twoFACode: 'Invalid 2FA code' }, timestamp: Date.now() },
+ {
+ fieldErrors: { twoFACode: 'Invalid 2FA code' },
+ timestamp: Date.now(),
+ },
{ status: 400 },
)
}
const { accessToken, refreshToken, user } = result.data!
- const cookies = createAuthCookies({ accessToken, refreshToken }, !dontRemember)
+ const cookies = createAuthCookies(
+ { accessToken, refreshToken },
+ !dontRemember,
+ )
- const redirectTo = user.hasCompletedOnboarding ? '/dashboard' : '/onboarding'
+ const redirectTo = user.hasCompletedOnboarding
+ ? '/dashboard'
+ : '/onboarding'
return redirect(redirectTo, {
headers: createHeadersWithCookies(cookies),
@@ -112,7 +134,9 @@ export async function action({ request }: ActionFunctionArgs) {
)
}
- const redirectTo = result.data?.user.hasCompletedOnboarding ? '/dashboard' : '/onboarding'
+ const redirectTo = result.data?.user.hasCompletedOnboarding
+ ? '/dashboard'
+ : '/onboarding'
return redirect(redirectTo, {
headers: createHeadersWithCookies(result.cookies),
diff --git a/web/app/routes/onboarding.tsx b/web/app/routes/onboarding.tsx
index 878b39fd5..a4ff66b7a 100644
--- a/web/app/routes/onboarding.tsx
+++ b/web/app/routes/onboarding.tsx
@@ -1,4 +1,8 @@
-import type { ActionFunctionArgs, LoaderFunctionArgs, MetaFunction } from 'react-router'
+import type {
+ ActionFunctionArgs,
+ LoaderFunctionArgs,
+ MetaFunction,
+} from 'react-router'
import { data } from 'react-router'
import { SitemapFunction } from 'remix-sitemap'
@@ -6,7 +10,10 @@ import { getAuthenticatedUser, serverFetch } from '~/api/api.server'
import { Project } from '~/lib/models/Project'
import { User } from '~/lib/models/User'
import Onboarding from '~/pages/Onboarding'
-import { redirectIfNotAuthenticated, createHeadersWithCookies } from '~/utils/session.server'
+import {
+ redirectIfNotAuthenticated,
+ createHeadersWithCookies,
+} from '~/utils/session.server'
export const sitemap: SitemapFunction = () => ({
exclude: true,
@@ -15,7 +22,10 @@ export const sitemap: SitemapFunction = () => ({
export const meta: MetaFunction = () => {
return [
{ title: 'Onboarding - Swetrix' },
- { name: 'description', content: 'Get started with Swetrix analytics in just a few steps.' },
+ {
+ name: 'description',
+ content: 'Get started with Swetrix analytics in just a few steps.',
+ },
]
}
@@ -30,7 +40,10 @@ export async function loader({ request }: LoaderFunctionArgs) {
const user = authResult?.user
const cookies: string[] = authResult?.cookies || []
- if (user?.user?.onboardingStep === 'setup_tracking' || user?.user?.onboardingStep === 'waiting_for_events') {
+ if (
+ user?.user?.onboardingStep === 'setup_tracking' ||
+ user?.user?.onboardingStep === 'waiting_for_events'
+ ) {
const projectsResult = await serverFetch<{
results: Project[]
total: number
@@ -89,7 +102,10 @@ export async function action({ request }: ActionFunctionArgs) {
if (name.length > 50) {
return data<OnboardingActionData>(
- { intent, fieldErrors: { name: 'Project name must be 50 characters or less' } },
+ {
+ intent,
+ fieldErrors: { name: 'Project name must be 50 characters or less' },
+ },
{ status: 400 },
)
}
@@ -100,7 +116,10 @@ export async function action({ request }: ActionFunctionArgs) {
})
if (result.error) {
- return data<OnboardingActionData>({ intent, error: result.error as string }, { status: 400 })
+ return data<OnboardingActionData>(
+ { intent, error: result.error as string },
+ { status: 400 },
+ )
}
return data<OnboardingActionData>(
@@ -118,7 +137,10 @@ export async function action({ request }: ActionFunctionArgs) {
})
if (result.error) {
- return data<OnboardingActionData>({ intent, error: result.error as string }, { status: 400 })
+ return data<OnboardingActionData>(
+ { intent, error: result.error as string },
+ { status: 400 },
+ )
}
return data<OnboardingActionData>(
@@ -128,12 +150,19 @@ export async function action({ request }: ActionFunctionArgs) {
}
case 'complete-onboarding': {
- const result = await serverFetch<User>(request, 'user/onboarding/complete', {
- method: 'POST',
- })
+ const result = await serverFetch<User>(
+ request,
+ 'user/onboarding/complete',
+ {
+ method: 'POST',
+ },
+ )
if (result.error) {
- return data<OnboardingActionData>({ intent, error: result.error as string }, { status: 400 })
+ return data<OnboardingActionData>(
+ { intent, error: result.error as string },
+ { status: 400 },
+ )
}
return data<OnboardingActionData>(
@@ -148,7 +177,10 @@ export async function action({ request }: ActionFunctionArgs) {
})
if (result.error) {
- return data<OnboardingActionData>({ intent, error: result.error as string }, { status: 400 })
+ return data<OnboardingActionData>(
+ { intent, error: result.error as string },
+ { status: 400 },
+ )
}
return data<OnboardingActionData>(
@@ -158,7 +190,10 @@ export async function action({ request }: ActionFunctionArgs) {
}
default:
- return data<OnboardingActionData>({ error: 'Unknown action' }, { status: 400 })
+ return data<OnboardingActionData>(
+ { error: 'Unknown action' },
+ { status: 400 },
+ )
}
}
diff --git a/web/app/routes/open.tsx b/web/app/routes/open.tsx
index 84fd91d28..a0872f7d8 100644
--- a/web/app/routes/open.tsx
+++ b/web/app/routes/open.tsx
@@ -1,4 +1,9 @@
-import { redirect, type LoaderFunctionArgs, useLoaderData, LinksFunction } from 'react-router'
+import {
+ redirect,
+ type LoaderFunctionArgs,
+ useLoaderData,
+ LinksFunction,
+} from 'react-router'
import type { SitemapFunction } from 'remix-sitemap'
import { getGeneralStats } from '~/api/api.server'
diff --git a/web/app/routes/organisation.invite.$id.tsx b/web/app/routes/organisation.invite.$id.tsx
index 677792879..a916c067e 100644
--- a/web/app/routes/organisation.invite.$id.tsx
+++ b/web/app/routes/organisation.invite.$id.tsx
@@ -15,7 +15,10 @@ export interface OrganisationInviteLoaderData {
error?: string
}
-export async function loader({ request, params }: LoaderFunctionArgs): Promise<OrganisationInviteLoaderData> {
+export async function loader({
+ request,
+ params,
+}: LoaderFunctionArgs): Promise<OrganisationInviteLoaderData> {
const { id } = params
if (!id) {
@@ -27,7 +30,10 @@ export async function loader({ request, params }: LoaderFunctionArgs): Promise<O
})
if (result.error) {
- const errorMessage = typeof result.error === 'string' ? result.error : 'Failed to accept invitation'
+ const errorMessage =
+ typeof result.error === 'string'
+ ? result.error
+ : 'Failed to accept invitation'
return { success: false, error: errorMessage }
}
diff --git a/web/app/routes/organisations.$id.tsx b/web/app/routes/organisations.$id.tsx
index f0fc455e7..eeb58ad4b 100644
--- a/web/app/routes/organisations.$id.tsx
+++ b/web/app/routes/organisations.$id.tsx
@@ -6,7 +6,10 @@ import { serverFetch } from '~/api/api.server'
import { isSelfhosted } from '~/lib/constants'
import { DetailedOrganisation } from '~/lib/models/Organisation'
import OrganisationSettings from '~/pages/Organisations/Settings'
-import { redirectIfNotAuthenticated, createHeadersWithCookies } from '~/utils/session.server'
+import {
+ redirectIfNotAuthenticated,
+ createHeadersWithCookies,
+} from '~/utils/session.server'
export const sitemap: SitemapFunction = () => ({
exclude: true,
@@ -26,12 +29,18 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
const { id } = params
- const result = await serverFetch<DetailedOrganisation>(request, `organisation/${id}`)
+ const result = await serverFetch<DetailedOrganisation>(
+ request,
+ `organisation/${id}`,
+ )
if (result.error) {
return data<OrganisationLoaderData>(
{ organisation: null, error: result.error as string },
- { status: result.status, headers: createHeadersWithCookies(result.cookies) },
+ {
+ status: result.status,
+ headers: createHeadersWithCookies(result.cookies),
+ },
)
}
@@ -88,22 +97,38 @@ export async function action({ request, params }: ActionFunctionArgs) {
if (name.length > 50) {
return data<OrganisationSettingsActionData>(
- { intent, fieldErrors: { name: 'Organisation name must be 50 characters or less' } },
+ {
+ intent,
+ fieldErrors: {
+ name: 'Organisation name must be 50 characters or less',
+ },
+ },
{ status: 400 },
)
}
- const result = await serverFetch<DetailedOrganisation>(request, `organisation/${id}`, {
- method: 'PATCH',
- body: { name: name.trim() },
- })
+ const result = await serverFetch<DetailedOrganisation>(
+ request,
+ `organisation/${id}`,
+ {
+ method: 'PATCH',
+ body: { name: name.trim() },
+ },
+ )
if (result.error) {
- return data<OrganisationSettingsActionData>({ intent, error: result.error as string }, { status: 400 })
+ return data<OrganisationSettingsActionData>(
+ { intent, error: result.error as string },
+ { status: 400 },
+ )
}
return data<OrganisationSettingsActionData>(
- { intent, success: true, organisation: result.data as DetailedOrganisation },
+ {
+ intent,
+ success: true,
+ organisation: result.data as DetailedOrganisation,
+ },
{ headers: createHeadersWithCookies(result.cookies) },
)
}
@@ -114,7 +139,10 @@ export async function action({ request, params }: ActionFunctionArgs) {
})
if (result.error) {
- return data<OrganisationSettingsActionData>({ intent, error: result.error as string }, { status: 400 })
+ return data<OrganisationSettingsActionData>(
+ { intent, error: result.error as string },
+ { status: 400 },
+ )
}
return data<OrganisationSettingsActionData>(
@@ -129,7 +157,10 @@ export async function action({ request, params }: ActionFunctionArgs) {
if (!email || !email.includes('@')) {
return data<OrganisationSettingsActionData>(
- { intent, fieldErrors: { email: 'Please enter a valid email address' } },
+ {
+ intent,
+ fieldErrors: { email: 'Please enter a valid email address' },
+ },
{ status: 400 },
)
}
@@ -140,7 +171,10 @@ export async function action({ request, params }: ActionFunctionArgs) {
})
if (result.error) {
- return data<OrganisationSettingsActionData>({ intent, error: result.error as string }, { status: 400 })
+ return data<OrganisationSettingsActionData>(
+ { intent, error: result.error as string },
+ { status: 400 },
+ )
}
return data<OrganisationSettingsActionData>(
@@ -152,12 +186,19 @@ export async function action({ request, params }: ActionFunctionArgs) {
case 'remove-member': {
const memberId = formData.get('memberId')?.toString()
- const result = await serverFetch(request, `organisation/member/${memberId}`, {
- method: 'DELETE',
- })
+ const result = await serverFetch(
+ request,
+ `organisation/member/${memberId}`,
+ {
+ method: 'DELETE',
+ },
+ )
if (result.error) {
- return data<OrganisationSettingsActionData>({ intent, error: result.error as string }, { status: 400 })
+ return data<OrganisationSettingsActionData>(
+ { intent, error: result.error as string },
+ { status: 400 },
+ )
}
return data<OrganisationSettingsActionData>(
@@ -170,13 +211,20 @@ export async function action({ request, params }: ActionFunctionArgs) {
const memberId = formData.get('memberId')?.toString()
const role = formData.get('role')?.toString()
- const result = await serverFetch(request, `organisation/member/${memberId}`, {
- method: 'PATCH',
- body: { role },
- })
+ const result = await serverFetch(
+ request,
+ `organisation/member/${memberId}`,
+ {
+ method: 'PATCH',
+ body: { role },
+ },
+ )
if (result.error) {
- return data<OrganisationSettingsActionData>({ intent, error: result.error as string }, { status: 400 })
+ return data<OrganisationSettingsActionData>(
+ { intent, error: result.error as string },
+ { status: 400 },
+ )
}
return data<OrganisationSettingsActionData>(
@@ -189,7 +237,10 @@ export async function action({ request, params }: ActionFunctionArgs) {
const projectId = formData.get('projectId')?.toString()
if (!projectId) {
- return data<OrganisationSettingsActionData>({ intent, error: 'Project ID is required' }, { status: 400 })
+ return data<OrganisationSettingsActionData>(
+ { intent, error: 'Project ID is required' },
+ { status: 400 },
+ )
}
const result = await serverFetch(request, `project/organisation/${id}`, {
@@ -198,7 +249,10 @@ export async function action({ request, params }: ActionFunctionArgs) {
})
if (result.error) {
- return data<OrganisationSettingsActionData>({ intent, error: result.error as string }, { status: 400 })
+ return data<OrganisationSettingsActionData>(
+ { intent, error: result.error as string },
+ { status: 400 },
+ )
}
return data<OrganisationSettingsActionData>(
@@ -211,15 +265,25 @@ export async function action({ request, params }: ActionFunctionArgs) {
const projectId = formData.get('projectId')?.toString()
if (!projectId) {
- return data<OrganisationSettingsActionData>({ intent, error: 'Project ID is required' }, { status: 400 })
+ return data<OrganisationSettingsActionData>(
+ { intent, error: 'Project ID is required' },
+ { status: 400 },
+ )
}
- const result = await serverFetch(request, `project/organisation/${id}/${projectId}`, {
- method: 'DELETE',
- })
+ const result = await serverFetch(
+ request,
+ `project/organisation/${id}/${projectId}`,
+ {
+ method: 'DELETE',
+ },
+ )
if (result.error) {
- return data<OrganisationSettingsActionData>({ intent, error: result.error as string }, { status: 400 })
+ return data<OrganisationSettingsActionData>(
+ { intent, error: result.error as string },
+ { status: 400 },
+ )
}
return data<OrganisationSettingsActionData>(
@@ -239,17 +303,27 @@ export async function action({ request, params }: ActionFunctionArgs) {
)
if (result.error) {
- return data<OrganisationSettingsActionData>({ intent, error: result.error as string }, { status: 400 })
+ return data<OrganisationSettingsActionData>(
+ { intent, error: result.error as string },
+ { status: 400 },
+ )
}
return data<OrganisationSettingsActionData>(
- { intent, success: true, availableProjects: result.data as AvailableProjectsResponse },
+ {
+ intent,
+ success: true,
+ availableProjects: result.data as AvailableProjectsResponse,
+ },
{ headers: createHeadersWithCookies(result.cookies) },
)
}
default:
- return data<OrganisationSettingsActionData>({ error: 'Unknown action' }, { status: 400 })
+ return data<OrganisationSettingsActionData>(
+ { error: 'Unknown action' },
+ { status: 400 },
+ )
}
}
diff --git a/web/app/routes/organisations._index.tsx b/web/app/routes/organisations._index.tsx
index 808d08df3..86fe83080 100644
--- a/web/app/routes/organisations._index.tsx
+++ b/web/app/routes/organisations._index.tsx
@@ -6,7 +6,10 @@ import { serverFetch } from '~/api/api.server'
import { ENTRIES_PER_PAGE_DASHBOARD, isSelfhosted } from '~/lib/constants'
import { DetailedOrganisation } from '~/lib/models/Organisation'
import Organisations from '~/pages/Organisations'
-import { redirectIfNotAuthenticated, createHeadersWithCookies } from '~/utils/session.server'
+import {
+ redirectIfNotAuthenticated,
+ createHeadersWithCookies,
+} from '~/utils/session.server'
export const sitemap: SitemapFunction = () => ({
exclude: true,
@@ -44,7 +47,13 @@ export async function loader({ request }: LoaderFunctionArgs) {
if (result.error) {
return data<OrganisationsLoaderData>(
- { organisations: [], total: 0, page, search, error: result.error as string },
+ {
+ organisations: [],
+ total: 0,
+ page,
+ search,
+ error: result.error as string,
+ },
{ status: 400, headers: createHeadersWithCookies(result.cookies) },
)
}
@@ -93,22 +102,38 @@ export async function action({ request }: ActionFunctionArgs) {
if (name.length > 50) {
return data<OrganisationsActionData>(
- { intent, fieldErrors: { name: 'Organisation name must be 50 characters or less' } },
+ {
+ intent,
+ fieldErrors: {
+ name: 'Organisation name must be 50 characters or less',
+ },
+ },
{ status: 400 },
)
}
- const result = await serverFetch<DetailedOrganisation>(request, 'organisation', {
- method: 'POST',
- body: { name: name.trim() },
- })
+ const result = await serverFetch<DetailedOrganisation>(
+ request,
+ 'organisation',
+ {
+ method: 'POST',
+ body: { name: name.trim() },
+ },
+ )
if (result.error) {
- return data<OrganisationsActionData>({ intent, error: result.error as string }, { status: 400 })
+ return data<OrganisationsActionData>(
+ { intent, error: result.error as string },
+ { status: 400 },
+ )
}
return data<OrganisationsActionData>(
- { intent, success: true, organisation: result.data as DetailedOrganisation },
+ {
+ intent,
+ success: true,
+ organisation: result.data as DetailedOrganisation,
+ },
{ headers: createHeadersWithCookies(result.cookies) },
)
}
@@ -117,15 +142,25 @@ export async function action({ request }: ActionFunctionArgs) {
const membershipId = formData.get('membershipId')?.toString()
if (!membershipId) {
- return data<OrganisationsActionData>({ intent, error: 'Membership ID is required' }, { status: 400 })
+ return data<OrganisationsActionData>(
+ { intent, error: 'Membership ID is required' },
+ { status: 400 },
+ )
}
- const result = await serverFetch(request, `user/organisation/${membershipId}`, {
- method: 'POST',
- })
+ const result = await serverFetch(
+ request,
+ `user/organisation/${membershipId}`,
+ {
+ method: 'POST',
+ },
+ )
if (result.error) {
- return data<OrganisationsActionData>({ intent, error: result.error as string }, { status: 400 })
+ return data<OrganisationsActionData>(
+ { intent, error: result.error as string },
+ { status: 400 },
+ )
}
return data<OrganisationsActionData>(
@@ -138,15 +173,25 @@ export async function action({ request }: ActionFunctionArgs) {
const membershipId = formData.get('membershipId')?.toString()
if (!membershipId) {
- return data<OrganisationsActionData>({ intent, error: 'Membership ID is required' }, { status: 400 })
+ return data<OrganisationsActionData>(
+ { intent, error: 'Membership ID is required' },
+ { status: 400 },
+ )
}
- const result = await serverFetch(request, `user/organisation/${membershipId}`, {
- method: 'DELETE',
- })
+ const result = await serverFetch(
+ request,
+ `user/organisation/${membershipId}`,
+ {
+ method: 'DELETE',
+ },
+ )
if (result.error) {
- return data<OrganisationsActionData>({ intent, error: result.error as string }, { status: 400 })
+ return data<OrganisationsActionData>(
+ { intent, error: result.error as string },
+ { status: 400 },
+ )
}
return data<OrganisationsActionData>(
@@ -156,7 +201,10 @@ export async function action({ request }: ActionFunctionArgs) {
}
default:
- return data<OrganisationsActionData>({ error: 'Unknown action' }, { status: 400 })
+ return data<OrganisationsActionData>(
+ { error: 'Unknown action' },
+ { status: 400 },
+ )
}
}
diff --git a/web/app/routes/password-reset.$id.tsx b/web/app/routes/password-reset.$id.tsx
index 76fdab618..f8773c27f 100644
--- a/web/app/routes/password-reset.$id.tsx
+++ b/web/app/routes/password-reset.$id.tsx
@@ -4,7 +4,11 @@ import type { SitemapFunction } from 'remix-sitemap'
import { serverFetch } from '~/api/api.server'
import CreateNewPassword from '~/pages/Auth/CreateNewPassword'
-import { isValidPassword, MIN_PASSWORD_CHARS, MAX_PASSWORD_CHARS } from '~/utils/validator'
+import {
+ isValidPassword,
+ MIN_PASSWORD_CHARS,
+ MAX_PASSWORD_CHARS,
+} from '~/utils/validator'
export const headers: HeadersFunction = ({ parentHeaders }) => {
parentHeaders.set('X-Frame-Options', 'DENY')
@@ -46,17 +50,27 @@ export async function action({ request, params }: ActionFunctionArgs) {
}
if (fieldErrors.password || fieldErrors.repeat) {
- return data<CreateNewPasswordActionData>({ fieldErrors, timestamp: Date.now() }, { status: 400 })
+ return data<CreateNewPasswordActionData>(
+ { fieldErrors, timestamp: Date.now() },
+ { status: 400 },
+ )
}
- const result = await serverFetch(request, `v1/auth/reset-password/confirm/${id}`, {
- method: 'POST',
- body: { newPassword: password },
- skipAuth: true,
- })
+ const result = await serverFetch(
+ request,
+ `v1/auth/reset-password/confirm/${id}`,
+ {
+ method: 'POST',
+ body: { newPassword: password },
+ skipAuth: true,
+ },
+ )
if (result.error) {
- return data<CreateNewPasswordActionData>({ error: result.error as string, timestamp: Date.now() }, { status: 400 })
+ return data<CreateNewPasswordActionData>(
+ { error: result.error as string, timestamp: Date.now() },
+ { status: 400 },
+ )
}
return redirect('/login?password_updated=true')
diff --git a/web/app/routes/pay.tsx b/web/app/routes/pay.tsx
index 9dd2cdbc9..924e338b1 100644
--- a/web/app/routes/pay.tsx
+++ b/web/app/routes/pay.tsx
@@ -54,7 +54,9 @@ export default function Index() {
return (
<div className='min-h-page bg-gray-50 dark:bg-slate-900'>
<div className='mx-auto px-4 pt-12 pb-16 sm:px-6 md:w-4/5 lg:px-8'>
- <h1 className='text-4xl font-bold text-gray-900 dark:text-gray-50'>Swetrix Payment</h1>
+ <h1 className='text-4xl font-bold text-gray-900 dark:text-gray-50'>
+ Swetrix Payment
+ </h1>
</div>
</div>
)
diff --git a/web/app/routes/project.transfer.cancel.tsx b/web/app/routes/project.transfer.cancel.tsx
index 4f8f93d2b..6eb3291b4 100644
--- a/web/app/routes/project.transfer.cancel.tsx
+++ b/web/app/routes/project.transfer.cancel.tsx
@@ -15,7 +15,9 @@ export interface TransferCancelLoaderData {
error?: string
}
-export async function loader({ request }: LoaderFunctionArgs): Promise<TransferCancelLoaderData> {
+export async function loader({
+ request,
+}: LoaderFunctionArgs): Promise<TransferCancelLoaderData> {
const url = new URL(request.url)
const token = url.searchParams.get('token')
@@ -28,7 +30,10 @@ export async function loader({ request }: LoaderFunctionArgs): Promise<TransferC
})
if (result.error) {
- const errorMessage = typeof result.error === 'string' ? result.error : 'Invalid or expired token'
+ const errorMessage =
+ typeof result.error === 'string'
+ ? result.error
+ : 'Invalid or expired token'
return { success: false, error: errorMessage }
}
diff --git a/web/app/routes/project.transfer.confirm.tsx b/web/app/routes/project.transfer.confirm.tsx
index 727a29ba3..2fff037de 100644
--- a/web/app/routes/project.transfer.confirm.tsx
+++ b/web/app/routes/project.transfer.confirm.tsx
@@ -15,7 +15,9 @@ export interface TransferConfirmLoaderData {
error?: string
}
-export async function loader({ request }: LoaderFunctionArgs): Promise<TransferConfirmLoaderData> {
+export async function loader({
+ request,
+}: LoaderFunctionArgs): Promise<TransferConfirmLoaderData> {
const url = new URL(request.url)
const token = url.searchParams.get('token')
@@ -26,7 +28,10 @@ export async function loader({ request }: LoaderFunctionArgs): Promise<TransferC
const result = await serverFetch(request, `project/transfer?token=${token}`)
if (result.error) {
- const errorMessage = typeof result.error === 'string' ? result.error : 'Invalid or expired token'
+ const errorMessage =
+ typeof result.error === 'string'
+ ? result.error
+ : 'Invalid or expired token'
return { success: false, error: errorMessage }
}
diff --git a/web/app/routes/projects.$id.subscribers.invite.tsx b/web/app/routes/projects.$id.subscribers.invite.tsx
index 608c88dec..686da3e33 100644
--- a/web/app/routes/projects.$id.subscribers.invite.tsx
+++ b/web/app/routes/projects.$id.subscribers.invite.tsx
@@ -15,7 +15,10 @@ export interface SubscriberInviteLoaderData {
error?: string
}
-export async function loader({ request, params }: LoaderFunctionArgs): Promise<SubscriberInviteLoaderData> {
+export async function loader({
+ request,
+ params,
+}: LoaderFunctionArgs): Promise<SubscriberInviteLoaderData> {
const { id } = params
const url = new URL(request.url)
const token = url.searchParams.get('token')
@@ -24,12 +27,19 @@ export async function loader({ request, params }: LoaderFunctionArgs): Promise<S
return { success: false, error: 'Invalid invitation link' }
}
- const result = await serverFetch(request, `project/${id}/subscribers/invite?token=${token}`, {
- skipAuth: true,
- })
+ const result = await serverFetch(
+ request,
+ `project/${id}/subscribers/invite?token=${token}`,
+ {
+ skipAuth: true,
+ },
+ )
if (result.error) {
- const errorMessage = typeof result.error === 'string' ? result.error : 'Invalid or expired token'
+ const errorMessage =
+ typeof result.error === 'string'
+ ? result.error
+ : 'Invalid or expired token'
return { success: false, error: errorMessage }
}
diff --git a/web/app/routes/projects.$id.tsx b/web/app/routes/projects.$id.tsx
index 7c2d7a230..0a3d90609 100644
--- a/web/app/routes/projects.$id.tsx
+++ b/web/app/routes/projects.$id.tsx
@@ -2,7 +2,12 @@ import _includes from 'lodash/includes'
import _some from 'lodash/some'
import _split from 'lodash/split'
import _startsWith from 'lodash/startsWith'
-import { type ActionFunctionArgs, type LinksFunction, type LoaderFunctionArgs, type MetaFunction } from 'react-router'
+import {
+ type ActionFunctionArgs,
+ type LinksFunction,
+ type LoaderFunctionArgs,
+ type MetaFunction,
+} from 'react-router'
import { data, redirect } from 'react-router'
import {
@@ -37,7 +42,12 @@ import {
type AnalyticsFilter,
} from '~/api/api.server'
import { useRequiredParams } from '~/hooks/useRequiredParams'
-import { API_URL, MAIN_URL, DEFAULT_TIMEZONE, PROJECT_TABS } from '~/lib/constants'
+import {
+ API_URL,
+ MAIN_URL,
+ DEFAULT_TIMEZONE,
+ PROJECT_TABS,
+} from '~/lib/constants'
import { Project } from '~/lib/models/Project'
import ViewProject from '~/pages/Project/View'
import { CurrentProjectProvider } from '~/providers/CurrentProjectProvider'
@@ -49,7 +59,9 @@ import {
createProjectPasswordCookie,
} from '~/utils/session.server'
-export const links: LinksFunction = () => [{ rel: 'stylesheet', href: ProjectViewStyle }]
+export const links: LinksFunction = () => [
+ { rel: 'stylesheet', href: ProjectViewStyle },
+]
export const meta: MetaFunction = ({ location }) => {
const { pathname } = location
@@ -95,7 +107,11 @@ const validDynamicFilters = ['ev:key:', 'tag:key:']
function isFilterValid(filter: string, checkDynamicFilters = false) {
let normalised = filter
- if (_startsWith(normalised, '!') || _startsWith(normalised, '~') || _startsWith(normalised, '^')) {
+ if (
+ _startsWith(normalised, '!') ||
+ _startsWith(normalised, '~') ||
+ _startsWith(normalised, '^')
+ ) {
normalised = normalised.substring(1)
}
@@ -103,7 +119,10 @@ function isFilterValid(filter: string, checkDynamicFilters = false) {
return true
}
- if (checkDynamicFilters && _some(validDynamicFilters, (prefix) => _startsWith(normalised, prefix))) {
+ if (
+ checkDynamicFilters &&
+ _some(validDynamicFilters, (prefix) => _startsWith(normalised, prefix))
+ ) {
return true
}
@@ -157,7 +176,9 @@ export interface ProjectLoaderData {
overallStats?: Promise<Record<string, OverallObject> | null>
trafficCompareData?: Promise<TrafficLogResponse | null>
overallCompareStats?: Promise<Record<string, OverallObject> | null>
- customEventsData?: Promise<{ chart?: { events?: Record<string, unknown> } } | null>
+ customEventsData?: Promise<{
+ chart?: { events?: Record<string, unknown> }
+ } | null>
// Performance data
perfData?: Promise<PerformanceDataResponse | null>
perfOverallStats?: Promise<Record<string, PerformanceOverallObject> | null>
@@ -197,8 +218,15 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
}
return data<ProjectLoaderData>(
- { project: null, isPasswordRequired: false, error: result.error as string },
- { status: result.status, headers: createHeadersWithCookies(result.cookies) },
+ {
+ project: null,
+ isPasswordRequired: false,
+ error: result.error as string,
+ },
+ {
+ status: result.status,
+ headers: createHeadersWithCookies(result.cookies),
+ },
)
}
@@ -217,7 +245,9 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
}
// Parse URL params for analytics data
- const tab = (url.searchParams.get('tab') as keyof typeof PROJECT_TABS) || PROJECT_TABS.traffic
+ const tab =
+ (url.searchParams.get('tab') as keyof typeof PROJECT_TABS) ||
+ PROJECT_TABS.traffic
const period = url.searchParams.get('period') || '7d'
const timeBucket = url.searchParams.get('timeBucket') || 'day'
const from = url.searchParams.get('from') || ''
@@ -236,7 +266,9 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
// Traffic custom events params
const customEventsParam = url.searchParams.get('customEvents') || ''
- const customEvents = customEventsParam ? customEventsParam.split(',').filter(Boolean) : []
+ const customEvents = customEventsParam
+ ? customEventsParam.split(',').filter(Boolean)
+ : []
const analyticsParams = {
timeBucket,
@@ -252,10 +284,16 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
let trafficData: Promise<TrafficLogResponse | null> | undefined
let overallStats: Promise<Record<string, OverallObject> | null> | undefined
let trafficCompareData: Promise<TrafficLogResponse | null> | undefined
- let overallCompareStats: Promise<Record<string, OverallObject> | null> | undefined
- let customEventsData: Promise<{ chart?: { events?: Record<string, unknown> } } | null> | undefined
+ let overallCompareStats:
+ | Promise<Record<string, OverallObject> | null>
+ | undefined
+ let customEventsData:
+ | Promise<{ chart?: { events?: Record<string, unknown> } } | null>
+ | undefined
let perfData: Promise<PerformanceDataResponse | null> | undefined
- let perfOverallStats: Promise<Record<string, PerformanceOverallObject> | null> | undefined
+ let perfOverallStats:
+ | Promise<Record<string, PerformanceOverallObject> | null>
+ | undefined
let sessionsData: Promise<SessionsResponse | null> | undefined
let sessionDetails: Promise<SessionDetailsResponse | null> | undefined
let errorsData: Promise<ErrorsResponse | null> | undefined
@@ -269,8 +307,16 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
// Only fetch data if project is valid and not locked
if (project && !project.isLocked && projectId) {
if (tab === PROJECT_TABS.traffic) {
- trafficData = getProjectDataServer(request, projectId, analyticsParams).then((res) => res.data)
- overallStats = getOverallStatsServer(request, [projectId], analyticsParams).then((res) => res.data)
+ trafficData = getProjectDataServer(
+ request,
+ projectId,
+ analyticsParams,
+ ).then((res) => res.data)
+ overallStats = getOverallStatsServer(
+ request,
+ [projectId],
+ analyticsParams,
+ ).then((res) => res.data)
// Fetch compare data if enabled
if (compareEnabled && compareFrom && compareTo) {
@@ -280,45 +326,88 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
from: compareFrom,
to: compareTo,
}
- trafficCompareData = getProjectDataServer(request, projectId, compareParams).then((res) => res.data)
- overallCompareStats = getOverallStatsServer(request, [projectId], compareParams).then((res) => res.data)
+ trafficCompareData = getProjectDataServer(
+ request,
+ projectId,
+ compareParams,
+ ).then((res) => res.data)
+ overallCompareStats = getOverallStatsServer(
+ request,
+ [projectId],
+ compareParams,
+ ).then((res) => res.data)
}
// Fetch custom events data if any custom events are selected
if (customEvents.length > 0) {
- customEventsData = getCustomEventsDataServer(request, projectId, analyticsParams, customEvents).then(
- (res) => res.data,
- )
+ customEventsData = getCustomEventsDataServer(
+ request,
+ projectId,
+ analyticsParams,
+ customEvents,
+ ).then((res) => res.data)
}
} else if (tab === PROJECT_TABS.performance) {
// Use measure from URL, or 'quantiles' if perfMetric is quantiles
- const effectiveMeasure = perfMetric === 'quantiles' ? 'quantiles' : measure
+ const effectiveMeasure =
+ perfMetric === 'quantiles' ? 'quantiles' : measure
const perfParams = { ...analyticsParams, measure: effectiveMeasure }
- perfData = getPerfDataServer(request, projectId, perfParams).then((res) => res.data)
- perfOverallStats = getPerformanceOverallStatsServer(request, [projectId], perfParams).then((res) => res.data)
+ perfData = getPerfDataServer(request, projectId, perfParams).then(
+ (res) => res.data,
+ )
+ perfOverallStats = getPerformanceOverallStatsServer(
+ request,
+ [projectId],
+ perfParams,
+ ).then((res) => res.data)
} else if (tab === PROJECT_TABS.sessions) {
- sessionsData = getSessionsServer(request, projectId, analyticsParams).then((res) => res.data)
+ sessionsData = getSessionsServer(
+ request,
+ projectId,
+ analyticsParams,
+ ).then((res) => res.data)
// Fetch session details if psid is in URL
const psid = url.searchParams.get('psid')
if (psid) {
- sessionDetails = getSessionServer(request, projectId, psid, timezone, password || undefined).then(
- (res) => res.data,
- )
+ sessionDetails = getSessionServer(
+ request,
+ projectId,
+ psid,
+ timezone,
+ password || undefined,
+ ).then((res) => res.data)
}
} else if (tab === PROJECT_TABS.errors) {
- errorsData = getErrorsServer(request, projectId, analyticsParams).then((res) => res.data)
- errorOverview = getErrorOverviewServer(request, projectId, analyticsParams).then((res) => res.data)
+ errorsData = getErrorsServer(request, projectId, analyticsParams).then(
+ (res) => res.data,
+ )
+ errorOverview = getErrorOverviewServer(
+ request,
+ projectId,
+ analyticsParams,
+ ).then((res) => res.data)
// Fetch error details if eid is in URL
const eid = url.searchParams.get('eid')
if (eid) {
- errorDetails = getErrorServer(request, projectId, eid, analyticsParams).then((res) => res.data)
+ errorDetails = getErrorServer(
+ request,
+ projectId,
+ eid,
+ analyticsParams,
+ ).then((res) => res.data)
}
} else if (tab === PROJECT_TABS.featureFlags) {
- featureFlagsData = getProjectFeatureFlagsServer(request, projectId).then((res) => res.data)
+ featureFlagsData = getProjectFeatureFlagsServer(request, projectId).then(
+ (res) => res.data,
+ )
} else if (tab === PROJECT_TABS.goals) {
- goalsData = getProjectGoalsServer(request, projectId).then((res) => res.data)
+ goalsData = getProjectGoalsServer(request, projectId).then(
+ (res) => res.data,
+ )
} else if (tab === PROJECT_TABS.alerts) {
- alertsData = getProjectAlertsServer(request, projectId).then((res) => res.data)
+ alertsData = getProjectAlertsServer(request, projectId).then(
+ (res) => res.data,
+ )
} else if (tab === PROJECT_TABS.funnels) {
// Fetch funnel data if funnelId is in URL
const funnelId = url.searchParams.get('funnelId')
@@ -393,7 +482,10 @@ export async function action({ request, params }: ActionFunctionArgs) {
})
if (result.error) {
- return data<ProjectViewActionData>({ intent, error: result.error as string }, { status: 400 })
+ return data<ProjectViewActionData>(
+ { intent, error: result.error as string },
+ { status: 400 },
+ )
}
return data<ProjectViewActionData>(
@@ -415,7 +507,10 @@ export async function action({ request, params }: ActionFunctionArgs) {
})
if (result.error) {
- return data<ProjectViewActionData>({ intent, error: result.error as string }, { status: 400 })
+ return data<ProjectViewActionData>(
+ { intent, error: result.error as string },
+ { status: 400 },
+ )
}
return data<ProjectViewActionData>(
@@ -432,7 +527,10 @@ export async function action({ request, params }: ActionFunctionArgs) {
})
if (result.error) {
- return data<ProjectViewActionData>({ intent, error: result.error as string }, { status: 400 })
+ return data<ProjectViewActionData>(
+ { intent, error: result.error as string },
+ { status: 400 },
+ )
}
return data<ProjectViewActionData>(
@@ -452,7 +550,10 @@ export async function action({ request, params }: ActionFunctionArgs) {
})
if (result.error) {
- return data<ProjectViewActionData>({ intent, error: result.error as string }, { status: 400 })
+ return data<ProjectViewActionData>(
+ { intent, error: result.error as string },
+ { status: 400 },
+ )
}
return data<ProjectViewActionData>(
@@ -472,7 +573,10 @@ export async function action({ request, params }: ActionFunctionArgs) {
})
if (result.error) {
- return data<ProjectViewActionData>({ intent, error: result.error as string }, { status: 400 })
+ return data<ProjectViewActionData>(
+ { intent, error: result.error as string },
+ { status: 400 },
+ )
}
return data<ProjectViewActionData>(
@@ -484,12 +588,19 @@ export async function action({ request, params }: ActionFunctionArgs) {
case 'delete-funnel': {
const funnelId = formData.get('funnelId')?.toString()
- const result = await serverFetch(request, `project/funnel/${funnelId}/${projectId}`, {
- method: 'DELETE',
- })
+ const result = await serverFetch(
+ request,
+ `project/funnel/${funnelId}/${projectId}`,
+ {
+ method: 'DELETE',
+ },
+ )
if (result.error) {
- return data<ProjectViewActionData>({ intent, error: result.error as string }, { status: 400 })
+ return data<ProjectViewActionData>(
+ { intent, error: result.error as string },
+ { status: 400 },
+ )
}
return data<ProjectViewActionData>(
@@ -501,13 +612,19 @@ export async function action({ request, params }: ActionFunctionArgs) {
// Alerts
case 'create-alert': {
const name = formData.get('name')?.toString() || ''
- const queryMetric = formData.get('queryMetric')?.toString() || 'page_views'
+ const queryMetric =
+ formData.get('queryMetric')?.toString() || 'page_views'
const queryCondition = formData.get('queryCondition')?.toString() || null
- const queryValue = formData.get('queryValue') ? Number(formData.get('queryValue')) : null
+ const queryValue = formData.get('queryValue')
+ ? Number(formData.get('queryValue'))
+ : null
const queryTime = formData.get('queryTime')?.toString() || null
- const queryCustomEvent = formData.get('queryCustomEvent')?.toString() || null
- const alertOnNewErrorsOnly = formData.get('alertOnNewErrorsOnly') === 'true'
- const alertOnEveryCustomEvent = formData.get('alertOnEveryCustomEvent') === 'true'
+ const queryCustomEvent =
+ formData.get('queryCustomEvent')?.toString() || null
+ const alertOnNewErrorsOnly =
+ formData.get('alertOnNewErrorsOnly') === 'true'
+ const alertOnEveryCustomEvent =
+ formData.get('alertOnEveryCustomEvent') === 'true'
const result = await serverFetch(request, 'alert', {
method: 'POST',
@@ -526,7 +643,10 @@ export async function action({ request, params }: ActionFunctionArgs) {
})
if (result.error) {
- return data<ProjectViewActionData>({ intent, error: result.error as string }, { status: 400 })
+ return data<ProjectViewActionData>(
+ { intent, error: result.error as string },
+ { status: 400 },
+ )
}
return data<ProjectViewActionData>(
@@ -541,9 +661,12 @@ export async function action({ request, params }: ActionFunctionArgs) {
const active = formData.get('active') === 'true'
const queryMetric = formData.get('queryMetric')?.toString()
const queryCondition = formData.get('queryCondition')?.toString() || null
- const queryValue = formData.get('queryValue') ? Number(formData.get('queryValue')) : null
+ const queryValue = formData.get('queryValue')
+ ? Number(formData.get('queryValue'))
+ : null
const queryTime = formData.get('queryTime')?.toString() || null
- const queryCustomEvent = formData.get('queryCustomEvent')?.toString() || null
+ const queryCustomEvent =
+ formData.get('queryCustomEvent')?.toString() || null
const alertOnNewErrorsOnly = formData.has('alertOnNewErrorsOnly')
? formData.get('alertOnNewErrorsOnly') === 'true'
: undefined
@@ -559,8 +682,10 @@ export async function action({ request, params }: ActionFunctionArgs) {
body.queryValue = queryValue
body.queryTime = queryTime
body.queryCustomEvent = queryCustomEvent
- if (alertOnNewErrorsOnly !== undefined) body.alertOnNewErrorsOnly = alertOnNewErrorsOnly
- if (alertOnEveryCustomEvent !== undefined) body.alertOnEveryCustomEvent = alertOnEveryCustomEvent
+ if (alertOnNewErrorsOnly !== undefined)
+ body.alertOnNewErrorsOnly = alertOnNewErrorsOnly
+ if (alertOnEveryCustomEvent !== undefined)
+ body.alertOnEveryCustomEvent = alertOnEveryCustomEvent
const result = await serverFetch(request, `alert/${alertId}`, {
method: 'PUT',
@@ -568,7 +693,10 @@ export async function action({ request, params }: ActionFunctionArgs) {
})
if (result.error) {
- return data<ProjectViewActionData>({ intent, error: result.error as string }, { status: 400 })
+ return data<ProjectViewActionData>(
+ { intent, error: result.error as string },
+ { status: 400 },
+ )
}
return data<ProjectViewActionData>(
@@ -585,7 +713,10 @@ export async function action({ request, params }: ActionFunctionArgs) {
})
if (result.error) {
- return data<ProjectViewActionData>({ intent, error: result.error as string }, { status: 400 })
+ return data<ProjectViewActionData>(
+ { intent, error: result.error as string },
+ { status: 400 },
+ )
}
return data<ProjectViewActionData>(
@@ -598,13 +729,20 @@ export async function action({ request, params }: ActionFunctionArgs) {
case 'get-annotations': {
const password = formData.get('password')?.toString() || ''
- const result = await serverFetch(request, `project/annotations/${projectId}`, {
- method: 'GET',
- headers: password ? { 'x-password': password } : undefined,
- })
+ const result = await serverFetch(
+ request,
+ `project/annotations/${projectId}`,
+ {
+ method: 'GET',
+ headers: password ? { 'x-password': password } : undefined,
+ },
+ )
if (result.error) {
- return data<ProjectViewActionData>({ intent, error: result.error as string }, { status: 400 })
+ return data<ProjectViewActionData>(
+ { intent, error: result.error as string },
+ { status: 400 },
+ )
}
return data<ProjectViewActionData>(
@@ -623,7 +761,10 @@ export async function action({ request, params }: ActionFunctionArgs) {
})
if (result.error) {
- return data<ProjectViewActionData>({ intent, error: result.error as string }, { status: 400 })
+ return data<ProjectViewActionData>(
+ { intent, error: result.error as string },
+ { status: 400 },
+ )
}
return data<ProjectViewActionData>(
@@ -643,7 +784,10 @@ export async function action({ request, params }: ActionFunctionArgs) {
})
if (result.error) {
- return data<ProjectViewActionData>({ intent, error: result.error as string }, { status: 400 })
+ return data<ProjectViewActionData>(
+ { intent, error: result.error as string },
+ { status: 400 },
+ )
}
return data<ProjectViewActionData>(
@@ -655,12 +799,19 @@ export async function action({ request, params }: ActionFunctionArgs) {
case 'delete-annotation': {
const annotationId = formData.get('annotationId')?.toString()
- const result = await serverFetch(request, `project/annotation/${annotationId}/${projectId}`, {
- method: 'DELETE',
- })
+ const result = await serverFetch(
+ request,
+ `project/annotation/${annotationId}/${projectId}`,
+ {
+ method: 'DELETE',
+ },
+ )
if (result.error) {
- return data<ProjectViewActionData>({ intent, error: result.error as string }, { status: 400 })
+ return data<ProjectViewActionData>(
+ { intent, error: result.error as string },
+ { status: 400 },
+ )
}
return data<ProjectViewActionData>(
@@ -679,7 +830,10 @@ export async function action({ request, params }: ActionFunctionArgs) {
})
if (result.error) {
- return data<ProjectViewActionData>({ intent, error: result.error as string }, { status: 400 })
+ return data<ProjectViewActionData>(
+ { intent, error: result.error as string },
+ { status: 400 },
+ )
}
return data<ProjectViewActionData>(
@@ -692,7 +846,9 @@ export async function action({ request, params }: ActionFunctionArgs) {
const name = formData.get('name')?.toString() || ''
const type = formData.get('type')?.toString() || 'traffic'
const filters = JSON.parse(formData.get('filters')?.toString() || '[]')
- const customEvents = JSON.parse(formData.get('customEvents')?.toString() || '[]')
+ const customEvents = JSON.parse(
+ formData.get('customEvents')?.toString() || '[]',
+ )
const result = await serverFetch(request, `project/${projectId}/views`, {
method: 'POST',
@@ -700,7 +856,10 @@ export async function action({ request, params }: ActionFunctionArgs) {
})
if (result.error) {
- return data<ProjectViewActionData>({ intent, error: result.error as string }, { status: 400 })
+ return data<ProjectViewActionData>(
+ { intent, error: result.error as string },
+ { status: 400 },
+ )
}
return data<ProjectViewActionData>(
@@ -713,15 +872,24 @@ export async function action({ request, params }: ActionFunctionArgs) {
const viewId = formData.get('viewId')?.toString()
const name = formData.get('name')?.toString() || ''
const filters = JSON.parse(formData.get('filters')?.toString() || '[]')
- const customEvents = JSON.parse(formData.get('customEvents')?.toString() || '[]')
+ const customEvents = JSON.parse(
+ formData.get('customEvents')?.toString() || '[]',
+ )
- const result = await serverFetch(request, `project/${projectId}/views/${viewId}`, {
- method: 'PATCH',
- body: { name, filters, customEvents },
- })
+ const result = await serverFetch(
+ request,
+ `project/${projectId}/views/${viewId}`,
+ {
+ method: 'PATCH',
+ body: { name, filters, customEvents },
+ },
+ )
if (result.error) {
- return data<ProjectViewActionData>({ intent, error: result.error as string }, { status: 400 })
+ return data<ProjectViewActionData>(
+ { intent, error: result.error as string },
+ { status: 400 },
+ )
}
return data<ProjectViewActionData>(
@@ -733,12 +901,19 @@ export async function action({ request, params }: ActionFunctionArgs) {
case 'delete-project-view': {
const viewId = formData.get('viewId')?.toString()
- const result = await serverFetch(request, `project/${projectId}/views/${viewId}`, {
- method: 'DELETE',
- })
+ const result = await serverFetch(
+ request,
+ `project/${projectId}/views/${viewId}`,
+ {
+ method: 'DELETE',
+ },
+ )
if (result.error) {
- return data<ProjectViewActionData>({ intent, error: result.error as string }, { status: 400 })
+ return data<ProjectViewActionData>(
+ { intent, error: result.error as string },
+ { status: 400 },
+ )
}
return data<ProjectViewActionData>(
@@ -751,12 +926,19 @@ export async function action({ request, params }: ActionFunctionArgs) {
case 'get-recent-ai-chats': {
const limit = Number(formData.get('limit') || '5')
- const result = await serverFetch(request, `ai/${projectId}/chats?limit=${limit}`, {
- method: 'GET',
- })
+ const result = await serverFetch(
+ request,
+ `ai/${projectId}/chats?limit=${limit}`,
+ {
+ method: 'GET',
+ },
+ )
if (result.error) {
- return data<ProjectViewActionData>({ intent, error: result.error as string }, { status: 400 })
+ return data<ProjectViewActionData>(
+ { intent, error: result.error as string },
+ { status: 400 },
+ )
}
return data<ProjectViewActionData>(
@@ -769,12 +951,19 @@ export async function action({ request, params }: ActionFunctionArgs) {
const skip = Number(formData.get('skip') || '0')
const take = Number(formData.get('take') || '20')
- const result = await serverFetch(request, `ai/${projectId}/chats/all?skip=${skip}&take=${take}`, {
- method: 'GET',
- })
+ const result = await serverFetch(
+ request,
+ `ai/${projectId}/chats/all?skip=${skip}&take=${take}`,
+ {
+ method: 'GET',
+ },
+ )
if (result.error) {
- return data<ProjectViewActionData>({ intent, error: result.error as string }, { status: 400 })
+ return data<ProjectViewActionData>(
+ { intent, error: result.error as string },
+ { status: 400 },
+ )
}
return data<ProjectViewActionData>(
@@ -786,12 +975,19 @@ export async function action({ request, params }: ActionFunctionArgs) {
case 'get-ai-chat': {
const chatId = formData.get('chatId')?.toString()
- const result = await serverFetch(request, `ai/${projectId}/chats/${chatId}`, {
- method: 'GET',
- })
+ const result = await serverFetch(
+ request,
+ `ai/${projectId}/chats/${chatId}`,
+ {
+ method: 'GET',
+ },
+ )
if (result.error) {
- return data<ProjectViewActionData>({ intent, error: result.error as string }, { status: 400 })
+ return data<ProjectViewActionData>(
+ { intent, error: result.error as string },
+ { status: 400 },
+ )
}
return data<ProjectViewActionData>(
@@ -810,7 +1006,10 @@ export async function action({ request, params }: ActionFunctionArgs) {
})
if (result.error) {
- return data<ProjectViewActionData>({ intent, error: result.error as string }, { status: 400 })
+ return data<ProjectViewActionData>(
+ { intent, error: result.error as string },
+ { status: 400 },
+ )
}
return data<ProjectViewActionData>(
@@ -821,20 +1020,29 @@ export async function action({ request, params }: ActionFunctionArgs) {
case 'update-ai-chat': {
const chatId = formData.get('chatId')?.toString()
- const messages = formData.get('messages') ? JSON.parse(formData.get('messages')!.toString()) : undefined
+ const messages = formData.get('messages')
+ ? JSON.parse(formData.get('messages')!.toString())
+ : undefined
const name = formData.get('name')?.toString()
const body: Record<string, unknown> = {}
if (messages) body.messages = messages
if (name !== undefined) body.name = name
- const result = await serverFetch(request, `ai/${projectId}/chats/${chatId}`, {
- method: 'POST',
- body,
- })
+ const result = await serverFetch(
+ request,
+ `ai/${projectId}/chats/${chatId}`,
+ {
+ method: 'POST',
+ body,
+ },
+ )
if (result.error) {
- return data<ProjectViewActionData>({ intent, error: result.error as string }, { status: 400 })
+ return data<ProjectViewActionData>(
+ { intent, error: result.error as string },
+ { status: 400 },
+ )
}
return data<ProjectViewActionData>(
@@ -846,12 +1054,19 @@ export async function action({ request, params }: ActionFunctionArgs) {
case 'delete-ai-chat': {
const chatId = formData.get('chatId')?.toString()
- const result = await serverFetch(request, `ai/${projectId}/chats/${chatId}`, {
- method: 'DELETE',
- })
+ const result = await serverFetch(
+ request,
+ `ai/${projectId}/chats/${chatId}`,
+ {
+ method: 'DELETE',
+ },
+ )
if (result.error) {
- return data<ProjectViewActionData>({ intent, error: result.error as string }, { status: 400 })
+ return data<ProjectViewActionData>(
+ { intent, error: result.error as string },
+ { status: 400 },
+ )
}
return data<ProjectViewActionData>(
@@ -866,15 +1081,25 @@ export async function action({ request, params }: ActionFunctionArgs) {
const skip = Number(formData.get('skip') || '0')
const search = formData.get('search')?.toString() || ''
- const params = new URLSearchParams({ take: String(take), skip: String(skip) })
+ const params = new URLSearchParams({
+ take: String(take),
+ skip: String(skip),
+ })
if (search) params.append('search', search)
- const result = await serverFetch(request, `feature-flag/project/${projectId}?${params.toString()}`, {
- method: 'GET',
- })
+ const result = await serverFetch(
+ request,
+ `feature-flag/project/${projectId}?${params.toString()}`,
+ {
+ method: 'GET',
+ },
+ )
if (result.error) {
- return data<ProjectViewActionData>({ intent, error: result.error as string }, { status: 400 })
+ return data<ProjectViewActionData>(
+ { intent, error: result.error as string },
+ { status: 400 },
+ )
}
return data<ProjectViewActionData>(
@@ -891,7 +1116,10 @@ export async function action({ request, params }: ActionFunctionArgs) {
})
if (result.error) {
- return data<ProjectViewActionData>({ intent, error: result.error as string }, { status: 400 })
+ return data<ProjectViewActionData>(
+ { intent, error: result.error as string },
+ { status: 400 },
+ )
}
return data<ProjectViewActionData>(
@@ -904,17 +1132,32 @@ export async function action({ request, params }: ActionFunctionArgs) {
const key = formData.get('key')?.toString() || ''
const description = formData.get('description')?.toString() || ''
const flagType = formData.get('flagType')?.toString() || 'boolean'
- const rolloutPercentage = Number(formData.get('rolloutPercentage') || '100')
- const targetingRules = JSON.parse(formData.get('targetingRules')?.toString() || '[]')
+ const rolloutPercentage = Number(
+ formData.get('rolloutPercentage') || '100',
+ )
+ const targetingRules = JSON.parse(
+ formData.get('targetingRules')?.toString() || '[]',
+ )
const enabled = formData.get('enabled') === 'true'
const result = await serverFetch(request, 'feature-flag', {
method: 'POST',
- body: { pid: projectId, key, description, flagType, rolloutPercentage, targetingRules, enabled },
+ body: {
+ pid: projectId,
+ key,
+ description,
+ flagType,
+ rolloutPercentage,
+ targetingRules,
+ enabled,
+ },
})
if (result.error) {
- return data<ProjectViewActionData>({ intent, error: result.error as string }, { status: 400 })
+ return data<ProjectViewActionData>(
+ { intent, error: result.error as string },
+ { status: 400 },
+ )
}
return data<ProjectViewActionData>(
@@ -934,13 +1177,16 @@ export async function action({ request, params }: ActionFunctionArgs) {
const targetingRules = formData.get('targetingRules')
? JSON.parse(formData.get('targetingRules')!.toString())
: undefined
- const enabled = formData.has('enabled') ? formData.get('enabled') === 'true' : undefined
+ const enabled = formData.has('enabled')
+ ? formData.get('enabled') === 'true'
+ : undefined
const body: Record<string, unknown> = {}
if (key !== undefined) body.key = key
if (description !== undefined) body.description = description
if (flagType !== undefined) body.flagType = flagType
- if (rolloutPercentage !== undefined) body.rolloutPercentage = rolloutPercentage
+ if (rolloutPercentage !== undefined)
+ body.rolloutPercentage = rolloutPercentage
if (targetingRules !== undefined) body.targetingRules = targetingRules
if (enabled !== undefined) body.enabled = enabled
@@ -950,7 +1196,10 @@ export async function action({ request, params }: ActionFunctionArgs) {
})
if (result.error) {
- return data<ProjectViewActionData>({ intent, error: result.error as string }, { status: 400 })
+ return data<ProjectViewActionData>(
+ { intent, error: result.error as string },
+ { status: 400 },
+ )
}
return data<ProjectViewActionData>(
@@ -967,7 +1216,10 @@ export async function action({ request, params }: ActionFunctionArgs) {
})
if (result.error) {
- return data<ProjectViewActionData>({ intent, error: result.error as string }, { status: 400 })
+ return data<ProjectViewActionData>(
+ { intent, error: result.error as string },
+ { status: 400 },
+ )
}
return data<ProjectViewActionData>(
@@ -988,12 +1240,19 @@ export async function action({ request, params }: ActionFunctionArgs) {
if (toDate) params.append('to', toDate)
if (tz) params.append('timezone', tz)
- const result = await serverFetch(request, `feature-flag/${flagId}/stats?${params.toString()}`, {
- method: 'GET',
- })
+ const result = await serverFetch(
+ request,
+ `feature-flag/${flagId}/stats?${params.toString()}`,
+ {
+ method: 'GET',
+ },
+ )
if (result.error) {
- return data<ProjectViewActionData>({ intent, error: result.error as string }, { status: 400 })
+ return data<ProjectViewActionData>(
+ { intent, error: result.error as string },
+ { status: 400 },
+ )
}
return data<ProjectViewActionData>(
@@ -1012,23 +1271,43 @@ export async function action({ request, params }: ActionFunctionArgs) {
const skip = Number(formData.get('skip') || '0')
const resultFilter = formData.get('result')?.toString() || ''
- const params = new URLSearchParams({ period, take: String(take), skip: String(skip) })
+ const params = new URLSearchParams({
+ period,
+ take: String(take),
+ skip: String(skip),
+ })
if (fromDate) params.append('from', fromDate)
if (toDate) params.append('to', toDate)
if (tz) params.append('timezone', tz)
- if (resultFilter && resultFilter !== 'all') params.append('result', resultFilter)
+ if (resultFilter && resultFilter !== 'all')
+ params.append('result', resultFilter)
- const result = await serverFetch(request, `feature-flag/${flagId}/profiles?${params.toString()}`, {
- method: 'GET',
- })
+ const result = await serverFetch(
+ request,
+ `feature-flag/${flagId}/profiles?${params.toString()}`,
+ {
+ method: 'GET',
+ },
+ )
if (result.error) {
- return data<ProjectViewActionData>({ intent, error: result.error as string }, { status: 400 })
+ return data<ProjectViewActionData>(
+ { intent, error: result.error as string },
+ { status: 400 },
+ )
}
const profilesData = result.data as { profiles: unknown[]; total: number }
return data<ProjectViewActionData>(
- { intent, success: true, data: { flagId, profiles: profilesData.profiles, total: profilesData.total } },
+ {
+ intent,
+ success: true,
+ data: {
+ flagId,
+ profiles: profilesData.profiles,
+ total: profilesData.total,
+ },
+ },
{ headers: createHeadersWithCookies(result.cookies) },
)
}
@@ -1039,15 +1318,25 @@ export async function action({ request, params }: ActionFunctionArgs) {
const skip = Number(formData.get('skip') || '0')
const search = formData.get('search')?.toString() || ''
- const params = new URLSearchParams({ take: String(take), skip: String(skip) })
+ const params = new URLSearchParams({
+ take: String(take),
+ skip: String(skip),
+ })
if (search) params.append('search', search)
- const result = await serverFetch(request, `experiment/project/${projectId}?${params.toString()}`, {
- method: 'GET',
- })
+ const result = await serverFetch(
+ request,
+ `experiment/project/${projectId}?${params.toString()}`,
+ {
+ method: 'GET',
+ },
+ )
if (result.error) {
- return data<ProjectViewActionData>({ intent, error: result.error as string }, { status: 400 })
+ return data<ProjectViewActionData>(
+ { intent, error: result.error as string },
+ { status: 400 },
+ )
}
return data<ProjectViewActionData>(
@@ -1064,7 +1353,10 @@ export async function action({ request, params }: ActionFunctionArgs) {
})
if (result.error) {
- return data<ProjectViewActionData>({ intent, error: result.error as string }, { status: 400 })
+ return data<ProjectViewActionData>(
+ { intent, error: result.error as string },
+ { status: 400 },
+ )
}
return data<ProjectViewActionData>(
@@ -1077,13 +1369,17 @@ export async function action({ request, params }: ActionFunctionArgs) {
const name = formData.get('name')?.toString() || ''
const description = formData.get('description')?.toString() || ''
const hypothesis = formData.get('hypothesis')?.toString() || ''
- const exposureTrigger = formData.get('exposureTrigger')?.toString() || 'feature_flag'
+ const exposureTrigger =
+ formData.get('exposureTrigger')?.toString() || 'feature_flag'
const customEventName = formData.get('customEventName')?.toString() || ''
- const multipleVariantHandling = formData.get('multipleVariantHandling')?.toString() || 'exclude'
+ const multipleVariantHandling =
+ formData.get('multipleVariantHandling')?.toString() || 'exclude'
const filterInternalUsers = formData.get('filterInternalUsers') === 'true'
- const featureFlagMode = formData.get('featureFlagMode')?.toString() || 'create'
+ const featureFlagMode =
+ formData.get('featureFlagMode')?.toString() || 'create'
const featureFlagKey = formData.get('featureFlagKey')?.toString() || ''
- const existingFeatureFlagId = formData.get('existingFeatureFlagId')?.toString() || ''
+ const existingFeatureFlagId =
+ formData.get('existingFeatureFlagId')?.toString() || ''
const goalId = formData.get('goalId')?.toString() || ''
const variants = JSON.parse(formData.get('variants')?.toString() || '[]')
@@ -1096,11 +1392,13 @@ export async function action({ request, params }: ActionFunctionArgs) {
if (hypothesis) body.hypothesis = hypothesis
if (exposureTrigger) body.exposureTrigger = exposureTrigger
if (customEventName) body.customEventName = customEventName
- if (multipleVariantHandling) body.multipleVariantHandling = multipleVariantHandling
+ if (multipleVariantHandling)
+ body.multipleVariantHandling = multipleVariantHandling
body.filterInternalUsers = filterInternalUsers
if (featureFlagMode) body.featureFlagMode = featureFlagMode
if (featureFlagKey) body.featureFlagKey = featureFlagKey
- if (existingFeatureFlagId) body.existingFeatureFlagId = existingFeatureFlagId
+ if (existingFeatureFlagId)
+ body.existingFeatureFlagId = existingFeatureFlagId
if (goalId) body.goalId = goalId
const result = await serverFetch(request, 'experiment', {
@@ -1109,7 +1407,10 @@ export async function action({ request, params }: ActionFunctionArgs) {
})
if (result.error) {
- return data<ProjectViewActionData>({ intent, error: result.error as string }, { status: 400 })
+ return data<ProjectViewActionData>(
+ { intent, error: result.error as string },
+ { status: 400 },
+ )
}
return data<ProjectViewActionData>(
@@ -1125,15 +1426,21 @@ export async function action({ request, params }: ActionFunctionArgs) {
const hypothesis = formData.get('hypothesis')?.toString()
const exposureTrigger = formData.get('exposureTrigger')?.toString()
const customEventName = formData.get('customEventName')?.toString()
- const multipleVariantHandling = formData.get('multipleVariantHandling')?.toString()
+ const multipleVariantHandling = formData
+ .get('multipleVariantHandling')
+ ?.toString()
const filterInternalUsers = formData.has('filterInternalUsers')
? formData.get('filterInternalUsers') === 'true'
: undefined
const featureFlagMode = formData.get('featureFlagMode')?.toString()
const featureFlagKey = formData.get('featureFlagKey')?.toString()
- const existingFeatureFlagId = formData.get('existingFeatureFlagId')?.toString()
+ const existingFeatureFlagId = formData
+ .get('existingFeatureFlagId')
+ ?.toString()
const goalId = formData.get('goalId')?.toString()
- const variants = formData.get('variants') ? JSON.parse(formData.get('variants')!.toString()) : undefined
+ const variants = formData.get('variants')
+ ? JSON.parse(formData.get('variants')!.toString())
+ : undefined
const body: Record<string, unknown> = {}
if (name !== undefined) body.name = name
@@ -1141,11 +1448,14 @@ export async function action({ request, params }: ActionFunctionArgs) {
if (hypothesis !== undefined) body.hypothesis = hypothesis
if (exposureTrigger !== undefined) body.exposureTrigger = exposureTrigger
if (customEventName !== undefined) body.customEventName = customEventName
- if (multipleVariantHandling !== undefined) body.multipleVariantHandling = multipleVariantHandling
- if (filterInternalUsers !== undefined) body.filterInternalUsers = filterInternalUsers
+ if (multipleVariantHandling !== undefined)
+ body.multipleVariantHandling = multipleVariantHandling
+ if (filterInternalUsers !== undefined)
+ body.filterInternalUsers = filterInternalUsers
if (featureFlagMode !== undefined) body.featureFlagMode = featureFlagMode
if (featureFlagKey !== undefined) body.featureFlagKey = featureFlagKey
- if (existingFeatureFlagId !== undefined) body.existingFeatureFlagId = existingFeatureFlagId
+ if (existingFeatureFlagId !== undefined)
+ body.existingFeatureFlagId = existingFeatureFlagId
if (goalId !== undefined) body.goalId = goalId
if (variants !== undefined) body.variants = variants
@@ -1155,7 +1465,10 @@ export async function action({ request, params }: ActionFunctionArgs) {
})
if (result.error) {
- return data<ProjectViewActionData>({ intent, error: result.error as string }, { status: 400 })
+ return data<ProjectViewActionData>(
+ { intent, error: result.error as string },
+ { status: 400 },
+ )
}
return data<ProjectViewActionData>(
@@ -1172,7 +1485,10 @@ export async function action({ request, params }: ActionFunctionArgs) {
})
if (result.error) {
- return data<ProjectViewActionData>({ intent, error: result.error as string }, { status: 400 })
+ return data<ProjectViewActionData>(
+ { intent, error: result.error as string },
+ { status: 400 },
+ )
}
return data<ProjectViewActionData>(
@@ -1184,12 +1500,19 @@ export async function action({ request, params }: ActionFunctionArgs) {
case 'start-experiment': {
const experimentId = formData.get('experimentId')?.toString()
- const result = await serverFetch(request, `experiment/${experimentId}/start`, {
- method: 'POST',
- })
+ const result = await serverFetch(
+ request,
+ `experiment/${experimentId}/start`,
+ {
+ method: 'POST',
+ },
+ )
if (result.error) {
- return data<ProjectViewActionData>({ intent, error: result.error as string }, { status: 400 })
+ return data<ProjectViewActionData>(
+ { intent, error: result.error as string },
+ { status: 400 },
+ )
}
return data<ProjectViewActionData>(
@@ -1201,12 +1524,19 @@ export async function action({ request, params }: ActionFunctionArgs) {
case 'pause-experiment': {
const experimentId = formData.get('experimentId')?.toString()
- const result = await serverFetch(request, `experiment/${experimentId}/pause`, {
- method: 'POST',
- })
+ const result = await serverFetch(
+ request,
+ `experiment/${experimentId}/pause`,
+ {
+ method: 'POST',
+ },
+ )
if (result.error) {
- return data<ProjectViewActionData>({ intent, error: result.error as string }, { status: 400 })
+ return data<ProjectViewActionData>(
+ { intent, error: result.error as string },
+ { status: 400 },
+ )
}
return data<ProjectViewActionData>(
@@ -1218,12 +1548,19 @@ export async function action({ request, params }: ActionFunctionArgs) {
case 'complete-experiment': {
const experimentId = formData.get('experimentId')?.toString()
- const result = await serverFetch(request, `experiment/${experimentId}/complete`, {
- method: 'POST',
- })
+ const result = await serverFetch(
+ request,
+ `experiment/${experimentId}/complete`,
+ {
+ method: 'POST',
+ },
+ )
if (result.error) {
- return data<ProjectViewActionData>({ intent, error: result.error as string }, { status: 400 })
+ return data<ProjectViewActionData>(
+ { intent, error: result.error as string },
+ { status: 400 },
+ )
}
return data<ProjectViewActionData>(
@@ -1245,12 +1582,19 @@ export async function action({ request, params }: ActionFunctionArgs) {
if (toDate) params.append('to', toDate)
if (tz) params.append('timezone', tz)
- const result = await serverFetch(request, `experiment/${experimentId}/results?${params.toString()}`, {
- method: 'GET',
- })
+ const result = await serverFetch(
+ request,
+ `experiment/${experimentId}/results?${params.toString()}`,
+ {
+ method: 'GET',
+ },
+ )
if (result.error) {
- return data<ProjectViewActionData>({ intent, error: result.error as string }, { status: 400 })
+ return data<ProjectViewActionData>(
+ { intent, error: result.error as string },
+ { status: 400 },
+ )
}
return data<ProjectViewActionData>(
@@ -1265,15 +1609,25 @@ export async function action({ request, params }: ActionFunctionArgs) {
const skip = Number(formData.get('skip') || '0')
const search = formData.get('search')?.toString() || ''
- const params = new URLSearchParams({ take: String(take), skip: String(skip) })
+ const params = new URLSearchParams({
+ take: String(take),
+ skip: String(skip),
+ })
if (search) params.append('search', search)
- const result = await serverFetch(request, `goal/project/${projectId}?${params.toString()}`, {
- method: 'GET',
- })
+ const result = await serverFetch(
+ request,
+ `goal/project/${projectId}?${params.toString()}`,
+ {
+ method: 'GET',
+ },
+ )
if (result.error) {
- return data<ProjectViewActionData>({ intent, error: result.error as string }, { status: 400 })
+ return data<ProjectViewActionData>(
+ { intent, error: result.error as string },
+ { status: 400 },
+ )
}
return data<ProjectViewActionData>(
@@ -1290,7 +1644,10 @@ export async function action({ request, params }: ActionFunctionArgs) {
})
if (result.error) {
- return data<ProjectViewActionData>({ intent, error: result.error as string }, { status: 400 })
+ return data<ProjectViewActionData>(
+ { intent, error: result.error as string },
+ { status: 400 },
+ )
}
return data<ProjectViewActionData>(
@@ -1311,12 +1668,19 @@ export async function action({ request, params }: ActionFunctionArgs) {
if (toDate) params.append('to', toDate)
if (tz) params.append('timezone', tz)
- const result = await serverFetch(request, `goal/${goalId}/stats?${params.toString()}`, {
- method: 'GET',
- })
+ const result = await serverFetch(
+ request,
+ `goal/${goalId}/stats?${params.toString()}`,
+ {
+ method: 'GET',
+ },
+ )
if (result.error) {
- return data<ProjectViewActionData>({ intent, error: result.error as string }, { status: 400 })
+ return data<ProjectViewActionData>(
+ { intent, error: result.error as string },
+ { status: 400 },
+ )
}
return data<ProjectViewActionData>(
@@ -1338,12 +1702,19 @@ export async function action({ request, params }: ActionFunctionArgs) {
if (toDate) params.append('to', toDate)
if (tz) params.append('timezone', tz)
- const result = await serverFetch(request, `goal/${goalId}/chart?${params.toString()}`, {
- method: 'GET',
- })
+ const result = await serverFetch(
+ request,
+ `goal/${goalId}/chart?${params.toString()}`,
+ {
+ method: 'GET',
+ },
+ )
if (result.error) {
- return data<ProjectViewActionData>({ intent, error: result.error as string }, { status: 400 })
+ return data<ProjectViewActionData>(
+ { intent, error: result.error as string },
+ { status: 400 },
+ )
}
return data<ProjectViewActionData>(
@@ -1356,13 +1727,20 @@ export async function action({ request, params }: ActionFunctionArgs) {
case 'get-funnels': {
const password = formData.get('password')?.toString() || ''
- const result = await serverFetch(request, `project/funnels/${projectId}`, {
- method: 'GET',
- headers: password ? { 'x-password': password } : undefined,
- })
+ const result = await serverFetch(
+ request,
+ `project/funnels/${projectId}`,
+ {
+ method: 'GET',
+ headers: password ? { 'x-password': password } : undefined,
+ },
+ )
if (result.error) {
- return data<ProjectViewActionData>({ intent, error: result.error as string }, { status: 400 })
+ return data<ProjectViewActionData>(
+ { intent, error: result.error as string },
+ { status: 400 },
+ )
}
return data<ProjectViewActionData>(
@@ -1386,13 +1764,20 @@ export async function action({ request, params }: ActionFunctionArgs) {
if (tz) params.append('timezone', tz)
if (funnelId) params.append('funnelId', funnelId)
- const result = await serverFetch(request, `log/funnel?${params.toString()}`, {
- method: 'GET',
- headers: password ? { 'x-password': password } : undefined,
- })
+ const result = await serverFetch(
+ request,
+ `log/funnel?${params.toString()}`,
+ {
+ method: 'GET',
+ headers: password ? { 'x-password': password } : undefined,
+ },
+ )
if (result.error) {
- return data<ProjectViewActionData>({ intent, error: result.error as string }, { status: 400 })
+ return data<ProjectViewActionData>(
+ { intent, error: result.error as string },
+ { status: 400 },
+ )
}
return data<ProjectViewActionData>(
@@ -1406,12 +1791,19 @@ export async function action({ request, params }: ActionFunctionArgs) {
const take = Number(formData.get('take') || '25')
const skip = Number(formData.get('skip') || '0')
- const result = await serverFetch(request, `alert/project/${projectId}?take=${take}&skip=${skip}`, {
- method: 'GET',
- })
+ const result = await serverFetch(
+ request,
+ `alert/project/${projectId}?take=${take}&skip=${skip}`,
+ {
+ method: 'GET',
+ },
+ )
if (result.error) {
- return data<ProjectViewActionData>({ intent, error: result.error as string }, { status: 400 })
+ return data<ProjectViewActionData>(
+ { intent, error: result.error as string },
+ { status: 400 },
+ )
}
return data<ProjectViewActionData>(
@@ -1428,7 +1820,10 @@ export async function action({ request, params }: ActionFunctionArgs) {
})
if (result.error) {
- return data<ProjectViewActionData>({ intent, error: result.error as string }, { status: 400 })
+ return data<ProjectViewActionData>(
+ { intent, error: result.error as string },
+ { status: 400 },
+ )
}
return data<ProjectViewActionData>(
@@ -1442,13 +1837,20 @@ export async function action({ request, params }: ActionFunctionArgs) {
const filterType = formData.get('type')?.toString() || ''
const password = formData.get('password')?.toString() || ''
- const result = await serverFetch(request, `log/filters?pid=${projectId}&type=${filterType}`, {
- method: 'GET',
- headers: password ? { 'x-password': password } : undefined,
- })
+ const result = await serverFetch(
+ request,
+ `log/filters?pid=${projectId}&type=${filterType}`,
+ {
+ method: 'GET',
+ headers: password ? { 'x-password': password } : undefined,
+ },
+ )
if (result.error) {
- return data<ProjectViewActionData>({ intent, error: result.error as string }, { status: 400 })
+ return data<ProjectViewActionData>(
+ { intent, error: result.error as string },
+ { status: 400 },
+ )
}
return data<ProjectViewActionData>(
@@ -1461,13 +1863,20 @@ export async function action({ request, params }: ActionFunctionArgs) {
const filterType = formData.get('type')?.toString() || ''
const password = formData.get('password')?.toString() || ''
- const result = await serverFetch(request, `log/errors-filters?pid=${projectId}&type=${filterType}`, {
- method: 'GET',
- headers: password ? { 'x-password': password } : undefined,
- })
+ const result = await serverFetch(
+ request,
+ `log/errors-filters?pid=${projectId}&type=${filterType}`,
+ {
+ method: 'GET',
+ headers: password ? { 'x-password': password } : undefined,
+ },
+ )
if (result.error) {
- return data<ProjectViewActionData>({ intent, error: result.error as string }, { status: 400 })
+ return data<ProjectViewActionData>(
+ { intent, error: result.error as string },
+ { status: 400 },
+ )
}
return data<ProjectViewActionData>(
@@ -1491,7 +1900,10 @@ export async function action({ request, params }: ActionFunctionArgs) {
)
if (result.error) {
- return data<ProjectViewActionData>({ intent, error: result.error as string }, { status: 400 })
+ return data<ProjectViewActionData>(
+ { intent, error: result.error as string },
+ { status: 400 },
+ )
}
return data<ProjectViewActionData>(
@@ -1503,7 +1915,9 @@ export async function action({ request, params }: ActionFunctionArgs) {
// Error status update
case 'update-error-status': {
const eid = formData.get('eid')?.toString()
- const eids = formData.get('eids') ? JSON.parse(formData.get('eids')!.toString()) : undefined
+ const eids = formData.get('eids')
+ ? JSON.parse(formData.get('eids')!.toString())
+ : undefined
const status = formData.get('status')?.toString() || 'active'
const result = await serverFetch(request, 'log/error-status', {
@@ -1512,7 +1926,10 @@ export async function action({ request, params }: ActionFunctionArgs) {
})
if (result.error) {
- return data<ProjectViewActionData>({ intent, error: result.error as string }, { status: 400 })
+ return data<ProjectViewActionData>(
+ { intent, error: result.error as string },
+ { status: 400 },
+ )
}
return data<ProjectViewActionData>(
@@ -1531,7 +1948,10 @@ export async function action({ request, params }: ActionFunctionArgs) {
})
if (result.error) {
- return data<ProjectViewActionData>({ intent, error: result.error as string }, { status: result.status })
+ return data<ProjectViewActionData>(
+ { intent, error: result.error as string },
+ { status: result.status },
+ )
}
return data<ProjectViewActionData>(
@@ -1543,13 +1963,20 @@ export async function action({ request, params }: ActionFunctionArgs) {
case 'check-password': {
const password = formData.get('password')?.toString() || ''
- const result = await serverFetch<boolean>(request, `project/password/${projectId}`, {
- method: 'GET',
- headers: { 'x-password': password },
- })
+ const result = await serverFetch<boolean>(
+ request,
+ `project/password/${projectId}`,
+ {
+ method: 'GET',
+ headers: { 'x-password': password },
+ },
+ )
if (result.error) {
- return data<ProjectViewActionData>({ intent, error: result.error as string }, { status: 400 })
+ return data<ProjectViewActionData>(
+ { intent, error: result.error as string },
+ { status: 400 },
+ )
}
return data<ProjectViewActionData>(
@@ -1559,7 +1986,10 @@ export async function action({ request, params }: ActionFunctionArgs) {
}
default:
- return data<ProjectViewActionData>({ error: 'Unknown action' }, { status: 400 })
+ return data<ProjectViewActionData>(
+ { error: 'Unknown action' },
+ { status: 400 },
+ )
}
}
diff --git a/web/app/routes/projects.settings.$id.tsx b/web/app/routes/projects.settings.$id.tsx
index 39309abc9..279d0b327 100644
--- a/web/app/routes/projects.settings.$id.tsx
+++ b/web/app/routes/projects.settings.$id.tsx
@@ -5,7 +5,10 @@ import { serverFetch } from '~/api/api.server'
import { Project } from '~/lib/models/Project'
import { Subscriber } from '~/lib/models/Subscriber'
import ProjectSettings from '~/pages/Project/Settings'
-import { redirectIfNotAuthenticated, createHeadersWithCookies } from '~/utils/session.server'
+import {
+ redirectIfNotAuthenticated,
+ createHeadersWithCookies,
+} from '~/utils/session.server'
export async function loader({ request, params }: LoaderFunctionArgs) {
redirectIfNotAuthenticated(request)
@@ -85,7 +88,9 @@ export async function action({ request, params }: ActionFunctionArgs) {
const password = formData.get('password')?.toString()
const origins = formData.get('origins')?.toString()
const ipBlacklist = formData.get('ipBlacklist')?.toString()
- const botsProtectionLevel = formData.get('botsProtectionLevel')?.toString()
+ const botsProtectionLevel = formData
+ .get('botsProtectionLevel')
+ ?.toString()
const countryBlacklist = formData.get('countryBlacklist')?.toString()
const websiteUrl = formData.get('websiteUrl')?.toString()
const captchaDifficulty = formData.get('captchaDifficulty')?.toString()
@@ -97,7 +102,10 @@ export async function action({ request, params }: ActionFunctionArgs) {
}
if (fieldErrors.name) {
- return data<ProjectSettingsActionData>({ intent, fieldErrors }, { status: 400 })
+ return data<ProjectSettingsActionData>(
+ { intent, fieldErrors },
+ { status: 400 },
+ )
}
const updateData: Record<string, unknown> = {}
@@ -105,14 +113,23 @@ export async function action({ request, params }: ActionFunctionArgs) {
updateData.public = isPublic
updateData.isPasswordProtected = isPasswordProtected
if (password !== undefined) updateData.password = password
- if (origins !== undefined) updateData.origins = origins ? origins.split(',').map((o) => o.trim()) : null
+ if (origins !== undefined)
+ updateData.origins = origins
+ ? origins.split(',').map((o) => o.trim())
+ : null
if (ipBlacklist !== undefined)
- updateData.ipBlacklist = ipBlacklist ? ipBlacklist.split(',').map((ip) => ip.trim()) : null
- if (botsProtectionLevel !== undefined) updateData.botsProtectionLevel = botsProtectionLevel
+ updateData.ipBlacklist = ipBlacklist
+ ? ipBlacklist.split(',').map((ip) => ip.trim())
+ : null
+ if (botsProtectionLevel !== undefined)
+ updateData.botsProtectionLevel = botsProtectionLevel
if (countryBlacklist !== undefined)
- updateData.countryBlacklist = countryBlacklist ? JSON.parse(countryBlacklist) : []
+ updateData.countryBlacklist = countryBlacklist
+ ? JSON.parse(countryBlacklist)
+ : []
if (websiteUrl !== undefined) updateData.websiteUrl = websiteUrl || null
- if (captchaDifficulty !== undefined) updateData.captchaDifficulty = Number(captchaDifficulty)
+ if (captchaDifficulty !== undefined)
+ updateData.captchaDifficulty = Number(captchaDifficulty)
const result = await serverFetch<Project>(request, `project/${id}`, {
method: 'PUT',
@@ -120,7 +137,10 @@ export async function action({ request, params }: ActionFunctionArgs) {
})
if (result.error) {
- return data<ProjectSettingsActionData>({ intent, error: result.error as string }, { status: 400 })
+ return data<ProjectSettingsActionData>(
+ { intent, error: result.error as string },
+ { status: 400 },
+ )
}
return data<ProjectSettingsActionData>(
@@ -135,7 +155,10 @@ export async function action({ request, params }: ActionFunctionArgs) {
})
if (result.error) {
- return data<ProjectSettingsActionData>({ intent, error: result.error as string }, { status: 400 })
+ return data<ProjectSettingsActionData>(
+ { intent, error: result.error as string },
+ { status: 400 },
+ )
}
return data<ProjectSettingsActionData>(
@@ -150,7 +173,10 @@ export async function action({ request, params }: ActionFunctionArgs) {
})
if (result.error) {
- return data<ProjectSettingsActionData>({ intent, error: result.error as string }, { status: 400 })
+ return data<ProjectSettingsActionData>(
+ { intent, error: result.error as string },
+ { status: 400 },
+ )
}
return data<ProjectSettingsActionData>(
@@ -169,7 +195,10 @@ export async function action({ request, params }: ActionFunctionArgs) {
})
if (result.error) {
- return data<ProjectSettingsActionData>({ intent, error: result.error as string }, { status: 400 })
+ return data<ProjectSettingsActionData>(
+ { intent, error: result.error as string },
+ { status: 400 },
+ )
}
return data<ProjectSettingsActionData>(
@@ -191,7 +220,10 @@ export async function action({ request, params }: ActionFunctionArgs) {
)
if (result.error) {
- return data<ProjectSettingsActionData>({ intent, error: result.error as string }, { status: 400 })
+ return data<ProjectSettingsActionData>(
+ { intent, error: result.error as string },
+ { status: 400 },
+ )
}
return data<ProjectSettingsActionData>(
@@ -205,7 +237,12 @@ export async function action({ request, params }: ActionFunctionArgs) {
if (!email || !email.includes('@')) {
return data<ProjectSettingsActionData>(
- { intent, fieldErrors: { transferEmail: 'Please enter a valid email address' } },
+ {
+ intent,
+ fieldErrors: {
+ transferEmail: 'Please enter a valid email address',
+ },
+ },
{ status: 400 },
)
}
@@ -216,7 +253,10 @@ export async function action({ request, params }: ActionFunctionArgs) {
})
if (result.error) {
- return data<ProjectSettingsActionData>({ intent, error: result.error as string }, { status: 400 })
+ return data<ProjectSettingsActionData>(
+ { intent, error: result.error as string },
+ { status: 400 },
+ )
}
return data<ProjectSettingsActionData>(
@@ -234,7 +274,10 @@ export async function action({ request, params }: ActionFunctionArgs) {
})
if (result.error) {
- return data<ProjectSettingsActionData>({ intent, error: result.error as string }, { status: 400 })
+ return data<ProjectSettingsActionData>(
+ { intent, error: result.error as string },
+ { status: 400 },
+ )
}
return data<ProjectSettingsActionData>(
@@ -244,16 +287,29 @@ export async function action({ request, params }: ActionFunctionArgs) {
}
case 'regenerate-captcha-key': {
- const result = await serverFetch<{ captchaSecretKey: string }>(request, `project/secret-gen/${id}`, {
- method: 'POST',
- })
+ const result = await serverFetch<{ captchaSecretKey: string }>(
+ request,
+ `project/secret-gen/${id}`,
+ {
+ method: 'POST',
+ },
+ )
if (result.error) {
- return data<ProjectSettingsActionData>({ intent, error: result.error as string }, { status: 400 })
+ return data<ProjectSettingsActionData>(
+ { intent, error: result.error as string },
+ { status: 400 },
+ )
}
return data<ProjectSettingsActionData>(
- { intent, success: true, project: { captchaSecretKey: result.data?.captchaSecretKey } as Project },
+ {
+ intent,
+ success: true,
+ project: {
+ captchaSecretKey: result.data?.captchaSecretKey,
+ } as Project,
+ },
{ headers: createHeadersWithCookies(result.cookies) },
)
}
@@ -262,17 +318,25 @@ export async function action({ request, params }: ActionFunctionArgs) {
const offset = Number(formData.get('offset') || 0)
const limit = Number(formData.get('limit') || 10)
- const result = await serverFetch<{ subscribers: Subscriber[]; count: number }>(
- request,
- `project/${id}/subscribers?offset=${offset}&limit=${limit}`,
- )
+ const result = await serverFetch<{
+ subscribers: Subscriber[]
+ count: number
+ }>(request, `project/${id}/subscribers?offset=${offset}&limit=${limit}`)
if (result.error) {
- return data<ProjectSettingsActionData>({ intent, error: result.error as string }, { status: 400 })
+ return data<ProjectSettingsActionData>(
+ { intent, error: result.error as string },
+ { status: 400 },
+ )
}
return data<ProjectSettingsActionData>(
- { intent, success: true, subscribers: result.data?.subscribers, subscribersCount: result.data?.count },
+ {
+ intent,
+ success: true,
+ subscribers: result.data?.subscribers,
+ subscribersCount: result.data?.count,
+ },
{ headers: createHeadersWithCookies(result.cookies) },
)
}
@@ -282,16 +346,26 @@ export async function action({ request, params }: ActionFunctionArgs) {
const reportFrequency = formData.get('reportFrequency')?.toString()
if (!email) {
- return data<ProjectSettingsActionData>({ intent, error: 'Email is required' }, { status: 400 })
+ return data<ProjectSettingsActionData>(
+ { intent, error: 'Email is required' },
+ { status: 400 },
+ )
}
- const result = await serverFetch<Subscriber>(request, `project/${id}/subscribers`, {
- method: 'POST',
- body: { email, reportFrequency },
- })
+ const result = await serverFetch<Subscriber>(
+ request,
+ `project/${id}/subscribers`,
+ {
+ method: 'POST',
+ body: { email, reportFrequency },
+ },
+ )
if (result.error) {
- return data<ProjectSettingsActionData>({ intent, error: result.error as string }, { status: 400 })
+ return data<ProjectSettingsActionData>(
+ { intent, error: result.error as string },
+ { status: 400 },
+ )
}
return data<ProjectSettingsActionData>(
@@ -305,16 +379,26 @@ export async function action({ request, params }: ActionFunctionArgs) {
const reportFrequency = formData.get('reportFrequency')?.toString()
if (!subscriberId) {
- return data<ProjectSettingsActionData>({ intent, error: 'Subscriber ID is required' }, { status: 400 })
+ return data<ProjectSettingsActionData>(
+ { intent, error: 'Subscriber ID is required' },
+ { status: 400 },
+ )
}
- const result = await serverFetch<Subscriber>(request, `project/${id}/subscribers/${subscriberId}`, {
- method: 'PUT',
- body: { reportFrequency },
- })
+ const result = await serverFetch<Subscriber>(
+ request,
+ `project/${id}/subscribers/${subscriberId}`,
+ {
+ method: 'PUT',
+ body: { reportFrequency },
+ },
+ )
if (result.error) {
- return data<ProjectSettingsActionData>({ intent, error: result.error as string }, { status: 400 })
+ return data<ProjectSettingsActionData>(
+ { intent, error: result.error as string },
+ { status: 400 },
+ )
}
return data<ProjectSettingsActionData>(
@@ -327,15 +411,25 @@ export async function action({ request, params }: ActionFunctionArgs) {
const subscriberId = formData.get('subscriberId')?.toString()
if (!subscriberId) {
- return data<ProjectSettingsActionData>({ intent, error: 'Subscriber ID is required' }, { status: 400 })
+ return data<ProjectSettingsActionData>(
+ { intent, error: 'Subscriber ID is required' },
+ { status: 400 },
+ )
}
- const result = await serverFetch(request, `project/${id}/subscribers/${subscriberId}`, {
- method: 'DELETE',
- })
+ const result = await serverFetch(
+ request,
+ `project/${id}/subscribers/${subscriberId}`,
+ {
+ method: 'DELETE',
+ },
+ )
if (result.error) {
- return data<ProjectSettingsActionData>({ intent, error: result.error as string }, { status: 400 })
+ return data<ProjectSettingsActionData>(
+ { intent, error: result.error as string },
+ { status: 400 },
+ )
}
return data<ProjectSettingsActionData>(
@@ -349,16 +443,26 @@ export async function action({ request, params }: ActionFunctionArgs) {
const role = formData.get('role')?.toString()
if (!email) {
- return data<ProjectSettingsActionData>({ intent, fieldErrors: { email: 'Email is required' } }, { status: 400 })
+ return data<ProjectSettingsActionData>(
+ { intent, fieldErrors: { email: 'Email is required' } },
+ { status: 400 },
+ )
}
- const result = await serverFetch<Project>(request, `project/${id}/share`, {
- method: 'POST',
- body: { email, role },
- })
+ const result = await serverFetch<Project>(
+ request,
+ `project/${id}/share`,
+ {
+ method: 'POST',
+ body: { email, role },
+ },
+ )
if (result.error) {
- return data<ProjectSettingsActionData>({ intent, error: result.error as string }, { status: 400 })
+ return data<ProjectSettingsActionData>(
+ { intent, error: result.error as string },
+ { status: 400 },
+ )
}
return data<ProjectSettingsActionData>(
@@ -371,7 +475,10 @@ export async function action({ request, params }: ActionFunctionArgs) {
const userId = formData.get('userId')?.toString()
if (!userId) {
- return data<ProjectSettingsActionData>({ intent, error: 'User ID is required' }, { status: 400 })
+ return data<ProjectSettingsActionData>(
+ { intent, error: 'User ID is required' },
+ { status: 400 },
+ )
}
const result = await serverFetch(request, `project/${id}/${userId}`, {
@@ -379,7 +486,10 @@ export async function action({ request, params }: ActionFunctionArgs) {
})
if (result.error) {
- return data<ProjectSettingsActionData>({ intent, error: result.error as string }, { status: 400 })
+ return data<ProjectSettingsActionData>(
+ { intent, error: result.error as string },
+ { status: 400 },
+ )
}
return data<ProjectSettingsActionData>(
@@ -393,7 +503,10 @@ export async function action({ request, params }: ActionFunctionArgs) {
const role = formData.get('role')?.toString()
if (!shareId) {
- return data<ProjectSettingsActionData>({ intent, error: 'Share ID is required' }, { status: 400 })
+ return data<ProjectSettingsActionData>(
+ { intent, error: 'Share ID is required' },
+ { status: 400 },
+ )
}
const result = await serverFetch(request, `project/share/${shareId}`, {
@@ -402,7 +515,10 @@ export async function action({ request, params }: ActionFunctionArgs) {
})
if (result.error) {
- return data<ProjectSettingsActionData>({ intent, error: result.error as string }, { status: 400 })
+ return data<ProjectSettingsActionData>(
+ { intent, error: result.error as string },
+ { status: 400 },
+ )
}
return data<ProjectSettingsActionData>(
@@ -412,10 +528,16 @@ export async function action({ request, params }: ActionFunctionArgs) {
}
case 'get-revenue-status': {
- const result = await serverFetch<RevenueStatus>(request, `project/${id}/revenue/status`)
+ const result = await serverFetch<RevenueStatus>(
+ request,
+ `project/${id}/revenue/status`,
+ )
if (result.error) {
- return data<ProjectSettingsActionData>({ intent, error: result.error as string }, { status: 400 })
+ return data<ProjectSettingsActionData>(
+ { intent, error: result.error as string },
+ { status: 400 },
+ )
}
return data<ProjectSettingsActionData>(
@@ -430,16 +552,26 @@ export async function action({ request, params }: ActionFunctionArgs) {
const currency = formData.get('currency')?.toString() || 'USD'
if (!provider || !apiKey) {
- return data<ProjectSettingsActionData>({ intent, error: 'Provider and API key are required' }, { status: 400 })
+ return data<ProjectSettingsActionData>(
+ { intent, error: 'Provider and API key are required' },
+ { status: 400 },
+ )
}
- const result = await serverFetch(request, `project/${id}/revenue/connect`, {
- method: 'POST',
- body: { provider, apiKey, currency },
- })
+ const result = await serverFetch(
+ request,
+ `project/${id}/revenue/connect`,
+ {
+ method: 'POST',
+ body: { provider, apiKey, currency },
+ },
+ )
if (result.error) {
- return data<ProjectSettingsActionData>({ intent, error: result.error as string }, { status: 400 })
+ return data<ProjectSettingsActionData>(
+ { intent, error: result.error as string },
+ { status: 400 },
+ )
}
return data<ProjectSettingsActionData>(
@@ -449,12 +581,19 @@ export async function action({ request, params }: ActionFunctionArgs) {
}
case 'disconnect-revenue': {
- const result = await serverFetch(request, `project/${id}/revenue/disconnect`, {
- method: 'DELETE',
- })
+ const result = await serverFetch(
+ request,
+ `project/${id}/revenue/disconnect`,
+ {
+ method: 'DELETE',
+ },
+ )
if (result.error) {
- return data<ProjectSettingsActionData>({ intent, error: result.error as string }, { status: 400 })
+ return data<ProjectSettingsActionData>(
+ { intent, error: result.error as string },
+ { status: 400 },
+ )
}
return data<ProjectSettingsActionData>(
@@ -467,16 +606,26 @@ export async function action({ request, params }: ActionFunctionArgs) {
const currency = formData.get('currency')?.toString()
if (!currency) {
- return data<ProjectSettingsActionData>({ intent, error: 'Currency is required' }, { status: 400 })
+ return data<ProjectSettingsActionData>(
+ { intent, error: 'Currency is required' },
+ { status: 400 },
+ )
}
- const result = await serverFetch(request, `project/${id}/revenue/currency`, {
- method: 'POST',
- body: { currency },
- })
+ const result = await serverFetch(
+ request,
+ `project/${id}/revenue/currency`,
+ {
+ method: 'POST',
+ body: { currency },
+ },
+ )
if (result.error) {
- return data<ProjectSettingsActionData>({ intent, error: result.error as string }, { status: 400 })
+ return data<ProjectSettingsActionData>(
+ { intent, error: result.error as string },
+ { status: 400 },
+ )
}
return data<ProjectSettingsActionData>(
@@ -487,12 +636,19 @@ export async function action({ request, params }: ActionFunctionArgs) {
// Google Search Console
case 'gsc-connect': {
- const result = await serverFetch<{ url: string }>(request, `v1/project/gsc/${id}/connect`, {
- method: 'POST',
- })
+ const result = await serverFetch<{ url: string }>(
+ request,
+ `v1/project/gsc/${id}/connect`,
+ {
+ method: 'POST',
+ },
+ )
if (result.error) {
- return data<ProjectSettingsActionData>({ intent, error: result.error as string }, { status: 400 })
+ return data<ProjectSettingsActionData>(
+ { intent, error: result.error as string },
+ { status: 400 },
+ )
}
return data<ProjectSettingsActionData>(
@@ -502,10 +658,16 @@ export async function action({ request, params }: ActionFunctionArgs) {
}
case 'gsc-status': {
- const result = await serverFetch<GscStatus>(request, `v1/project/gsc/${id}/status`)
+ const result = await serverFetch<GscStatus>(
+ request,
+ `v1/project/gsc/${id}/status`,
+ )
if (result.error) {
- return data<ProjectSettingsActionData>({ intent, error: result.error as string }, { status: 400 })
+ return data<ProjectSettingsActionData>(
+ { intent, error: result.error as string },
+ { status: 400 },
+ )
}
return data<ProjectSettingsActionData>(
@@ -515,10 +677,16 @@ export async function action({ request, params }: ActionFunctionArgs) {
}
case 'gsc-properties': {
- const result = await serverFetch<GscProperty[]>(request, `v1/project/gsc/${id}/properties`)
+ const result = await serverFetch<GscProperty[]>(
+ request,
+ `v1/project/gsc/${id}/properties`,
+ )
if (result.error) {
- return data<ProjectSettingsActionData>({ intent, error: result.error as string }, { status: 400 })
+ return data<ProjectSettingsActionData>(
+ { intent, error: result.error as string },
+ { status: 400 },
+ )
}
return data<ProjectSettingsActionData>(
@@ -531,16 +699,26 @@ export async function action({ request, params }: ActionFunctionArgs) {
const propertyUri = formData.get('propertyUri')?.toString()
if (!propertyUri) {
- return data<ProjectSettingsActionData>({ intent, error: 'Property URI is required' }, { status: 400 })
+ return data<ProjectSettingsActionData>(
+ { intent, error: 'Property URI is required' },
+ { status: 400 },
+ )
}
- const result = await serverFetch(request, `v1/project/gsc/${id}/property`, {
- method: 'POST',
- body: { propertyUri },
- })
+ const result = await serverFetch(
+ request,
+ `v1/project/gsc/${id}/property`,
+ {
+ method: 'POST',
+ body: { propertyUri },
+ },
+ )
if (result.error) {
- return data<ProjectSettingsActionData>({ intent, error: result.error as string }, { status: 400 })
+ return data<ProjectSettingsActionData>(
+ { intent, error: result.error as string },
+ { status: 400 },
+ )
}
return data<ProjectSettingsActionData>(
@@ -550,12 +728,19 @@ export async function action({ request, params }: ActionFunctionArgs) {
}
case 'gsc-disconnect': {
- const result = await serverFetch(request, `v1/project/gsc/${id}/disconnect`, {
- method: 'DELETE',
- })
+ const result = await serverFetch(
+ request,
+ `v1/project/gsc/${id}/disconnect`,
+ {
+ method: 'DELETE',
+ },
+ )
if (result.error) {
- return data<ProjectSettingsActionData>({ intent, error: result.error as string }, { status: 400 })
+ return data<ProjectSettingsActionData>(
+ { intent, error: result.error as string },
+ { status: 400 },
+ )
}
return data<ProjectSettingsActionData>(
@@ -565,7 +750,10 @@ export async function action({ request, params }: ActionFunctionArgs) {
}
default:
- return data<ProjectSettingsActionData>({ error: 'Unknown action' }, { status: 400 })
+ return data<ProjectSettingsActionData>(
+ { error: 'Unknown action' },
+ { status: 400 },
+ )
}
}
diff --git a/web/app/routes/recovery.tsx b/web/app/routes/recovery.tsx
index 69ccba1c3..6808c5f82 100644
--- a/web/app/routes/recovery.tsx
+++ b/web/app/routes/recovery.tsx
@@ -1,4 +1,8 @@
-import type { ActionFunctionArgs, HeadersFunction, LoaderFunctionArgs } from 'react-router'
+import type {
+ ActionFunctionArgs,
+ HeadersFunction,
+ LoaderFunctionArgs,
+} from 'react-router'
import { data, redirect } from 'react-router'
import { SitemapFunction } from 'remix-sitemap'
@@ -40,7 +44,10 @@ export async function action({ request }: ActionFunctionArgs) {
if (!isValidEmail(email)) {
return data<ForgotPasswordActionData>(
- { fieldErrors: { email: 'Please enter a valid email address' }, timestamp: Date.now() },
+ {
+ fieldErrors: { email: 'Please enter a valid email address' },
+ timestamp: Date.now(),
+ },
{ status: 400 },
)
}
@@ -52,7 +59,10 @@ export async function action({ request }: ActionFunctionArgs) {
})
if (result.error) {
- return data<ForgotPasswordActionData>({ error: result.error as string, timestamp: Date.now() }, { status: 400 })
+ return data<ForgotPasswordActionData>(
+ { error: result.error as string, timestamp: Date.now() },
+ { status: 400 },
+ )
}
return redirect('/?password_reset_sent=true')
diff --git a/web/app/routes/reports-unsubscribe.$token.tsx b/web/app/routes/reports-unsubscribe.$token.tsx
index 83c2dec98..6804a8408 100644
--- a/web/app/routes/reports-unsubscribe.$token.tsx
+++ b/web/app/routes/reports-unsubscribe.$token.tsx
@@ -16,7 +16,10 @@ export interface UnsubscribeLoaderData {
error?: string
}
-export async function loader({ request, params }: LoaderFunctionArgs): Promise<UnsubscribeLoaderData | Response> {
+export async function loader({
+ request,
+ params,
+}: LoaderFunctionArgs): Promise<UnsubscribeLoaderData | Response> {
if (isSelfhosted) {
return redirect('/login', 302)
}
@@ -32,7 +35,8 @@ export async function loader({ request, params }: LoaderFunctionArgs): Promise<U
})
if (result.error) {
- const errorMessage = typeof result.error === 'string' ? result.error : 'Failed to unsubscribe'
+ const errorMessage =
+ typeof result.error === 'string' ? result.error : 'Failed to unsubscribe'
return { success: false, error: errorMessage }
}
diff --git a/web/app/routes/share.$id.tsx b/web/app/routes/share.$id.tsx
index aa523bc3b..1c18ca772 100644
--- a/web/app/routes/share.$id.tsx
+++ b/web/app/routes/share.$id.tsx
@@ -15,7 +15,10 @@ export interface ShareLoaderData {
error?: string
}
-export async function loader({ request, params }: LoaderFunctionArgs): Promise<ShareLoaderData> {
+export async function loader({
+ request,
+ params,
+}: LoaderFunctionArgs): Promise<ShareLoaderData> {
const { id } = params
if (!id) {
@@ -25,7 +28,10 @@ export async function loader({ request, params }: LoaderFunctionArgs): Promise<S
const result = await serverFetch(request, `/project/share/${id}`)
if (result.error) {
- const errorMessage = typeof result.error === 'string' ? result.error : 'Failed to accept invitation'
+ const errorMessage =
+ typeof result.error === 'string'
+ ? result.error
+ : 'Failed to accept invitation'
return { success: false, error: errorMessage }
}
diff --git a/web/app/routes/signup.tsx b/web/app/routes/signup.tsx
index 96b97f4df..24c20cc16 100644
--- a/web/app/routes/signup.tsx
+++ b/web/app/routes/signup.tsx
@@ -1,4 +1,8 @@
-import type { ActionFunctionArgs, HeadersFunction, LoaderFunctionArgs } from 'react-router'
+import type {
+ ActionFunctionArgs,
+ HeadersFunction,
+ LoaderFunctionArgs,
+} from 'react-router'
import { redirect, data } from 'react-router'
import type { SitemapFunction } from 'remix-sitemap'
@@ -72,11 +76,20 @@ export async function action({ request }: ActionFunctionArgs) {
fieldErrors.tos = 'You must accept the Terms of Service'
}
- if (fieldErrors.email || fieldErrors.password || fieldErrors.repeat || fieldErrors.tos) {
+ if (
+ fieldErrors.email ||
+ fieldErrors.password ||
+ fieldErrors.repeat ||
+ fieldErrors.tos
+ ) {
return data({ fieldErrors, timestamp: Date.now() }, { status: 400 })
}
- const result = await registerUser(request, { email, password, checkIfLeaked }, true)
+ const result = await registerUser(
+ request,
+ { email, password, checkIfLeaked },
+ true,
+ )
if (!result.success) {
return data({ error: result.error, timestamp: Date.now() }, { status: 400 })
diff --git a/web/app/routes/tools._index.tsx b/web/app/routes/tools._index.tsx
index fba0458cb..9cd0a3ea0 100644
--- a/web/app/routes/tools._index.tsx
+++ b/web/app/routes/tools._index.tsx
@@ -21,24 +21,42 @@ export async function loader() {
const TOOLS = [
{
title: 'ROI Calculator',
- description: 'Calculate ROAS, ROI, CAC, and other key metrics to measure your marketing campaign performance',
+ description:
+ 'Calculate ROAS, ROI, CAC, and other key metrics to measure your marketing campaign performance',
href: '/tools/roi-calculator',
color: 'from-green-500 to-emerald-600',
- features: ['ROAS & ROI', 'CAC Analysis', 'Profit Margins', 'Break-even Analysis'],
+ features: [
+ 'ROAS & ROI',
+ 'CAC Analysis',
+ 'Profit Margins',
+ 'Break-even Analysis',
+ ],
},
{
title: 'CTR Calculator',
- description: 'Calculate your Click-Through Rate and understand your campaign performance instantly',
+ description:
+ 'Calculate your Click-Through Rate and understand your campaign performance instantly',
href: '/tools/ctr-calculator',
color: 'from-blue-500 to-indigo-600',
- features: ['CTR Analysis', 'Performance Insights', 'Industry Benchmarks', 'Optimization Tips'],
+ features: [
+ 'CTR Analysis',
+ 'Performance Insights',
+ 'Industry Benchmarks',
+ 'Optimization Tips',
+ ],
},
{
title: 'UTM Generator',
- description: 'Create trackable URLs with UTM parameters to measure your marketing campaigns effectively',
+ description:
+ 'Create trackable URLs with UTM parameters to measure your marketing campaigns effectively',
href: '/tools/utm-generator',
color: 'from-purple-500 to-pink-600',
- features: ['UTM Builder', 'Campaign Tracking', 'URL Shortener Compatible', 'Auto-detection'],
+ features: [
+ 'UTM Builder',
+ 'Campaign Tracking',
+ 'URL Shortener Compatible',
+ 'Auto-detection',
+ ],
},
]
@@ -60,8 +78,8 @@ export default function Tools() {
</h1>
<p className='mx-auto mt-6 max-w-2xl text-lg text-gray-600 dark:text-gray-400'>
- Professional marketing calculators and generators to optimize your campaigns, track performance, and
- maximize ROI. No sign-up required.
+ Professional marketing calculators and generators to optimize your
+ campaigns, track performance, and maximize ROI. No sign-up required.
</p>
</div>
@@ -73,13 +91,20 @@ export default function Tools() {
className='group relative overflow-hidden rounded-2xl bg-white p-8 ring-1 ring-gray-200 transition-all dark:bg-slate-800 dark:ring-slate-700'
>
<div className='relative'>
- <h3 className='mb-2 text-2xl font-bold text-gray-900 dark:text-white'>{tool.title}</h3>
+ <h3 className='mb-2 text-2xl font-bold text-gray-900 dark:text-white'>
+ {tool.title}
+ </h3>
- <p className='mb-6 text-gray-600 dark:text-gray-400'>{tool.description}</p>
+ <p className='mb-6 text-gray-600 dark:text-gray-400'>
+ {tool.description}
+ </p>
<div className='mb-6 space-y-2'>
{tool.features.map((feature) => (
- <div key={feature} className='flex items-center text-sm text-gray-600 dark:text-gray-400'>
+ <div
+ key={feature}
+ className='flex items-center text-sm text-gray-600 dark:text-gray-400'
+ >
<CheckIcon className='mr-2 h-4 w-4 text-green-500' />
{feature}
</div>
diff --git a/web/app/routes/tools.ctr-calculator.tsx b/web/app/routes/tools.ctr-calculator.tsx
index cf499c14b..883e8795a 100644
--- a/web/app/routes/tools.ctr-calculator.tsx
+++ b/web/app/routes/tools.ctr-calculator.tsx
@@ -138,14 +138,17 @@ export default function CTRCalculator() {
CTR Calculator
</h1>
<p className='mt-4 text-lg text-gray-600 dark:text-gray-400'>
- Calculate your Click-Through Rate and understand your campaign performance instantly
+ Calculate your Click-Through Rate and understand your campaign
+ performance instantly
</p>
</div>
<div className='mt-12 rounded-xl bg-white p-8 ring-1 ring-gray-200 dark:bg-slate-800 dark:ring-slate-700'>
<div className='space-y-6'>
<div>
- <h2 className='mb-6 text-2xl font-semibold text-gray-900 dark:text-white'>Calculate Your CTR</h2>
+ <h2 className='mb-6 text-2xl font-semibold text-gray-900 dark:text-white'>
+ Calculate Your CTR
+ </h2>
<div className='grid gap-6 md:grid-cols-2'>
<div>
@@ -154,11 +157,15 @@ export default function CTRCalculator() {
placeholder='Enter number of clicks'
label='Total Clicks'
value={metrics.clicks}
- onChange={(e) => handleMetricChange('clicks', e.target.value)}
+ onChange={(e) =>
+ handleMetricChange('clicks', e.target.value)
+ }
className='w-full'
min='0'
/>
- <p className='mt-1 text-sm text-gray-500 dark:text-gray-400'>How many times your ad was clicked</p>
+ <p className='mt-1 text-sm text-gray-500 dark:text-gray-400'>
+ How many times your ad was clicked
+ </p>
</div>
<div>
@@ -167,11 +174,15 @@ export default function CTRCalculator() {
placeholder='Enter number of impressions'
label='Total Impressions'
value={metrics.impressions}
- onChange={(e) => handleMetricChange('impressions', e.target.value)}
+ onChange={(e) =>
+ handleMetricChange('impressions', e.target.value)
+ }
className='w-full'
min='1'
/>
- <p className='mt-1 text-sm text-gray-500 dark:text-gray-400'>How many times your ad was shown</p>
+ <p className='mt-1 text-sm text-gray-500 dark:text-gray-400'>
+ How many times your ad was shown
+ </p>
</div>
</div>
@@ -184,26 +195,38 @@ export default function CTRCalculator() {
{result ? (
<div className='border-t border-gray-200 pt-6 dark:border-gray-700'>
- <h3 className='mb-4 text-lg font-medium text-gray-900 dark:text-white'>Results</h3>
+ <h3 className='mb-4 text-lg font-medium text-gray-900 dark:text-white'>
+ Results
+ </h3>
<div className='rounded-lg bg-gray-50 p-6 dark:bg-slate-700/50'>
<div className='text-center'>
- <div className='text-5xl font-bold text-gray-900 dark:text-white'>{result.ctr.toFixed(2)}%</div>
- <div className='mt-2 text-lg text-gray-600 dark:text-gray-400'>Click-Through Rate</div>
- <div className={`mt-4 text-lg font-semibold ${result.color}`}>
+ <div className='text-5xl font-bold text-gray-900 dark:text-white'>
+ {result.ctr.toFixed(2)}%
+ </div>
+ <div className='mt-2 text-lg text-gray-600 dark:text-gray-400'>
+ Click-Through Rate
+ </div>
+ <div
+ className={`mt-4 text-lg font-semibold ${result.color}`}
+ >
{result.performance} Performance
</div>
</div>
<div className='mt-6 grid gap-4 text-sm md:grid-cols-2'>
<div className='rounded-lg bg-white p-4 dark:bg-slate-800'>
- <div className='text-gray-500 dark:text-gray-400'>Formula Used</div>
+ <div className='text-gray-500 dark:text-gray-400'>
+ Formula Used
+ </div>
<div className='mt-1 font-mono text-gray-900 dark:text-white'>
CTR = (Clicks ÷ Impressions) × 100
</div>
</div>
<div className='rounded-lg bg-white p-4 dark:bg-slate-800'>
- <div className='text-gray-500 dark:text-gray-400'>Your Calculation</div>
+ <div className='text-gray-500 dark:text-gray-400'>
+ Your Calculation
+ </div>
<div className='mt-1 font-mono text-gray-900 dark:text-white'>
({metrics.clicks} ÷ {metrics.impressions}) × 100
</div>
@@ -251,18 +274,27 @@ export default function CTRCalculator() {
className='group rounded-lg border border-gray-200 bg-white dark:border-gray-700 dark:bg-slate-800'
>
<summary className='flex w-full cursor-pointer items-center justify-between px-6 py-4 text-left hover:bg-gray-50 dark:hover:bg-slate-700/50'>
- <h3 className='text-lg font-medium text-gray-900 dark:text-white'>{item.question}</h3>
+ <h3 className='text-lg font-medium text-gray-900 dark:text-white'>
+ {item.question}
+ </h3>
<svg
className='h-5 w-5 text-gray-500 transition-transform group-open:rotate-180'
fill='none'
viewBox='0 0 24 24'
stroke='currentColor'
>
- <path strokeLinecap='round' strokeLinejoin='round' strokeWidth={2} d='M19 9l-7 7-7-7' />
+ <path
+ strokeLinecap='round'
+ strokeLinejoin='round'
+ strokeWidth={2}
+ d='M19 9l-7 7-7-7'
+ />
</svg>
</summary>
<div className='border-t border-gray-200 px-6 py-4 dark:border-gray-700'>
- <p className='text-gray-600 dark:text-gray-400'>{item.answer}</p>
+ <p className='text-gray-600 dark:text-gray-400'>
+ {item.answer}
+ </p>
</div>
</details>
))}
diff --git a/web/app/routes/tools.roi-calculator.tsx b/web/app/routes/tools.roi-calculator.tsx
index 341bfba9f..b0835de69 100644
--- a/web/app/routes/tools.roi-calculator.tsx
+++ b/web/app/routes/tools.roi-calculator.tsx
@@ -1,4 +1,9 @@
-import { TrendingUpIcon, DollarSignIcon, ShoppingCartIcon, ChevronDownIcon } from 'lucide-react'
+import {
+ TrendingUpIcon,
+ DollarSignIcon,
+ ShoppingCartIcon,
+ ChevronDownIcon,
+} from 'lucide-react'
import { useState, useEffect } from 'react'
import { redirect } from 'react-router'
import type { SitemapFunction } from 'remix-sitemap'
@@ -155,7 +160,8 @@ export default function ROICalculator() {
const cac = conversions > 0 ? adSpend / conversions : 0
const profit = revenue - adSpend
const breakEvenRoas = profitMargin > 0 ? 100 / profitMargin : 0
- const marginOfSafety = breakEvenRoas > 0 && roas > 0 ? ((roas - breakEvenRoas) / roas) * 100 : 0
+ const marginOfSafety =
+ breakEvenRoas > 0 && roas > 0 ? ((roas - breakEvenRoas) / roas) * 100 : 0
setCalculated({
roi,
@@ -202,7 +208,8 @@ export default function ROICalculator() {
Marketing ROI Calculator
</h1>
<p className='mt-4 text-lg text-gray-600 dark:text-gray-400'>
- Calculate ROAS, ROI, CAC, and other key metrics to measure your marketing campaign performance
+ Calculate ROAS, ROI, CAC, and other key metrics to measure your
+ marketing campaign performance
</p>
</div>
@@ -210,7 +217,9 @@ export default function ROICalculator() {
{/* Input Section */}
<div className='lg:col-span-2'>
<div className='rounded-xl bg-white p-8 ring-1 ring-gray-200 dark:bg-slate-800 dark:ring-slate-700'>
- <h2 className='mb-6 text-2xl font-semibold text-gray-900 dark:text-white'>Campaign Metrics</h2>
+ <h2 className='mb-6 text-2xl font-semibold text-gray-900 dark:text-white'>
+ Campaign Metrics
+ </h2>
<div className='space-y-6'>
<Input
@@ -218,7 +227,9 @@ export default function ROICalculator() {
placeholder='Q4 Facebook Campaign'
label='Campaign Name (optional)'
value={metrics.campaignName}
- onChange={(e) => handleMetricChange('campaignName', e.target.value)}
+ onChange={(e) =>
+ handleMetricChange('campaignName', e.target.value)
+ }
className='w-full'
/>
@@ -230,11 +241,16 @@ export default function ROICalculator() {
label={
<>
Ad Spend ($)
- <Tooltip className='ml-1' text='Total amount spent on advertising for this campaign' />
+ <Tooltip
+ className='ml-1'
+ text='Total amount spent on advertising for this campaign'
+ />
</>
}
value={metrics.adSpend || ''}
- onChange={(e) => handleMetricChange('adSpend', e.target.value)}
+ onChange={(e) =>
+ handleMetricChange('adSpend', e.target.value)
+ }
className='w-full'
/>
</div>
@@ -246,11 +262,16 @@ export default function ROICalculator() {
label={
<>
Revenue Generated ($)
- <Tooltip className='ml-1' text='Total revenue attributed to this campaign' />
+ <Tooltip
+ className='ml-1'
+ text='Total revenue attributed to this campaign'
+ />
</>
}
value={metrics.revenue || ''}
- onChange={(e) => handleMetricChange('revenue', e.target.value)}
+ onChange={(e) =>
+ handleMetricChange('revenue', e.target.value)
+ }
className='w-full'
/>
</div>
@@ -262,11 +283,16 @@ export default function ROICalculator() {
label={
<>
Conversions
- <Tooltip className='ml-1' text='Number of conversions (sales, sign-ups, etc.)' />
+ <Tooltip
+ className='ml-1'
+ text='Number of conversions (sales, sign-ups, etc.)'
+ />
</>
}
value={metrics.conversions || ''}
- onChange={(e) => handleMetricChange('conversions', e.target.value)}
+ onChange={(e) =>
+ handleMetricChange('conversions', e.target.value)
+ }
className='w-full'
/>
</div>
@@ -278,11 +304,16 @@ export default function ROICalculator() {
label={
<>
Clicks
- <Tooltip className='ml-1' text='Total number of clicks on your ads' />
+ <Tooltip
+ className='ml-1'
+ text='Total number of clicks on your ads'
+ />
</>
}
value={metrics.clicks || ''}
- onChange={(e) => handleMetricChange('clicks', e.target.value)}
+ onChange={(e) =>
+ handleMetricChange('clicks', e.target.value)
+ }
className='w-full'
/>
</div>
@@ -294,11 +325,16 @@ export default function ROICalculator() {
label={
<>
Impressions
- <Tooltip className='ml-1' text='Total number of times your ads were shown' />
+ <Tooltip
+ className='ml-1'
+ text='Total number of times your ads were shown'
+ />
</>
}
value={metrics.impressions || ''}
- onChange={(e) => handleMetricChange('impressions', e.target.value)}
+ onChange={(e) =>
+ handleMetricChange('impressions', e.target.value)
+ }
className='w-full'
/>
</div>
@@ -310,11 +346,16 @@ export default function ROICalculator() {
label={
<>
Profit Margin (%)
- <Tooltip className='ml-1' text='Your average profit margin on products/services' />
+ <Tooltip
+ className='ml-1'
+ text='Your average profit margin on products/services'
+ />
</>
}
value={profitMargin || ''}
- onChange={(e) => setProfitMargin(parseFloat(e.target.value) || 0)}
+ onChange={(e) =>
+ setProfitMargin(parseFloat(e.target.value) || 0)
+ }
className='w-full'
/>
</div>
@@ -328,15 +369,21 @@ export default function ROICalculator() {
<div className='sticky top-8 space-y-6'>
{/* Primary Metrics */}
<div className='rounded-xl bg-white p-6 ring-1 ring-gray-200 dark:bg-slate-800 dark:ring-slate-700'>
- <h3 className='mb-4 text-lg font-semibold text-gray-900 dark:text-white'>Key Performance Metrics</h3>
+ <h3 className='mb-4 text-lg font-semibold text-gray-900 dark:text-white'>
+ Key Performance Metrics
+ </h3>
<div className='space-y-4'>
<div className='flex items-center justify-between rounded-lg bg-gray-50 p-4 dark:bg-slate-700/50'>
<div className='flex items-center'>
<TrendingUpIcon className='mr-2 h-5 w-5 text-gray-500 dark:text-gray-400' />
- <span className='font-medium text-gray-700 dark:text-gray-300'>ROI</span>
+ <span className='font-medium text-gray-700 dark:text-gray-300'>
+ ROI
+ </span>
</div>
- <span className={`text-2xl font-bold ${getROIColor(calculated.roi)}`}>
+ <span
+ className={`text-2xl font-bold ${getROIColor(calculated.roi)}`}
+ >
{formatPercentage(calculated.roi)}
</span>
</div>
@@ -344,9 +391,13 @@ export default function ROICalculator() {
<div className='flex items-center justify-between rounded-lg bg-gray-50 p-4 dark:bg-slate-700/50'>
<div className='flex items-center'>
<DollarSignIcon className='mr-2 h-5 w-5 text-gray-500 dark:text-gray-400' />
- <span className='font-medium text-gray-700 dark:text-gray-300'>ROAS</span>
+ <span className='font-medium text-gray-700 dark:text-gray-300'>
+ ROAS
+ </span>
</div>
- <span className={`text-2xl font-bold ${getROASColor(calculated.roas)}`}>
+ <span
+ className={`text-2xl font-bold ${getROASColor(calculated.roas)}`}
+ >
{formatRatio(calculated.roas)}
</span>
</div>
@@ -354,7 +405,9 @@ export default function ROICalculator() {
<div className='flex items-center justify-between rounded-lg bg-gray-50 p-4 dark:bg-slate-700/50'>
<div className='flex items-center'>
<ShoppingCartIcon className='mr-2 h-5 w-5 text-gray-500 dark:text-gray-400' />
- <span className='font-medium text-gray-700 dark:text-gray-300'>Profit</span>
+ <span className='font-medium text-gray-700 dark:text-gray-300'>
+ Profit
+ </span>
</div>
<span
className={`text-xl font-bold ${calculated.profit >= 0 ? 'text-green-600 dark:text-green-400' : 'text-red-600 dark:text-red-400'}`}
@@ -367,39 +420,51 @@ export default function ROICalculator() {
{/* Secondary Metrics */}
<div className='rounded-xl bg-white p-6 ring-1 ring-gray-200 dark:bg-slate-800 dark:ring-slate-700'>
- <h3 className='mb-4 text-lg font-semibold text-gray-900 dark:text-white'>Detailed Metrics</h3>
+ <h3 className='mb-4 text-lg font-semibold text-gray-900 dark:text-white'>
+ Detailed Metrics
+ </h3>
<div className='space-y-3'>
<div className='flex justify-between'>
- <span className='text-sm text-gray-600 dark:text-gray-400'>CAC</span>
+ <span className='text-sm text-gray-600 dark:text-gray-400'>
+ CAC
+ </span>
<span className='font-semibold text-gray-900 dark:text-white'>
{formatCurrency(calculated.cac)}
</span>
</div>
<div className='flex justify-between'>
- <span className='text-sm text-gray-600 dark:text-gray-400'>CPC</span>
+ <span className='text-sm text-gray-600 dark:text-gray-400'>
+ CPC
+ </span>
<span className='font-semibold text-gray-900 dark:text-white'>
{formatCurrency(calculated.cpc)}
</span>
</div>
<div className='flex justify-between'>
- <span className='text-sm text-gray-600 dark:text-gray-400'>CPM</span>
+ <span className='text-sm text-gray-600 dark:text-gray-400'>
+ CPM
+ </span>
<span className='font-semibold text-gray-900 dark:text-white'>
{formatCurrency(calculated.cpm)}
</span>
</div>
<div className='flex justify-between'>
- <span className='text-sm text-gray-600 dark:text-gray-400'>CTR</span>
+ <span className='text-sm text-gray-600 dark:text-gray-400'>
+ CTR
+ </span>
<span className='font-semibold text-gray-900 dark:text-white'>
{formatPercentage(calculated.ctr)}
</span>
</div>
<div className='flex justify-between'>
- <span className='text-sm text-gray-600 dark:text-gray-400'>Conversion Rate</span>
+ <span className='text-sm text-gray-600 dark:text-gray-400'>
+ Conversion Rate
+ </span>
<span className='font-semibold text-gray-900 dark:text-white'>
{formatPercentage(calculated.conversionRate)}
</span>
@@ -407,14 +472,18 @@ export default function ROICalculator() {
<div className='border-t pt-3 dark:border-gray-700'>
<div className='flex justify-between'>
- <span className='text-sm text-gray-600 dark:text-gray-400'>Break-Even ROAS</span>
+ <span className='text-sm text-gray-600 dark:text-gray-400'>
+ Break-Even ROAS
+ </span>
<span className='font-semibold text-gray-900 dark:text-white'>
{formatRatio(calculated.breakEvenRoas)}
</span>
</div>
<div className='mt-2 flex justify-between'>
- <span className='text-sm text-gray-600 dark:text-gray-400'>Margin of Safety</span>
+ <span className='text-sm text-gray-600 dark:text-gray-400'>
+ Margin of Safety
+ </span>
<span
className={`font-semibold ${calculated.marginOfSafety >= 0 ? 'text-green-600 dark:text-green-400' : 'text-red-600 dark:text-red-400'}`}
>
@@ -428,7 +497,9 @@ export default function ROICalculator() {
{/* Performance Indicator */}
{metrics.adSpend > 0 ? (
<div className='rounded-xl bg-gradient-to-r from-indigo-500 to-purple-600 p-6 text-white'>
- <h3 className='mb-2 text-lg font-semibold'>Campaign Performance</h3>
+ <h3 className='mb-2 text-lg font-semibold'>
+ Campaign Performance
+ </h3>
<p className='text-sm opacity-90'>
{calculated.roas >= 4
? 'Excellent! Your campaign is highly profitable.'
@@ -457,11 +528,15 @@ export default function ROICalculator() {
className='group rounded-lg border border-gray-200 bg-white dark:border-gray-700 dark:bg-slate-800'
>
<summary className='flex w-full cursor-pointer items-center justify-between px-6 py-4 text-left hover:bg-gray-50 dark:hover:bg-slate-700/50'>
- <h3 className='text-lg font-medium text-gray-900 dark:text-white'>{item.question}</h3>
+ <h3 className='text-lg font-medium text-gray-900 dark:text-white'>
+ {item.question}
+ </h3>
<ChevronDownIcon className='h-5 w-5 text-gray-500 transition-transform group-open:rotate-180' />
</summary>
<div className='border-t border-gray-200 px-6 py-4 dark:border-gray-700'>
- <p className='text-gray-600 dark:text-gray-400'>{item.answer}</p>
+ <p className='text-gray-600 dark:text-gray-400'>
+ {item.answer}
+ </p>
</div>
</details>
))}
diff --git a/web/app/routes/tools.utm-generator.tsx b/web/app/routes/tools.utm-generator.tsx
index 417efdcb4..ff074c75e 100644
--- a/web/app/routes/tools.utm-generator.tsx
+++ b/web/app/routes/tools.utm-generator.tsx
@@ -97,15 +97,22 @@ export default function UTMGenerator() {
// If URL field is being updated, try to extract UTM parameters from it
if (key === 'url' && value) {
try {
- const url = new URL(value.startsWith('http') ? value : `https://${value}`)
+ const url = new URL(
+ value.startsWith('http') ? value : `https://${value}`,
+ )
const urlParams = new URLSearchParams(url.search)
// Extract UTM parameters and populate the fields
- if (urlParams.has('utm_source')) newParams.utm_source = urlParams.get('utm_source') || ''
- if (urlParams.has('utm_medium')) newParams.utm_medium = urlParams.get('utm_medium') || ''
- if (urlParams.has('utm_campaign')) newParams.utm_campaign = urlParams.get('utm_campaign') || ''
- if (urlParams.has('utm_content')) newParams.utm_content = urlParams.get('utm_content') || ''
- if (urlParams.has('utm_term')) newParams.utm_term = urlParams.get('utm_term') || ''
+ if (urlParams.has('utm_source'))
+ newParams.utm_source = urlParams.get('utm_source') || ''
+ if (urlParams.has('utm_medium'))
+ newParams.utm_medium = urlParams.get('utm_medium') || ''
+ if (urlParams.has('utm_campaign'))
+ newParams.utm_campaign = urlParams.get('utm_campaign') || ''
+ if (urlParams.has('utm_content'))
+ newParams.utm_content = urlParams.get('utm_content') || ''
+ if (urlParams.has('utm_term'))
+ newParams.utm_term = urlParams.get('utm_term') || ''
} catch {
// If URL parsing fails, that's fine, just keep the URL as is
}
@@ -171,7 +178,13 @@ export default function UTMGenerator() {
// Using native <details>/<summary> for FAQ to ensure content is present in the DOM for SEO
- const sourceExamples = ['google', 'facebook', 'twitter', 'newsletter', 'linkedin']
+ const sourceExamples = [
+ 'google',
+ 'facebook',
+ 'twitter',
+ 'newsletter',
+ 'linkedin',
+ ]
const mediumExamples = ['cpc', 'email', 'social', 'referral', 'banner']
const campaignExamples = ['spring_sale', 'product_launch', 'black_friday']
@@ -184,14 +197,17 @@ export default function UTMGenerator() {
UTM Link Generator
</h1>
<p className='mt-4 text-lg text-gray-600 dark:text-gray-400'>
- Create trackable URLs with UTM parameters to measure your marketing campaigns effectively
+ Create trackable URLs with UTM parameters to measure your
+ marketing campaigns effectively
</p>
</div>
<div className='mt-12 rounded-xl bg-white p-8 ring-1 ring-gray-200 dark:bg-slate-800 dark:ring-slate-700'>
<div className='space-y-6'>
<div>
- <h2 className='mb-6 text-2xl font-semibold text-gray-900 dark:text-white'>Build your UTM link</h2>
+ <h2 className='mb-6 text-2xl font-semibold text-gray-900 dark:text-white'>
+ Build your UTM link
+ </h2>
<div className='space-y-6'>
<Input
@@ -205,7 +221,9 @@ export default function UTMGenerator() {
<div className='grid gap-6 md:grid-cols-2'>
<div>
- <h3 className='mb-4 text-lg font-medium text-gray-900 dark:text-white'>Campaign parameters</h3>
+ <h3 className='mb-4 text-lg font-medium text-gray-900 dark:text-white'>
+ Campaign parameters
+ </h3>
<div className='space-y-4'>
<div>
@@ -222,7 +240,9 @@ export default function UTMGenerator() {
</>
}
value={params.utm_source}
- onChange={(e) => handleParamChange('utm_source', e.target.value)}
+ onChange={(e) =>
+ handleParamChange('utm_source', e.target.value)
+ }
className='w-full'
/>
</div>
@@ -241,7 +261,9 @@ export default function UTMGenerator() {
</>
}
value={params.utm_medium}
- onChange={(e) => handleParamChange('utm_medium', e.target.value)}
+ onChange={(e) =>
+ handleParamChange('utm_medium', e.target.value)
+ }
className='w-full'
/>
</div>
@@ -260,7 +282,9 @@ export default function UTMGenerator() {
</>
}
value={params.utm_campaign}
- onChange={(e) => handleParamChange('utm_campaign', e.target.value)}
+ onChange={(e) =>
+ handleParamChange('utm_campaign', e.target.value)
+ }
className='w-full'
/>
</div>
@@ -268,7 +292,9 @@ export default function UTMGenerator() {
</div>
<div>
- <h3 className='mb-4 text-lg font-medium text-gray-900 dark:text-white'>Optional parameters</h3>
+ <h3 className='mb-4 text-lg font-medium text-gray-900 dark:text-white'>
+ Optional parameters
+ </h3>
<div className='space-y-4'>
<div>
@@ -285,7 +311,9 @@ export default function UTMGenerator() {
</>
}
value={params.utm_content}
- onChange={(e) => handleParamChange('utm_content', e.target.value)}
+ onChange={(e) =>
+ handleParamChange('utm_content', e.target.value)
+ }
className='w-full'
/>
</div>
@@ -304,7 +332,9 @@ export default function UTMGenerator() {
/>
</>
}
- onChange={(e) => handleParamChange('utm_term', e.target.value)}
+ onChange={(e) =>
+ handleParamChange('utm_term', e.target.value)
+ }
className='w-full'
/>
</div>
@@ -315,7 +345,9 @@ export default function UTMGenerator() {
</div>
<div className='border-t border-gray-200 pt-6 dark:border-gray-700'>
- <h3 className='mb-4 text-lg font-medium text-gray-900 dark:text-white'>Result</h3>
+ <h3 className='mb-4 text-lg font-medium text-gray-900 dark:text-white'>
+ Result
+ </h3>
<div className='flex flex-col items-center gap-2 md:flex-row'>
<Input
type='text'
@@ -324,7 +356,12 @@ export default function UTMGenerator() {
className='w-full font-mono text-sm tracking-tight'
disabled={!generatedURL}
/>
- <Button onClick={copyToClipboard} disabled={!generatedURL} primary regular>
+ <Button
+ onClick={copyToClipboard}
+ disabled={!generatedURL}
+ primary
+ regular
+ >
<CopyIcon className='mr-1 h-4 w-4' />
{copied ? 'Copied!' : 'Copy'}
</Button>
@@ -345,11 +382,15 @@ export default function UTMGenerator() {
className='group rounded-lg border border-gray-200 bg-white dark:border-gray-700 dark:bg-slate-800'
>
<summary className='flex w-full cursor-pointer items-center justify-between px-6 py-4 text-left hover:bg-gray-50 dark:hover:bg-slate-700/50'>
- <h3 className='text-lg font-medium text-gray-900 dark:text-white'>{item.question}</h3>
+ <h3 className='text-lg font-medium text-gray-900 dark:text-white'>
+ {item.question}
+ </h3>
<ChevronDownIcon className='h-5 w-5 text-gray-500 transition-transform group-open:rotate-180' />
</summary>
<div className='border-t border-gray-200 px-6 py-4 dark:border-gray-700'>
- <p className='text-gray-600 dark:text-gray-400'>{item.answer}</p>
+ <p className='text-gray-600 dark:text-gray-400'>
+ {item.answer}
+ </p>
</div>
</details>
))}
diff --git a/web/app/routes/user-settings.tsx b/web/app/routes/user-settings.tsx
index 1727775c8..13c8ec9b6 100644
--- a/web/app/routes/user-settings.tsx
+++ b/web/app/routes/user-settings.tsx
@@ -5,8 +5,17 @@ import type { SitemapFunction } from 'remix-sitemap'
import { serverFetch } from '~/api/api.server'
import { User } from '~/lib/models/User'
import UserSettings from '~/pages/UserSettings'
-import { redirectIfNotAuthenticated, createHeadersWithCookies, createAuthCookies } from '~/utils/session.server'
-import { isValidEmail, isValidPassword, MIN_PASSWORD_CHARS, MAX_PASSWORD_CHARS } from '~/utils/validator'
+import {
+ redirectIfNotAuthenticated,
+ createHeadersWithCookies,
+ createAuthCookies,
+} from '~/utils/session.server'
+import {
+ isValidEmail,
+ isValidPassword,
+ MIN_PASSWORD_CHARS,
+ MAX_PASSWORD_CHARS,
+} from '~/utils/validator'
export const sitemap: SitemapFunction = () => ({
exclude: true,
@@ -69,7 +78,10 @@ export async function action({ request }: ActionFunctionArgs) {
}
if (fieldErrors.email || fieldErrors.password || fieldErrors.repeat) {
- return data<UserSettingsActionData>({ intent, fieldErrors }, { status: 400 })
+ return data<UserSettingsActionData>(
+ { intent, fieldErrors },
+ { status: 400 },
+ )
}
const updateData: Record<string, unknown> = {}
@@ -85,7 +97,10 @@ export async function action({ request }: ActionFunctionArgs) {
})
if (result.error) {
- return data<UserSettingsActionData>({ intent, error: result.error as string }, { status: 400 })
+ return data<UserSettingsActionData>(
+ { intent, error: result.error as string },
+ { status: 400 },
+ )
}
return data<UserSettingsActionData>(
@@ -95,12 +110,19 @@ export async function action({ request }: ActionFunctionArgs) {
}
case 'generate-api-key': {
- const result = await serverFetch<{ apiKey: string }>(request, 'user/api-key', {
- method: 'POST',
- })
+ const result = await serverFetch<{ apiKey: string }>(
+ request,
+ 'user/api-key',
+ {
+ method: 'POST',
+ },
+ )
if (result.error) {
- return data<UserSettingsActionData>({ intent, error: result.error as string }, { status: 400 })
+ return data<UserSettingsActionData>(
+ { intent, error: result.error as string },
+ { status: 400 },
+ )
}
return data<UserSettingsActionData>(
@@ -115,7 +137,10 @@ export async function action({ request }: ActionFunctionArgs) {
})
if (result.error) {
- return data<UserSettingsActionData>({ intent, error: result.error as string }, { status: 400 })
+ return data<UserSettingsActionData>(
+ { intent, error: result.error as string },
+ { status: 400 },
+ )
}
return data<UserSettingsActionData>(
@@ -127,13 +152,20 @@ export async function action({ request }: ActionFunctionArgs) {
case 'toggle-live-visitors': {
const show = formData.get('show') === 'true'
- const result = await serverFetch<Partial<User>>(request, 'user/live-visitors', {
- method: 'PUT',
- body: { show },
- })
+ const result = await serverFetch<Partial<User>>(
+ request,
+ 'user/live-visitors',
+ {
+ method: 'PUT',
+ body: { show },
+ },
+ )
if (result.error) {
- return data<UserSettingsActionData>({ intent, error: result.error as string }, { status: 400 })
+ return data<UserSettingsActionData>(
+ { intent, error: result.error as string },
+ { status: 400 },
+ )
}
return data<UserSettingsActionData>(
@@ -143,15 +175,23 @@ export async function action({ request }: ActionFunctionArgs) {
}
case 'toggle-login-notifications': {
- const receiveLoginNotifications = formData.get('receiveLoginNotifications') === 'true'
+ const receiveLoginNotifications =
+ formData.get('receiveLoginNotifications') === 'true'
- const result = await serverFetch(request, 'user/recieve-login-notifications', {
- method: 'POST',
- body: { receiveLoginNotifications },
- })
+ const result = await serverFetch(
+ request,
+ 'user/recieve-login-notifications',
+ {
+ method: 'POST',
+ body: { receiveLoginNotifications },
+ },
+ )
if (result.error) {
- return data<UserSettingsActionData>({ intent, error: result.error as string }, { status: 400 })
+ return data<UserSettingsActionData>(
+ { intent, error: result.error as string },
+ { status: 400 },
+ )
}
return data<UserSettingsActionData>(
@@ -166,7 +206,10 @@ export async function action({ request }: ActionFunctionArgs) {
})
if (result.error) {
- return data<UserSettingsActionData>({ intent, error: result.error as string }, { status: 400 })
+ return data<UserSettingsActionData>(
+ { intent, error: result.error as string },
+ { status: 400 },
+ )
}
return data<UserSettingsActionData>(
@@ -184,7 +227,10 @@ export async function action({ request }: ActionFunctionArgs) {
})
if (result.error) {
- return data<UserSettingsActionData>({ intent, error: result.error as string }, { status: 400 })
+ return data<UserSettingsActionData>(
+ { intent, error: result.error as string },
+ { status: 400 },
+ )
}
return data<UserSettingsActionData>(
@@ -194,16 +240,27 @@ export async function action({ request }: ActionFunctionArgs) {
}
case 'generate-2fa': {
- const result = await serverFetch<{ secret: string; otpauthUrl: string }>(request, '2fa/generate', {
- method: 'POST',
- })
+ const result = await serverFetch<{ secret: string; otpauthUrl: string }>(
+ request,
+ '2fa/generate',
+ {
+ method: 'POST',
+ },
+ )
if (result.error) {
- return data<UserSettingsActionData>({ intent, error: result.error as string }, { status: 400 })
+ return data<UserSettingsActionData>(
+ { intent, error: result.error as string },
+ { status: 400 },
+ )
}
return data<UserSettingsActionData>(
- { intent, success: true, twoFAData: result.data as { secret: string; otpauthUrl: string } },
+ {
+ intent,
+ success: true,
+ twoFAData: result.data as { secret: string; otpauthUrl: string },
+ },
{ headers: createHeadersWithCookies(result.cookies) },
)
}
@@ -211,17 +268,20 @@ export async function action({ request }: ActionFunctionArgs) {
case 'enable-2fa': {
const twoFactorAuthenticationCode = formData.get('code')?.toString() || ''
- const result = await serverFetch<{ twoFactorRecoveryCode: string; accessToken: string; refreshToken: string }>(
- request,
- '2fa/enable',
- {
- method: 'POST',
- body: { twoFactorAuthenticationCode },
- },
- )
+ const result = await serverFetch<{
+ twoFactorRecoveryCode: string
+ accessToken: string
+ refreshToken: string
+ }>(request, '2fa/enable', {
+ method: 'POST',
+ body: { twoFactorAuthenticationCode },
+ })
if (result.error) {
- return data<UserSettingsActionData>({ intent, error: result.error as string }, { status: 400 })
+ return data<UserSettingsActionData>(
+ { intent, error: result.error as string },
+ { status: 400 },
+ )
}
// Set new auth cookies from the response
@@ -243,7 +303,10 @@ export async function action({ request }: ActionFunctionArgs) {
})
if (result.error) {
- return data<UserSettingsActionData>({ intent, error: result.error as string }, { status: 400 })
+ return data<UserSettingsActionData>(
+ { intent, error: result.error as string },
+ { status: 400 },
+ )
}
return data<UserSettingsActionData>(
@@ -256,7 +319,10 @@ export async function action({ request }: ActionFunctionArgs) {
const shareId = formData.get('shareId')?.toString()
if (!shareId) {
- return data<UserSettingsActionData>({ intent, error: 'Share ID is required' }, { status: 400 })
+ return data<UserSettingsActionData>(
+ { intent, error: 'Share ID is required' },
+ { status: 400 },
+ )
}
const result = await serverFetch(request, `user/share/${shareId}`, {
@@ -264,7 +330,10 @@ export async function action({ request }: ActionFunctionArgs) {
})
if (result.error) {
- return data<UserSettingsActionData>({ intent, error: result.error as string }, { status: 400 })
+ return data<UserSettingsActionData>(
+ { intent, error: result.error as string },
+ { status: 400 },
+ )
}
return data<UserSettingsActionData>(
@@ -277,7 +346,10 @@ export async function action({ request }: ActionFunctionArgs) {
const shareId = formData.get('shareId')?.toString()
if (!shareId) {
- return data<UserSettingsActionData>({ intent, error: 'Share ID is required' }, { status: 400 })
+ return data<UserSettingsActionData>(
+ { intent, error: 'Share ID is required' },
+ { status: 400 },
+ )
}
const result = await serverFetch(request, `user/share/${shareId}`, {
@@ -285,7 +357,10 @@ export async function action({ request }: ActionFunctionArgs) {
})
if (result.error) {
- return data<UserSettingsActionData>({ intent, error: result.error as string }, { status: 400 })
+ return data<UserSettingsActionData>(
+ { intent, error: result.error as string },
+ { status: 400 },
+ )
}
return data<UserSettingsActionData>(
@@ -298,7 +373,10 @@ export async function action({ request }: ActionFunctionArgs) {
const provider = formData.get('provider')?.toString()
if (!provider) {
- return data<UserSettingsActionData>({ intent, error: 'Provider is required' }, { status: 400 })
+ return data<UserSettingsActionData>(
+ { intent, error: 'Provider is required' },
+ { status: 400 },
+ )
}
const result = await serverFetch(request, 'v1/auth/sso/unlink', {
@@ -307,7 +385,10 @@ export async function action({ request }: ActionFunctionArgs) {
})
if (result.error) {
- return data<UserSettingsActionData>({ intent, error: result.error as string }, { status: 400 })
+ return data<UserSettingsActionData>(
+ { intent, error: result.error as string },
+ { status: 400 },
+ )
}
return data<UserSettingsActionData>(
@@ -320,7 +401,10 @@ export async function action({ request }: ActionFunctionArgs) {
const tgID = formData.get('tgID')?.toString()
if (!tgID) {
- return data<UserSettingsActionData>({ intent, error: 'Telegram ID is required' }, { status: 400 })
+ return data<UserSettingsActionData>(
+ { intent, error: 'Telegram ID is required' },
+ { status: 400 },
+ )
}
const result = await serverFetch(request, `user/tg/${tgID}`, {
@@ -328,7 +412,10 @@ export async function action({ request }: ActionFunctionArgs) {
})
if (result.error) {
- return data<UserSettingsActionData>({ intent, error: result.error as string }, { status: 400 })
+ return data<UserSettingsActionData>(
+ { intent, error: result.error as string },
+ { status: 400 },
+ )
}
return data<UserSettingsActionData>(
@@ -341,15 +428,25 @@ export async function action({ request }: ActionFunctionArgs) {
const membershipId = formData.get('membershipId')?.toString()
if (!membershipId) {
- return data<UserSettingsActionData>({ intent, error: 'Membership ID is required' }, { status: 400 })
+ return data<UserSettingsActionData>(
+ { intent, error: 'Membership ID is required' },
+ { status: 400 },
+ )
}
- const result = await serverFetch(request, `user/organisation/${membershipId}`, {
- method: 'POST',
- })
+ const result = await serverFetch(
+ request,
+ `user/organisation/${membershipId}`,
+ {
+ method: 'POST',
+ },
+ )
if (result.error) {
- return data<UserSettingsActionData>({ intent, error: result.error as string }, { status: 400 })
+ return data<UserSettingsActionData>(
+ { intent, error: result.error as string },
+ { status: 400 },
+ )
}
return data<UserSettingsActionData>(
@@ -362,15 +459,25 @@ export async function action({ request }: ActionFunctionArgs) {
const membershipId = formData.get('membershipId')?.toString()
if (!membershipId) {
- return data<UserSettingsActionData>({ intent, error: 'Membership ID is required' }, { status: 400 })
+ return data<UserSettingsActionData>(
+ { intent, error: 'Membership ID is required' },
+ { status: 400 },
+ )
}
- const result = await serverFetch(request, `user/organisation/${membershipId}`, {
- method: 'DELETE',
- })
+ const result = await serverFetch(
+ request,
+ `user/organisation/${membershipId}`,
+ {
+ method: 'DELETE',
+ },
+ )
if (result.error) {
- return data<UserSettingsActionData>({ intent, error: result.error as string }, { status: 400 })
+ return data<UserSettingsActionData>(
+ { intent, error: result.error as string },
+ { status: 400 },
+ )
}
return data<UserSettingsActionData>(
@@ -380,7 +487,10 @@ export async function action({ request }: ActionFunctionArgs) {
}
default:
- return data<UserSettingsActionData>({ error: 'Unknown action' }, { status: 400 })
+ return data<UserSettingsActionData>(
+ { error: 'Unknown action' },
+ { status: 400 },
+ )
}
}
diff --git a/web/app/routes/verify.$id.tsx b/web/app/routes/verify.$id.tsx
index e04d2e56a..41c8e4f70 100644
--- a/web/app/routes/verify.$id.tsx
+++ b/web/app/routes/verify.$id.tsx
@@ -16,7 +16,10 @@ export interface VerifyEmailLoaderData {
error?: string
}
-export async function loader({ request, params }: LoaderFunctionArgs): Promise<VerifyEmailLoaderData | Response> {
+export async function loader({
+ request,
+ params,
+}: LoaderFunctionArgs): Promise<VerifyEmailLoaderData | Response> {
if (isSelfhosted) {
return redirect('/login', 302)
}
@@ -32,7 +35,8 @@ export async function loader({ request, params }: LoaderFunctionArgs): Promise<V
})
if (result.error) {
- const errorMessage = typeof result.error === 'string' ? result.error : 'Verification failed'
+ const errorMessage =
+ typeof result.error === 'string' ? result.error : 'Verification failed'
return { success: false, error: errorMessage }
}
@@ -59,7 +63,13 @@ export default function VerifyEmailRoute() {
<StatusPage
type='success'
title='Email verified successfully'
- actions={[{ label: 'Continue to Onboarding', to: routes.onboarding, primary: true }]}
+ actions={[
+ {
+ label: 'Continue to Onboarding',
+ to: routes.onboarding,
+ primary: true,
+ },
+ ]}
/>
)
}
diff --git a/web/app/styles/tailwind.css b/web/app/styles/tailwind.css
index 494b31f33..d3f501de8 100644
--- a/web/app/styles/tailwind.css
+++ b/web/app/styles/tailwind.css
@@ -6,12 +6,18 @@
@theme {
/* Fonts */
--font-sans:
- -apple-system, system-ui, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', ui-sans-serif, sans-serif,
- ui-sans-serif, system-ui, sans-serif, 'Apple Color Emoji', 'Segoe UI Emoji', 'Segoe UI Symbol', 'Noto Color Emoji';
- --font-mono: ui-monospace, SFMono-Regular, SF Mono, Menlo, Consolas, Liberation Mono, monospace;
+ -apple-system, system-ui, BlinkMacSystemFont, 'Segoe UI', Roboto,
+ 'Helvetica Neue', ui-sans-serif, sans-serif, ui-sans-serif, system-ui,
+ sans-serif, 'Apple Color Emoji', 'Segoe UI Emoji', 'Segoe UI Symbol',
+ 'Noto Color Emoji';
+ --font-mono:
+ ui-monospace, SFMono-Regular, SF Mono, Menlo, Consolas, Liberation Mono,
+ monospace;
/* Colors */
- --color-gray-750: oklch(23.11% 0.0357 262.54); /* Converting #141d2e to OKLCH */
+ --color-gray-750: oklch(
+ 23.11% 0.0357 262.54
+ ); /* Converting #141d2e to OKLCH */
/* Heights */
--header-height: 60px;
@@ -207,33 +213,41 @@
/* Open animations (handle both delayed and instant) */
.tooltip-content[data-state='delayed-open'][data-side='top'],
.tooltip-content[data-state='instant-open'][data-side='top'] {
- animation: tooltipSlideUpAndFadeIn var(--default-transition-duration, 250ms) cubic-bezier(0.16, 1, 0.3, 1);
+ animation: tooltipSlideUpAndFadeIn var(--default-transition-duration, 250ms)
+ cubic-bezier(0.16, 1, 0.3, 1);
}
.tooltip-content[data-state='delayed-open'][data-side='bottom'],
.tooltip-content[data-state='instant-open'][data-side='bottom'] {
- animation: tooltipSlideDownAndFadeIn var(--default-transition-duration, 250ms) cubic-bezier(0.16, 1, 0.3, 1);
+ animation: tooltipSlideDownAndFadeIn
+ var(--default-transition-duration, 250ms) cubic-bezier(0.16, 1, 0.3, 1);
}
.tooltip-content[data-state='delayed-open'][data-side='left'],
.tooltip-content[data-state='instant-open'][data-side='left'] {
- animation: tooltipSlideLeftAndFadeIn var(--default-transition-duration, 250ms) cubic-bezier(0.16, 1, 0.3, 1);
+ animation: tooltipSlideLeftAndFadeIn
+ var(--default-transition-duration, 250ms) cubic-bezier(0.16, 1, 0.3, 1);
}
.tooltip-content[data-state='delayed-open'][data-side='right'],
.tooltip-content[data-state='instant-open'][data-side='right'] {
- animation: tooltipSlideRightAndFadeIn var(--default-transition-duration, 250ms) cubic-bezier(0.16, 1, 0.3, 1);
+ animation: tooltipSlideRightAndFadeIn
+ var(--default-transition-duration, 250ms) cubic-bezier(0.16, 1, 0.3, 1);
}
/* Close animations */
.tooltip-content[data-state='closed'][data-side='top'] {
- animation: tooltipSlideUpAndFadeOut var(--default-transition-duration, 250ms) cubic-bezier(0.16, 1, 0.3, 1);
+ animation: tooltipSlideUpAndFadeOut
+ var(--default-transition-duration, 250ms) cubic-bezier(0.16, 1, 0.3, 1);
}
.tooltip-content[data-state='closed'][data-side='bottom'] {
- animation: tooltipSlideDownAndFadeOut var(--default-transition-duration, 250ms) cubic-bezier(0.16, 1, 0.3, 1);
+ animation: tooltipSlideDownAndFadeOut
+ var(--default-transition-duration, 250ms) cubic-bezier(0.16, 1, 0.3, 1);
}
.tooltip-content[data-state='closed'][data-side='left'] {
- animation: tooltipSlideLeftAndFadeOut var(--default-transition-duration, 250ms) cubic-bezier(0.16, 1, 0.3, 1);
+ animation: tooltipSlideLeftAndFadeOut
+ var(--default-transition-duration, 250ms) cubic-bezier(0.16, 1, 0.3, 1);
}
.tooltip-content[data-state='closed'][data-side='right'] {
- animation: tooltipSlideRightAndFadeOut var(--default-transition-duration, 250ms) cubic-bezier(0.16, 1, 0.3, 1);
+ animation: tooltipSlideRightAndFadeOut
+ var(--default-transition-duration, 250ms) cubic-bezier(0.16, 1, 0.3, 1);
}
}
diff --git a/web/app/ui/BillboardChart.tsx b/web/app/ui/BillboardChart.tsx
index 62094e43e..dd93391fc 100644
--- a/web/app/ui/BillboardChart.tsx
+++ b/web/app/ui/BillboardChart.tsx
@@ -9,11 +9,20 @@ interface BillboardChartProps {
deps?: any[]
}
-const BillboardChart = ({ options, dataNames, className, onReady, deps }: BillboardChartProps) => {
+const BillboardChart = ({
+ options,
+ dataNames,
+ className,
+ onReady,
+ deps,
+}: BillboardChartProps) => {
const containerRef = useRef<HTMLDivElement | null>(null)
const chartRef = useRef<Chart | null>(null)
- const mergedDeps = useMemo(() => deps || [options, dataNames], [deps, options, dataNames])
+ const mergedDeps = useMemo(
+ () => deps || [options, dataNames],
+ [deps, options, dataNames],
+ )
useEffect(() => {
if (!containerRef.current) {
@@ -30,7 +39,10 @@ const BillboardChart = ({ options, dataNames, className, onReady, deps }: Billbo
if (onReady) onReady(null)
}
- const opts: ChartOptions = { ...options, bindto: containerRef.current as unknown as HTMLElement }
+ const opts: ChartOptions = {
+ ...options,
+ bindto: containerRef.current as unknown as HTMLElement,
+ }
const chart = billboard.generate(opts)
chartRef.current = chart
diff --git a/web/app/ui/Button.tsx b/web/app/ui/Button.tsx
index 21c1e8253..939613905 100644
--- a/web/app/ui/Button.tsx
+++ b/web/app/ui/Button.tsx
@@ -5,7 +5,9 @@ import { cn } from '~/utils/generic'
import Spin from './icons/Spin'
-interface ButtonProps extends React.ComponentPropsWithoutRef<typeof HeadlessButton> {
+interface ButtonProps extends React.ComponentPropsWithoutRef<
+ typeof HeadlessButton
+> {
text?: string
children?: React.ReactNode
primary?: boolean
@@ -56,20 +58,24 @@ const Button = ({
{
'border-transparent bg-slate-900 text-gray-50 shadow-xs hover:bg-slate-700 dark:border-slate-700/50 dark:bg-slate-800 dark:hover:bg-slate-700':
primary,
- 'border-transparent bg-slate-300 text-slate-900 hover:bg-slate-200': secondary,
+ 'border-transparent bg-slate-300 text-slate-900 hover:bg-slate-200':
+ secondary,
'border-transparent bg-white text-gray-700 hover:bg-gray-50': white,
- 'border-transparent bg-red-500 text-gray-50 hover:bg-red-600 dark:bg-red-600 dark:hover:bg-red-700': danger,
+ 'border-transparent bg-red-500 text-gray-50 hover:bg-red-600 dark:bg-red-600 dark:hover:bg-red-700':
+ danger,
'border-1 border-red-600 text-red-500 hover:bg-red-500 hover:text-white dark:border-red-500 dark:text-red-200 dark:hover:bg-red-600':
semiDanger,
'border-transparent bg-transparent text-gray-700 hover:border-gray-300 hover:bg-white dark:text-gray-200 dark:hover:border-slate-700/80 dark:hover:bg-slate-800':
ghost,
- 'border-none text-gray-700 focus:border-none focus:ring-0 focus:ring-offset-0 dark:text-white': noBorder,
+ 'border-none text-gray-700 focus:border-none focus:ring-0 focus:ring-offset-0 dark:text-white':
+ noBorder,
'px-2.5 py-1.5 text-xs': small,
'px-2.5 py-1.5 text-sm': semiSmall,
'px-4 py-2 text-sm': large,
'px-6 py-3 text-base': giant,
'px-3 py-2 text-sm': regular,
- 'focus:ring-2 focus:ring-indigo-500 focus:ring-offset-2 focus:outline-hidden': focus,
+ 'focus:ring-2 focus:ring-indigo-500 focus:ring-offset-2 focus:outline-hidden':
+ focus,
},
className,
)}
diff --git a/web/app/ui/Checkbox.tsx b/web/app/ui/Checkbox.tsx
index 9841295e3..cabfc647c 100644
--- a/web/app/ui/Checkbox.tsx
+++ b/web/app/ui/Checkbox.tsx
@@ -1,4 +1,9 @@
-import { Checkbox as HeadlessCheckbox, Description, Field, Label } from '@headlessui/react'
+import {
+ Checkbox as HeadlessCheckbox,
+ Description,
+ Field,
+ Label,
+} from '@headlessui/react'
import { CheckIcon } from '@heroicons/react/24/outline'
import cx from 'clsx'
import React, { memo } from 'react'
@@ -16,7 +21,15 @@ interface CheckboxProps {
}
}
-const Checkbox = ({ label, hint, name, onChange, checked, disabled, classes }: CheckboxProps) => (
+const Checkbox = ({
+ label,
+ hint,
+ name,
+ onChange,
+ checked,
+ disabled,
+ classes,
+}: CheckboxProps) => (
<Field disabled={disabled}>
<div className={cx('flex items-center gap-2', classes?.label)}>
<HeadlessCheckbox
@@ -27,10 +40,19 @@ const Checkbox = ({ label, hint, name, onChange, checked, disabled, classes }: C
>
<CheckIcon className='pointer-events-none size-4 scale-90 text-white opacity-0 transition-all duration-100 group-data-[checked]:scale-100 group-data-[checked]:opacity-100 dark:text-black' />
</HeadlessCheckbox>
- <Label className='cursor-pointer text-sm font-medium text-gray-900 dark:text-gray-200'>{label}</Label>
+ <Label className='cursor-pointer text-sm font-medium text-gray-900 dark:text-gray-200'>
+ {label}
+ </Label>
</div>
{hint ? (
- <Description className={cx('mt-1 text-sm text-gray-500 dark:text-gray-300', classes?.hint)}>{hint}</Description>
+ <Description
+ className={cx(
+ 'mt-1 text-sm text-gray-500 dark:text-gray-300',
+ classes?.hint,
+ )}
+ >
+ {hint}
+ </Description>
) : null}
</Field>
)
diff --git a/web/app/ui/Combobox.tsx b/web/app/ui/Combobox.tsx
index f70a7c42b..7730cce5e 100644
--- a/web/app/ui/Combobox.tsx
+++ b/web/app/ui/Combobox.tsx
@@ -60,12 +60,17 @@ const Combobox = ({
buttonClassName,
)}
// @ts-expect-error
- displayValue={(item) => (labelExtractor ? labelExtractor(item, 0) : item)}
+ displayValue={(item) =>
+ labelExtractor ? labelExtractor(item, 0) : item
+ }
onChange={(event) => setQuery(event.target.value)}
placeholder={placeholder}
/>
<ComboboxButton className='absolute inset-y-0 right-0 flex items-center pr-2'>
- <ChevronUpDownIcon className='h-5 w-5 text-gray-400' aria-hidden='true' />
+ <ChevronUpDownIcon
+ className='h-5 w-5 text-gray-400'
+ aria-hidden='true'
+ />
</ComboboxButton>
</div>
<Transition
@@ -85,24 +90,32 @@ const Combobox = ({
<ComboboxOption
key={keyExtractor ? keyExtractor(item, index) : item}
className={({ active }) =>
- cx('relative cursor-default py-2 pr-4 pl-8 select-none dark:text-white', {
- 'bg-indigo-600 text-white': active,
- 'text-gray-900': !active,
- })
+ cx(
+ 'relative cursor-default py-2 pr-4 pl-8 select-none dark:text-white',
+ {
+ 'bg-indigo-600 text-white': active,
+ 'text-gray-900': !active,
+ },
+ )
}
value={labelExtractor ? labelExtractor(item, index) : item}
>
{({ selected, active }) => (
<>
- <span className={`block truncate ${selected ? 'font-medium' : 'font-normal'}`}>
+ <span
+ className={`block truncate ${selected ? 'font-medium' : 'font-normal'}`}
+ >
{labelExtractor ? labelExtractor(item, index) : item}
</span>
{selected ? (
<span
- className={cx('absolute inset-y-0 left-0 flex items-center pl-1.5', {
- 'text-white': active,
- 'text-indigo-600': !active,
- })}
+ className={cx(
+ 'absolute inset-y-0 left-0 flex items-center pl-1.5',
+ {
+ 'text-white': active,
+ 'text-indigo-600': !active,
+ },
+ )}
>
<CheckIcon className='h-5 w-5' aria-hidden='true' />
</span>
diff --git a/web/app/ui/Datepicker.tsx b/web/app/ui/Datepicker.tsx
index 7bd723646..eaf48ec86 100644
--- a/web/app/ui/Datepicker.tsx
+++ b/web/app/ui/Datepicker.tsx
@@ -2,7 +2,15 @@ import cx from 'clsx'
import _clamp from 'lodash/clamp'
import _isEmpty from 'lodash/isEmpty'
import { ChevronLeftIcon, ChevronRightIcon } from 'lucide-react'
-import React, { memo, useEffect, useImperativeHandle, useMemo, useRef, useState, forwardRef } from 'react'
+import React, {
+ memo,
+ useEffect,
+ useImperativeHandle,
+ useMemo,
+ useRef,
+ useState,
+ forwardRef,
+} from 'react'
import { useTranslation } from 'react-i18next'
import useOnClickOutside from '~/hooks/useOnClickOutside'
@@ -24,8 +32,10 @@ type DatePickerHandle = {
closeCalendar: () => void
}
-const startOfDay = (d: Date) => new Date(d.getFullYear(), d.getMonth(), d.getDate())
-const endOfDay = (d: Date) => new Date(d.getFullYear(), d.getMonth(), d.getDate(), 23, 59, 59, 999)
+const startOfDay = (d: Date) =>
+ new Date(d.getFullYear(), d.getMonth(), d.getDate())
+const endOfDay = (d: Date) =>
+ new Date(d.getFullYear(), d.getMonth(), d.getDate(), 23, 59, 59, 999)
const addDays = (d: Date, days: number) => {
const res = new Date(d)
@@ -43,12 +53,18 @@ const removeMonths = (date: Date, months: number) => {
}
const areSameDay = (a: Date, b: Date) =>
- a.getFullYear() === b.getFullYear() && a.getMonth() === b.getMonth() && a.getDate() === b.getDate()
+ a.getFullYear() === b.getFullYear() &&
+ a.getMonth() === b.getMonth() &&
+ a.getDate() === b.getDate()
const getDaysMatrix = (anchor: Date) => {
const firstDay = new Date(anchor.getFullYear(), anchor.getMonth(), 1)
const startWeekday = firstDay.getDay() // 0 Sun .. 6 Sat
- const daysInMonth = new Date(anchor.getFullYear(), anchor.getMonth() + 1, 0).getDate()
+ const daysInMonth = new Date(
+ anchor.getFullYear(),
+ anchor.getMonth() + 1,
+ 0,
+ ).getDate()
const days: Date[] = []
// Prev month padding
@@ -67,461 +83,595 @@ const getDaysMatrix = (anchor: Date) => {
return days
}
-const formatRangeLabel = (locale: string, value?: Date[], mode: 'single' | 'range' = 'range') => {
+const formatRangeLabel = (
+ locale: string,
+ value?: Date[],
+ mode: 'single' | 'range' = 'range',
+) => {
if (!value || value.length < 1) return ''
- const formatter = new Intl.DateTimeFormat(locale, { year: 'numeric', month: 'short', day: '2-digit' })
- if (mode === 'single' || value.length === 1 || !value[1]) return formatter.format(value[0])
+ const formatter = new Intl.DateTimeFormat(locale, {
+ year: 'numeric',
+ month: 'short',
+ day: '2-digit',
+ })
+ if (mode === 'single' || value.length === 1 || !value[1])
+ return formatter.format(value[0])
return `${formatter.format(value[0])} — ${formatter.format(value[1])}`
}
-const DatePicker = forwardRef<DatePickerHandle, DatePickerProps>(function DatePickerInner(
- { onChange, value = [], maxDateMonths = MAX_MONTHS_IN_PAST, options, maxRange = 0, className, mode = 'range' },
- ref,
-) {
- const isSingleMode = mode === 'single'
- const { i18n } = useTranslation('common')
- const locale = i18n.language
-
- const today = useMemo(() => startOfDay(new Date()), [])
- const absoluteMinDate = useMemo(() => startOfDay(removeMonths(new Date(), maxDateMonths)), [maxDateMonths])
-
- const [open, setOpen] = useState(false)
- const [anchorMonth, setAnchorMonth] = useState<Date>(() => startOfDay(value?.[0] || today))
- const [start, setStart] = useState<Date | null>(() => (value?.[0] ? startOfDay(value[0]) : null))
- const [end, setEnd] = useState<Date | null>(() => (value?.[1] ? startOfDay(value[1]) : null))
- const [hoverDate, setHoverDate] = useState<Date | null>(null)
- const popoverRef = useRef<HTMLDivElement>(null)
-
- // Close on outside click
- useOnClickOutside(popoverRef as React.RefObject<HTMLDivElement | HTMLUListElement>, () => setOpen(false))
-
- // Imperative API
- useImperativeHandle(ref, () => ({
- openCalendar: () => setOpen(true),
- closeCalendar: () => setOpen(false),
- }))
-
- // Sync with external value
- useEffect(() => {
- if (!_isEmpty(value)) {
- setStart(value[0] ? startOfDay(value[0]) : null) // eslint-disable-line react-hooks/set-state-in-effect -- Syncing internal state with controlled value prop
- setEnd(value[1] ? startOfDay(value[1]) : null)
- if (value[0]) setAnchorMonth(startOfDay(value[0]))
+const DatePicker = forwardRef<DatePickerHandle, DatePickerProps>(
+ function DatePickerInner(
+ {
+ onChange,
+ value = [],
+ maxDateMonths = MAX_MONTHS_IN_PAST,
+ options,
+ maxRange = 0,
+ className,
+ mode = 'range',
+ },
+ ref,
+ ) {
+ const isSingleMode = mode === 'single'
+ const { i18n } = useTranslation('common')
+ const locale = i18n.language
+
+ const today = useMemo(() => startOfDay(new Date()), [])
+ const absoluteMinDate = useMemo(
+ () => startOfDay(removeMonths(new Date(), maxDateMonths)),
+ [maxDateMonths],
+ )
+
+ const [open, setOpen] = useState(false)
+ const [anchorMonth, setAnchorMonth] = useState<Date>(() =>
+ startOfDay(value?.[0] || today),
+ )
+ const [start, setStart] = useState<Date | null>(() =>
+ value?.[0] ? startOfDay(value[0]) : null,
+ )
+ const [end, setEnd] = useState<Date | null>(() =>
+ value?.[1] ? startOfDay(value[1]) : null,
+ )
+ const [hoverDate, setHoverDate] = useState<Date | null>(null)
+ const popoverRef = useRef<HTMLDivElement>(null)
+
+ // Close on outside click
+ useOnClickOutside(
+ popoverRef as React.RefObject<HTMLDivElement | HTMLUListElement>,
+ () => setOpen(false),
+ )
+
+ // Imperative API
+ useImperativeHandle(ref, () => ({
+ openCalendar: () => setOpen(true),
+ closeCalendar: () => setOpen(false),
+ }))
+
+ // Sync with external value
+ useEffect(() => {
+ if (!_isEmpty(value)) {
+ setStart(value[0] ? startOfDay(value[0]) : null) // eslint-disable-line react-hooks/set-state-in-effect -- Syncing internal state with controlled value prop
+ setEnd(value[1] ? startOfDay(value[1]) : null)
+ if (value[0]) setAnchorMonth(startOfDay(value[0]))
+ }
+ }, [value])
+
+ const weekFormatter = useMemo(
+ () => new Intl.DateTimeFormat(locale, { weekday: 'short' }),
+ [locale],
+ )
+
+ const weekdays = useMemo(() => {
+ const base = new Date(2021, 7, 1) // Sunday
+ return Array.from({ length: 7 }).map((_, i) =>
+ weekFormatter.format(addDays(base, i)),
+ )
+ }, [weekFormatter])
+
+ const rangeBounds = useMemo(() => {
+ if (!start || maxRange <= 0) {
+ return { min: absoluteMinDate, max: today }
+ }
+ const min = startOfDay(addDays(start, -maxRange))
+ const max = startOfDay(addDays(start, maxRange))
+ return {
+ min: min < absoluteMinDate ? absoluteMinDate : min,
+ max: max > today ? today : max,
+ }
+ }, [start, maxRange, absoluteMinDate, today])
+
+ const isDisabled = (d: Date) => {
+ const sd = startOfDay(d)
+ if (sd < rangeBounds.min) return true
+ if (sd > rangeBounds.max) return true
+ return false
}
- }, [value])
-
- const weekFormatter = useMemo(() => new Intl.DateTimeFormat(locale, { weekday: 'short' }), [locale])
-
- const weekdays = useMemo(() => {
- const base = new Date(2021, 7, 1) // Sunday
- return Array.from({ length: 7 }).map((_, i) => weekFormatter.format(addDays(base, i)))
- }, [weekFormatter])
- const rangeBounds = useMemo(() => {
- if (!start || maxRange <= 0) {
- return { min: absoluteMinDate, max: today }
+ const isInCurrentMonth = (d: Date) =>
+ d.getMonth() === anchorMonth.getMonth() &&
+ d.getFullYear() === anchorMonth.getFullYear()
+
+ const days = useMemo(() => getDaysMatrix(anchorMonth), [anchorMonth])
+
+ const minYear = absoluteMinDate.getFullYear()
+ const maxYear = today.getFullYear()
+ const minMonthOfMinYear = absoluteMinDate.getMonth()
+ const maxMonthOfMaxYear = today.getMonth()
+
+ const monthNames = useMemo(
+ () =>
+ Array.from({ length: 12 }).map((_, idx) =>
+ new Intl.DateTimeFormat(locale, { month: 'short' }).format(
+ new Date(2021, idx, 1),
+ ),
+ ),
+ [locale],
+ )
+
+ const setAnchor = (year: number, month: number) => {
+ const clampedYear = Math.max(minYear, Math.min(maxYear, year))
+ let clampedMonth = month
+ if (clampedYear === minYear)
+ clampedMonth = Math.max(minMonthOfMinYear, clampedMonth)
+ if (clampedYear === maxYear)
+ clampedMonth = Math.min(maxMonthOfMaxYear, clampedMonth)
+ setAnchorMonth(new Date(clampedYear, clampedMonth, 1))
}
- const min = startOfDay(addDays(start, -maxRange))
- const max = startOfDay(addDays(start, maxRange))
- return { min: min < absoluteMinDate ? absoluteMinDate : min, max: max > today ? today : max }
- }, [start, maxRange, absoluteMinDate, today])
-
- const isDisabled = (d: Date) => {
- const sd = startOfDay(d)
- if (sd < rangeBounds.min) return true
- if (sd > rangeBounds.max) return true
- return false
- }
-
- const isInCurrentMonth = (d: Date) =>
- d.getMonth() === anchorMonth.getMonth() && d.getFullYear() === anchorMonth.getFullYear()
-
- const days = useMemo(() => getDaysMatrix(anchorMonth), [anchorMonth])
-
- const minYear = absoluteMinDate.getFullYear()
- const maxYear = today.getFullYear()
- const minMonthOfMinYear = absoluteMinDate.getMonth()
- const maxMonthOfMaxYear = today.getMonth()
-
- const monthNames = useMemo(
- () =>
- Array.from({ length: 12 }).map((_, idx) =>
- new Intl.DateTimeFormat(locale, { month: 'short' }).format(new Date(2021, idx, 1)),
- ),
- [locale],
- )
-
- const setAnchor = (year: number, month: number) => {
- const clampedYear = Math.max(minYear, Math.min(maxYear, year))
- let clampedMonth = month
- if (clampedYear === minYear) clampedMonth = Math.max(minMonthOfMinYear, clampedMonth)
- if (clampedYear === maxYear) clampedMonth = Math.min(maxMonthOfMaxYear, clampedMonth)
- setAnchorMonth(new Date(clampedYear, clampedMonth, 1))
- }
-
- const handlePrevMonth = () => {
- const prev = new Date(anchorMonth.getFullYear(), anchorMonth.getMonth() - 1, 1)
- // Clamp within [absoluteMinDate, today]
- const minMonth = new Date(absoluteMinDate.getFullYear(), absoluteMinDate.getMonth(), 1)
- if (prev < minMonth) return
- setAnchorMonth(prev)
- }
-
- const handleNextMonth = () => {
- const next = new Date(anchorMonth.getFullYear(), anchorMonth.getMonth() + 1, 1)
- const maxMonth = new Date(today.getFullYear(), today.getMonth(), 1)
- if (next > maxMonth) return
- setAnchorMonth(next)
- }
- const commitRange = (a: Date, b: Date) => {
- const from = startOfDay(a)
- const to = startOfDay(b)
- const startN = from <= to ? from : to
- const endN = from <= to ? to : from
- setStart(startN)
- setEnd(endN)
- onChange?.([startN, endOfDay(endN)])
- setOpen(false)
- }
+ const handlePrevMonth = () => {
+ const prev = new Date(
+ anchorMonth.getFullYear(),
+ anchorMonth.getMonth() - 1,
+ 1,
+ )
+ // Clamp within [absoluteMinDate, today]
+ const minMonth = new Date(
+ absoluteMinDate.getFullYear(),
+ absoluteMinDate.getMonth(),
+ 1,
+ )
+ if (prev < minMonth) return
+ setAnchorMonth(prev)
+ }
- const onDayClick = (d: Date) => {
- const sd = startOfDay(d)
+ const handleNextMonth = () => {
+ const next = new Date(
+ anchorMonth.getFullYear(),
+ anchorMonth.getMonth() + 1,
+ 1,
+ )
+ const maxMonth = new Date(today.getFullYear(), today.getMonth(), 1)
+ if (next > maxMonth) return
+ setAnchorMonth(next)
+ }
- // Single mode: immediately select and close
- if (isSingleMode) {
- setStart(sd)
- setEnd(null)
- onChange?.([sd])
+ const commitRange = (a: Date, b: Date) => {
+ const from = startOfDay(a)
+ const to = startOfDay(b)
+ const startN = from <= to ? from : to
+ const endN = from <= to ? to : from
+ setStart(startN)
+ setEnd(endN)
+ onChange?.([startN, endOfDay(endN)])
setOpen(false)
- return
}
- // Range mode logic
- if (!start || (start && end)) {
- setStart(sd)
- setEnd(null)
- setHoverDate(null)
- // Move anchor when clicking other month day
- setAnchorMonth(new Date(sd.getFullYear(), sd.getMonth(), 1))
- return
- }
- // If second click on the same date -> single-day range
- if (start && areSameDay(start, sd)) {
- commitRange(sd, sd)
- return
- }
- // Enforce maxRange
- if (maxRange > 0) {
- const minAllowed = startOfDay(addDays(start, -maxRange))
- const maxAllowed = startOfDay(addDays(start, maxRange))
- const clamped = startOfDay(
- new Date(_clamp(sd.getTime(), minAllowed.getTime(), Math.min(maxAllowed.getTime(), today.getTime()))),
- )
- commitRange(start, clamped)
- return
+ const onDayClick = (d: Date) => {
+ const sd = startOfDay(d)
+
+ // Single mode: immediately select and close
+ if (isSingleMode) {
+ setStart(sd)
+ setEnd(null)
+ onChange?.([sd])
+ setOpen(false)
+ return
+ }
+
+ // Range mode logic
+ if (!start || (start && end)) {
+ setStart(sd)
+ setEnd(null)
+ setHoverDate(null)
+ // Move anchor when clicking other month day
+ setAnchorMonth(new Date(sd.getFullYear(), sd.getMonth(), 1))
+ return
+ }
+ // If second click on the same date -> single-day range
+ if (start && areSameDay(start, sd)) {
+ commitRange(sd, sd)
+ return
+ }
+ // Enforce maxRange
+ if (maxRange > 0) {
+ const minAllowed = startOfDay(addDays(start, -maxRange))
+ const maxAllowed = startOfDay(addDays(start, maxRange))
+ const clamped = startOfDay(
+ new Date(
+ _clamp(
+ sd.getTime(),
+ minAllowed.getTime(),
+ Math.min(maxAllowed.getTime(), today.getTime()),
+ ),
+ ),
+ )
+ commitRange(start, clamped)
+ return
+ }
+ commitRange(start, sd)
}
- commitRange(start, sd)
- }
- const inRange = (d: Date) => {
- // No range highlighting in single mode
- if (isSingleMode) return false
- if (!start) return false
- const sd = startOfDay(d)
- const [lo, hi] = end
- ? [start <= end ? start : end, start <= end ? end : start]
- : hoverDate
- ? [start <= hoverDate ? start : hoverDate, start <= hoverDate ? hoverDate : start]
- : [null, null]
- if (!lo || !hi) return false
- return sd >= lo && sd <= hi
- }
+ const inRange = (d: Date) => {
+ // No range highlighting in single mode
+ if (isSingleMode) return false
+ if (!start) return false
+ const sd = startOfDay(d)
+ const [lo, hi] = end
+ ? [start <= end ? start : end, start <= end ? end : start]
+ : hoverDate
+ ? [
+ start <= hoverDate ? start : hoverDate,
+ start <= hoverDate ? hoverDate : start,
+ ]
+ : [null, null]
+ if (!lo || !hi) return false
+ return sd >= lo && sd <= hi
+ }
- const label = useMemo(
- () => formatRangeLabel(locale, start && end ? [start, end] : start ? [start] : [], mode),
- [locale, start, end, mode],
- )
-
- return (
- <div className={options ? undefined : cn('relative inline-block h-0 align-top', className)}>
- {/* Trigger input (optional visible) */}
- {options ? (
- <input
- readOnly
- onClick={() => setOpen(true)}
- value={label || ''}
- placeholder={isSingleMode ? 'Select a date...' : 'Select a date range...'}
- className={options.altInputClass}
- />
- ) : null}
-
- {/* Popover */}
- {open ? (
- options ? (
- // Centered modal when used as input
- <div className='fixed inset-0 z-50 flex items-start justify-center bg-black/20 p-4'>
- <div
- ref={popoverRef}
- className='mt-10 w-[320px] rounded-xl border border-gray-200 bg-white p-3 shadow-xl dark:border-slate-800 dark:bg-slate-900'
- >
- <div className='flex items-center justify-between'>
- <button
- type='button'
- className='rounded-md p-2 hover:bg-gray-100 dark:hover:bg-slate-800'
- onClick={handlePrevMonth}
- aria-label='Previous month'
- >
- <ChevronLeftIcon className='size-5' />
- </button>
- <div className='flex items-center gap-2'>
- <div className='relative'>
- <select
- aria-label='Month'
- className='appearance-none rounded-md border border-gray-200 bg-white px-2 py-1 pr-7 text-sm text-gray-900 hover:bg-gray-50 dark:border-slate-700 dark:bg-slate-800 dark:text-gray-50'
- value={anchorMonth.getMonth()}
- onChange={(e) => setAnchor(anchorMonth.getFullYear(), Number(e.target.value))}
- >
- {monthNames.map((m, idx) => (
- <option
- key={idx}
- value={idx}
- disabled={
- (anchorMonth.getFullYear() === minYear && idx < minMonthOfMinYear) ||
- (anchorMonth.getFullYear() === maxYear && idx > maxMonthOfMaxYear)
- }
- >
- {m}
- </option>
- ))}
- </select>
- </div>
- <div className='relative'>
- <select
- aria-label='Year'
- className='appearance-none rounded-md border border-gray-200 bg-white px-2 py-1 pr-7 text-sm text-gray-900 hover:bg-gray-50 dark:border-slate-700 dark:bg-slate-800 dark:text-gray-50'
- value={anchorMonth.getFullYear()}
- onChange={(e) => setAnchor(Number(e.target.value), anchorMonth.getMonth())}
- >
- {Array.from({ length: maxYear - minYear + 1 }).map((_, i) => {
- const y = minYear + i
- return (
- <option key={y} value={y}>
- {y}
- </option>
- )
- })}
- </select>
- </div>
- </div>
- <button
- type='button'
- className='rounded-md p-2 hover:bg-gray-100 dark:hover:bg-slate-800'
- onClick={handleNextMonth}
- aria-label='Next month'
- >
- <ChevronRightIcon className='size-5' />
- </button>
- </div>
- <div className='mt-2 grid grid-cols-7 gap-1 text-center text-xs text-gray-500 dark:text-gray-300'>
- {weekdays.map((wd, idx) => (
- <div key={idx}>{wd}</div>
- ))}
- </div>
- <div className='mt-1 grid grid-cols-7 gap-1'>
- {days.map((d, idx) => {
- const disabled = isDisabled(d)
- const isStart = !!start && areSameDay(d, start)
- const isEnd = !!end && areSameDay(d, end)
- const isBetween = inRange(d)
- const isCurrentMonth = isInCurrentMonth(d)
- return (
- <button
- key={idx}
- type='button'
- disabled={disabled}
- onMouseEnter={() => setHoverDate(start && !end ? startOfDay(d) : null)}
- onMouseLeave={() => setHoverDate(null)}
- onClick={() => !disabled && onDayClick(d)}
- className={cx('relative h-9 w-9 rounded-md text-sm select-none', {
- 'text-gray-900 dark:text-gray-100': isCurrentMonth && !disabled,
- 'text-gray-400 dark:text-gray-500': !isCurrentMonth || disabled,
- 'bg-indigo-600 text-white dark:bg-indigo-500': isStart || isEnd,
- 'bg-gray-100 dark:bg-slate-800': isBetween && !isStart && !isEnd,
- 'cursor-not-allowed opacity-50': disabled,
- 'hover:bg-gray-200 dark:hover:bg-slate-700': !disabled && !isStart && !isEnd,
- })}
- >
- {d.getDate()}
- </button>
- )
- })}
- </div>
- <div className='mt-3 flex items-center justify-between'>
- <div className='text-xs text-gray-600 dark:text-gray-300'>
- {label || new Intl.DateTimeFormat(locale, { year: 'numeric', month: 'short' }).format(anchorMonth)}
- </div>
- <div className='flex gap-2'>
+ const label = useMemo(
+ () =>
+ formatRangeLabel(
+ locale,
+ start && end ? [start, end] : start ? [start] : [],
+ mode,
+ ),
+ [locale, start, end, mode],
+ )
+
+ return (
+ <div
+ className={
+ options
+ ? undefined
+ : cn('relative inline-block h-0 align-top', className)
+ }
+ >
+ {/* Trigger input (optional visible) */}
+ {options ? (
+ <input
+ readOnly
+ onClick={() => setOpen(true)}
+ value={label || ''}
+ placeholder={
+ isSingleMode ? 'Select a date...' : 'Select a date range...'
+ }
+ className={options.altInputClass}
+ />
+ ) : null}
+
+ {/* Popover */}
+ {open ? (
+ options ? (
+ // Centered modal when used as input
+ <div className='fixed inset-0 z-50 flex items-start justify-center bg-black/20 p-4'>
+ <div
+ ref={popoverRef}
+ className='mt-10 w-[320px] rounded-xl border border-gray-200 bg-white p-3 shadow-xl dark:border-slate-800 dark:bg-slate-900'
+ >
+ <div className='flex items-center justify-between'>
<button
type='button'
- className='rounded-md px-2 py-1 text-xs text-gray-700 hover:bg-gray-100 dark:text-gray-200 dark:hover:bg-slate-800'
- onClick={() => {
- setStart(null)
- setEnd(null)
- setHoverDate(null)
- }}
+ className='rounded-md p-2 hover:bg-gray-100 dark:hover:bg-slate-800'
+ onClick={handlePrevMonth}
+ aria-label='Previous month'
>
- Clear
+ <ChevronLeftIcon className='size-5' />
</button>
+ <div className='flex items-center gap-2'>
+ <div className='relative'>
+ <select
+ aria-label='Month'
+ className='appearance-none rounded-md border border-gray-200 bg-white px-2 py-1 pr-7 text-sm text-gray-900 hover:bg-gray-50 dark:border-slate-700 dark:bg-slate-800 dark:text-gray-50'
+ value={anchorMonth.getMonth()}
+ onChange={(e) =>
+ setAnchor(
+ anchorMonth.getFullYear(),
+ Number(e.target.value),
+ )
+ }
+ >
+ {monthNames.map((m, idx) => (
+ <option
+ key={idx}
+ value={idx}
+ disabled={
+ (anchorMonth.getFullYear() === minYear &&
+ idx < minMonthOfMinYear) ||
+ (anchorMonth.getFullYear() === maxYear &&
+ idx > maxMonthOfMaxYear)
+ }
+ >
+ {m}
+ </option>
+ ))}
+ </select>
+ </div>
+ <div className='relative'>
+ <select
+ aria-label='Year'
+ className='appearance-none rounded-md border border-gray-200 bg-white px-2 py-1 pr-7 text-sm text-gray-900 hover:bg-gray-50 dark:border-slate-700 dark:bg-slate-800 dark:text-gray-50'
+ value={anchorMonth.getFullYear()}
+ onChange={(e) =>
+ setAnchor(
+ Number(e.target.value),
+ anchorMonth.getMonth(),
+ )
+ }
+ >
+ {Array.from({ length: maxYear - minYear + 1 }).map(
+ (_, i) => {
+ const y = minYear + i
+ return (
+ <option key={y} value={y}>
+ {y}
+ </option>
+ )
+ },
+ )}
+ </select>
+ </div>
+ </div>
<button
type='button'
- className='rounded-md bg-indigo-600 px-2 py-1 text-xs font-semibold text-white hover:bg-indigo-500'
- disabled={!start}
- onClick={() => {
- if (!start) return
- commitRange(start, end || start)
- }}
+ className='rounded-md p-2 hover:bg-gray-100 dark:hover:bg-slate-800'
+ onClick={handleNextMonth}
+ aria-label='Next month'
>
- Apply
+ <ChevronRightIcon className='size-5' />
</button>
</div>
- </div>
- </div>
- </div>
- ) : (
- // Anchored popover (toolbar usage)
- <div className='absolute top-7 right-0 z-50'>
- <div
- ref={popoverRef}
- className='w-[320px] rounded-xl border border-gray-200 bg-white p-3 shadow-xl dark:border-slate-800 dark:bg-slate-900'
- >
- <div className='flex items-center justify-between'>
- <button
- type='button'
- className='rounded-md p-2 hover:bg-gray-100 dark:hover:bg-slate-800'
- onClick={handlePrevMonth}
- aria-label='Previous month'
- >
- <ChevronLeftIcon className='size-5' />
- </button>
- <div className='flex items-center gap-2'>
- <div className='relative'>
- <select
- aria-label='Month'
- className='appearance-none rounded-md border border-gray-200 bg-white px-2 py-1 pr-7 text-sm text-gray-900 hover:bg-gray-50 dark:border-slate-700 dark:bg-slate-800 dark:text-gray-50'
- value={anchorMonth.getMonth()}
- onChange={(e) => setAnchor(anchorMonth.getFullYear(), Number(e.target.value))}
- >
- {monthNames.map((m, idx) => (
- <option
- key={idx}
- value={idx}
- disabled={
- (anchorMonth.getFullYear() === minYear && idx < minMonthOfMinYear) ||
- (anchorMonth.getFullYear() === maxYear && idx > maxMonthOfMaxYear)
- }
- >
- {m}
- </option>
- ))}
- </select>
+ <div className='mt-2 grid grid-cols-7 gap-1 text-center text-xs text-gray-500 dark:text-gray-300'>
+ {weekdays.map((wd, idx) => (
+ <div key={idx}>{wd}</div>
+ ))}
+ </div>
+ <div className='mt-1 grid grid-cols-7 gap-1'>
+ {days.map((d, idx) => {
+ const disabled = isDisabled(d)
+ const isStart = !!start && areSameDay(d, start)
+ const isEnd = !!end && areSameDay(d, end)
+ const isBetween = inRange(d)
+ const isCurrentMonth = isInCurrentMonth(d)
+ return (
+ <button
+ key={idx}
+ type='button'
+ disabled={disabled}
+ onMouseEnter={() =>
+ setHoverDate(start && !end ? startOfDay(d) : null)
+ }
+ onMouseLeave={() => setHoverDate(null)}
+ onClick={() => !disabled && onDayClick(d)}
+ className={cx(
+ 'relative h-9 w-9 rounded-md text-sm select-none',
+ {
+ 'text-gray-900 dark:text-gray-100':
+ isCurrentMonth && !disabled,
+ 'text-gray-400 dark:text-gray-500':
+ !isCurrentMonth || disabled,
+ 'bg-indigo-600 text-white dark:bg-indigo-500':
+ isStart || isEnd,
+ 'bg-gray-100 dark:bg-slate-800':
+ isBetween && !isStart && !isEnd,
+ 'cursor-not-allowed opacity-50': disabled,
+ 'hover:bg-gray-200 dark:hover:bg-slate-700':
+ !disabled && !isStart && !isEnd,
+ },
+ )}
+ >
+ {d.getDate()}
+ </button>
+ )
+ })}
+ </div>
+ <div className='mt-3 flex items-center justify-between'>
+ <div className='text-xs text-gray-600 dark:text-gray-300'>
+ {label ||
+ new Intl.DateTimeFormat(locale, {
+ year: 'numeric',
+ month: 'short',
+ }).format(anchorMonth)}
</div>
- <div className='relative'>
- <select
- aria-label='Year'
- className='appearance-none rounded-md border border-gray-200 bg-white px-2 py-1 pr-7 text-sm text-gray-900 hover:bg-gray-50 dark:border-slate-700 dark:bg-slate-800 dark:text-gray-50'
- value={anchorMonth.getFullYear()}
- onChange={(e) => setAnchor(Number(e.target.value), anchorMonth.getMonth())}
+ <div className='flex gap-2'>
+ <button
+ type='button'
+ className='rounded-md px-2 py-1 text-xs text-gray-700 hover:bg-gray-100 dark:text-gray-200 dark:hover:bg-slate-800'
+ onClick={() => {
+ setStart(null)
+ setEnd(null)
+ setHoverDate(null)
+ }}
>
- {Array.from({ length: maxYear - minYear + 1 }).map((_, i) => {
- const y = minYear + i
- return (
- <option key={y} value={y}>
- {y}
- </option>
- )
- })}
- </select>
- </div>
- </div>
- <button
- type='button'
- className='rounded-md p-2 hover:bg-gray-100 dark:hover:bg-slate-800'
- onClick={handleNextMonth}
- aria-label='Next month'
- >
- <ChevronRightIcon className='size-5' />
- </button>
- </div>
- <div className='mt-2 grid grid-cols-7 gap-1 text-center text-xs text-gray-500 dark:text-gray-300'>
- {weekdays.map((wd, idx) => (
- <div key={idx}>{wd}</div>
- ))}
- </div>
- <div className='mt-1 grid grid-cols-7 gap-1'>
- {days.map((d, idx) => {
- const disabled = isDisabled(d)
- const isStart = !!start && areSameDay(d, start)
- const isEnd = !!end && areSameDay(d, end)
- const isBetween = inRange(d)
- const isCurrentMonth = isInCurrentMonth(d)
- return (
+ Clear
+ </button>
<button
- key={idx}
type='button'
- disabled={disabled}
- onMouseEnter={() => setHoverDate(start && !end ? startOfDay(d) : null)}
- onMouseLeave={() => setHoverDate(null)}
- onClick={() => !disabled && onDayClick(d)}
- className={cx('relative h-9 w-9 rounded-md text-sm select-none', {
- 'text-gray-900 dark:text-gray-100': isCurrentMonth && !disabled,
- 'text-gray-400 dark:text-gray-500': !isCurrentMonth || disabled,
- 'bg-indigo-600 text-white dark:bg-indigo-500': isStart || isEnd,
- 'bg-gray-100 dark:bg-slate-800': isBetween && !isStart && !isEnd,
- 'cursor-not-allowed opacity-50': disabled,
- 'hover:bg-gray-200 dark:hover:bg-slate-700': !disabled && !isStart && !isEnd,
- })}
+ className='rounded-md bg-indigo-600 px-2 py-1 text-xs font-semibold text-white hover:bg-indigo-500'
+ disabled={!start}
+ onClick={() => {
+ if (!start) return
+ commitRange(start, end || start)
+ }}
>
- {d.getDate()}
+ Apply
</button>
- )
- })}
- </div>
- <div className='mt-3 flex items-center justify-between'>
- <div className='text-xs text-gray-600 dark:text-gray-300'>
- {label || new Intl.DateTimeFormat(locale, { year: 'numeric', month: 'short' }).format(anchorMonth)}
+ </div>
</div>
- <div className='flex gap-2'>
+ </div>
+ </div>
+ ) : (
+ // Anchored popover (toolbar usage)
+ <div className='absolute top-7 right-0 z-50'>
+ <div
+ ref={popoverRef}
+ className='w-[320px] rounded-xl border border-gray-200 bg-white p-3 shadow-xl dark:border-slate-800 dark:bg-slate-900'
+ >
+ <div className='flex items-center justify-between'>
<button
type='button'
- className='rounded-md px-2 py-1 text-xs text-gray-700 hover:bg-gray-100 dark:text-gray-200 dark:hover:bg-slate-800'
- onClick={() => {
- setStart(null)
- setEnd(null)
- setHoverDate(null)
- }}
+ className='rounded-md p-2 hover:bg-gray-100 dark:hover:bg-slate-800'
+ onClick={handlePrevMonth}
+ aria-label='Previous month'
>
- Clear
+ <ChevronLeftIcon className='size-5' />
</button>
+ <div className='flex items-center gap-2'>
+ <div className='relative'>
+ <select
+ aria-label='Month'
+ className='appearance-none rounded-md border border-gray-200 bg-white px-2 py-1 pr-7 text-sm text-gray-900 hover:bg-gray-50 dark:border-slate-700 dark:bg-slate-800 dark:text-gray-50'
+ value={anchorMonth.getMonth()}
+ onChange={(e) =>
+ setAnchor(
+ anchorMonth.getFullYear(),
+ Number(e.target.value),
+ )
+ }
+ >
+ {monthNames.map((m, idx) => (
+ <option
+ key={idx}
+ value={idx}
+ disabled={
+ (anchorMonth.getFullYear() === minYear &&
+ idx < minMonthOfMinYear) ||
+ (anchorMonth.getFullYear() === maxYear &&
+ idx > maxMonthOfMaxYear)
+ }
+ >
+ {m}
+ </option>
+ ))}
+ </select>
+ </div>
+ <div className='relative'>
+ <select
+ aria-label='Year'
+ className='appearance-none rounded-md border border-gray-200 bg-white px-2 py-1 pr-7 text-sm text-gray-900 hover:bg-gray-50 dark:border-slate-700 dark:bg-slate-800 dark:text-gray-50'
+ value={anchorMonth.getFullYear()}
+ onChange={(e) =>
+ setAnchor(
+ Number(e.target.value),
+ anchorMonth.getMonth(),
+ )
+ }
+ >
+ {Array.from({ length: maxYear - minYear + 1 }).map(
+ (_, i) => {
+ const y = minYear + i
+ return (
+ <option key={y} value={y}>
+ {y}
+ </option>
+ )
+ },
+ )}
+ </select>
+ </div>
+ </div>
<button
type='button'
- className='rounded-md bg-indigo-600 px-2 py-1 text-xs font-semibold text-white hover:bg-indigo-500'
- disabled={!start}
- onClick={() => {
- if (!start) return
- commitRange(start, end || start)
- }}
+ className='rounded-md p-2 hover:bg-gray-100 dark:hover:bg-slate-800'
+ onClick={handleNextMonth}
+ aria-label='Next month'
>
- Apply
+ <ChevronRightIcon className='size-5' />
</button>
</div>
+ <div className='mt-2 grid grid-cols-7 gap-1 text-center text-xs text-gray-500 dark:text-gray-300'>
+ {weekdays.map((wd, idx) => (
+ <div key={idx}>{wd}</div>
+ ))}
+ </div>
+ <div className='mt-1 grid grid-cols-7 gap-1'>
+ {days.map((d, idx) => {
+ const disabled = isDisabled(d)
+ const isStart = !!start && areSameDay(d, start)
+ const isEnd = !!end && areSameDay(d, end)
+ const isBetween = inRange(d)
+ const isCurrentMonth = isInCurrentMonth(d)
+ return (
+ <button
+ key={idx}
+ type='button'
+ disabled={disabled}
+ onMouseEnter={() =>
+ setHoverDate(start && !end ? startOfDay(d) : null)
+ }
+ onMouseLeave={() => setHoverDate(null)}
+ onClick={() => !disabled && onDayClick(d)}
+ className={cx(
+ 'relative h-9 w-9 rounded-md text-sm select-none',
+ {
+ 'text-gray-900 dark:text-gray-100':
+ isCurrentMonth && !disabled,
+ 'text-gray-400 dark:text-gray-500':
+ !isCurrentMonth || disabled,
+ 'bg-indigo-600 text-white dark:bg-indigo-500':
+ isStart || isEnd,
+ 'bg-gray-100 dark:bg-slate-800':
+ isBetween && !isStart && !isEnd,
+ 'cursor-not-allowed opacity-50': disabled,
+ 'hover:bg-gray-200 dark:hover:bg-slate-700':
+ !disabled && !isStart && !isEnd,
+ },
+ )}
+ >
+ {d.getDate()}
+ </button>
+ )
+ })}
+ </div>
+ <div className='mt-3 flex items-center justify-between'>
+ <div className='text-xs text-gray-600 dark:text-gray-300'>
+ {label ||
+ new Intl.DateTimeFormat(locale, {
+ year: 'numeric',
+ month: 'short',
+ }).format(anchorMonth)}
+ </div>
+ <div className='flex gap-2'>
+ <button
+ type='button'
+ className='rounded-md px-2 py-1 text-xs text-gray-700 hover:bg-gray-100 dark:text-gray-200 dark:hover:bg-slate-800'
+ onClick={() => {
+ setStart(null)
+ setEnd(null)
+ setHoverDate(null)
+ }}
+ >
+ Clear
+ </button>
+ <button
+ type='button'
+ className='rounded-md bg-indigo-600 px-2 py-1 text-xs font-semibold text-white hover:bg-indigo-500'
+ disabled={!start}
+ onClick={() => {
+ if (!start) return
+ commitRange(start, end || start)
+ }}
+ >
+ Apply
+ </button>
+ </div>
+ </div>
</div>
</div>
- </div>
- )
- ) : null}
- </div>
- )
-})
+ )
+ ) : null}
+ </div>
+ )
+ },
+)
export default memo(DatePicker)
diff --git a/web/app/ui/Dropdown.tsx b/web/app/ui/Dropdown.tsx
index 3f845427a..9f5812c5a 100644
--- a/web/app/ui/Dropdown.tsx
+++ b/web/app/ui/Dropdown.tsx
@@ -1,4 +1,10 @@
-import { Menu, MenuButton, MenuItems, MenuItem, Transition } from '@headlessui/react'
+import {
+ Menu,
+ MenuButton,
+ MenuItems,
+ MenuItem,
+ Transition,
+} from '@headlessui/react'
import { ChevronDownIcon as ChevronDownIconMini } from '@heroicons/react/20/solid'
import { ChevronDownIcon } from '@heroicons/react/24/solid'
import _isEmpty from 'lodash/isEmpty'
@@ -14,9 +20,16 @@ interface DropdownProps<T> {
desc?: string | number | React.ReactNode
className?: string
items: T[]
- labelExtractor?: (item: T, close: () => void) => string | number | React.ReactNode
+ labelExtractor?: (
+ item: T,
+ close: () => void,
+ ) => string | number | React.ReactNode
keyExtractor?: (item: T, close: () => void) => Key
- onSelect: (item: T, e: React.MouseEvent<HTMLElement>, close: () => void) => void | null
+ onSelect: (
+ item: T,
+ e: React.MouseEvent<HTMLElement>,
+ close: () => void,
+ ) => void | null
aside?: boolean
buttonClassName?: string
selectItemClassName?: string
@@ -54,7 +67,9 @@ function Dropdown<T>({
<Menu as='div' className={cn('relative inline-block text-left', className)}>
{({ open, close }) => (
<>
- {!_isEmpty(desc) ? <p className='mb-2 text-sm text-gray-900'>{desc}</p> : null}
+ {!_isEmpty(desc) ? (
+ <p className='mb-2 text-sm text-gray-900'>{desc}</p>
+ ) : null}
<MenuButton
onClick={onClick}
disabled={disabled}
@@ -65,7 +80,8 @@ function Dropdown<T>({
'justify-center': !aside,
'inline-flex w-full rounded-md border border-gray-300 bg-white px-3 py-2 text-sm font-medium hover:bg-gray-50 focus:ring-2 focus:ring-indigo-500 focus:ring-offset-2 focus:ring-offset-gray-100 focus:outline-hidden md:px-4 dark:border-gray-800 dark:bg-slate-800 dark:hover:bg-slate-700':
!headless,
- 'group inline-flex w-full px-3 py-2 text-sm font-medium outline-hidden md:px-4': headless,
+ 'group inline-flex w-full px-3 py-2 text-sm font-medium outline-hidden md:px-4':
+ headless,
'text-gray-700 dark:text-gray-50': !disabled,
'cursor-not-allowed text-gray-500 dark:text-gray-400': disabled,
},
@@ -75,17 +91,23 @@ function Dropdown<T>({
<span>{title}</span>
{chevron === 'regular' ? (
<ChevronDownIcon
- className={cn('ml-2 h-5 w-5 transform-gpu transition-transform', {
- 'rotate-180': open,
- })}
+ className={cn(
+ 'ml-2 h-5 w-5 transform-gpu transition-transform',
+ {
+ 'rotate-180': open,
+ },
+ )}
aria-hidden='true'
/>
) : null}
{chevron === 'mini' ? (
<ChevronDownIconMini
- className={cn('ml-1 h-5 w-5 transform-gpu transition-transform', {
- 'rotate-180': open,
- })}
+ className={cn(
+ 'ml-1 h-5 w-5 transform-gpu transition-transform',
+ {
+ 'rotate-180': open,
+ },
+ )}
aria-hidden='true'
/>
) : null}
@@ -112,7 +134,11 @@ function Dropdown<T>({
menuItemsClassName,
)}
>
- {header ? <p className='mb-1 p-2 text-sm font-medium text-gray-700 dark:text-gray-50'>{header}</p> : null}
+ {header ? (
+ <p className='mb-1 p-2 text-sm font-medium text-gray-700 dark:text-gray-50'>
+ {header}
+ </p>
+ ) : null}
{loading ? (
<div className='px-4 py-2'>
<Spin className='!ml-0' />
@@ -120,7 +146,11 @@ function Dropdown<T>({
</div>
) : (
_map(items, (item) => (
- <MenuItem key={keyExtractor ? keyExtractor(item, close) : (item as Key)}>
+ <MenuItem
+ key={
+ keyExtractor ? keyExtractor(item, close) : (item as Key)
+ }
+ >
<span
className={cn(
'block cursor-pointer rounded-md p-2 text-sm text-gray-700 transition-colors hover:bg-gray-200 dark:text-gray-50 dark:hover:bg-slate-700',
@@ -128,9 +158,13 @@ function Dropdown<T>({
)}
role='menuitem'
tabIndex={0}
- onClick={(e: React.MouseEvent<HTMLElement>) => onSelect(item, e, close)}
+ onClick={(e: React.MouseEvent<HTMLElement>) =>
+ onSelect(item, e, close)
+ }
>
- {labelExtractor ? labelExtractor(item, close) : (item as React.ReactNode)}
+ {labelExtractor
+ ? labelExtractor(item, close)
+ : (item as React.ReactNode)}
</span>
</MenuItem>
))
diff --git a/web/app/ui/FilterValueInput.tsx b/web/app/ui/FilterValueInput.tsx
index e7300913c..90ced1c1e 100644
--- a/web/app/ui/FilterValueInput.tsx
+++ b/web/app/ui/FilterValueInput.tsx
@@ -34,10 +34,21 @@ import {
TvIcon,
WatchIcon,
} from 'lucide-react'
-import { useState, useEffect, useCallback, useRef, useMemo, ReactNode } from 'react'
+import {
+ useState,
+ useEffect,
+ useCallback,
+ useRef,
+ useMemo,
+ ReactNode,
+} from 'react'
import { useTranslation } from 'react-i18next'
-import { BROWSER_LOGO_MAP, OS_LOGO_MAP, OS_LOGO_MAP_DARK } from '~/lib/constants'
+import {
+ BROWSER_LOGO_MAP,
+ OS_LOGO_MAP,
+ OS_LOGO_MAP_DARK,
+} from '~/lib/constants'
import Flag from '~/ui/Flag'
import Spin from '~/ui/icons/Spin'
import countries from '~/utils/isoCountries'
@@ -81,10 +92,13 @@ const deviceIconMapping: Record<string, ReactNode> = {
const VERSION_SEPARATOR = '|||'
// Helper to create combined version value
-export const createVersionValue = (parent: string, version: string) => `${parent}${VERSION_SEPARATOR}${version}`
+export const createVersionValue = (parent: string, version: string) =>
+ `${parent}${VERSION_SEPARATOR}${version}`
// Helper to parse combined version value
-export const parseVersionValue = (value: string): { parent: string; version: string } | null => {
+export const parseVersionValue = (
+ value: string,
+): { parent: string; version: string } | null => {
if (!value.includes(VERSION_SEPARATOR)) return null
const [parent, version] = value.split(VERSION_SEPARATOR)
return { parent, version }
@@ -125,7 +139,10 @@ const FilterValueInput = ({
// Close dropdown when clicking outside
useEffect(() => {
const handleClickOutside = (event: MouseEvent) => {
- if (containerRef.current && !containerRef.current.contains(event.target as Node)) {
+ if (
+ containerRef.current &&
+ !containerRef.current.contains(event.target as Node)
+ ) {
setIsOpen(false)
}
}
@@ -153,7 +170,15 @@ const FilterValueInput = ({
const getIconForItem = useCallback(
(item: string): ReactNode => {
if (column === 'cc') {
- return <Flag className='shrink-0 rounded-xs' country={item} size={16} alt='' aria-hidden='true' />
+ return (
+ <Flag
+ className='shrink-0 rounded-xs'
+ country={item}
+ size={16}
+ alt=''
+ aria-hidden='true'
+ />
+ )
}
if (column === 'br') {
@@ -187,7 +212,13 @@ const FilterValueInput = ({
logoUrl ||= logoUrlLight
if (logoUrl) {
- return <img src={logoUrl} className='size-4 shrink-0 dark:fill-gray-50' alt='' />
+ return (
+ <img
+ src={logoUrl}
+ className='size-4 shrink-0 dark:fill-gray-50'
+ alt=''
+ />
+ )
}
return <GlobeIcon className='size-4 shrink-0' strokeWidth={1.5} />
}
@@ -204,7 +235,13 @@ const FilterValueInput = ({
logoUrl ||= logoUrlLight
if (logoUrl) {
- return <img src={logoUrl} className='size-4 shrink-0 dark:fill-gray-50' alt='' />
+ return (
+ <img
+ src={logoUrl}
+ className='size-4 shrink-0 dark:fill-gray-50'
+ alt=''
+ />
+ )
}
}
return <GlobeIcon className='size-4 shrink-0' strokeWidth={1.5} />
@@ -215,7 +252,9 @@ const FilterValueInput = ({
if (icon) {
return <span className='shrink-0'>{icon}</span>
}
- return <CircleQuestionMark className='size-4 shrink-0' strokeWidth={1.5} />
+ return (
+ <CircleQuestionMark className='size-4 shrink-0' strokeWidth={1.5} />
+ )
}
return null
@@ -273,12 +312,17 @@ const FilterValueInput = ({
onChange(alpha2)
} else {
// Check if it's already a valid alpha2 code
- const validCode = items.find((item) => _toLower(item) === _toLower(inputValue))
+ const validCode = items.find(
+ (item) => _toLower(item) === _toLower(inputValue),
+ )
onChange(validCode || inputValue.trim())
}
} else {
// Check if input matches an existing item (case insensitive)
- const matchingItem = items.find((item) => _toLower(getLabelForItem(item)) === _toLower(inputValue.trim()))
+ const matchingItem = items.find(
+ (item) =>
+ _toLower(getLabelForItem(item)) === _toLower(inputValue.trim()),
+ )
onChange(matchingItem || inputValue.trim())
}
setInputValue('')
@@ -297,7 +341,9 @@ const FilterValueInput = ({
<div ref={containerRef} className={cx('relative flex-1', className)}>
<div className='relative'>
{showIconInInput ? (
- <span className='pointer-events-none absolute inset-y-0 left-0 flex items-center pl-2.5'>{selectedIcon}</span>
+ <span className='pointer-events-none absolute inset-y-0 left-0 flex items-center pl-2.5'>
+ {selectedIcon}
+ </span>
) : null}
<input
ref={inputRef}
@@ -318,7 +364,11 @@ const FilterValueInput = ({
disabled={disabled}
/>
<span className='pointer-events-none absolute inset-y-0 right-0 flex items-center pr-2'>
- {isLoading ? <Spin className='size-4' /> : <ChevronsUpDownIcon className='h-4 w-4 text-gray-400' />}
+ {isLoading ? (
+ <Spin className='size-4' />
+ ) : (
+ <ChevronsUpDownIcon className='h-4 w-4 text-gray-400' />
+ )}
</span>
</div>
@@ -336,7 +386,10 @@ const FilterValueInput = ({
type='button'
onClick={() => {
if (column === 'cc') {
- const alpha2 = countries.getAlpha2Code(inputValue, language)
+ const alpha2 = countries.getAlpha2Code(
+ inputValue,
+ language,
+ )
onChange(alpha2 || inputValue.trim())
} else {
onChange(inputValue.trim())
@@ -349,7 +402,9 @@ const FilterValueInput = ({
{t('project.filterUseValue', { value: inputValue.trim() })}
</button>
) : (
- <span className='text-gray-500 dark:text-gray-400'>{t('common.nothingFound')}</span>
+ <span className='text-gray-500 dark:text-gray-400'>
+ {t('common.nothingFound')}
+ </span>
)}
</div>
) : (
@@ -386,7 +441,13 @@ const FilterValueInput = ({
}}
>
{icon}
- <span className={cx('block truncate', { 'font-medium': selected })}>{labelValue}</span>
+ <span
+ className={cx('block truncate', {
+ 'font-medium': selected,
+ })}
+ >
+ {labelValue}
+ </span>
{selected ? (
<CheckIcon className='ml-auto h-4 w-4 shrink-0 text-indigo-600 dark:text-indigo-400' />
) : null}
diff --git a/web/app/ui/Flag.tsx b/web/app/ui/Flag.tsx
index b23911630..1463b671b 100644
--- a/web/app/ui/Flag.tsx
+++ b/web/app/ui/Flag.tsx
@@ -22,7 +22,13 @@ const Flag = ({ country, size = 24, alt, ...props }: FlagProps) => {
}
return (
- <img src={`${FLAGS_PREFIX_PATH}/${countryLower}.svg`} alt={alt || ' '} {...props} width={width} height={height} />
+ <img
+ src={`${FLAGS_PREFIX_PATH}/${countryLower}.svg`}
+ alt={alt || ' '}
+ {...props}
+ width={width}
+ height={height}
+ />
)
}
diff --git a/web/app/ui/Input.tsx b/web/app/ui/Input.tsx
index d60b82319..da4105faa 100644
--- a/web/app/ui/Input.tsx
+++ b/web/app/ui/Input.tsx
@@ -1,4 +1,9 @@
-import { Description, Field, Input as HeadlessInput, Label } from '@headlessui/react'
+import {
+ Description,
+ Field,
+ Input as HeadlessInput,
+ Label,
+} from '@headlessui/react'
import cx from 'clsx'
import _isEmpty from 'lodash/isEmpty'
import { Eye, EyeOff } from 'lucide-react'
@@ -44,7 +49,8 @@ const Input = ({
{
'text-red-900 placeholder-red-300 ring-red-600': isError,
'ring-gray-300 dark:ring-slate-800/50': !isError,
- 'cursor-text bg-gray-100 text-gray-500 dark:bg-slate-700 dark:text-gray-400': disabled,
+ 'cursor-text bg-gray-100 text-gray-500 dark:bg-slate-700 dark:text-gray-400':
+ disabled,
'pr-10': isPassword,
},
classes?.input,
@@ -61,7 +67,9 @@ const Input = ({
{label || labelCorner ? (
<div className='mb-1 flex items-center justify-between gap-x-2'>
{label ? (
- <Label className='flex text-sm font-medium text-gray-900 dark:text-gray-200'>{label}</Label>
+ <Label className='flex text-sm font-medium text-gray-900 dark:text-gray-200'>
+ {label}
+ </Label>
) : (
<span />
)}
@@ -69,7 +77,9 @@ const Input = ({
</div>
) : null}
{hint && hintPosition === 'top' ? (
- <Description className='mt-1 text-sm whitespace-pre-line text-gray-500 dark:text-gray-300'>{hint}</Description>
+ <Description className='mt-1 text-sm whitespace-pre-line text-gray-500 dark:text-gray-300'>
+ {hint}
+ </Description>
) : null}
{isPassword ? (
<div className='relative'>
@@ -79,15 +89,23 @@ const Input = ({
onClick={() => setShowPassword(!showPassword)}
className='absolute inset-y-0 right-0 flex items-center pr-3 text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-200'
>
- {showPassword ? <EyeOff className='size-5' /> : <Eye className='size-5' />}
+ {showPassword ? (
+ <EyeOff className='size-5' />
+ ) : (
+ <Eye className='size-5' />
+ )}
</button>
</div>
) : (
inputElement
)}
- {isError ? <p className='mt-2 text-sm text-red-600 dark:text-red-500'>{error}</p> : null}
+ {isError ? (
+ <p className='mt-2 text-sm text-red-600 dark:text-red-500'>{error}</p>
+ ) : null}
{hint && hintPosition === 'bottom' ? (
- <Description className='mt-2 text-sm whitespace-pre-line text-gray-500 dark:text-gray-300'>{hint}</Description>
+ <Description className='mt-2 text-sm whitespace-pre-line text-gray-500 dark:text-gray-300'>
+ {hint}
+ </Description>
) : null}
</Field>
)
diff --git a/web/app/ui/LoadingBar.tsx b/web/app/ui/LoadingBar.tsx
index ab2769236..8d82629ab 100644
--- a/web/app/ui/LoadingBar.tsx
+++ b/web/app/ui/LoadingBar.tsx
@@ -7,18 +7,25 @@ interface LoadingBarProps {
const LoadingBar: React.FC<LoadingBarProps> = ({ className }) => {
return (
- <div className={cx('fixed top-0 right-0 left-0 z-50 h-0.5 w-full overflow-hidden', className)}>
+ <div
+ className={cx(
+ 'fixed top-0 right-0 left-0 z-50 h-0.5 w-full overflow-hidden',
+ className,
+ )}
+ >
<div
className='absolute h-full rounded-full bg-gradient-to-r from-indigo-500 to-blue-600 opacity-90 shadow-sm'
style={{
- animation: 'indeterminate1 2.1s cubic-bezier(0.65, 0.815, 0.735, 0.395) infinite',
+ animation:
+ 'indeterminate1 2.1s cubic-bezier(0.65, 0.815, 0.735, 0.395) infinite',
}}
/>
<div
className='absolute h-full rounded-full bg-gradient-to-r from-indigo-500 to-blue-600 opacity-75 shadow-sm'
style={{
- animation: 'indeterminate2 2.1s cubic-bezier(0.165, 0.84, 0.44, 1) infinite',
+ animation:
+ 'indeterminate2 2.1s cubic-bezier(0.165, 0.84, 0.44, 1) infinite',
animationDelay: '1.15s',
}}
/>
diff --git a/web/app/ui/Modal.tsx b/web/app/ui/Modal.tsx
index 643cdaf37..e37c33b93 100644
--- a/web/app/ui/Modal.tsx
+++ b/web/app/ui/Modal.tsx
@@ -1,4 +1,9 @@
-import { Dialog, DialogBackdrop, DialogPanel, DialogTitle } from '@headlessui/react'
+import {
+ Dialog,
+ DialogBackdrop,
+ DialogPanel,
+ DialogTitle,
+} from '@headlessui/react'
import {
CheckIcon,
ExclamationTriangleIcon,
@@ -51,7 +56,11 @@ const Modal = ({
const { t } = useTranslation()
return (
- <Dialog className={cn('relative z-40', className)} open={isOpened} onClose={onClose}>
+ <Dialog
+ className={cn('relative z-40', className)}
+ open={isOpened}
+ onClose={onClose}
+ >
<DialogBackdrop
transition
className='fixed inset-0 bg-gray-500/75 transition-opacity data-closed:opacity-0 data-enter:ease-out data-leave:duration-200 data-leave:ease-in'
@@ -76,37 +85,55 @@ const Modal = ({
<div className='sm:flex sm:items-start'>
{type === 'success' ? (
<div className='mx-auto flex h-12 w-12 shrink-0 items-center justify-center rounded-full bg-green-100 sm:mr-3 sm:h-10 sm:w-10'>
- <CheckIcon className='h-6 w-6 text-green-600' aria-hidden='true' />
+ <CheckIcon
+ className='h-6 w-6 text-green-600'
+ aria-hidden='true'
+ />
</div>
) : null}
{type === 'error' ? (
<div className='mx-auto flex h-12 w-12 shrink-0 items-center justify-center rounded-full bg-red-100 sm:mr-3 sm:h-10 sm:w-10'>
- <ExclamationTriangleIcon className='h-6 w-6 text-red-600' aria-hidden='true' />
+ <ExclamationTriangleIcon
+ className='h-6 w-6 text-red-600'
+ aria-hidden='true'
+ />
</div>
) : null}
{type === 'info' ? (
<div className='mx-auto flex h-12 w-12 shrink-0 items-center justify-center rounded-full bg-blue-100 text-center sm:mr-3 sm:h-10 sm:w-10'>
- <InformationCircleIcon className='h-6 w-6 text-blue-600' aria-hidden='true' />
+ <InformationCircleIcon
+ className='h-6 w-6 text-blue-600'
+ aria-hidden='true'
+ />
</div>
) : null}
{type === 'warning' ? (
<div className='mx-auto flex h-12 w-12 shrink-0 items-center justify-center rounded-full bg-orange-100 sm:mr-3 sm:h-10 sm:w-10'>
- <ExclamationTriangleIcon className='h-6 w-6 text-amber-600' aria-hidden='true' />
+ <ExclamationTriangleIcon
+ className='h-6 w-6 text-amber-600'
+ aria-hidden='true'
+ />
</div>
) : null}
{type === 'confirmed' ? (
<div className='mx-auto flex h-12 w-12 shrink-0 items-center justify-center rounded-full bg-green-100 sm:mr-3 sm:h-10 sm:w-10'>
- <UserGroupIcon className='h-6 w-6 text-green-600' aria-hidden='true' />
+ <UserGroupIcon
+ className='h-6 w-6 text-green-600'
+ aria-hidden='true'
+ />
</div>
) : null}
<div className='w-full text-center sm:text-left'>
{title ? (
<DialogTitle
as='h3'
- className={cn('flex items-center text-lg leading-6 font-medium text-gray-900 dark:text-gray-50', {
- 'justify-between': !closeText,
- 'justify-center sm:justify-start': closeText,
- })}
+ className={cn(
+ 'flex items-center text-lg leading-6 font-medium text-gray-900 dark:text-gray-50',
+ {
+ 'justify-between': !closeText,
+ 'justify-center sm:justify-start': closeText,
+ },
+ )}
>
<div>{title}</div>
{!closeText ? (
@@ -125,7 +152,9 @@ const Modal = ({
) : null}
</DialogTitle>
) : null}
- <div className='mt-2 text-sm whitespace-pre-line text-gray-600 dark:text-gray-200'>{message}</div>
+ <div className='mt-2 text-sm whitespace-pre-line text-gray-600 dark:text-gray-200'>
+ {message}
+ </div>
</div>
</div>
<div className='px-4 py-3 transition-colors sm:flex sm:flex-row-reverse sm:px-0 sm:pb-0'>
@@ -139,8 +168,10 @@ const Modal = ({
'bg-indigo-600': submitType === 'regular',
'bg-red-600': submitType === 'danger',
'cursor-not-allowed opacity-70': submitDisabled,
- 'hover:bg-indigo-700': submitType === 'regular' && !submitDisabled,
- 'hover:bg-red-700': submitType === 'danger' && !submitDisabled,
+ 'hover:bg-indigo-700':
+ submitType === 'regular' && !submitDisabled,
+ 'hover:bg-red-700':
+ submitType === 'danger' && !submitDisabled,
},
)}
onClick={onSubmit}
diff --git a/web/app/ui/MultiProgress.tsx b/web/app/ui/MultiProgress.tsx
index 604a5e62f..bbcdf4691 100644
--- a/web/app/ui/MultiProgress.tsx
+++ b/web/app/ui/MultiProgress.tsx
@@ -20,7 +20,12 @@ const MultiProgress = ({ progress, className }: MultiProgressProps) => {
return (
<div className='relative'>
- <div className={cx('flex h-5 overflow-hidden rounded-sm bg-gray-200 text-xs dark:bg-slate-600', className)}>
+ <div
+ className={cx(
+ 'flex h-5 overflow-hidden rounded-sm bg-gray-200 text-xs dark:bg-slate-600',
+ className,
+ )}
+ >
{_map(progress, ({ value, lightColour, darkColour }) => (
<div
key={`${value}-${lightColour}-${darkColour}`}
diff --git a/web/app/ui/MultiSelect.tsx b/web/app/ui/MultiSelect.tsx
index 8c8b22c47..acf72655e 100644
--- a/web/app/ui/MultiSelect.tsx
+++ b/web/app/ui/MultiSelect.tsx
@@ -39,7 +39,10 @@ const MultiSelect = ({
useEffect(() => {
const handleClickOutside = (event: MouseEvent) => {
- if (dropdownRef.current && !dropdownRef.current.contains(event.target as Node)) {
+ if (
+ dropdownRef.current &&
+ !dropdownRef.current.contains(event.target as Node)
+ ) {
setIsOpen(false)
setSearchValue('')
if (onSearch) {
@@ -84,7 +87,10 @@ const MultiSelect = ({
}
return (
- <div ref={dropdownRef} className={cx('relative flex w-full flex-col', className)}>
+ <div
+ ref={dropdownRef}
+ className={cx('relative flex w-full flex-col', className)}
+ >
{/* Search input as the dropdown trigger */}
<div className='relative'>
<input
@@ -112,20 +118,27 @@ const MultiSelect = ({
{/* Options list */}
<div className='px-1'>
{_isEmpty(items) ? (
- <div className='px-3 py-2 text-gray-500 dark:text-gray-400'>No options available</div>
+ <div className='px-3 py-2 text-gray-500 dark:text-gray-400'>
+ No options available
+ </div>
) : (
_map(items, (item) => {
const isSelected = _includes(label, item)
return (
<button
type='button'
- key={keyExtractor ? `${keyExtractor(item)}select` : `${item}select`}
+ key={
+ keyExtractor
+ ? `${keyExtractor(item)}select`
+ : `${item}select`
+ }
onClick={() => handleSelectItem(item)}
className={cx(
'relative flex w-full cursor-pointer items-center gap-2 rounded-md py-2 pr-4 pl-3 text-left text-sm transition-colors select-none',
{
'bg-indigo-50 dark:bg-indigo-900/30': isSelected,
- 'hover:bg-gray-100 dark:hover:bg-slate-700': !isSelected,
+ 'hover:bg-gray-100 dark:hover:bg-slate-700':
+ !isSelected,
'text-gray-900 dark:text-white': isSelected,
'text-gray-700 dark:text-gray-50': !isSelected,
},
@@ -166,7 +179,9 @@ const MultiSelect = ({
key={keyExtractor ? keyExtractor(item) : item}
className='inline-flex items-center gap-1.5 rounded-md bg-gray-100 py-1.5 pr-2 pl-2.5 text-sm font-medium text-gray-700 dark:bg-slate-700 dark:text-gray-200'
>
- <span className='flex items-center gap-1.5'>{labelExtractor ? labelExtractor(item) : item}</span>
+ <span className='flex items-center gap-1.5'>
+ {labelExtractor ? labelExtractor(item) : item}
+ </span>
<button
type='button'
onClick={(e) => {
@@ -177,8 +192,17 @@ const MultiSelect = ({
className='inline-flex h-4 w-4 shrink-0 items-center justify-center rounded-full text-gray-400 hover:bg-gray-200 hover:text-gray-600 focus:bg-gray-300 focus:text-gray-700 focus:outline-hidden dark:text-gray-400 dark:hover:bg-slate-600 dark:hover:text-gray-200'
>
<span className='sr-only'>Remove</span>
- <svg className='h-2.5 w-2.5' stroke='currentColor' fill='none' viewBox='0 0 8 8'>
- <path strokeLinecap='round' strokeWidth='1.5' d='m1 1 6 6m0-6-6 6' />
+ <svg
+ className='h-2.5 w-2.5'
+ stroke='currentColor'
+ fill='none'
+ viewBox='0 0 8 8'
+ >
+ <path
+ strokeLinecap='round'
+ strokeWidth='1.5'
+ d='m1 1 6 6m0-6-6 6'
+ />
</svg>
</button>
</span>
@@ -187,7 +211,11 @@ const MultiSelect = ({
) : null}
{/* Hint text */}
- {hint ? <p className='mt-2 text-sm whitespace-pre-line text-gray-500 dark:text-gray-300'>{hint}</p> : null}
+ {hint ? (
+ <p className='mt-2 text-sm whitespace-pre-line text-gray-500 dark:text-gray-300'>
+ {hint}
+ </p>
+ ) : null}
</div>
)
}
diff --git a/web/app/ui/OutsideClickHandler.tsx b/web/app/ui/OutsideClickHandler.tsx
index dd21ba609..e675a2266 100644
--- a/web/app/ui/OutsideClickHandler.tsx
+++ b/web/app/ui/OutsideClickHandler.tsx
@@ -6,11 +6,9 @@ interface OutsideClickHandlerProps extends React.HTMLAttributes<HTMLDivElement>
onOutsideClick: (event: MouseEvent | TouchEvent) => void
}
-const OutsideClickHandler: React.FC<React.PropsWithChildren<OutsideClickHandlerProps>> = ({
- onOutsideClick,
- children,
- ...rest
-}) => {
+const OutsideClickHandler: React.FC<
+ React.PropsWithChildren<OutsideClickHandlerProps>
+> = ({ onOutsideClick, children, ...rest }) => {
const containerRef = useRef<HTMLDivElement>(null)
useOnClickOutside(containerRef, onOutsideClick)
diff --git a/web/app/ui/Pagination.tsx b/web/app/ui/Pagination.tsx
index 6ecf0a15d..a43932bac 100644
--- a/web/app/ui/Pagination.tsx
+++ b/web/app/ui/Pagination.tsx
@@ -32,14 +32,19 @@ const Pagination = ({
const { t } = useTranslation('common')
const paginationRange = usePagination(total, page, 1, pageSize)
- const processedPageSizeOptions = _map(pageSizeOptions, (option) => option.toString())
+ const processedPageSizeOptions = _map(pageSizeOptions, (option) =>
+ option.toString(),
+ )
const start = (page - 1) * pageSize + 1
const end = Math.min(start + pageSize - 1, total)
return (
<div
- className={cx('flex items-center justify-between border-t border-gray-200 py-3 dark:border-gray-700', className)}
+ className={cx(
+ 'flex items-center justify-between border-t border-gray-200 py-3 dark:border-gray-700',
+ className,
+ )}
>
<div className='flex flex-1 justify-between sm:hidden'>
<button
@@ -85,14 +90,20 @@ const Pagination = ({
</div>
<div className='hidden w-full sm:flex sm:flex-wrap sm:items-center sm:justify-between sm:gap-y-4'>
<p className='text-sm text-gray-700 dark:text-gray-200'>
- <Trans t={t} i18nKey='common.pagination' values={{ start, end, total }}>
+ <Trans
+ t={t}
+ i18nKey='common.pagination'
+ values={{ start, end, total }}
+ >
<span className='font-medium' />
</Trans>
</p>
<div className='flex items-center gap-4'>
{pageSizeOptions && onPageSizeChange ? (
<div className='flex items-center gap-2'>
- <span className='text-sm text-gray-700 dark:text-gray-200'>{t('common.resultsPerPage')}</span>
+ <span className='text-sm text-gray-700 dark:text-gray-200'>
+ {t('common.resultsPerPage')}
+ </span>
<Select<string>
label={t('common.resultsPerPage')}
fieldLabelClassName='sr-only'
@@ -104,7 +115,10 @@ const Pagination = ({
/>
</div>
) : null}
- <nav className='isolate inline-flex -space-x-px rounded-md' aria-label='Pagination'>
+ <nav
+ className='isolate inline-flex -space-x-px rounded-md'
+ aria-label='Pagination'
+ >
<button
type='button'
onClick={() => {
@@ -135,7 +149,9 @@ const Pagination = ({
onClick={() => {
const lastShownPage = paginationRange[index - 1] as number
const nextShownPage = paginationRange[index + 1] as number
- const middlePage = Math.floor((lastShownPage + nextShownPage) / 2)
+ const middlePage = Math.floor(
+ (lastShownPage + nextShownPage) / 2,
+ )
setPage(middlePage)
}}
@@ -154,8 +170,10 @@ const Pagination = ({
className={cx(
'relative inline-flex items-center border border-gray-300 px-4 py-2 text-sm font-semibold focus:z-20 dark:border-gray-800',
{
- 'z-10 bg-slate-800 text-white dark:bg-slate-700': item === page,
- 'text-gray-900 hover:bg-gray-100 dark:text-gray-200 dark:hover:bg-slate-700': item !== page,
+ 'z-10 bg-slate-800 text-white dark:bg-slate-700':
+ item === page,
+ 'text-gray-900 hover:bg-gray-100 dark:text-gray-200 dark:hover:bg-slate-700':
+ item !== page,
},
)}
>
@@ -177,7 +195,8 @@ const Pagination = ({
'relative inline-flex items-center rounded-r-md border border-gray-300 px-2 py-2 text-gray-400 focus:z-20 dark:border-gray-800',
{
'cursor-not-allowed': page === pageAmount,
- 'hover:bg-gray-100 dark:hover:bg-slate-700': page !== pageAmount,
+ 'hover:bg-gray-100 dark:hover:bg-slate-700':
+ page !== pageAmount,
},
)}
>
diff --git a/web/app/ui/ProgressRing.tsx b/web/app/ui/ProgressRing.tsx
index b5025007e..57b3806a5 100644
--- a/web/app/ui/ProgressRing.tsx
+++ b/web/app/ui/ProgressRing.tsx
@@ -57,7 +57,10 @@ const ProgressRing = ({
showValue = true,
thresholds = DEFAULT_THRESHOLDS,
}: ProgressRingProps) => {
- const normalizedValue = useMemo(() => Math.min(100, Math.max(0, value)), [value])
+ const normalizedValue = useMemo(
+ () => Math.min(100, Math.max(0, value)),
+ [value],
+ )
const { radius, circumference, strokeDashoffset } = useMemo(() => {
const r = (size - strokeWidth) / 2
@@ -71,12 +74,20 @@ const ProgressRing = ({
}
}, [size, strokeWidth, normalizedValue])
- const colourClasses = useMemo(() => getColourClasses(normalizedValue, thresholds), [normalizedValue, thresholds])
+ const colourClasses = useMemo(
+ () => getColourClasses(normalizedValue, thresholds),
+ [normalizedValue, thresholds],
+ )
const center = size / 2
return (
- <div className={cn('relative inline-flex items-center justify-center', className)}>
+ <div
+ className={cn(
+ 'relative inline-flex items-center justify-center',
+ className,
+ )}
+ >
<svg width={size} height={size} className='-rotate-90'>
{/* Background circle */}
<circle
@@ -97,12 +108,18 @@ const ProgressRing = ({
strokeLinecap='round'
strokeDasharray={circumference}
strokeDashoffset={strokeDashoffset}
- className={cn('transition-all duration-300 ease-out', colourClasses.stroke)}
+ className={cn(
+ 'transition-all duration-300 ease-out',
+ colourClasses.stroke,
+ )}
/>
</svg>
{showValue ? (
<span
- className={cn('absolute text-center font-semibold', colourClasses.text)}
+ className={cn(
+ 'absolute text-center font-semibold',
+ colourClasses.text,
+ )}
style={{ fontSize: size * 0.22 }}
>
{Math.round(normalizedValue)}%
diff --git a/web/app/ui/Select.tsx b/web/app/ui/Select.tsx
index af582c9d5..7d59b80c2 100644
--- a/web/app/ui/Select.tsx
+++ b/web/app/ui/Select.tsx
@@ -1,4 +1,11 @@
-import { Listbox, Transition, Label, ListboxButton, ListboxOptions, ListboxOption } from '@headlessui/react'
+import {
+ Listbox,
+ Transition,
+ Label,
+ ListboxButton,
+ ListboxOptions,
+ ListboxOption,
+} from '@headlessui/react'
import { CheckIcon, ChevronUpDownIcon } from '@heroicons/react/24/solid'
import cx from 'clsx'
import _map from 'lodash/map'
@@ -82,7 +89,10 @@ function Select<T>({
{title}
</span>
<span className='pointer-events-none absolute inset-y-0 right-0 flex items-center pr-2'>
- <ChevronUpDownIcon className='h-5 w-5 text-gray-400' aria-hidden='true' />
+ <ChevronUpDownIcon
+ className='h-5 w-5 text-gray-400'
+ aria-hidden='true'
+ />
</span>
</ListboxButton>
@@ -104,14 +114,20 @@ function Select<T>({
const selected = isItemSelected(item)
return (
<ListboxOption
- key={keyExtractor ? keyExtractor(item, index) : (item as Key)}
+ key={
+ keyExtractor ? keyExtractor(item, index) : (item as Key)
+ }
className={({ focus }) =>
- cx('relative mx-1 cursor-pointer rounded-md py-2 pr-4 pl-8 transition-colors select-none', {
- 'bg-gray-200 dark:bg-slate-700': focus && !selected,
- 'bg-gray-300 dark:bg-slate-600': selected,
- 'text-gray-700 dark:text-gray-50': !focus && !selected,
- 'text-gray-900 dark:text-white': focus || selected,
- })
+ cx(
+ 'relative mx-1 cursor-pointer rounded-md py-2 pr-4 pl-8 transition-colors select-none',
+ {
+ 'bg-gray-200 dark:bg-slate-700': focus && !selected,
+ 'bg-gray-300 dark:bg-slate-600': selected,
+ 'text-gray-700 dark:text-gray-50':
+ !focus && !selected,
+ 'text-gray-900 dark:text-white': focus || selected,
+ },
+ )
}
value={item}
>
@@ -127,11 +143,17 @@ function Select<T>({
labelClassName,
)}
>
- {labelExtractor ? labelExtractor(item, index) : (item as React.ReactNode)}
+ {labelExtractor
+ ? labelExtractor(item, index)
+ : (item as React.ReactNode)}
</span>
{iconExtractor ? (
- <span className={cx('absolute inset-y-0 left-0 flex items-center pl-1.5')}>
+ <span
+ className={cx(
+ 'absolute inset-y-0 left-0 flex items-center pl-1.5',
+ )}
+ >
{iconExtractor(item, index)}
</span>
) : null}
@@ -153,7 +175,12 @@ function Select<T>({
</Transition>
</div>
{hint ? (
- <p className={cx('mt-2 text-sm whitespace-pre-line text-gray-500 dark:text-gray-300', hintClassName)}>
+ <p
+ className={cx(
+ 'mt-2 text-sm whitespace-pre-line text-gray-500 dark:text-gray-300',
+ hintClassName,
+ )}
+ >
{hint}
</p>
) : null}
diff --git a/web/app/ui/StatusPage.tsx b/web/app/ui/StatusPage.tsx
index d00aec893..2985298ba 100644
--- a/web/app/ui/StatusPage.tsx
+++ b/web/app/ui/StatusPage.tsx
@@ -1,4 +1,8 @@
-import { CheckCircleIcon, XCircleIcon, InformationCircleIcon } from '@heroicons/react/24/solid'
+import {
+ CheckCircleIcon,
+ XCircleIcon,
+ InformationCircleIcon,
+} from '@heroicons/react/24/solid'
import type { ReactNode } from 'react'
import { useTranslation } from 'react-i18next'
import { Link } from 'react-router'
@@ -36,9 +40,24 @@ interface StatusPageProps {
}
const iconMap: Record<StatusType, ReactNode> = {
- success: <CheckCircleIcon className='size-8 text-green-500 dark:text-green-400' aria-hidden='true' />,
- error: <XCircleIcon className='size-8 text-red-500 dark:text-red-400' aria-hidden='true' />,
- info: <InformationCircleIcon className='size-8 text-amber-500 dark:text-amber-400' aria-hidden='true' />,
+ success: (
+ <CheckCircleIcon
+ className='size-8 text-green-500 dark:text-green-400'
+ aria-hidden='true'
+ />
+ ),
+ error: (
+ <XCircleIcon
+ className='size-8 text-red-500 dark:text-red-400'
+ aria-hidden='true'
+ />
+ ),
+ info: (
+ <InformationCircleIcon
+ className='size-8 text-amber-500 dark:text-amber-400'
+ aria-hidden='true'
+ />
+ ),
}
const iconBgMap: Record<StatusType, string> = {
@@ -47,7 +66,14 @@ const iconBgMap: Record<StatusType, string> = {
info: 'bg-amber-100 dark:bg-amber-500/10',
}
-const StatusPage = ({ loading, type = 'success', title, description, icon, actions }: StatusPageProps) => {
+const StatusPage = ({
+ loading,
+ type = 'success',
+ title,
+ description,
+ icon,
+ actions,
+}: StatusPageProps) => {
const { t } = useTranslation('common')
if (loading) {
@@ -66,7 +92,12 @@ const StatusPage = ({ loading, type = 'success', title, description, icon, actio
return (
<div className='flex min-h-page items-center justify-center bg-gray-50 px-4 dark:bg-slate-900'>
<div className='mx-auto w-full max-w-md text-center'>
- <div className={cn('mx-auto mb-6 flex size-14 items-center justify-center rounded-xl', iconBgMap[type])}>
+ <div
+ className={cn(
+ 'mx-auto mb-6 flex size-14 items-center justify-center rounded-xl',
+ iconBgMap[type],
+ )}
+ >
{displayIcon}
</div>
diff --git a/web/app/ui/Switch.tsx b/web/app/ui/Switch.tsx
index 44169dd35..4826fb60a 100644
--- a/web/app/ui/Switch.tsx
+++ b/web/app/ui/Switch.tsx
@@ -12,7 +12,14 @@ interface SwitchProps {
id?: string
}
-export const Switch = ({ checked, onChange, disabled = false, className, label, id }: SwitchProps) => {
+export const Switch = ({
+ checked,
+ onChange,
+ disabled = false,
+ className,
+ label,
+ id,
+}: SwitchProps) => {
const generatedId = useId()
const switchId = id || generatedId
diff --git a/web/app/ui/Text.tsx b/web/app/ui/Text.tsx
index 324c79ce8..d74982eaa 100644
--- a/web/app/ui/Text.tsx
+++ b/web/app/ui/Text.tsx
@@ -2,10 +2,36 @@ import React from 'react'
import { cn } from '~/utils/generic'
-type TextElement = 'span' | 'p' | 'h1' | 'h2' | 'h3' | 'h4' | 'h5' | 'h6' | 'label' | 'div'
-type TextSize = 'xxs' | 'xs' | 'sm' | 'base' | 'lg' | 'xl' | '2xl' | '3xl' | '4xl'
+type TextElement =
+ | 'span'
+ | 'p'
+ | 'h1'
+ | 'h2'
+ | 'h3'
+ | 'h4'
+ | 'h5'
+ | 'h6'
+ | 'label'
+ | 'div'
+type TextSize =
+ | 'xxs'
+ | 'xs'
+ | 'sm'
+ | 'base'
+ | 'lg'
+ | 'xl'
+ | '2xl'
+ | '3xl'
+ | '4xl'
type TextWeight = 'light' | 'normal' | 'medium' | 'semibold' | 'bold'
-type TextColour = 'primary' | 'secondary' | 'muted' | 'success' | 'warning' | 'error' | 'inherit'
+type TextColour =
+ | 'primary'
+ | 'secondary'
+ | 'muted'
+ | 'success'
+ | 'warning'
+ | 'error'
+ | 'inherit'
type Tracking = 'tight' | 'normal' | 'wide'
interface TextProps {
@@ -76,7 +102,8 @@ export const Text = ({
colourClasses[colour],
trackingClasses[tracking],
{ truncate },
- code && 'rounded bg-gray-200/80 px-1.5 py-0.5 font-mono dark:bg-slate-700',
+ code &&
+ 'rounded bg-gray-200/80 px-1.5 py-0.5 font-mono dark:bg-slate-700',
className,
)}
{...props}
diff --git a/web/app/ui/Textarea.tsx b/web/app/ui/Textarea.tsx
index 097bd5eb0..b452b83ce 100644
--- a/web/app/ui/Textarea.tsx
+++ b/web/app/ui/Textarea.tsx
@@ -1,4 +1,9 @@
-import { Description, Field, Label, Textarea as HeadlessTextarea } from '@headlessui/react'
+import {
+ Description,
+ Field,
+ Label,
+ Textarea as HeadlessTextarea,
+} from '@headlessui/react'
import _isEmpty from 'lodash/isEmpty'
import React, { memo } from 'react'
@@ -38,7 +43,11 @@ const Textarea = ({
return (
<Field as='div' className={classes?.container}>
- {label ? <Label className='flex text-sm font-medium text-gray-900 dark:text-gray-200'>{label}</Label> : null}
+ {label ? (
+ <Label className='flex text-sm font-medium text-gray-900 dark:text-gray-200'>
+ {label}
+ </Label>
+ ) : null}
<HeadlessTextarea
rows={rows}
name={name}
@@ -47,7 +56,8 @@ const Textarea = ({
{
'text-red-900 placeholder-red-300 ring-red-600': isError,
'ring-gray-300 dark:ring-slate-800/50': !isError,
- 'cursor-not-allowed bg-gray-100 text-gray-500 dark:bg-slate-700 dark:text-gray-400': disabled,
+ 'cursor-not-allowed bg-gray-100 text-gray-500 dark:bg-slate-700 dark:text-gray-400':
+ disabled,
},
classes?.textarea,
)}
@@ -58,9 +68,13 @@ const Textarea = ({
readOnly={readOnly}
invalid={isError}
/>
- {isError ? <p className='mt-2 text-sm text-red-600 dark:text-red-500'>{error}</p> : null}
+ {isError ? (
+ <p className='mt-2 text-sm text-red-600 dark:text-red-500'>{error}</p>
+ ) : null}
{hint ? (
- <Description className='mt-2 text-sm whitespace-pre-line text-gray-500 dark:text-gray-300'>{hint}</Description>
+ <Description className='mt-2 text-sm whitespace-pre-line text-gray-500 dark:text-gray-300'>
+ {hint}
+ </Description>
) : null}
</Field>
)
diff --git a/web/app/ui/TimezonePicker.tsx b/web/app/ui/TimezonePicker.tsx
index 9e151f0d3..ec5f63869 100644
--- a/web/app/ui/TimezonePicker.tsx
+++ b/web/app/ui/TimezonePicker.tsx
@@ -16,12 +16,17 @@ const options = _reduce(
const tz = now.timezone()
const tzStrings = soft(zone[0])
- const abbr = now.isDST() ? tzStrings[0].daylight?.abbr : tzStrings[0].standard?.abbr
- const altName = now.isDST() ? tzStrings[0].daylight?.name : tzStrings[0].standard?.name
+ const abbr = now.isDST()
+ ? tzStrings[0].daylight?.abbr
+ : tzStrings[0].standard?.abbr
+ const altName = now.isDST()
+ ? tzStrings[0].daylight?.name
+ : tzStrings[0].standard?.name
const min = tz.current.offset * 60
- const hr = `${(min / 60) ^ 0}:` + (min % 60 === 0 ? '00' : Math.abs(min % 60))
+ const hr =
+ `${(min / 60) ^ 0}:` + (min % 60 === 0 ? '00' : Math.abs(min % 60))
const label = `(GMT${_includes(hr, '-') ? hr : `+${hr}`}) ${zone[1]}`
selectOptions.push({
diff --git a/web/app/ui/Tooltip.tsx b/web/app/ui/Tooltip.tsx
index d4d0d5e9c..358d6c1f4 100644
--- a/web/app/ui/Tooltip.tsx
+++ b/web/app/ui/Tooltip.tsx
@@ -41,8 +41,17 @@ interface TooltipProps {
disableHoverableContent?: boolean
}
-const Tooltip = ({ text, className, tooltipNode, delay = 50, disableHoverableContent }: TooltipProps) => (
- <TooltipProvider delayDuration={delay} disableHoverableContent={disableHoverableContent}>
+const Tooltip = ({
+ text,
+ className,
+ tooltipNode,
+ delay = 50,
+ disableHoverableContent,
+}: TooltipProps) => (
+ <TooltipProvider
+ delayDuration={delay}
+ disableHoverableContent={disableHoverableContent}
+ >
<TooltipRoot>
<TooltipTrigger className={className}>
{tooltipNode || (
@@ -52,7 +61,11 @@ const Tooltip = ({ text, className, tooltipNode, delay = 50, disableHoverableCon
/>
)}
</TooltipTrigger>
- <TooltipContent className={disableHoverableContent ? 'pointer-events-none' : undefined}>{text}</TooltipContent>
+ <TooltipContent
+ className={disableHoverableContent ? 'pointer-events-none' : undefined}
+ >
+ {text}
+ </TooltipContent>
</TooltipRoot>
</TooltipProvider>
)
diff --git a/web/app/ui/icons/GoogleSearchConsole.tsx b/web/app/ui/icons/GoogleSearchConsole.tsx
index ca4ef10a6..888909375 100644
--- a/web/app/ui/icons/GoogleSearchConsole.tsx
+++ b/web/app/ui/icons/GoogleSearchConsole.tsx
@@ -1,5 +1,8 @@
const GoogleSearchConsoleSVG = ({ className }: { className?: string }) => (
- <svg className={className} viewBox='6.239 2.66350997 503.09749003 503.10849003'>
+ <svg
+ className={className}
+ viewBox='6.239 2.66350997 503.09749003 503.10849003'
+ >
<g fill='none'>
<path
d='m113.296 424.432-75.52 75.536c-5.825 5.804-15.247 5.804-21.072 0l-4.672-4.672c-5.793-5.823-5.793-15.233 0-21.056l75.52-75.536c5.827-5.814 15.26-5.814 21.088 0l4.656 4.656a14.88 14.88 0 0 1 0 21.072z'
diff --git a/web/app/ui/icons/PulsatingCircle.tsx b/web/app/ui/icons/PulsatingCircle.tsx
index f43e6e2fc..f04f548cc 100644
--- a/web/app/ui/icons/PulsatingCircle.tsx
+++ b/web/app/ui/icons/PulsatingCircle.tsx
@@ -20,10 +20,29 @@ interface PulsatingCircleProps {
type: 'small' | 'big' | 'giant'
}
-const PulsatingCircle = ({ className, type = 'small' }: PulsatingCircleProps) => (
- <span className={cx('flex items-center justify-center', types[type]?.pulse, className)}>
- <span className={cx('animate-ping-slow absolute inline-flex rounded-full bg-green-400', types[type]?.pulse)} />
- <span className={cx('relative inline-flex rounded-full bg-green-500', types[type]?.base)} />
+const PulsatingCircle = ({
+ className,
+ type = 'small',
+}: PulsatingCircleProps) => (
+ <span
+ className={cx(
+ 'flex items-center justify-center',
+ types[type]?.pulse,
+ className,
+ )}
+ >
+ <span
+ className={cx(
+ 'animate-ping-slow absolute inline-flex rounded-full bg-green-400',
+ types[type]?.pulse,
+ )}
+ />
+ <span
+ className={cx(
+ 'relative inline-flex rounded-full bg-green-500',
+ types[type]?.base,
+ )}
+ />
</span>
)
diff --git a/web/app/ui/icons/Sort.tsx b/web/app/ui/icons/Sort.tsx
index 580fecf76..6c5710bfe 100644
--- a/web/app/ui/icons/Sort.tsx
+++ b/web/app/ui/icons/Sort.tsx
@@ -1,4 +1,8 @@
-import { ChevronUpDownIcon, ChevronUpIcon, ChevronDownIcon } from '@heroicons/react/24/outline'
+import {
+ ChevronUpDownIcon,
+ ChevronUpIcon,
+ ChevronDownIcon,
+} from '@heroicons/react/24/outline'
import cx from 'clsx'
interface SortProps {
diff --git a/web/app/ui/icons/Spin.tsx b/web/app/ui/icons/Spin.tsx
index fcf7999ac..569d5c395 100644
--- a/web/app/ui/icons/Spin.tsx
+++ b/web/app/ui/icons/Spin.tsx
@@ -19,7 +19,14 @@ const Spin = ({ className, alwaysLight }: SpinProps) => (
fill='none'
viewBox='0 0 24 24'
>
- <circle className='opacity-25' cx='12' cy='12' r='10' stroke='currentColor' strokeWidth='4' />
+ <circle
+ className='opacity-25'
+ cx='12'
+ cy='12'
+ r='10'
+ stroke='currentColor'
+ strokeWidth='4'
+ />
<path
className='opacity-75'
fill='currentColor'
diff --git a/web/app/ui/icons/SwetrixLogo.tsx b/web/app/ui/icons/SwetrixLogo.tsx
index ba66f8ea8..788d48149 100644
--- a/web/app/ui/icons/SwetrixLogo.tsx
+++ b/web/app/ui/icons/SwetrixLogo.tsx
@@ -10,28 +10,49 @@ interface SwetrixLogoProps {
theme?: ThemeType
}
-const SwetrixLogo = ({ className, lazy, theme: themeOverride }: SwetrixLogoProps) => {
+const SwetrixLogo = ({
+ className,
+ lazy,
+ theme: themeOverride,
+}: SwetrixLogoProps) => {
const { theme: currentTheme } = useTheme()
const { t } = useTranslation()
const theme = themeOverride || currentTheme
return (
- <div className={cx('flex -translate-y-[2px] items-center gap-2 select-none', className)}>
+ <div
+ className={cx(
+ 'flex -translate-y-[2px] items-center gap-2 select-none',
+ className,
+ )}
+ >
<img
className='-translate-y-[1px]'
height='28px'
width='24px'
- src={theme === 'dark' ? '/assets/logo/white.png' : '/assets/logo/blue.png'}
+ src={
+ theme === 'dark' ? '/assets/logo/white.png' : '/assets/logo/blue.png'
+ }
alt=''
loading={lazy ? 'lazy' : 'eager'}
/>
<div className='flex flex-col'>
- <span className={cx('text-2xl leading-5 font-bold', theme === 'dark' ? 'text-white' : 'text-indigo-950')}>
+ <span
+ className={cx(
+ 'text-2xl leading-5 font-bold',
+ theme === 'dark' ? 'text-white' : 'text-indigo-950',
+ )}
+ >
Swetrix
</span>
{isSelfhosted ? (
- <span className={cx('text-xs font-semibold', theme === 'dark' ? 'text-white' : 'text-indigo-600')}>
+ <span
+ className={cx(
+ 'text-xs font-semibold',
+ theme === 'dark' ? 'text-white' : 'text-indigo-600',
+ )}
+ >
{t('common.communityEdition')}
</span>
) : null}
diff --git a/web/app/ui/icons/Telegram.tsx b/web/app/ui/icons/Telegram.tsx
index 670da25d4..09a992a12 100644
--- a/web/app/ui/icons/Telegram.tsx
+++ b/web/app/ui/icons/Telegram.tsx
@@ -2,13 +2,31 @@ const Telegram = ({ className }: { className?: string }) => (
<svg className={className} viewBox='0 0 1000 1000'>
<title>Telegram</title>
<defs>
- <linearGradient x1='50%' y1='0%' x2='50%' y2='99.2583404%' id='linearGradient-1'>
+ <linearGradient
+ x1='50%'
+ y1='0%'
+ x2='50%'
+ y2='99.2583404%'
+ id='linearGradient-1'
+ >
<stop stopColor='#2AABEE' offset='0%' />
<stop stopColor='#229ED9' offset='100%' />
</linearGradient>
</defs>
- <g id='Artboard' stroke='none' strokeWidth={1} fill='none' fillRule='evenodd'>
- <circle id='Oval' fill='url(#linearGradient-1)' cx='500' cy='500' r='500' />
+ <g
+ id='Artboard'
+ stroke='none'
+ strokeWidth={1}
+ fill='none'
+ fillRule='evenodd'
+ >
+ <circle
+ id='Oval'
+ fill='url(#linearGradient-1)'
+ cx='500'
+ cy='500'
+ r='500'
+ />
<path
d='M226.328419,494.722069 C372.088573,431.216685 469.284839,389.350049 517.917216,369.122161 C656.772535,311.36743 685.625481,301.334815 704.431427,301.003532 C708.567621,300.93067 717.815839,301.955743 723.806446,306.816707 C728.864797,310.92121 730.256552,316.46581 730.922551,320.357329 C731.588551,324.248848 732.417879,333.113828 731.758626,340.040666 C724.234007,419.102486 691.675104,610.964674 675.110982,699.515267 C668.10208,736.984342 654.301336,749.547532 640.940618,750.777006 C611.904684,753.448938 589.856115,731.588035 561.733393,713.153237 C517.726886,684.306416 492.866009,666.349181 450.150074,638.200013 C400.78442,605.66878 432.786119,587.789048 460.919462,558.568563 C468.282091,550.921423 596.21508,434.556479 598.691227,424.000355 C599.00091,422.680135 599.288312,417.758981 596.36474,415.160431 C593.441168,412.561881 589.126229,413.450484 586.012448,414.157198 C581.598758,415.158943 511.297793,461.625274 375.109553,553.556189 C355.154858,567.258623 337.080515,573.934908 320.886524,573.585046 C303.033948,573.199351 268.692754,563.490928 243.163606,555.192408 C211.851067,545.013936 186.964484,539.632504 189.131547,522.346309 C190.260287,513.342589 202.659244,504.134509 226.328419,494.722069 Z'
id='Path-3'
diff --git a/web/app/utils/analytics.ts b/web/app/utils/analytics.ts
index 2a41a004d..cd171f92e 100644
--- a/web/app/utils/analytics.ts
+++ b/web/app/utils/analytics.ts
@@ -1,7 +1,12 @@
import _includes from 'lodash/includes'
import * as Swetrix from 'swetrix'
-import { isBrowser, isDevelopment, isIframe, isSelfhosted } from '~/lib/constants'
+import {
+ isBrowser,
+ isDevelopment,
+ isIframe,
+ isSelfhosted,
+} from '~/lib/constants'
export const SWETRIX_PID = 'STEzHcB1rALV'
@@ -170,7 +175,10 @@ export const trackError = (payload: Swetrix.IErrorEventPayload) => {
Swetrix.trackError(payload)
}
-export const trackCustom = (ev: string, meta?: Swetrix.TrackEventOptions['meta']) => {
+export const trackCustom = (
+ ev: string,
+ meta?: Swetrix.TrackEventOptions['meta'],
+) => {
if (isSelfhosted || !isBrowser) {
return
}
diff --git a/web/app/utils/auth.ts b/web/app/utils/auth.ts
index 529d2725b..c00d33121 100644
--- a/web/app/utils/auth.ts
+++ b/web/app/utils/auth.ts
@@ -9,7 +9,10 @@ import {
import { getCookie } from './cookie'
import { removeItem } from './localstorage'
-export const shouldShowLowEventsBanner = (totalMonthlyEvents: number, maxEventsCount: number) => {
+export const shouldShowLowEventsBanner = (
+ totalMonthlyEvents: number,
+ maxEventsCount: number,
+) => {
if (isSelfhosted) {
return false
}
diff --git a/web/app/utils/blog.ts b/web/app/utils/blog.ts
index c70e45901..6c7ffd2c3 100644
--- a/web/app/utils/blog.ts
+++ b/web/app/utils/blog.ts
@@ -1,3 +1,4 @@
// Removes first 10 characters from the string (i.e. 2023-10-07-)
export const getSlugFromFilename = (filename: string) => filename.substring(11)
-export const getDateFromFilename = (filename: string) => filename.substring(0, 10)
+export const getDateFromFilename = (filename: string) =>
+ filename.substring(0, 10)
diff --git a/web/app/utils/cookie.ts b/web/app/utils/cookie.ts
index 2e1726a1f..e6e1b91c1 100644
--- a/web/app/utils/cookie.ts
+++ b/web/app/utils/cookie.ts
@@ -1,6 +1,12 @@
-import { isDevelopment, isSelfhosted, isBrowser, COOKIE_DOMAIN } from '~/lib/constants'
+import {
+ isDevelopment,
+ isSelfhosted,
+ isBrowser,
+ COOKIE_DOMAIN,
+} from '~/lib/constants'
-const COOKIE_SUFFIX = isDevelopment || isSelfhosted ? '' : `; domain=${COOKIE_DOMAIN}; secure`
+const COOKIE_SUFFIX =
+ isDevelopment || isSelfhosted ? '' : `; domain=${COOKIE_DOMAIN}; secure`
export const getCookie = (key: string) => {
if (!isBrowser) {
@@ -20,11 +26,21 @@ export const getCookie = (key: string) => {
return null
}
-const generateCookieString = (key: string, value: string | number | boolean, maxAge = 3600, sameSite = 'strict') => {
+const generateCookieString = (
+ key: string,
+ value: string | number | boolean,
+ maxAge = 3600,
+ sameSite = 'strict',
+) => {
return `${key}=${value}; max-age=${maxAge}; path=/; SameSite=${sameSite}${COOKIE_SUFFIX}`
}
-export const setCookie = (key: string, value: string | number | boolean, maxAge = 3600, sameSite = 'strict') => {
+export const setCookie = (
+ key: string,
+ value: string | number | boolean,
+ maxAge = 3600,
+ sameSite = 'strict',
+) => {
if (!isBrowser) {
return null
}
diff --git a/web/app/utils/generic.ts b/web/app/utils/generic.ts
index 8d9a28a73..14a53b11b 100644
--- a/web/app/utils/generic.ts
+++ b/web/app/utils/generic.ts
@@ -18,9 +18,14 @@ const formatterLookup = [
]
export const nFormatter = (num: any, digits = 1) => {
- const item = _find(formatterLookup.slice().reverse(), ({ value }) => Math.abs(num) >= value)
+ const item = _find(
+ formatterLookup.slice().reverse(),
+ ({ value }) => Math.abs(num) >= value,
+ )
- return item ? _replace((num / item.value).toFixed(digits), rx, '$1') + item.symbol : '0'
+ return item
+ ? _replace((num / item.value).toFixed(digits), rx, '$1') + item.symbol
+ : '0'
}
export const nLocaleFormatter = (num: number): string => {
@@ -33,10 +38,16 @@ export const nLocaleFormatter = (num: number): string => {
// returns something like [123, 'k'], [5.5, 'M'], [425, null]
export const nFormatterSeparated = (num: any, digits = 1) => {
- const item = _find(formatterLookup.slice().reverse(), ({ value }) => num >= value)
+ const item = _find(
+ formatterLookup.slice().reverse(),
+ ({ value }) => num >= value,
+ )
if (item) {
- return [Number(_replace((num / item.value).toFixed(digits), rx, '$1')), item.symbol || null]
+ return [
+ Number(_replace((num / item.value).toFixed(digits), rx, '$1')),
+ item.symbol || null,
+ ]
}
return [0, null]
@@ -115,7 +126,11 @@ export const loadScript = (url: string) => {
document.body.appendChild(script)
}
-export const calculateRelativePercentage = (oldVal: number, newVal: number, round = 2) => {
+export const calculateRelativePercentage = (
+ oldVal: number,
+ newVal: number,
+ round = 2,
+) => {
if (oldVal === newVal) return 0
if (oldVal === 0) return 100
if (newVal === 0) return -100
@@ -131,7 +146,10 @@ const displayNamesPolyfill = {
of: (name: string) => name,
}
-export const getLocaleDisplayName = (locale: string | null, language: string): string => {
+export const getLocaleDisplayName = (
+ locale: string | null,
+ language: string,
+): string => {
if (!locale) return ''
const languageNames = Intl.DisplayNames
@@ -145,7 +163,8 @@ export const getLocaleDisplayName = (locale: string | null, language: string): s
}
}
-export const delay = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms))
+export const delay = (ms: number) =>
+ new Promise((resolve) => setTimeout(resolve, ms))
export const cn = (...args: ClassValue[]) => {
return twMerge(clsx(args))
diff --git a/web/app/utils/getPosts.server.ts b/web/app/utils/getPosts.server.ts
index e9ed3f89f..aa12d7eba 100644
--- a/web/app/utils/getPosts.server.ts
+++ b/web/app/utils/getPosts.server.ts
@@ -5,7 +5,12 @@ import sanitizeHtml from 'sanitize-html'
import { getBlogPost, getBlogPostWithCategory } from '~/api/api.server'
import { renderTimeToSwitchCta, renderDitchGoogleCta } from './renderCtaHtml'
-import { extractTableOfContents, ensureHeaderIds, generateSlug, renderTocAsHtml } from './toc'
+import {
+ extractTableOfContents,
+ ensureHeaderIds,
+ generateSlug,
+ renderTocAsHtml,
+} from './toc'
const renderer = new marked.Renderer()
@@ -133,7 +138,9 @@ const ALERT_CONFIGS = {
type AlertType = keyof typeof ALERT_CONFIGS
renderer.blockquote = ({ text }: Tokens.Blockquote) => {
- const alertMatch = text.match(/^\s*(?:<p>)?\[!(NOTE|TIP|IMPORTANT|WARNING|CAUTION)\](?:<br\s*\/?>|\n)?(?:<\/p>)?\s*/i)
+ const alertMatch = text.match(
+ /^\s*(?:<p>)?\[!(NOTE|TIP|IMPORTANT|WARNING|CAUTION)\](?:<br\s*\/?>|\n)?(?:<\/p>)?\s*/i,
+ )
if (alertMatch) {
const alertType = alertMatch[1].toUpperCase() as AlertType
@@ -158,7 +165,10 @@ renderer.blockquote = ({ text }: Tokens.Blockquote) => {
}
function replaceEmojiWithIcons(html: string): string {
- return html.replace(/✅/g, CHECK_ICON_SVG).replace(/❌/g, CROSS_ICON_SVG).replace(/⚠️/g, WARNING_ICON_SVG)
+ return html
+ .replace(/✅/g, CHECK_ICON_SVG)
+ .replace(/❌/g, CROSS_ICON_SVG)
+ .replace(/⚠️/g, WARNING_ICON_SVG)
}
function replaceSwetrixLogo(html: string): string {
diff --git a/web/app/utils/profileAvatars.tsx b/web/app/utils/profileAvatars.tsx
index ed0f701dd..4380f3d8d 100644
--- a/web/app/utils/profileAvatars.tsx
+++ b/web/app/utils/profileAvatars.tsx
@@ -185,7 +185,10 @@ const generateDisplayName = (profileId: string): string => {
/**
* Get display name for a profile - handles both identified and anonymous users
*/
-export const getProfileDisplayName = (profileId: string, isIdentified: boolean): string => {
+export const getProfileDisplayName = (
+ profileId: string,
+ isIdentified: boolean,
+): string => {
if (isIdentified) {
const userId = profileId.replace('usr_', '')
if (userId.length <= 20) {
@@ -205,10 +208,19 @@ interface ProfileAvatarProps {
/**
* Avatar component for user profiles using boring-avatars
*/
-export const ProfileAvatar = ({ profileId, size = 40, className }: ProfileAvatarProps) => {
+export const ProfileAvatar = ({
+ profileId,
+ size = 40,
+ className,
+}: ProfileAvatarProps) => {
return (
<div className={className}>
- <Avatar size={size} name={profileId} variant='beam' colors={AVATAR_COLORS} />
+ <Avatar
+ size={size}
+ name={profileId}
+ variant='beam'
+ colors={AVATAR_COLORS}
+ />
</div>
)
}
diff --git a/web/app/utils/referrers.ts b/web/app/utils/referrers.ts
index 35b62476f..70b3a053d 100644
--- a/web/app/utils/referrers.ts
+++ b/web/app/utils/referrers.ts
@@ -66,7 +66,9 @@ const matchByMap = (host: string): string | null => {
return null
}
-const getCanonicalRefGroup = (refValue: string | null): { key: string; name: string } | null => {
+const getCanonicalRefGroup = (
+ refValue: string | null,
+): { key: string; name: string } | null => {
const value = (refValue || '').trim()
const host = extractHostname(value)
@@ -111,8 +113,12 @@ export const getFaviconHost = (value: string | null): string | null => {
if (hostFromValue) return hostFromValue
// 3) If value is a mapped referrer group name, use the first domain-like pattern
- const mapping = REFERRER_MAP.find((m) => value.toLowerCase() === m.name.toLowerCase())
+ const mapping = REFERRER_MAP.find(
+ (m) => value.toLowerCase() === m.name.toLowerCase(),
+ )
if (!mapping) return null
- const domainLike = mapping.patterns.find((p) => !p.includes('://') && p.includes('.'))
+ const domainLike = mapping.patterns.find(
+ (p) => !p.includes('://') && p.includes('.'),
+ )
return domainLike || null
}
diff --git a/web/app/utils/server.ts b/web/app/utils/server.ts
index 45acd79dc..9896f9ccf 100644
--- a/web/app/utils/server.ts
+++ b/web/app/utils/server.ts
@@ -10,7 +10,9 @@ import routes from '~/utils/routes'
*/
export function detectTheme(request: Request): ThemeType {
// Stage 1: Check if theme is set via `theme` query param
- const queryTheme = new URL(request.url).searchParams.get('theme') as ThemeType | null
+ const queryTheme = new URL(request.url).searchParams.get(
+ 'theme',
+ ) as ThemeType | null
if (queryTheme && _includes(SUPPORTED_THEMES, queryTheme)) {
return queryTheme
@@ -27,7 +29,9 @@ export function detectTheme(request: Request): ThemeType {
// Stage 3: Try to detect theme based on Sec-CH browser hints
// Currently only Chromium-based browsers support this feature
// https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Sec-CH-Prefers-Color-Scheme
- const hintedTheme = request.headers.get('Sec-CH-Prefers-Color-Scheme') as ThemeType
+ const hintedTheme = request.headers.get(
+ 'Sec-CH-Prefers-Color-Scheme',
+ ) as ThemeType
if (_includes(SUPPORTED_THEMES, hintedTheme)) {
return hintedTheme
@@ -45,7 +49,11 @@ interface GetPageMeta {
prefixLessTitle: string
}
-export const getPageMeta = (t: typeof i18next.t, url?: string, _pathname?: string): GetPageMeta => {
+export const getPageMeta = (
+ t: typeof i18next.t,
+ url?: string,
+ _pathname?: string,
+): GetPageMeta => {
const DEFAULT_RESULT = {
title: t('titles.main'),
} as Partial<GetPageMeta>
diff --git a/web/app/utils/session.server.ts b/web/app/utils/session.server.ts
index 2b95a0379..f245b8634 100644
--- a/web/app/utils/session.server.ts
+++ b/web/app/utils/session.server.ts
@@ -15,7 +15,11 @@ function getCookieDomain(): string | undefined {
// In development or selfhosted without explicit domain, don't set domain
// TODO: Eventually we should support this variable for selfhosted Swetrix as well
- if (!domain || process.env.NODE_ENV === 'development' || process.env.__SELFHOSTED) {
+ if (
+ !domain ||
+ process.env.NODE_ENV === 'development' ||
+ process.env.__SELFHOSTED
+ ) {
return undefined
}
@@ -65,7 +69,10 @@ export function hasAuthTokens(request: Request): boolean {
return !!getAccessToken(request) || !!getRefreshToken(request)
}
-export function redirectIfNotAuthenticated(request: Request, redirectTo = '/login'): Response | null {
+export function redirectIfNotAuthenticated(
+ request: Request,
+ redirectTo = '/login',
+): Response | null {
if (hasAuthTokens(request)) {
return null
}
@@ -119,7 +126,10 @@ function buildCookieHeader(
return cookie
}
-export function createAuthCookies(tokens: AuthTokens, remember: boolean): string[] {
+export function createAuthCookies(
+ tokens: AuthTokens,
+ remember: boolean,
+): string[] {
const maxAge = remember ? PERSISTENT_COOKIE_MAX_AGE : undefined
const cookies = [
@@ -128,7 +138,11 @@ export function createAuthCookies(tokens: AuthTokens, remember: boolean): string
]
if (remember) {
- cookies.push(buildCookieHeader('is_persistent', 'true', { maxAge: PERSISTENT_COOKIE_MAX_AGE }))
+ cookies.push(
+ buildCookieHeader('is_persistent', 'true', {
+ maxAge: PERSISTENT_COOKIE_MAX_AGE,
+ }),
+ )
}
return cookies
@@ -147,8 +161,12 @@ export function clearAuthCookies(): string[] {
]
if (domain) {
- cookies.push(`${ACCESS_TOKEN_COOKIE}=; Path=/; Max-Age=0; SameSite=Lax; Domain=${domain}`)
- cookies.push(`${REFRESH_TOKEN_COOKIE}=; Path=/; Max-Age=0; SameSite=Lax; Domain=${domain}`)
+ cookies.push(
+ `${ACCESS_TOKEN_COOKIE}=; Path=/; Max-Age=0; SameSite=Lax; Domain=${domain}`,
+ )
+ cookies.push(
+ `${REFRESH_TOKEN_COOKIE}=; Path=/; Max-Age=0; SameSite=Lax; Domain=${domain}`,
+ )
}
return cookies
@@ -169,14 +187,24 @@ export function createHeadersWithCookies(cookies: string[]): Headers {
const PROJECT_PASSWORD_COOKIE_PREFIX = 'swx_pp_'
const PROJECT_PASSWORD_MAX_AGE = 604800 // 1 week in seconds
-export function getProjectPasswordCookie(request: Request, projectId: string): string | null {
+export function getProjectPasswordCookie(
+ request: Request,
+ projectId: string,
+): string | null {
const cookies = parseCookies(request)
return cookies[`${PROJECT_PASSWORD_COOKIE_PREFIX}${projectId}`] || null
}
-export function createProjectPasswordCookie(projectId: string, password: string): string {
- return buildCookieHeader(`${PROJECT_PASSWORD_COOKIE_PREFIX}${projectId}`, password, {
- maxAge: PROJECT_PASSWORD_MAX_AGE,
- sameSite: 'Lax',
- })
+export function createProjectPasswordCookie(
+ projectId: string,
+ password: string,
+): string {
+ return buildCookieHeader(
+ `${PROJECT_PASSWORD_COOKIE_PREFIX}${projectId}`,
+ password,
+ {
+ maxAge: PROJECT_PASSWORD_MAX_AGE,
+ sameSite: 'Lax',
+ },
+ )
}
diff --git a/web/app/utils/toc.ts b/web/app/utils/toc.ts
index e1525f43c..595a98cdc 100644
--- a/web/app/utils/toc.ts
+++ b/web/app/utils/toc.ts
@@ -40,13 +40,19 @@ export function generateSlug(text: string): string {
export function renderTocAsHtml(items: TocItem[]): string {
if (items.length === 0) return ''
- const renderTocList = (tocItems: TocItem[], level = 0, parentNum = ''): string => {
+ const renderTocList = (
+ tocItems: TocItem[],
+ level = 0,
+ parentNum = '',
+ ): string => {
if (tocItems.length === 0) return ''
let html = `<ol class="${level > 0 ? '!my-0' : ''}">`
tocItems.forEach((item, index) => {
- const currentNumber = parentNum ? `${parentNum}.${index + 1}` : `${index + 1}`
+ const currentNumber = parentNum
+ ? `${parentNum}.${index + 1}`
+ : `${index + 1}`
html += `<li class="flex flex-col">`
html += `<div class="flex items-start gap-0.5">`
diff --git a/web/app/utils/validator.ts b/web/app/utils/validator.ts
index 4d6c8914d..fe59e4ed2 100644
--- a/web/app/utils/validator.ts
+++ b/web/app/utils/validator.ts
@@ -3,4 +3,5 @@ export const MAX_PASSWORD_CHARS = 50
export const isValidEmail = (text: string) => text.match(/^\S+@\S+\.\S+$/)
-export const isValidPassword = (text: string) => text.length >= MIN_PASSWORD_CHARS
+export const isValidPassword = (text: string) =>
+ text.length >= MIN_PASSWORD_CHARS
diff --git a/web/package-lock.json b/web/package-lock.json
index 354cf86e3..c2d609d12 100644
--- a/web/package-lock.json
+++ b/web/package-lock.json
@@ -38,7 +38,6 @@
"lodash": "^4.17.21",
"lucide-react": "^0.562.0",
"marked": "^17.0.1",
- "prettier-plugin-tailwindcss": "^0.7.2",
"react": "^19.2.3",
"react-dom": "^19.2.3",
"react-hotkeys-hook": "^4.6.1",
@@ -70,8 +69,8 @@
"@types/sanitize-html": "^2.16.0",
"cross-env": "^10.1.0",
"knip": "^5.77.2",
+ "oxfmt": "^0.24.0",
"oxlint": "^0.16.10",
- "prettier": "^3.7.4",
"tailwindcss": "^4.1.18",
"typescript": "^5.9.3",
"vite": "^7.3.0",
@@ -1595,6 +1594,118 @@
"win32"
]
},
+ "node_modules/@oxfmt/darwin-arm64": {
+ "version": "0.24.0",
+ "resolved": "https://registry.npmjs.org/@oxfmt/darwin-arm64/-/darwin-arm64-0.24.0.tgz",
+ "integrity": "sha512-aYXuGf/yq8nsyEcHindGhiz9I+GEqLkVq8CfPbd+6VE259CpPEH+CaGHEO1j6vIOmNr8KHRq+IAjeRO2uJpb8A==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "darwin"
+ ]
+ },
+ "node_modules/@oxfmt/darwin-x64": {
+ "version": "0.24.0",
+ "resolved": "https://registry.npmjs.org/@oxfmt/darwin-x64/-/darwin-x64-0.24.0.tgz",
+ "integrity": "sha512-vs3b8Bs53hbiNvcNeBilzE/+IhDTWKjSBB3v/ztr664nZk65j0xr+5IHMBNz3CFppmX7o/aBta2PxY+t+4KoPg==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "darwin"
+ ]
+ },
+ "node_modules/@oxfmt/linux-arm64-gnu": {
+ "version": "0.24.0",
+ "resolved": "https://registry.npmjs.org/@oxfmt/linux-arm64-gnu/-/linux-arm64-gnu-0.24.0.tgz",
+ "integrity": "sha512-ItPDOPoQ0wLj/s8osc5ch57uUcA1Wk8r0YdO8vLRpXA3UNg7KPOm1vdbkIZRRiSUphZcuX5ioOEetEK8H7RlTw==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ]
+ },
+ "node_modules/@oxfmt/linux-arm64-musl": {
+ "version": "0.24.0",
+ "resolved": "https://registry.npmjs.org/@oxfmt/linux-arm64-musl/-/linux-arm64-musl-0.24.0.tgz",
+ "integrity": "sha512-JkQO3WnQjQTJONx8nxdgVBfl6BBFfpp9bKhChYhWeakwJdr7QPOAWJ/v3FGZfr0TbqINwnNR74aVZayDDRyXEA==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ]
+ },
+ "node_modules/@oxfmt/linux-x64-gnu": {
+ "version": "0.24.0",
+ "resolved": "https://registry.npmjs.org/@oxfmt/linux-x64-gnu/-/linux-x64-gnu-0.24.0.tgz",
+ "integrity": "sha512-N/SXlFO+2kak5gMt0oxApi0WXQDhwA0PShR0UbkY0PwtHjfSiDqJSOumyNqgQVoroKr1GNnoRmUqjZIz6DKIcw==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ]
+ },
+ "node_modules/@oxfmt/linux-x64-musl": {
+ "version": "0.24.0",
+ "resolved": "https://registry.npmjs.org/@oxfmt/linux-x64-musl/-/linux-x64-musl-0.24.0.tgz",
+ "integrity": "sha512-WM0pek5YDCQf50XQ7GLCE9sMBCMPW/NPAEPH/Hx6Qyir37lEsP4rUmSECo/QFNTU6KBc9NnsviAyJruWPpCMXw==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ]
+ },
+ "node_modules/@oxfmt/win32-arm64": {
+ "version": "0.24.0",
+ "resolved": "https://registry.npmjs.org/@oxfmt/win32-arm64/-/win32-arm64-0.24.0.tgz",
+ "integrity": "sha512-vFCseli1KWtwdHrVlT/jWfZ8jP8oYpnPPEjI23mPLW8K/6GEJmmvy0PZP5NpWUFNTzX0lqie58XnrATJYAe9Xw==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ]
+ },
+ "node_modules/@oxfmt/win32-x64": {
+ "version": "0.24.0",
+ "resolved": "https://registry.npmjs.org/@oxfmt/win32-x64/-/win32-x64-0.24.0.tgz",
+ "integrity": "sha512-0tmlNzcyewAnauNeBCq0xmAkmiKzl+H09p0IdHy+QKrTQdtixtf+AOjDAADbRfihkS+heF15Pjc4IyJMdAAJjw==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ]
+ },
"node_modules/@oxlint/darwin-arm64": {
"version": "0.16.12",
"resolved": "https://registry.npmjs.org/@oxlint/darwin-arm64/-/darwin-arm64-0.16.12.tgz",
@@ -6327,6 +6438,35 @@
"@oxc-resolver/binding-win32-x64-msvc": "11.16.2"
}
},
+ "node_modules/oxfmt": {
+ "version": "0.24.0",
+ "resolved": "https://registry.npmjs.org/oxfmt/-/oxfmt-0.24.0.tgz",
+ "integrity": "sha512-UjeM3Peez8Tl7IJ9s5UwAoZSiDRMww7BEc21gDYxLq3S3/KqJnM3mjNxsoSHgmBvSeX6RBhoVc2MfC/+96RdSw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "tinypool": "2.0.0"
+ },
+ "bin": {
+ "oxfmt": "bin/oxfmt"
+ },
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/Boshen"
+ },
+ "optionalDependencies": {
+ "@oxfmt/darwin-arm64": "0.24.0",
+ "@oxfmt/darwin-x64": "0.24.0",
+ "@oxfmt/linux-arm64-gnu": "0.24.0",
+ "@oxfmt/linux-arm64-musl": "0.24.0",
+ "@oxfmt/linux-x64-gnu": "0.24.0",
+ "@oxfmt/linux-x64-musl": "0.24.0",
+ "@oxfmt/win32-arm64": "0.24.0",
+ "@oxfmt/win32-x64": "0.24.0"
+ }
+ },
"node_modules/oxlint": {
"version": "0.16.12",
"resolved": "https://registry.npmjs.org/oxlint/-/oxlint-0.16.12.tgz",
@@ -6540,84 +6680,6 @@
"url": "https://github.com/prettier/prettier?sponsor=1"
}
},
- "node_modules/prettier-plugin-tailwindcss": {
- "version": "0.7.2",
- "resolved": "https://registry.npmjs.org/prettier-plugin-tailwindcss/-/prettier-plugin-tailwindcss-0.7.2.tgz",
- "integrity": "sha512-LkphyK3Fw+q2HdMOoiEHWf93fNtYJwfamoKPl7UwtjFQdei/iIBoX11G6j706FzN3ymX9mPVi97qIY8328vdnA==",
- "license": "MIT",
- "engines": {
- "node": ">=20.19"
- },
- "peerDependencies": {
- "@ianvs/prettier-plugin-sort-imports": "*",
- "@prettier/plugin-hermes": "*",
- "@prettier/plugin-oxc": "*",
- "@prettier/plugin-pug": "*",
- "@shopify/prettier-plugin-liquid": "*",
- "@trivago/prettier-plugin-sort-imports": "*",
- "@zackad/prettier-plugin-twig": "*",
- "prettier": "^3.0",
- "prettier-plugin-astro": "*",
- "prettier-plugin-css-order": "*",
- "prettier-plugin-jsdoc": "*",
- "prettier-plugin-marko": "*",
- "prettier-plugin-multiline-arrays": "*",
- "prettier-plugin-organize-attributes": "*",
- "prettier-plugin-organize-imports": "*",
- "prettier-plugin-sort-imports": "*",
- "prettier-plugin-svelte": "*"
- },
- "peerDependenciesMeta": {
- "@ianvs/prettier-plugin-sort-imports": {
- "optional": true
- },
- "@prettier/plugin-hermes": {
- "optional": true
- },
- "@prettier/plugin-oxc": {
- "optional": true
- },
- "@prettier/plugin-pug": {
- "optional": true
- },
- "@shopify/prettier-plugin-liquid": {
- "optional": true
- },
- "@trivago/prettier-plugin-sort-imports": {
- "optional": true
- },
- "@zackad/prettier-plugin-twig": {
- "optional": true
- },
- "prettier-plugin-astro": {
- "optional": true
- },
- "prettier-plugin-css-order": {
- "optional": true
- },
- "prettier-plugin-jsdoc": {
- "optional": true
- },
- "prettier-plugin-marko": {
- "optional": true
- },
- "prettier-plugin-multiline-arrays": {
- "optional": true
- },
- "prettier-plugin-organize-attributes": {
- "optional": true
- },
- "prettier-plugin-organize-imports": {
- "optional": true
- },
- "prettier-plugin-sort-imports": {
- "optional": true
- },
- "prettier-plugin-svelte": {
- "optional": true
- }
- }
- },
"node_modules/process-nextick-args": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/process-nextick-args/-/process-nextick-args-2.0.1.tgz",
@@ -7506,6 +7568,16 @@
"url": "https://github.com/sponsors/SuperchupuDev"
}
},
+ "node_modules/tinypool": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/tinypool/-/tinypool-2.0.0.tgz",
+ "integrity": "sha512-/RX9RzeH2xU5ADE7n2Ykvmi9ED3FBGPAjw9u3zucrNNaEBIO0HPSYgL0NT7+3p147ojeSdaVu08F6hjpv31HJg==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": "^20.0.0 || >=22.0.0"
+ }
+ },
"node_modules/to-regex-range": {
"version": "5.0.1",
"resolved": "https://registry.npmjs.org/to-regex-range/-/to-regex-range-5.0.1.tgz",
diff --git a/web/package.json b/web/package.json
index d1ad3ef94..df4415986 100644
--- a/web/package.json
+++ b/web/package.json
@@ -13,8 +13,8 @@
"lint": "oxlint",
"lint:fix": "oxlint --fix",
"lint:tsc": "tsc --noEmit",
- "format": "prettier --check --ignore-unknown ./app ./public",
- "format:fix": "prettier --write --ignore-unknown ./app ./public",
+ "format": "oxfmt --write ./app",
+ "format:check": "oxfmt --check ./app",
"knip": "knip"
},
"dependencies": {
@@ -50,7 +50,6 @@
"lodash": "^4.17.21",
"lucide-react": "^0.562.0",
"marked": "^17.0.1",
- "prettier-plugin-tailwindcss": "^0.7.2",
"react": "^19.2.3",
"react-dom": "^19.2.3",
"react-hotkeys-hook": "^4.6.1",
@@ -94,8 +93,8 @@
"@types/sanitize-html": "^2.16.0",
"cross-env": "^10.1.0",
"knip": "^5.77.2",
+ "oxfmt": "^0.24.0",
"oxlint": "^0.16.10",
- "prettier": "^3.7.4",
"tailwindcss": "^4.1.18",
"typescript": "^5.9.3",
"vite": "^7.3.0",