/** * Dailymotion Pro – Admin Video Embed: state toggles * * Enables/disables controls based on checkbox states and the global contextual toggle. */ import { getFormState, qs } from '../../Libs/Utils'; let initialFormStates = new Map(); /** * Initializes the form state tracking. */ export function initFormState(form: HTMLFormElement): void { initialFormStates.set(form, getFormState(form)); updateSubmitButtonState(form); } /** * Resets the stored initial state to the form's current state. * Use after an action that changes the form (e.g. disabling contextual) so * beforeunload no longer treats the form as dirty. */ export function resetFormState(form: HTMLFormElement): void { initialFormStates.set(form, getFormState(form)); updateSubmitButtonState(form); } const TOGGLE_FIELD = 'contextual_embed'; /** * Returns true when the only difference between initial and current is * contextual_embed going from on (truthy) to off (falsy). */ function isOnlyToggleOnToOff(initialJson: string, currentJson: string): boolean { try { const initial = JSON.parse(initialJson) as Record; const current = JSON.parse(currentJson) as Record; if (!(TOGGLE_FIELD in initial) && !(TOGGLE_FIELD in current)) return false; const initialToggle = initial[TOGGLE_FIELD]; const currentToggle = current[TOGGLE_FIELD]; const wasOn = initialToggle !== undefined && initialToggle !== '' && initialToggle !== null; const isOff = currentToggle === undefined || currentToggle === '' || currentToggle === null; if (!wasOn || !isOff) return false; delete initial[TOGGLE_FIELD]; delete current[TOGGLE_FIELD]; return JSON.stringify(initial) === JSON.stringify(current); } catch { return false; } } /** * Checks if a form has changes compared to its initial state. * Exception: not dirty when the only change is contextual_embed toggling from on to off. */ export function isFormDirty(form: HTMLFormElement): boolean { const initialState = initialFormStates.get(form); if (initialState === undefined) return false; const current = getFormState(form); if (initialState === current) return false; if (isOnlyToggleOnToOff(initialState, current)) return false; return true; } /** * Updates the disabled state of the submit button based on form changes. */ export function updateSubmitButtonState(form: HTMLFormElement): void { const saveBtn = form.querySelector('button[type="submit"]') as HTMLButtonElement | null; if (!saveBtn) return; saveBtn.disabled = !isFormDirty(form); }