Skip to content

Self-hosted personal gallery application with online photo management and albums, supporting Live/Motion Photos, EXIF parsing, geolocation recognition, and an explore map.

5.7 KB
Raw Blame
import type { InjectionKey } from 'vue'
import type {
  FieldDescriptor,
  SettingsBatchResponse,
  SettingsFieldsResponse,
} from '@chronoframe/gallery/shared/types/settings'
import {
  MAX_SOCIAL_LINKS,
  isSocialLinkErrorCode,
  SocialLinkError,
} from '@chronoframe/contracts/social-links'

export const settingsFieldCommitKey: InjectionKey<
  (fieldKey: string, value: any) => void
> = Symbol('settings-field-commit')

export function applySavedSettingsFields(
  fields: FieldDescriptor[],
  state: Record<string, any>,
  submitted: Record<string, any>,
  stateAtSubmission: Record<string, string | undefined>,
) {
  for (const [key, value] of Object.entries(submitted)) {
    const field = fields.find((item) => item.key === key)
    if (!field) continue

    field.value = value
    if (JSON.stringify(state[key]) === stateAtSubmission[key]) {
      state[key] = value
    }
  }
}

/**
 * Settings Form Composable
 * 统一处理获取字段描述、管理表单状态、提交更新
 * 避免在各个页面中重复实现相同逻辑
 *
 * @param namespace 设置命名空间(如 'app', 'map', 'location', 'storage')
 * @returns 字段列表、表单状态、加载状态、错误状态和提交函数
 *
 * @example
 * const { fields, state, submit, loading } = useSettingsForm('app')
 */
export function useSettingsForm(namespace: string) {
  const consoleApi = useConsoleApi()
  const { t } = useI18n()
  const toast = useToast()

  const fields = ref<FieldDescriptor[]>([])
  const state = reactive<Record<string, any>>({})
  // Start in loading state to avoid first-paint empty container before skeleton.
  const loading = ref(true)
  const error = ref<string | null>(null)

  /**
   * 从 API 获取字段描述和当前值
   */
  const fetchFields = async () => {
    loading.value = true
    error.value = null

    try {
      const response = await consoleApi<SettingsFieldsResponse>(
        '/api/system/settings/fields',
        {
          query: { namespace },
        },
      )

      fields.value = response.fields

      // 使用 API 返回的值初始化状态
      response.fields.forEach((field) => {
        state[field.key] = field.value ?? field.defaultValue ?? null
      })
    } catch (err) {
      const message = (err as Error).message
      error.value = message
      toast.add({
        title: t('settings.form.loadFailed'),
        description: message,
        color: 'error',
      })
    } finally {
      loading.value = false
    }
  }

  /**
   * 提交表单更新
   * 支持单条或多条更新
   *
   * @param data 要更新的字段数据
   * @example
   * await submit({ title: 'New Title', slogan: 'New Slogan' })
   */
  const submit = async (data: Record<string, any>) => {
    loading.value = true
    error.value = null
    const stateAtSubmission = Object.fromEntries(
      Object.keys(data).map((key) => [key, JSON.stringify(state[key])]),
    )

    try {
      // 准备批量更新请求
      const updates = Object.entries(data).map(([key, value]) => ({
        namespace,
        key,
        value,
      }))

      const result = await consoleApi<SettingsBatchResponse>(
        '/api/system/settings/batch',
        {
          method: 'PUT',
          body: { updates },
        },
      )
      if (!result.success) {
        const socialFailure = result.errors.find(
          (item) => item.namespace === 'app' && item.key === 'socialLinks',
        )
        if (socialFailure) {
          if (isSocialLinkErrorCode(socialFailure.code)) {
            throw new SocialLinkError(
              socialFailure.code,
              t(`settings.app.socialLinks.${socialFailure.code}`, {
                max: MAX_SOCIAL_LINKS,
              }),
            )
          }
          throw new Error(t('settings.form.saveFailed'))
        }
        throw new Error(
          result.errors?.map((item) => item.error).join('; ') ||
            t('settings.form.saveFailed'),
        )
      }

      // 刷新全局设置状态,确保所有使用 getSetting() 的地方都能获取到最新值
      await refreshSettings()

      applySavedSettingsFields(fields.value, state, data, stateAtSubmission)

      toast.add({
        title: t('settings.form.saveSuccess'),
        color: 'success',
      })
    } catch (err) {
      const message = (err as Error).message
      error.value = message
      toast.add({
        title: t('settings.form.saveFailed'),
        description: message,
        color: 'error',
      })
      throw err
    } finally {
      loading.value = false
    }
  }

  /**
   * 重置表单状态为当前字段值
   */
  const reset = () => {
    fields.value.forEach((field) => {
      state[field.key] = field.value ?? field.defaultValue ?? null
    })
  }

  /**
   * 更新特定字段的状态
   * 用于处理字段依赖关系或条件显示
   */
  const updateField = (fieldKey: string, value: any) => {
    state[fieldKey] = value
  }

  /**
   * 获取特定字段
   */
  const getField = (fieldKey: string): FieldDescriptor | undefined => {
    return fields.value.find((f) => f.key === fieldKey)
  }

  /**
   * 获取字段的当前值
   */
  const getFieldValue = (fieldKey: string): any => {
    return state[fieldKey]
  }

  const commitField = (fieldKey: string, value: any) => {
    state[fieldKey] = value
    const field = fields.value.find((item) => item.key === fieldKey)
    if (field) {
      field.value = value
    }
  }

  // 组件挂载时自动获取字段
  onMounted(() => {
    fetchFields()
  })

  return {
    // 数据
    fields: readonly(fields),
    state,

    // 状态
    loading: readonly(loading),
    error: readonly(error),

    // 方法
    submit,
    reset,
    fetchFields,
    updateField,
    getField,
    getFieldValue,
    commitField,
  }
}