Skip to content

The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.

clean circular deps (#34262)

Jordi Enric6f1cfef21373
diff --git a/apps/studio/components/interfaces/App/CommandMenu/ordering.ts b/apps/studio/components/interfaces/App/CommandMenu/ordering.ts
index b4fa9506f9c..5066ef56e2f 100644
--- a/apps/studio/components/interfaces/App/CommandMenu/ordering.ts
+++ b/apps/studio/components/interfaces/App/CommandMenu/ordering.ts
@@ -1,4 +1,4 @@
-import type { ICommandSection } from 'ui-patterns/CommandMenu/internal/CommandSection'
+import type { ICommandSection } from 'ui-patterns/CommandMenu/internal/types'
const DEFAULT_PRIORITY = 10
diff --git a/packages/common/hooks/useTelemetryCookie.tsx b/packages/common/hooks/useTelemetryCookie.tsx
index 32decc97d17..25fa2b73f82 100644
--- a/packages/common/hooks/useTelemetryCookie.tsx
+++ b/packages/common/hooks/useTelemetryCookie.tsx
@@ -2,7 +2,7 @@
import { useRouter } from 'next/compat/router'
import { useEffect } from 'react'
import { IS_PROD, LOCAL_STORAGE_KEYS } from '../constants'
-import { getSharedTelemetryData } from '../telemetry'
+import { getSharedTelemetryData } from '../telemetry-utils'
interface UseTelemetryCookieProps {
hasAcceptedConsent: boolean
diff --git a/packages/common/telemetry-utils.ts b/packages/common/telemetry-utils.ts
new file mode 100644
index 00000000000..00e25e69671
--- /dev/null
+++ b/packages/common/telemetry-utils.ts
@@ -0,0 +1,17 @@
+import { isBrowser } from './helpers'
+
+export function getSharedTelemetryData(pathname?: string) {
+ return {
+ page_url: isBrowser ? window.location.href : '',
+ page_title: isBrowser ? document?.title : '',
+ pathname: pathname ? pathname : isBrowser ? window.location.pathname : '',
+ ph: {
+ referrer: isBrowser ? document?.referrer : '',
+ language: navigator.language ?? 'en-US',
+ user_agent: navigator.userAgent,
+ search: isBrowser ? window.location.search : '',
+ viewport_height: isBrowser ? window.innerHeight : 0,
+ viewport_width: isBrowser ? window.innerWidth : 0,
+ },
+ }
+}
diff --git a/packages/common/telemetry.tsx b/packages/common/telemetry.tsx
index b4ae2d64e42..18d46f585cf 100644
--- a/packages/common/telemetry.tsx
+++ b/packages/common/telemetry.tsx
@@ -9,6 +9,7 @@ import { ensurePlatformSuffix, isBrowser } from './helpers'
import { useTelemetryCookie } from './hooks'
import { TelemetryEvent } from './telemetry-constants'
import { useUser } from './auth'
+import { getSharedTelemetryData } from './telemetry-utils'
//---
// PAGE TELEMETRY
@@ -215,23 +216,3 @@ export function useTelemetryIdentify(API_URL: string) {
export function handleResetTelemetry(API_URL: string) {
return post(`${API_URL}/telemetry/reset`, {})
}
-
-// ---
-// TELEMETRY UTILS
-// ---
-
-export function getSharedTelemetryData(pathname?: string) {
- return {
- page_url: isBrowser ? window.location.href : '',
- page_title: isBrowser ? document?.title : '',
- pathname: pathname ? pathname : isBrowser ? window.location.pathname : '',
- ph: {
- referrer: isBrowser ? document?.referrer : '',
- language: navigator.language ?? 'en-US',
- user_agent: navigator.userAgent,
- search: isBrowser ? window.location.search : '',
- viewport_height: isBrowser ? window.innerHeight : 0,
- viewport_width: isBrowser ? window.innerWidth : 0,
- },
- }
-}
diff --git a/packages/ui-patterns/CommandMenu/api/CommandList.tsx b/packages/ui-patterns/CommandMenu/api/CommandList.tsx
index 61937144171..851fbede951 100644
--- a/packages/ui-patterns/CommandMenu/api/CommandList.tsx
+++ b/packages/ui-patterns/CommandMenu/api/CommandList.tsx
@@ -4,7 +4,7 @@ import { forwardRef, useRef } from 'react'
import { CommandList_Shadcn_, cn } from 'ui'
-import { CommandItem, type ICommand } from '../internal/Command'
+import { CommandItem } from '../internal/Command'
import { CommandEmpty } from '../internal/CommandEmpty'
import { CommandGroup } from '../internal/CommandGroup'
import { useCommands } from './hooks/commandsHooks'
@@ -40,15 +40,11 @@ const CommandList = forwardRef<
<CommandGroup key={section.id} heading={section.name} forceMount={section.forceMount}>
{section.commands
.filter((command) => !command.defaultHidden || query)
- .map((_command) => {
- const command = _command as ICommand // strip the readonly applied from the proxy
-
- return (
- <CommandItem key={command.id} command={command}>
- <TextHighlighter>{command.name}</TextHighlighter>
- </CommandItem>
- )
- })}
+ .map((command) => (
+ <CommandItem key={command.id} command={command}>
+ <TextHighlighter>{command.name}</TextHighlighter>
+ </CommandItem>
+ ))}
</CommandGroup>
)
})}
diff --git a/packages/ui-patterns/CommandMenu/api/hooks/viewHooks.ts b/packages/ui-patterns/CommandMenu/api/hooks/viewHooks.ts
index 8c8bd0af348..ab2f4284fa7 100644
--- a/packages/ui-patterns/CommandMenu/api/hooks/viewHooks.ts
+++ b/packages/ui-patterns/CommandMenu/api/hooks/viewHooks.ts
@@ -2,9 +2,8 @@
import { useLayoutEffect, useRef } from 'react'
import { useSnapshot } from 'valtio'
-
import { useCommandContext } from '../../internal/Context'
-import { type DialogSize, type ITouchHandlers } from '../../internal/state/viewState'
+import { type DialogSize, type ITouchHandlers } from '../../internal/state/viewState.types'
const useCommandMenuInitiated = () => {
const { viewState } = useCommandContext()
diff --git a/packages/ui-patterns/CommandMenu/api/types.ts b/packages/ui-patterns/CommandMenu/api/types.ts
index 4021f8266a1..4613620d335 100644
--- a/packages/ui-patterns/CommandMenu/api/types.ts
+++ b/packages/ui-patterns/CommandMenu/api/types.ts
@@ -1,2 +1,2 @@
-export type { ICommand } from '../internal/Command'
+export type { ICommand } from '../internal/types'
export type { CommandOptions } from '../internal/state/commandsState'
diff --git a/packages/ui-patterns/CommandMenu/internal/Command.tsx b/packages/ui-patterns/CommandMenu/internal/Command.tsx
index 85d8727431e..e07c1a287ca 100644
--- a/packages/ui-patterns/CommandMenu/internal/Command.tsx
+++ b/packages/ui-patterns/CommandMenu/internal/Command.tsx
@@ -1,43 +1,10 @@
'use client'
-import { type PropsWithChildren, type ReactNode, forwardRef } from 'react'
-
+import { type PropsWithChildren, forwardRef } from 'react'
import { CommandItem_Shadcn_, cn } from 'ui'
import { useCrossCompatRouter } from '../api/hooks/useCrossCompatRouter'
-import { useQuery } from '../api/hooks/queryHooks'
import { useSetCommandMenuOpen } from '../api/hooks/viewHooks'
-
-type ICommand = IActionCommand | IRouteCommand
-
-interface IBaseCommand {
- id: string
- name: string
- value?: string
- className?: string
- forceMount?: boolean
- badge?: () => ReactNode
- icon?: () => ReactNode
- /**
- * Whether the item should be hidden until searched
- */
- defaultHidden?: boolean
- /**
- * Currently unused
- */
- keywords?: string[]
- /**
- * Currently unused
- */
- shortcut?: string
-}
-
-interface IActionCommand extends IBaseCommand {
- action: () => void
-}
-
-interface IRouteCommand extends IBaseCommand {
- route: `/${string}` | `http${string}`
-}
+import { type ICommand, type IActionCommand, type IRouteCommand } from './types'
const isActionCommand = (command: ICommand): command is IActionCommand => 'action' in command
const isRouteCommand = (command: ICommand): command is IRouteCommand => 'route' in command
@@ -123,5 +90,4 @@ const CommandItem = forwardRef<
})
CommandItem.displayName = CommandItem_Shadcn_.displayName
-export { CommandItem, generateCommandClassNames, isActionCommand, isRouteCommand }
-export type { ICommand }
+export { CommandItem, generateCommandClassNames }
diff --git a/packages/ui-patterns/CommandMenu/internal/CommandSection.tsx b/packages/ui-patterns/CommandMenu/internal/CommandSection.tsx
index ab52fac28b1..e30d7918f7b 100644
--- a/packages/ui-patterns/CommandMenu/internal/CommandSection.tsx
+++ b/packages/ui-patterns/CommandMenu/internal/CommandSection.tsx
@@ -1,12 +1,4 @@
-import { type ICommand } from './Command'
-
-type ICommandSection = {
- id: string
- name: string
- commands: Array<ICommand>
- forceMount?: boolean
- meta?: any
-}
+import { ICommandSection } from './types'
const toSectionId = (str: string) => str.toLowerCase().replace(/\s+/g, '-')
@@ -21,4 +13,3 @@ const section$new = (
})
export { section$new }
-export type { ICommandSection }
diff --git a/packages/ui-patterns/CommandMenu/internal/Context.tsx b/packages/ui-patterns/CommandMenu/internal/Context.tsx
index e8f67e1b834..f401e0ff58b 100644
--- a/packages/ui-patterns/CommandMenu/internal/Context.tsx
+++ b/packages/ui-patterns/CommandMenu/internal/Context.tsx
@@ -2,10 +2,10 @@
import { createContext, useContext } from 'react'
-import { type ICommandsState } from '../internal/state/commandsState'
+import { type ICommandsState } from '../internal/types'
import { type IPagesState } from '../internal/state/pagesState'
import { type IQueryState } from '../internal/state/queryState'
-import { type IViewState } from '../internal/state/viewState'
+import { type IViewState } from '../internal/state/viewState.types'
const CommandContext = createContext<
| {
diff --git a/packages/ui-patterns/CommandMenu/internal/state/commandsState.ts b/packages/ui-patterns/CommandMenu/internal/state/commandsState.ts
index 9c53e8afa89..0ac7cd5d903 100644
--- a/packages/ui-patterns/CommandMenu/internal/state/commandsState.ts
+++ b/packages/ui-patterns/CommandMenu/internal/state/commandsState.ts
@@ -1,29 +1,6 @@
import { proxy } from 'valtio'
-import { type ICommand } from '../Command'
-import { type ICommandSection, section$new } from '../CommandSection'
-
-type OrderSectionInstruction = (sections: ICommandSection[], idx: number) => ICommandSection[]
-type OrderCommandsInstruction = (
- commands: ICommand[],
- commandsToInsert: ICommand[]
-) => Array<ICommand>
-type CommandOptions = {
- deps?: any[]
- enabled?: boolean
- forceMountSection?: boolean
- sectionMeta?: any
- orderSection?: OrderSectionInstruction
- orderCommands?: OrderCommandsInstruction
-}
-
-type ICommandsState = {
- commandSections: ICommandSection[]
- registerSection: (
- sectionName: string,
- commands: ICommand[],
- options?: CommandOptions
- ) => () => void
-}
+import { type ICommandSection, type ICommandsState, type CommandOptions } from '../types'
+import { section$new } from '../CommandSection'
const initCommandsState = () => {
const state: ICommandsState = proxy({
@@ -82,4 +59,4 @@ const orderSectionFirst = (sections: ICommandSection[], idx: number) => [
]
export { initCommandsState, orderSectionFirst }
-export type { ICommandsState, CommandOptions }
+export type { CommandOptions }
diff --git a/packages/ui-patterns/CommandMenu/internal/state/commandsStates.test.ts b/packages/ui-patterns/CommandMenu/internal/state/commandsStates.test.ts
index 3479c9e2f81..35c4bc1bed4 100644
--- a/packages/ui-patterns/CommandMenu/internal/state/commandsStates.test.ts
+++ b/packages/ui-patterns/CommandMenu/internal/state/commandsStates.test.ts
@@ -1,7 +1,8 @@
import { beforeEach, describe, expect, it } from 'vitest'
-import { type ICommandSection, section$new } from '../CommandSection'
-import { initCommandsState, orderSectionFirst, type ICommandsState } from './commandsState'
+import { type ICommandsState, type ICommandSection } from '../types'
+import { initCommandsState, orderSectionFirst } from './commandsState'
+import { section$new } from '../CommandSection'
describe('orderSectionFirst', () => {
it('Orders newly created section first', () => {
diff --git a/packages/ui-patterns/CommandMenu/internal/state/pagesState.ts b/packages/ui-patterns/CommandMenu/internal/state/pagesState.ts
index 826a0e77dd6..9ca8e524fa3 100644
--- a/packages/ui-patterns/CommandMenu/internal/state/pagesState.ts
+++ b/packages/ui-patterns/CommandMenu/internal/state/pagesState.ts
@@ -1,7 +1,6 @@
import { type ReactNode } from 'react'
import { proxy } from 'valtio'
-
-import { type ICommandSection } from '../CommandSection'
+import { type ICommandSection } from '../types'
type PageComponent = () => ReactNode
diff --git a/packages/ui-patterns/CommandMenu/internal/state/viewState.ts b/packages/ui-patterns/CommandMenu/internal/state/viewState.ts
index 162b65aa75d..2186b89cee3 100644
--- a/packages/ui-patterns/CommandMenu/internal/state/viewState.ts
+++ b/packages/ui-patterns/CommandMenu/internal/state/viewState.ts
@@ -1,32 +1,17 @@
-import type { TouchEventHandler } from 'react'
-
import { proxy } from 'valtio'
-
-type DialogSize = 'small' | 'tiny' | 'medium' | 'large' | 'xlarge' | 'xxlarge' | 'xxxlarge'
-
-interface ITouchHandlers {
- handleTouchStart: TouchEventHandler
- handleTouchMove: TouchEventHandler
- handleTouchEnd: TouchEventHandler
-}
-
-type IViewState = {
- initiated: boolean
- init: () => void
- open: boolean
- setOpen: (open: boolean) => void
- toggleOpen: () => void
- size: DialogSize
- setSize: (size: DialogSize) => void
- touchHandlers: ITouchHandlers
- setTouchHandlers: (handlers: ITouchHandlers) => void
-}
+import { type IViewState, type DialogSize, type ITouchHandlers } from './viewState.types'
const initViewState = () => {
const state: IViewState = proxy({
initiated: false,
init: () => !state.initiated && (state.initiated = true),
open: false,
+ size: 'large',
+ touchHandlers: {
+ handleTouchStart: () => {},
+ handleTouchMove: () => {},
+ handleTouchEnd: () => {},
+ },
setOpen: (open) => {
state.init()
state.open = open
@@ -35,17 +20,16 @@ const initViewState = () => {
state.init()
state.open = !state.open
},
- size: 'large',
- setSize: (size) => (state.size = size),
- touchHandlers: {
- handleTouchStart: () => {},
- handleTouchMove: () => {},
- handleTouchEnd: () => {},
+ setSize: (size) => {
+ state.size = size
+ },
+ setTouchHandlers: (handlers) => {
+ state.touchHandlers = handlers
},
- setTouchHandlers: (handlers) => (state.touchHandlers = handlers),
})
+
return state
}
export { initViewState }
-export type { DialogSize, IViewState, ITouchHandlers }
+export type { DialogSize, ITouchHandlers }
diff --git a/packages/ui-patterns/CommandMenu/internal/state/viewState.types.ts b/packages/ui-patterns/CommandMenu/internal/state/viewState.types.ts
new file mode 100644
index 00000000000..37016ac37c9
--- /dev/null
+++ b/packages/ui-patterns/CommandMenu/internal/state/viewState.types.ts
@@ -0,0 +1,19 @@
+export type DialogSize = 'small' | 'tiny' | 'medium' | 'large' | 'xlarge' | 'xxlarge' | 'xxxlarge'
+
+export type ITouchHandlers = {
+ handleTouchStart: (e: React.TouchEvent<HTMLDivElement>) => void
+ handleTouchMove: (e: React.TouchEvent<HTMLDivElement>) => void
+ handleTouchEnd: (e: React.TouchEvent<HTMLDivElement>) => void
+}
+
+export interface IViewState {
+ initiated: boolean
+ init: () => boolean
+ open: boolean
+ size: DialogSize
+ touchHandlers: ITouchHandlers
+ setOpen: (open: boolean) => void
+ toggleOpen: () => void
+ setSize: (size: DialogSize) => void
+ setTouchHandlers: (handlers: ITouchHandlers) => void
+}
diff --git a/packages/ui-patterns/CommandMenu/internal/types.ts b/packages/ui-patterns/CommandMenu/internal/types.ts
new file mode 100644
index 00000000000..e3fe8eb7beb
--- /dev/null
+++ b/packages/ui-patterns/CommandMenu/internal/types.ts
@@ -0,0 +1,60 @@
+import { type ReactNode } from 'react'
+
+export interface IBaseCommand {
+ id: string
+ name: string
+ value?: string
+ className?: string
+ forceMount?: boolean
+ badge?: () => ReactNode
+ icon?: () => ReactNode
+ defaultHidden?: boolean
+}
+
+export interface IActionCommand extends IBaseCommand {
+ action: () => void
+}
+
+export interface IRouteCommand extends IBaseCommand {
+ route: `/${string}` | `http${string}`
+}
+
+export type ICommand = IActionCommand | IRouteCommand
+
+export const isActionCommand = (command: ICommand): command is IActionCommand => 'action' in command
+export const isRouteCommand = (command: ICommand): command is IRouteCommand => 'route' in command
+
+export interface ICommandSection {
+ id: string
+ name: string
+ commands: ICommand[]
+ meta?: any
+ forceMount?: boolean
+}
+
+export interface ICommandsState {
+ commandSections: ICommandSection[]
+ registerSection: (
+ sectionName: string,
+ commands: ICommand[],
+ options?: CommandOptions
+ ) => () => void
+}
+
+export type OrderSectionInstruction = (
+ sections: ICommandSection[],
+ idx: number
+) => ICommandSection[]
+export type OrderCommandsInstruction = (
+ commands: ICommand[],
+ commandsToInsert: ICommand[]
+) => Array<ICommand>
+
+export type CommandOptions = {
+ deps?: any[]
+ enabled?: boolean
+ forceMountSection?: boolean
+ sectionMeta?: any
+ orderSection?: OrderSectionInstruction
+ orderCommands?: OrderCommandsInstruction
+}
diff --git a/packages/ui-patterns/ConsentToast/index.tsx b/packages/ui-patterns/ConsentToast/index.tsx
index e5c80c8929e..cdf639a05b1 100644
--- a/packages/ui-patterns/ConsentToast/index.tsx
+++ b/packages/ui-patterns/ConsentToast/index.tsx
@@ -1,20 +1,9 @@
'use client'
-import {
- LOCAL_STORAGE_KEYS,
- handlePageTelemetry,
- isBrowser,
- useBreakpoint,
- useFeatureFlags,
-} from 'common'
+import { useBreakpoint } from 'common'
import { noop } from 'lodash'
-import { useCallback, useEffect, useRef, useState } from 'react'
-import { toast } from 'sonner'
-import { Button, cn } from 'ui'
-import { proxy, useSnapshot } from 'valtio'
+import { Button } from 'ui'
import { PrivacySettings } from '../PrivacySettings'
-import { useRouter } from 'next/compat/router'
-import { usePathname } from 'next/navigation'
interface ConsentToastProps {
onAccept: () => void
@@ -79,128 +68,4 @@ export const ConsentToast = ({ onAccept = noop, onOptOut = noop }: ConsentToastP
)
}
-// [Alaister]: Using global state here so multiple components can access the consent value
-const consentState = proxy({
- consentValue: (isBrowser ? localStorage?.getItem(LOCAL_STORAGE_KEYS.TELEMETRY_CONSENT) : null) as
- | string
- | null,
- setConsentValue: (value: string | null) => {
- consentState.consentValue = value
- },
-})
-
-export const useConsent = () => {
- const { TELEMETRY_CONSENT, TELEMETRY_DATA } = LOCAL_STORAGE_KEYS
- const consentToastId = useRef<string | number>()
- const router = useRouter()
- const appRouterPathname = usePathname()
- const featureFlags = useFeatureFlags()
-
- const { consentValue } = useSnapshot(consentState)
- const pathname =
- router?.pathname ?? appRouterPathname ?? (isBrowser ? window.location.pathname : '')
-
- const handleConsent = (value: 'true' | 'false') => {
- if (!isBrowser) return
-
- if (value === 'true') {
- const cookies = document.cookie.split(';')
- const telemetryCookie = cookies.find((cookie) => cookie.trim().startsWith(TELEMETRY_DATA))
- if (telemetryCookie) {
- try {
- const encodedData = telemetryCookie.split('=')[1]
- const telemetryData = JSON.parse(decodeURIComponent(encodedData))
- handlePageTelemetry(
- process.env.NEXT_PUBLIC_API_URL!,
- pathname,
- featureFlags.posthog,
- telemetryData
- )
- // remove the telemetry cookie
- document.cookie = `${TELEMETRY_DATA}=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/`
- } catch (error) {
- console.error('Invalid telemetry data:', error)
- }
- } else {
- handlePageTelemetry(process.env.NEXT_PUBLIC_API_URL!, pathname, featureFlags.posthog)
- }
- } else {
- // remove the telemetry cookie
- document.cookie = `${TELEMETRY_DATA}=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/`
- }
-
- consentState.setConsentValue(value)
- localStorage.setItem(TELEMETRY_CONSENT, value)
-
- if (consentToastId.current) {
- toast.dismiss(consentToastId.current)
- }
- }
-
- const triggerConsentToast = useCallback(() => {
- if (isBrowser && consentValue === null) {
- consentToastId.current = toast(
- <ConsentToast
- onAccept={() => handleConsent('true')}
- onOptOut={() => handleConsent('false')}
- />,
- {
- id: 'consent-toast',
- position: 'bottom-right',
- duration: Infinity,
- closeButton: false,
- dismissible: false,
- className: cn(
- '!w-screen !fixed !border-t !h-auto !left-0 !bottom-0 !top-auto !right-0 !rounded-none !max-w-none !bg-overlay !text',
- 'sm:!w-full sm:!max-w-[356px] sm:!left-auto sm:!right-8 sm:!bottom-8 sm:!rounded-lg sm:border'
- ),
- }
- )
- }
- }, [])
-
- useEffect(() => {
- const handleSetLocalStorage = () => {
- if (localStorage?.getItem(TELEMETRY_CONSENT)) toast.dismiss(consentToastId.current)
- }
-
- if (isBrowser) {
- window.addEventListener('storage', handleSetLocalStorage)
- return window.removeEventListener('storage', () => null)
- }
- }, [])
-
- useEffect(() => {
- setTimeout(() => {
- consentValue === null && triggerConsentToast()
- }, 300)
- }, [consentValue])
-
- return {
- consentValue,
- hasAcceptedConsent: consentValue === 'true',
- triggerConsentToast,
- }
-}
-
-export const useConsentValue = (KEY_NAME: string) => {
- const initialValue = isBrowser ? localStorage?.getItem(KEY_NAME) : null
- const [consentValue, setConsentValue] = useState<string | null>(initialValue)
-
- const handleConsent = (value: 'true' | 'false') => {
- if (!isBrowser) return
- setConsentValue(value)
- localStorage.setItem(KEY_NAME, value)
- window.dispatchEvent(new Event('storage'))
- if (value === 'true') {
- handlePageTelemetry(process.env.NEXT_PUBLIC_API_URL!, location.pathname)
- }
- }
-
- return {
- consentValue,
- setConsentValue,
- hasAccepted: consentValue === 'true',
- handleConsent,
- }
-}
+export { useConsent, useConsentValue } from '../shared/consent'
diff --git a/packages/ui-patterns/PrivacySettings/index.tsx b/packages/ui-patterns/PrivacySettings/index.tsx
index fdd2eb58607..e1981ce5b66 100644
--- a/packages/ui-patterns/PrivacySettings/index.tsx
+++ b/packages/ui-patterns/PrivacySettings/index.tsx
@@ -4,8 +4,7 @@ import { handleResetTelemetry, LOCAL_STORAGE_KEYS } from 'common'
import Link from 'next/link'
import { PropsWithChildren, useEffect, useState } from 'react'
import { Modal, Toggle } from 'ui'
-
-import { useConsentValue } from '../ConsentToast'
+import { useConsentValue } from '../shared/consent'
export const PrivacySettings = ({
children,
diff --git a/packages/ui-patterns/Toc/mdx-plugins/remark-heading.ts b/packages/ui-patterns/Toc/mdx-plugins/remark-heading.ts
index 9897e4b3102..e21803ae5d2 100644
--- a/packages/ui-patterns/Toc/mdx-plugins/remark-heading.ts
+++ b/packages/ui-patterns/Toc/mdx-plugins/remark-heading.ts
@@ -2,7 +2,7 @@ import Slugger from 'github-slugger'
import type { Heading, Root } from 'mdast'
import type { Data, Transformer } from 'unified'
import { visit } from 'unist-util-visit'
-import type { TOCItemType } from '../server/get-toc'
+import type { TOCItemType } from '../types'
import { flattenNode } from './remark-utils'
import type { VFile } from 'vfile'
diff --git a/packages/ui-patterns/Toc/server/get-toc.tsx b/packages/ui-patterns/Toc/server/get-toc.tsx
index 30a0e578d49..e395bc04426 100644
--- a/packages/ui-patterns/Toc/server/get-toc.tsx
+++ b/packages/ui-patterns/Toc/server/get-toc.tsx
@@ -1,16 +1,8 @@
import { remark } from 'remark'
import { remarkHeading } from '../mdx-plugins/remark-heading'
-import type { ReactNode } from 'react'
import type { PluggableList } from 'unified'
import type { Compatible } from 'vfile'
-
-export interface TOCItemType {
- title: ReactNode
- url: string
- depth: number
-}
-
-export type TableOfContents = TOCItemType[]
+import type { TableOfContents } from '../types'
/**
* Get Table of Contents from markdown/mdx document (using remark)
@@ -53,3 +45,5 @@ export function getTableOfContents(
return []
}
+
+export type { TableOfContents, TOCItemType } from '../types'
diff --git a/packages/ui-patterns/Toc/types.ts b/packages/ui-patterns/Toc/types.ts
new file mode 100644
index 00000000000..964788b1bc5
--- /dev/null
+++ b/packages/ui-patterns/Toc/types.ts
@@ -0,0 +1,9 @@
+import type { ReactNode } from 'react'
+
+export interface TOCItemType {
+ title: ReactNode
+ url: string
+ depth: number
+}
+
+export type TableOfContents = TOCItemType[]
diff --git a/packages/ui-patterns/shared/consent.tsx b/packages/ui-patterns/shared/consent.tsx
new file mode 100644
index 00000000000..a3e57172326
--- /dev/null
+++ b/packages/ui-patterns/shared/consent.tsx
@@ -0,0 +1,134 @@
+import { LOCAL_STORAGE_KEYS, handlePageTelemetry, isBrowser } from 'common'
+import { useCallback, useEffect, useRef, useState } from 'react'
+import { toast } from 'sonner'
+import { proxy, useSnapshot } from 'valtio'
+import { useRouter } from 'next/compat/router'
+import { usePathname } from 'next/navigation'
+import { useFeatureFlags } from 'common'
+import { cn } from 'ui'
+import { ConsentToast } from '../ConsentToast'
+
+const consentState = proxy({
+ consentValue: (isBrowser ? localStorage?.getItem(LOCAL_STORAGE_KEYS.TELEMETRY_CONSENT) : null) as
+ | string
+ | null,
+ setConsentValue: (value: string | null) => {
+ consentState.consentValue = value
+ },
+})
+
+export const useConsent = () => {
+ const { TELEMETRY_CONSENT, TELEMETRY_DATA } = LOCAL_STORAGE_KEYS
+ const consentToastId = useRef<string | number>()
+ const router = useRouter()
+ const appRouterPathname = usePathname()
+ const featureFlags = useFeatureFlags()
+
+ const { consentValue } = useSnapshot(consentState)
+ const pathname =
+ router?.pathname ?? appRouterPathname ?? (isBrowser ? window.location.pathname : '')
+
+ const handleConsent = (value: 'true' | 'false') => {
+ if (!isBrowser) return
+
+ if (value === 'true') {
+ const cookies = document.cookie.split(';')
+ const telemetryCookie = cookies.find((cookie) => cookie.trim().startsWith(TELEMETRY_DATA))
+ if (telemetryCookie) {
+ try {
+ const encodedData = telemetryCookie.split('=')[1]
+ const telemetryData = JSON.parse(decodeURIComponent(encodedData))
+ handlePageTelemetry(
+ process.env.NEXT_PUBLIC_API_URL!,
+ pathname,
+ featureFlags.posthog,
+ telemetryData
+ )
+ // remove the telemetry cookie
+ document.cookie = `${TELEMETRY_DATA}=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/`
+ } catch (error) {
+ console.error('Invalid telemetry data:', error)
+ }
+ } else {
+ handlePageTelemetry(process.env.NEXT_PUBLIC_API_URL!, pathname, featureFlags.posthog)
+ }
+ } else {
+ // remove the telemetry cookie
+ document.cookie = `${TELEMETRY_DATA}=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/`
+ }
+
+ consentState.setConsentValue(value)
+ localStorage.setItem(TELEMETRY_CONSENT, value)
+
+ if (consentToastId.current) {
+ toast.dismiss(consentToastId.current)
+ }
+ }
+
+ const triggerConsentToast = useCallback(() => {
+ if (isBrowser && consentValue === null) {
+ consentToastId.current = toast(
+ <ConsentToast
+ onAccept={() => handleConsent('true')}
+ onOptOut={() => handleConsent('false')}
+ />,
+ {
+ id: 'consent-toast',
+ position: 'bottom-right',
+ duration: Infinity,
+ closeButton: false,
+ dismissible: false,
+ className: cn(
+ '!w-screen !fixed !border-t !h-auto !left-0 !bottom-0 !top-auto !right-0 !rounded-none !max-w-none !bg-overlay !text',
+ 'sm:!w-full sm:!max-w-[356px] sm:!left-auto sm:!right-8 sm:!bottom-8 sm:!rounded-lg sm:border'
+ ),
+ }
+ )
+ }
+ }, [])
+
+ useEffect(() => {
+ const handleSetLocalStorage = () => {
+ if (localStorage?.getItem(TELEMETRY_CONSENT)) toast.dismiss(consentToastId.current)
+ }
+
+ if (isBrowser) {
+ window.addEventListener('storage', handleSetLocalStorage)
+ return window.removeEventListener('storage', () => null)
+ }
+ }, [])
+
+ useEffect(() => {
+ setTimeout(() => {
+ consentValue === null && triggerConsentToast()
+ }, 300)
+ }, [consentValue])
+
+ return {
+ consentValue,
+ hasAcceptedConsent: consentValue === 'true',
+ triggerConsentToast,
+ }
+}
+
+export const useConsentValue = (KEY_NAME: string) => {
+ const initialValue = isBrowser ? localStorage?.getItem(KEY_NAME) : null
+ const [consentValue, setConsentValue] = useState<string | null>(initialValue)
+
+ const handleConsent = (value: 'true' | 'false') => {
+ if (!isBrowser) return
+ setConsentValue(value)
+ localStorage.setItem(KEY_NAME, value)
+ window.dispatchEvent(new Event('storage'))
+ if (value === 'true') {
+ handlePageTelemetry(process.env.NEXT_PUBLIC_API_URL!, location.pathname)
+ }
+ }
+
+ return {
+ consentValue,
+ setConsentValue,
+ hasAccepted: consentValue === 'true',
+ handleConsent,
+ }
+}