import { defineStore } from 'pinia' import { computed, ref } from 'vue' import { getFieldErrors, getSaveErrorKind, getSchema, getValues, saveValues } from '@/api/SettingsAPI' import { isVisible } from '@/helpers/show-if' import type { SaveErrorKind, SettingsField, SettingsGroup, SettingsSaveResult, SettingsSchema } from '@/types/settings.types' const isSame = (a: unknown, b: unknown): boolean => JSON.stringify(a ?? null) === JSON.stringify(b ?? null) const copy = (value: T): T => (value === undefined ? value : JSON.parse(JSON.stringify(value))) // Field keys from classes/settings/fields/class-marketplace.php. const VENDOR_TERMS = ['wcvendors_vendor_singular', 'wcvendors_vendor_plural'] export const useSettingsStore = defineStore('settings', () => { const schema = ref(null) const values = ref>({}) const draft = ref>({}) const fieldErrors = ref>({}) const isLoading = ref(false) const loadError = ref(null) const isSaving = ref(false) const saveError = ref(null) const activePage = ref('') let schemaReload = 0 let appliedReload = 0 const fieldsById = computed>(() => { const map: Record = {} schema.value?.groups.forEach(group => { group.pages.forEach(page => { page.sections.forEach(section => { section.fields.forEach(field => { map[field.id] = field }) }) }) }) return map }) // Pages with a field, a locked section, an old-screen link or their own screen URL. Groups with such pages. const visibleGroups = computed(() => { return (schema.value?.groups ?? []) .map(group => ({ ...group, pages: group.pages.filter(page => (page.custom_markup && page.url !== '') || (page.old_screen?.url ?? '') !== '' || page.sections.some(section => section.fields.length > 0 || section.locked === true)) })) .filter(group => group.pages.length > 0) }) // A custom markup page is a nav link only. It never opens inside the app. const visiblePageIds = computed(() => visibleGroups.value.flatMap(group => group.pages.filter(page => !page.custom_markup).map(page => page.id))) const currentPage = computed(() => { for (const group of visibleGroups.value) { const page = group.pages.find(item => item.id === activePage.value) if (page !== undefined) { return page } } return null }) const pageFields = (pageId: string): SettingsField[] => { return Object.values(fieldsById.value).filter(field => field.page === pageId) } const isFieldVisible = (field: SettingsField): boolean => isVisible(field, fieldsById.value, draft.value) // A field that show_if hides is never sent, so it does not count as a change. const isFieldDirty = (field: SettingsField): boolean => { return isFieldVisible(field) && !isSame(draft.value[field.id], values.value[field.id]) } const dirtyIds = (pageId: string): string[] => { return pageFields(pageId) .filter(isFieldDirty) .map(field => field.id) } const isDirty = (pageId: string): boolean => dirtyIds(pageId).length > 0 const anyDirty = computed(() => Object.values(fieldsById.value).some(isFieldDirty)) // A hidden or unknown page id falls back to the first visible page. const resolvePage = (pageId: string): string => { return visiblePageIds.value.includes(pageId) ? pageId : (visiblePageIds.value[0] ?? '') } const setActivePage = (pageId: string): void => { activePage.value = resolvePage(pageId) saveError.value = null } const setValue = (fieldId: string, value: unknown): void => { draft.value = { ...draft.value, [fieldId]: value } if (fieldErrors.value[fieldId] !== undefined) { const next = { ...fieldErrors.value } delete next[fieldId] fieldErrors.value = next } } // Apply a value the server sent outside a save. The field stays clean. const applyServerValue = (fieldId: string, value: unknown): void => { values.value = { ...values.value, [fieldId]: copy(value) } draft.value = { ...draft.value, [fieldId]: copy(value) } } // Load the schema and the values of every page, so search can open any page. const load = async (): Promise => { isLoading.value = true loadError.value = null try { const [nextSchema, response] = await Promise.all([ schema.value ?? getSchema(), getValues() ]) schema.value = nextSchema values.value = { ...response.values } draft.value = copy(values.value) } catch (err: any) { loadError.value = err?.response?.data?.message ?? '' } finally { isLoading.value = false } } // A discard during a save would stay as an edit that reverts the saved value. const discard = (pageId: string): void => { if (isSaving.value) { return } const next = { ...draft.value } const nextErrors = { ...fieldErrors.value } pageFields(pageId).forEach(field => { next[field.id] = copy(values.value[field.id]) delete nextErrors[field.id] }) draft.value = next fieldErrors.value = nextErrors saveError.value = null } // Send only the changed fields that show_if does not hide. const save = async (pageId: string): Promise => { const payload: Record = {} pageFields(pageId) .filter(isFieldDirty) .forEach(field => { payload[field.id] = copy(draft.value[field.id]) }) isSaving.value = true saveError.value = null try { const before = values.value const result = await saveValues(pageId, payload) values.value = { ...values.value, ...result.values } // Keep an edit the owner made while the save was in progress. const nextDraft = { ...draft.value } Object.entries(result.values).forEach(([id, value]) => { const sent = id in payload ? payload[id] : before[id] if (isSame(nextDraft[id], sent)) { nextDraft[id] = copy(value) } }) draft.value = nextDraft const nextErrors = { ...fieldErrors.value } Object.keys(result.values).forEach(id => { delete nextErrors[id] }) fieldErrors.value = nextErrors // Labels use the vendor terms, so load the schema again after a term change. // Apply a reload only if it is newer than the last applied one, so an older response cannot overwrite a newer one. // Extensions (legacy) labels come from the stored legacy snapshot, so they change only after a page reload. if (VENDOR_TERMS.some(id => id in payload)) { const reload = ++schemaReload getSchema() .then(nextSchema => { if (reload > appliedReload) { appliedReload = reload schema.value = nextSchema } }) // Keep the old labels if the reload fails. A page reload fixes them. .catch(() => {}) } return result } catch (err) { saveError.value = getSaveErrorKind(err) if (saveError.value === 'invalid') { fieldErrors.value = { ...fieldErrors.value, ...getFieldErrors(err) } } return null } finally { isSaving.value = false } } return { schema, values, draft, fieldErrors, isLoading, loadError, isSaving, saveError, activePage, fieldsById, visibleGroups, currentPage, anyDirty, pageFields, isFieldVisible, isDirty, resolvePage, setActivePage, setValue, applyServerValue, load, discard, save } })