Skip to content

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

3.9 KB
Raw Blame
/**
 * Flatten React node trees to plain text for heading anchor ids.
 * MDX headings often mix strings with inline nodes (`code`, links, icons);
 * older code assumed every non-string had `props.children` and crashed when
 * that was missing (e.g. lucide icons inside docs MDX links).
 */
const flattenNodeText = (node: unknown): string => {
  if (node == null || typeof node === 'boolean') return ''
  if (typeof node === 'string' || typeof node === 'number') return String(node)
  if (Array.isArray(node)) return node.map(flattenNodeText).join('')
  if (typeof node === 'object' && node !== null && 'props' in node) {
    const props = (node as { props?: { children?: unknown } }).props
    return flattenNodeText(props?.children)
  }
  return ''
}

// Check if heading has custom anchor first, before forming the anchor based on the title
export const getAnchor = (text: any, { id }: { id?: string } = {}): string | undefined => {
  if (id) {
    // Component already defines its own id. Since the anchor must match the
    // id, return it directly.
    return id
  }

  if (typeof text === 'object') {
    if (Array.isArray(text)) {
      const customAnchor = text.find((x) => typeof x === 'string' && hasCustomAnchor(x))
      if (customAnchor !== undefined) {
        return parseCustomAnchor(customAnchor)
      }

      const formattedText = text
        .map((x) => {
          if (typeof x === 'string') {
            return x.trim()
          }
          return flattenNodeText(x)
        })
        .map((x) => {
          if (typeof x !== 'string') {
            return x
          }
          return slugify(x)
        })

      return formattedText.join('-').toLowerCase()
    } else {
      const flattened = flattenNodeText(text).trim()
      return flattened ? slugify(flattened) : undefined
    }
  } else if (typeof text === 'string') {
    if (hasCustomAnchor(text)) {
      return parseCustomAnchor(text)
    }
    return slugify(text)
  } else {
    return undefined
  }
}

const hasCustomAnchor = (value: string): boolean => value.includes('[#') && value.includes(']')

const parseCustomAnchor = (value: string): string =>
  value.slice(value.indexOf('[#') + 2, value.indexOf(']'))

const slugify = (value: string): string =>
  value
    .toLowerCase()
    .trim()
    .replace(/[^a-z0-9- ]/g, '')
    .replace(/[ ]/g, '-')

export const removeAnchor = (text: any) => {
  if (typeof text === 'object' && Array.isArray(text)) {
    return text.filter((x) => !(typeof x === 'string' && hasCustomAnchor(x)))
  } else if (typeof text === 'string') {
    if (text.indexOf('[#') > 0) return text.slice(0, text.indexOf('[#'))
    else return text
  }
  return text
}

export const highlightSelectedTocItem = (id: string) => {
  const tocMenuItems = document.querySelectorAll('.toc-menu a')

  // find any currently active items and remove them
  const currentActiveItem = document.querySelector('.toc-menu .toc__menu-item--active')
  currentActiveItem?.classList.remove('toc__menu-item--active')

  // Add active class to the current item
  tocMenuItems.forEach((item) => {
    // @ts-ignore
    if (item.href.split('#')[1] === id) {
      item.classList.add('toc__menu-item--active')
    }
  })
}

// find any currently active items and remove them on route change
export const unHighlightSelectedTocItems = () => {
  const currentActiveItem = document.querySelector('.toc-menu .toc__menu-item--active')
  currentActiveItem?.classList.remove('toc__menu-item--active')
}

export const highlightSelectedNavItem = (id: string) => {
  const navMenuItems = document.querySelectorAll<HTMLAnchorElement>('.function-link-item a')

  // find any currently active items and remove them
  const currentActiveItems = document.querySelectorAll('.function-link-list .text-primary')
  currentActiveItems.forEach((item) => item.classList.remove('text-primary'))

  // Add active class to the current item
  navMenuItems.forEach((item) => {
    if (item.href.split('/').at(-1) === id) {
      item.classList.add('text-primary')
    }
  })
}