SupportForm.utils.tsx 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208
  1. // End of third-party imports
  2. import {
  3. DocsSearchResultType as PageType,
  4. type DocsSearchResult as Page,
  5. type DocsSearchResultSection as PageSection,
  6. } from 'common'
  7. import dayjs from 'dayjs'
  8. import { partition } from 'lodash'
  9. import { Book, Github, Hash, MessageSquare } from 'lucide-react'
  10. import {
  11. createLoader,
  12. createParser,
  13. createSerializer,
  14. parseAsString,
  15. type inferParserType,
  16. type UseQueryStatesKeysMap,
  17. } from 'nuqs'
  18. import { CATEGORY_OPTIONS } from './Support.constants'
  19. import { getProjectDetail } from '@/data/projects/project-detail-query'
  20. import { DOCS_URL } from '@/lib/constants'
  21. import type { Organization } from '@/types'
  22. export const NO_PROJECT_MARKER = 'no-project'
  23. export const NO_ORG_MARKER = 'no-org'
  24. export const formatMessage = ({
  25. message,
  26. attachments = [],
  27. error,
  28. }: {
  29. message: string
  30. attachments?: Array<string>
  31. error: string | null | undefined
  32. }) => {
  33. const [harFiles, images] = partition(attachments, (x) => x.split('?token')[0].endsWith('.har'))
  34. const errorString = error != null ? `\n\nError: ${error}` : ''
  35. const imagesString = images.length > 0 ? `\n\nImage Attachments:\n${images.join('\n\n')}` : ''
  36. const harFilesString = harFiles.length > 0 ? `\n\nHAR Files:\n${harFiles.join('\n\n')}` : ''
  37. return `${message}${errorString}${imagesString}${harFilesString}`
  38. }
  39. export const formatStudioVersion = (commit: { commitSha: string; commitTime: string }): string => {
  40. const formattedTime =
  41. commit.commitTime === 'unknown'
  42. ? 'unknown time'
  43. : dayjs(commit.commitTime).format('YYYY-MM-DD HH:mm:ss Z')
  44. return `SHA ${commit.commitSha} deployed at ${formattedTime}`
  45. }
  46. export function getPageIcon(page: Page) {
  47. switch (page.type) {
  48. case PageType.Markdown:
  49. case PageType.Reference:
  50. case PageType.Integration:
  51. return <Book strokeWidth={1.5} className="mr-0! w-4! h-4!" />
  52. case PageType.GithubDiscussion:
  53. return <Github strokeWidth={1.5} className="mr-0! w-4! h-4!" />
  54. default:
  55. throw new Error(`Unknown page type '${page.type}'`)
  56. }
  57. }
  58. export function getPageSectionIcon(page: Page) {
  59. switch (page.type) {
  60. case PageType.Markdown:
  61. case PageType.Reference:
  62. case PageType.Integration:
  63. return <Hash strokeWidth={1.5} className="mr-0! w-4! h-4!" />
  64. case PageType.GithubDiscussion:
  65. return <MessageSquare strokeWidth={1.5} className="mr-0! w-4! h-4!" />
  66. default:
  67. throw new Error(`Unknown page type '${page.type}'`)
  68. }
  69. }
  70. export function generateLink(pageType: PageType, link: string): string {
  71. switch (pageType) {
  72. case PageType.Markdown:
  73. case PageType.Reference:
  74. return `${DOCS_URL}${link}`
  75. case PageType.Integration:
  76. return `https://supabase.com${link}`
  77. case PageType.GithubDiscussion:
  78. return link
  79. default:
  80. throw new Error(`Unknown page type '${pageType}'`)
  81. }
  82. }
  83. export function formatSectionUrl(page: Page, section: PageSection): string {
  84. switch (page.type) {
  85. case PageType.Markdown:
  86. case PageType.GithubDiscussion:
  87. return `${generateLink(page.type, page.path)}#${section.slug ?? ''}`
  88. case PageType.Reference:
  89. return `${generateLink(page.type, page.path)}/${section.slug ?? ''}`
  90. case PageType.Integration:
  91. return generateLink(page.type, page.path) // Assuming no section slug for Integration pages
  92. default:
  93. throw new Error(`Unknown page type '${page.type}'`)
  94. }
  95. }
  96. export function getOrgSubscriptionPlan(orgs: Organization[] | undefined, orgSlug: string | null) {
  97. if (!orgs || !orgSlug) return undefined
  98. const selectedOrg = orgs?.find((org) => org.slug === orgSlug)
  99. const subscriptionPlanId = selectedOrg?.plan.id
  100. return subscriptionPlanId
  101. }
  102. const categoryOptionsLower = CATEGORY_OPTIONS.map((option) => option.value.toLowerCase())
  103. const parseAsCategoryOption = createParser({
  104. parse(queryValue) {
  105. const lowerValue = queryValue.toLowerCase()
  106. const matchingIndex = categoryOptionsLower.indexOf(lowerValue)
  107. return matchingIndex !== -1 ? CATEGORY_OPTIONS[matchingIndex].value : null
  108. },
  109. serialize(value) {
  110. return value ?? null
  111. },
  112. })
  113. const supportFormUrlState = {
  114. projectRef: parseAsString.withDefault(''),
  115. orgSlug: parseAsString.withDefault(''),
  116. category: parseAsCategoryOption,
  117. subject: parseAsString.withDefault(''),
  118. message: parseAsString.withDefault(''),
  119. error: parseAsString,
  120. /** Sentry event ID */
  121. sid: parseAsString,
  122. } satisfies UseQueryStatesKeysMap
  123. export type SupportFormUrlKeys = inferParserType<typeof supportFormUrlState>
  124. export const loadSupportFormInitialParams = createLoader(supportFormUrlState)
  125. export function loadSupportFormInitialParamsFromObject(
  126. initialParams: Partial<SupportFormUrlKeys>
  127. ): SupportFormUrlKeys {
  128. const normalizedParams = Object.fromEntries(
  129. Object.entries(initialParams).flatMap(([key, value]) =>
  130. value == null ? [] : [[key, String(value)]]
  131. )
  132. )
  133. return loadSupportFormInitialParams(normalizedParams)
  134. }
  135. const serializeSupportFormInitialParams = createSerializer(supportFormUrlState)
  136. export function createSupportFormUrl(initialParams: Partial<SupportFormUrlKeys>) {
  137. const serializedParams = serializeSupportFormInitialParams(initialParams)
  138. const query = serializedParams && serializedParams !== '?' ? serializedParams : ''
  139. return `/support/new${query}`
  140. }
  141. /**
  142. * Determines which organization to select based on combination of:
  143. * - Selected project (if any)
  144. * - URL param (if any)
  145. * - Fallback
  146. */
  147. export async function selectInitialOrgAndProject({
  148. projectRef,
  149. orgSlug,
  150. orgs,
  151. }: {
  152. projectRef: string | null
  153. orgSlug: string | null
  154. orgs: Organization[]
  155. }): Promise<{ projectRef: string | null; orgSlug: string | null }> {
  156. if (projectRef) {
  157. try {
  158. const projectDetails = await getProjectDetail({ ref: projectRef })
  159. if (projectDetails?.organization_id) {
  160. const org = orgs.find((o) => o.id === projectDetails.organization_id)
  161. if (org?.slug) {
  162. return {
  163. projectRef,
  164. orgSlug: org.slug,
  165. }
  166. }
  167. }
  168. } catch {
  169. // Can safely ignore, consider provided project ref invalid
  170. }
  171. }
  172. if (orgSlug) {
  173. const org = orgs.find((o) => o.slug === orgSlug)
  174. if (org?.slug) {
  175. return {
  176. projectRef: null,
  177. orgSlug: org.slug,
  178. }
  179. }
  180. }
  181. return {
  182. projectRef: null,
  183. orgSlug: orgs[0]?.slug ?? null,
  184. }
  185. }