import * as React from 'react'
import {Card, Stack, Box, Label, Grid, Select} from '@sanity/ui'
import {ListGraphQLApisResult} from './use-list-graphql-apis'
import {parseUrl, buildUrl} from './url'
type HeaderProps = {
url: string | null
onUrlChange: (url: string) => void
apis: ListGraphQLApisResult
}
type APIInfo = {
projectId: string
dataset: string
tag: string
}
const defaultVersion = 'v2023-08-01'
const defaultPerspective = 'raw'
// Convert the selected API to a string that can be set on a
function toValue(info: APIInfo): string {
return `${info.projectId}:${info.dataset}:${info.tag}`
}
// Parse the value on an into the related API info
function fromValue(str: string): APIInfo {
const [projectId, dataset, tag] = str.split(':')
if (!projectId || !dataset || !tag) {
throw new Error('Could not parse value')
}
return {projectId, dataset, tag}
}
export function Header(props: HeaderProps) {
const {url, onUrlChange, apis} = props
const parsed = parseUrl(url)
const {version, perspective} = parsed
React.useEffect(
function () {
if (!apis.data?.[0] || url) {
return
}
onUrlChange(
buildUrl({
...apis.data[0],
version: defaultVersion,
perspective: defaultPerspective,
}),
)
},
[url, apis.data],
)
function handleApiChange(evt: React.ChangeEvent) {
onUrlChange(
buildUrl({
...parsed,
...fromValue(evt.target.value),
}),
)
}
function handleVersionChange(evt: React.ChangeEvent) {
onUrlChange(
buildUrl({
...parsed,
version: evt.target.value,
}),
)
}
function handlePerspectiveChange(evt: React.ChangeEvent) {
onUrlChange(
buildUrl({
...parsed,
perspective: evt.target.value,
}),
)
}
return (
)
}