webapp/src/components/Editor/TopicSelect/TopicSelect.tsx

79 lines
2.0 KiB
TypeScript
Raw Normal View History

2023-03-23 17:15:50 +00:00
import type { Topic } from '../../../graphql/types.gen'
import { createOptions, Select } from '@thisbeyond/solid-select'
import { useLocalize } from '../../../context/localize'
import '@thisbeyond/solid-select/style.css'
import './TopicSelect.scss'
2023-05-10 20:20:53 +00:00
import styles from './TopicSelect.module.scss'
import { clsx } from 'clsx'
import { createSignal } from 'solid-js'
import { slugify } from '../../../utils/slugify'
2023-03-23 17:15:50 +00:00
type TopicSelectProps = {
topics: Topic[]
selectedTopics: Topic[]
2023-03-23 17:15:50 +00:00
onChange: (selectedTopics: Topic[]) => void
2023-05-10 20:20:53 +00:00
mainTopic?: Topic
onMainTopicChange: (mainTopic: Topic) => void
2023-03-23 17:15:50 +00:00
}
export const TopicSelect = (props: TopicSelectProps) => {
const { t } = useLocalize()
2023-05-10 20:20:53 +00:00
const [isDisabled, setIsDisabled] = createSignal(false)
const createValue = (title): Topic => {
const minId = Math.min(...props.selectedTopics.map((topic) => topic.id))
const id = minId < 0 ? minId - 1 : -2
return { id, title, slug: slugify(title) }
}
const selectProps = createOptions(props.topics, {
key: 'title',
disable: (topic) => {
2023-03-24 13:39:52 +00:00
return props.selectedTopics.some((selectedTopic) => selectedTopic.slug === topic.slug)
2023-05-10 20:20:53 +00:00
},
createable: createValue
})
2023-03-23 17:15:50 +00:00
const handleChange = (selectedTopics: Topic[]) => {
props.onChange(selectedTopics)
}
2023-05-10 20:20:53 +00:00
const handleSelectedItemClick = (topic: Topic) => {
setIsDisabled(true)
props.onMainTopicChange(topic)
setIsDisabled(false)
}
const format = (item, type) => {
if (type === 'option') {
return item.label
}
const isMainTopic = item.id === props.mainTopic.id
return (
<div
class={clsx(styles.selectedItem, {
[styles.mainTopic]: isMainTopic
})}
onClick={() => handleSelectedItemClick(item)}
>
{item.title}
</div>
)
}
return (
<Select
multiple={true}
2023-05-10 20:20:53 +00:00
disabled={isDisabled()}
{...selectProps}
2023-05-10 20:20:53 +00:00
format={format}
placeholder={t('Topics')}
class="TopicSelect"
onChange={handleChange}
/>
)
2023-03-23 17:15:50 +00:00
}