This commit is contained in:
@@ -1,9 +1,11 @@
|
||||
import { createEffect, createSignal, For, Show } from 'solid-js'
|
||||
import { createEffect, createSignal, For, Show, on } from 'solid-js'
|
||||
import { Topic, useData } from '../context/data'
|
||||
import { query } from '../graphql'
|
||||
import { ADMIN_UPDATE_TOPIC_MUTATION } from '../graphql/mutations'
|
||||
import styles from '../styles/Form.module.css'
|
||||
import modalStyles from '../styles/Modal.module.css'
|
||||
import EditableCodePreview from '../ui/EditableCodePreview'
|
||||
import Modal from '../ui/Modal'
|
||||
import TopicPillsCloud, { type TopicPill } from '../ui/TopicPillsCloud'
|
||||
import HTMLEditor from '../ui/HTMLEditor'
|
||||
|
||||
interface TopicEditModalProps {
|
||||
topic: Topic
|
||||
@@ -28,35 +30,36 @@ export default function TopicEditModal(props: TopicEditModalProps) {
|
||||
|
||||
// Состояние для выбора родителей
|
||||
const [availableParents, setAvailableParents] = createSignal<Topic[]>([])
|
||||
const [parentSearch, setParentSearch] = createSignal('')
|
||||
|
||||
// Состояние для редактирования body
|
||||
const [showBodyEditor, setShowBodyEditor] = createSignal(false)
|
||||
const [bodyContent, setBodyContent] = createSignal('')
|
||||
|
||||
const [saving, setSaving] = createSignal(false)
|
||||
|
||||
// Инициализация формы при открытии
|
||||
createEffect(() => {
|
||||
if (props.isOpen && props.topic) {
|
||||
console.log('[TopicEditModal] Initializing with topic:', props.topic)
|
||||
const topicCommunity = props.topic.community || selectedCommunity() || 0
|
||||
setFormData({
|
||||
id: props.topic.id,
|
||||
title: props.topic.title || '',
|
||||
slug: props.topic.slug || '',
|
||||
body: props.topic.body || '',
|
||||
community: selectedCommunity() || 0,
|
||||
community: topicCommunity,
|
||||
parent_ids: props.topic.parent_ids || []
|
||||
})
|
||||
setBodyContent(props.topic.body || '')
|
||||
updateAvailableParents(selectedCommunity() || 0)
|
||||
updateAvailableParents(topicCommunity, props.topic.id)
|
||||
}
|
||||
})
|
||||
|
||||
// Обновление доступных родителей при изменении сообщества в форме
|
||||
createEffect(on(() => formData().community, (communityId) => {
|
||||
if (communityId > 0) {
|
||||
updateAvailableParents(communityId)
|
||||
}
|
||||
}))
|
||||
|
||||
// Обновление доступных родителей при смене сообщества
|
||||
const updateAvailableParents = (communityId: number) => {
|
||||
const updateAvailableParents = (communityId: number, excludeTopicId?: number) => {
|
||||
const allTopics = topics()
|
||||
const currentTopicId = formData().id
|
||||
const currentTopicId = excludeTopicId || formData().id
|
||||
|
||||
// Фильтруем топики того же сообщества, исключая текущий топик
|
||||
const filteredTopics = allTopics.filter(
|
||||
@@ -66,40 +69,32 @@ export default function TopicEditModal(props: TopicEditModalProps) {
|
||||
setAvailableParents(filteredTopics)
|
||||
}
|
||||
|
||||
// Фильтрация родителей по поиску
|
||||
const filteredParents = () => {
|
||||
const search = parentSearch().toLowerCase()
|
||||
if (!search) return availableParents()
|
||||
|
||||
return availableParents().filter(
|
||||
(topic) => topic.title?.toLowerCase().includes(search) || topic.slug?.toLowerCase().includes(search)
|
||||
)
|
||||
}
|
||||
|
||||
// Обработка изменения сообщества
|
||||
const handleCommunityChange = (e: Event) => {
|
||||
const target = e.target as HTMLSelectElement
|
||||
const communityId = Number.parseInt(target.value)
|
||||
|
||||
setFormData((prev) => ({
|
||||
...prev,
|
||||
community: communityId,
|
||||
parent_ids: [] // Сбрасываем родителей при смене сообщества
|
||||
}))
|
||||
|
||||
updateAvailableParents(communityId)
|
||||
}
|
||||
|
||||
// Обработка изменения родителей
|
||||
const handleParentToggle = (parentId: number) => {
|
||||
setFormData((prev) => ({
|
||||
...prev,
|
||||
parent_ids: prev.parent_ids.includes(parentId)
|
||||
? prev.parent_ids.filter((id) => id !== parentId)
|
||||
: [...prev.parent_ids, parentId]
|
||||
/**
|
||||
* Преобразование Topic в TopicPill для компонента TopicPillsCloud
|
||||
*/
|
||||
const convertTopicsToTopicPills = (topics: Topic[]): TopicPill[] => {
|
||||
return topics.map(topic => ({
|
||||
id: topic.id.toString(),
|
||||
title: topic.title || '',
|
||||
slug: topic.slug || '',
|
||||
community: getCommunityName(topic.community),
|
||||
parent_ids: (topic.parent_ids || []).map(id => id.toString()),
|
||||
}))
|
||||
}
|
||||
|
||||
/**
|
||||
* Обработка изменения выбора родительских топиков из таблеточек
|
||||
*/
|
||||
const handleParentSelectionChange = (selectedIds: string[]) => {
|
||||
const parentIds = selectedIds.map(id => Number.parseInt(id))
|
||||
setFormData((prev) => ({
|
||||
...prev,
|
||||
parent_ids: parentIds
|
||||
}))
|
||||
}
|
||||
|
||||
// Сообщество топика изменить нельзя, поэтому обработчик не нужен
|
||||
|
||||
// Обработка изменения полей формы
|
||||
const handleFieldChange = (field: string, value: string) => {
|
||||
setFormData((prev) => ({
|
||||
@@ -108,48 +103,39 @@ export default function TopicEditModal(props: TopicEditModalProps) {
|
||||
}))
|
||||
}
|
||||
|
||||
// Открытие редактора body
|
||||
const handleOpenBodyEditor = () => {
|
||||
setBodyContent(formData().body)
|
||||
setShowBodyEditor(true)
|
||||
}
|
||||
|
||||
// Сохранение body из редактора
|
||||
const handleBodySave = (content: string) => {
|
||||
setFormData((prev) => ({
|
||||
...prev,
|
||||
body: content
|
||||
}))
|
||||
setBodyContent(content)
|
||||
setShowBodyEditor(false)
|
||||
}
|
||||
|
||||
// Получение пути до корня для топика
|
||||
const getTopicPath = (topicId: number): string => {
|
||||
const topic = topics().find((t) => t.id === topicId)
|
||||
if (!topic) return 'Неизвестный топик'
|
||||
|
||||
const community = getCommunityName(topic.community)
|
||||
return `${community} → ${topic.title}`
|
||||
}
|
||||
|
||||
// Сохранение изменений
|
||||
const handleSave = async () => {
|
||||
try {
|
||||
setSaving(true)
|
||||
|
||||
const updatedTopic = {
|
||||
...props.topic,
|
||||
...formData()
|
||||
const topicData = formData()
|
||||
|
||||
// Вызываем админскую мутацию для сохранения
|
||||
const result = await query<{
|
||||
adminUpdateTopic: {
|
||||
success: boolean
|
||||
error?: string
|
||||
topic?: Topic
|
||||
}
|
||||
}>(`${location.origin}/graphql`, ADMIN_UPDATE_TOPIC_MUTATION, {
|
||||
topic: {
|
||||
id: topicData.id,
|
||||
title: topicData.title,
|
||||
slug: topicData.slug,
|
||||
body: topicData.body,
|
||||
community: topicData.community,
|
||||
parent_ids: topicData.parent_ids
|
||||
}
|
||||
})
|
||||
|
||||
if (result.adminUpdateTopic.success && result.adminUpdateTopic.topic) {
|
||||
console.log('[TopicEditModal] Topic saved successfully:', result.adminUpdateTopic.topic)
|
||||
props.onSave(result.adminUpdateTopic.topic)
|
||||
props.onClose()
|
||||
} else {
|
||||
const errorMessage = result.adminUpdateTopic.error || 'Неизвестная ошибка'
|
||||
throw new Error(errorMessage)
|
||||
}
|
||||
|
||||
console.log('[TopicEditModal] Saving topic:', updatedTopic)
|
||||
|
||||
// TODO: Здесь должен быть вызов API для сохранения
|
||||
// await updateTopic(updatedTopic)
|
||||
|
||||
props.onSave(updatedTopic)
|
||||
props.onClose()
|
||||
} catch (error) {
|
||||
console.error('[TopicEditModal] Error saving topic:', error)
|
||||
props.onError?.(error instanceof Error ? error.message : 'Ошибка сохранения топика')
|
||||
@@ -161,16 +147,34 @@ export default function TopicEditModal(props: TopicEditModalProps) {
|
||||
return (
|
||||
<>
|
||||
<Modal
|
||||
isOpen={props.isOpen && !showBodyEditor()}
|
||||
isOpen={props.isOpen}
|
||||
onClose={props.onClose}
|
||||
title="Редактирование топика"
|
||||
size="large"
|
||||
footer={
|
||||
<>
|
||||
<button
|
||||
type="button"
|
||||
class={`${styles.button} ${styles.secondary}`}
|
||||
onClick={props.onClose}
|
||||
disabled={saving()}
|
||||
>
|
||||
Отмена
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class={`${styles.button} ${styles.primary}`}
|
||||
onClick={handleSave}
|
||||
disabled={saving() || !formData().title || !formData().slug || formData().community === 0}
|
||||
>
|
||||
{saving() ? 'Сохранение...' : 'Сохранить'}
|
||||
</button>
|
||||
</>
|
||||
}
|
||||
>
|
||||
<div class={styles.form}>
|
||||
{/* Основная информация */}
|
||||
<div class={styles.section}>
|
||||
<h3>Основная информация</h3>
|
||||
|
||||
<div class={styles.field}>
|
||||
<label class={styles.label}>
|
||||
Название:
|
||||
@@ -200,147 +204,50 @@ export default function TopicEditModal(props: TopicEditModalProps) {
|
||||
<div class={styles.field}>
|
||||
<label class={styles.label}>
|
||||
Сообщество:
|
||||
<select class={styles.select} value={formData().community} onChange={handleCommunityChange}>
|
||||
<option value={0}>Выберите сообщество</option>
|
||||
<For each={communities()}>
|
||||
{(community) => <option value={community.id}>{community.name}</option>}
|
||||
</For>
|
||||
</select>
|
||||
<div class={`${styles.input} ${styles.disabled} ${styles.communityDisplay}`}>
|
||||
{getCommunityName(formData().community) || 'Сообщество не выбрано'}
|
||||
</div>
|
||||
</label>
|
||||
<div class={`${styles.hint} ${styles.warningHint}`}>
|
||||
📍 Сообщество топика нельзя изменить после создания
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Содержимое */}
|
||||
<div class={styles.section}>
|
||||
<h3>Содержимое</h3>
|
||||
|
||||
<div class={styles.field}>
|
||||
<label class={styles.label}>Body:</label>
|
||||
<div class={styles.bodyPreview} onClick={handleOpenBodyEditor}>
|
||||
<Show when={formData().body}>
|
||||
<div class={styles.bodyContent}>
|
||||
{formData().body.length > 200
|
||||
? `${formData().body.substring(0, 200)}...`
|
||||
: formData().body}
|
||||
</div>
|
||||
</Show>
|
||||
<Show when={!formData().body}>
|
||||
<div class={styles.bodyPlaceholder}>Нет содержимого. Нажмите для редактирования.</div>
|
||||
</Show>
|
||||
<div class={styles.bodyHint}>✏️ Кликните для редактирования в полноэкранном редакторе</div>
|
||||
</div>
|
||||
<label class={styles.label}>
|
||||
Описание:
|
||||
<HTMLEditor
|
||||
value={formData().body}
|
||||
onInput={(value) => handleFieldChange('body', value)}
|
||||
/>
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Родительские топики */}
|
||||
<Show when={formData().community > 0}>
|
||||
<div class={styles.section}>
|
||||
<h3>Родительские топики</h3>
|
||||
|
||||
{/* Компонент с таблеточками для выбора родителей */}
|
||||
<div class={styles.field}>
|
||||
<label class={styles.label}>
|
||||
Поиск родителей:
|
||||
<input
|
||||
type="text"
|
||||
class={styles.input}
|
||||
value={parentSearch()}
|
||||
onInput={(e) => setParentSearch(e.currentTarget.value)}
|
||||
placeholder="Введите название для поиска..."
|
||||
<TopicPillsCloud
|
||||
topics={convertTopicsToTopicPills(availableParents())}
|
||||
selectedTopics={formData().parent_ids.map(id => id.toString())}
|
||||
onSelectionChange={handleParentSelectionChange}
|
||||
excludeTopics={[formData().id.toString()]}
|
||||
showSearch={true}
|
||||
searchPlaceholder="Задайте родительские темы..."
|
||||
hideSelectedInHeader={true}
|
||||
/>
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<Show when={formData().parent_ids.length > 0}>
|
||||
<div class={styles.selectedParents}>
|
||||
<strong>Выбранные родители:</strong>
|
||||
<ul class={styles.parentsList}>
|
||||
<For each={formData().parent_ids}>
|
||||
{(parentId) => (
|
||||
<li class={styles.parentItem}>
|
||||
<span>{getTopicPath(parentId)}</span>
|
||||
<button
|
||||
type="button"
|
||||
class={styles.removeButton}
|
||||
onClick={() => handleParentToggle(parentId)}
|
||||
>
|
||||
✕
|
||||
</button>
|
||||
</li>
|
||||
)}
|
||||
</For>
|
||||
</ul>
|
||||
</div>
|
||||
</Show>
|
||||
|
||||
<div class={styles.availableParents}>
|
||||
<strong>Доступные родители:</strong>
|
||||
<div class={styles.parentsGrid}>
|
||||
<For each={filteredParents()}>
|
||||
{(parent) => (
|
||||
<label class={styles.parentCheckbox}>
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={formData().parent_ids.includes(parent.id)}
|
||||
onChange={() => handleParentToggle(parent.id)}
|
||||
/>
|
||||
<span class={styles.parentLabel}>
|
||||
<strong>{parent.title}</strong>
|
||||
<br />
|
||||
<small>{parent.slug}</small>
|
||||
</span>
|
||||
</label>
|
||||
)}
|
||||
</For>
|
||||
</div>
|
||||
|
||||
<Show when={filteredParents().length === 0}>
|
||||
<div class={styles.noParents}>
|
||||
<Show when={parentSearch()}>Не найдено топиков по запросу "{parentSearch()}"</Show>
|
||||
<Show when={!parentSearch()}>Нет доступных родительских топиков в этом сообществе</Show>
|
||||
</div>
|
||||
</Show>
|
||||
</div>
|
||||
</div>
|
||||
</Show>
|
||||
|
||||
{/* Кнопки */}
|
||||
<div class={modalStyles.modalActions}>
|
||||
<button
|
||||
type="button"
|
||||
class={`${styles.button} ${styles.buttonSecondary}`}
|
||||
onClick={props.onClose}
|
||||
disabled={saving()}
|
||||
>
|
||||
Отмена
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class={`${styles.button} ${styles.buttonPrimary}`}
|
||||
onClick={handleSave}
|
||||
disabled={saving() || !formData().title || !formData().slug || formData().community === 0}
|
||||
>
|
||||
{saving() ? 'Сохранение...' : 'Сохранить'}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</Modal>
|
||||
|
||||
{/* Редактор body */}
|
||||
<Modal
|
||||
isOpen={showBodyEditor()}
|
||||
onClose={() => setShowBodyEditor(false)}
|
||||
title="Редактирование содержимого топика"
|
||||
size="large"
|
||||
>
|
||||
<EditableCodePreview
|
||||
content={bodyContent()}
|
||||
maxHeight="85vh"
|
||||
onContentChange={setBodyContent}
|
||||
onSave={handleBodySave}
|
||||
onCancel={() => setShowBodyEditor(false)}
|
||||
placeholder="Введите содержимое топика..."
|
||||
/>
|
||||
</Modal>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
Reference in New Issue
Block a user