import "./configuration-detail-styles.scss"; import { NavLink, useNavigate, useParams } from "react-router-dom"; import { Controller, useForm } from "react-hook-form"; import Button from "@app/components/button/Button"; import CardSection from "@app/components/card-section/CardSection"; import SettingRow from "@app/components/setting-row/SettingRow"; import InputField from "@app/components/input-field/InputField"; import Select from "@app/components/select/Select"; import { ButtonProps, InteractiveCardMetaItem, SelectOption, ToggleOption, } from "@app/models/components"; import { SfSyncActionButton, SfSyncConfigListExpanded, SfSyncSettings, SfSyncSocialIcon, SfSyncSocialIconPlatform, Language, SfSyncConfigListKey, } from "@app/models/global"; import { saveConfig, removeAccount } from "@app/services/api"; import { DASHBOARD_APPEARANCE_ENABLED } from "@app/constants"; import { useSettings } from "@settings/contexts/SettingsContext"; import React, { useEffect, useRef, useState } from "react"; import CardContent from "@app/components/card-content/CardContent"; import CardFooter from "@app/components/card-footer/CardFooter"; import PageHeader, { PageHeaderProps } from "@app/components/page-header/PageHeader"; import CustomizableHeader from "@app/components/customizable-header/CustomizableHeader"; import Modal from "@app/components/modal/Modal"; import ColorPicker from "@app/components/color-picker/ColorPicker"; import Tooltip from "@app/components/Tooltip/Tooltip"; import IconButton from "@app/components/icon-button/IconButton"; import PageFooter from "@app/components/page-footer/PageFooter"; import AlertBar from "@app/components/alert-bar/AlertBar"; import EmptyState from "@app/components/EmptyState/EmptyState"; import { SfSyncLogo, DarkSfSyncLogo, AddIcon, CheckIcon, DarkMode, DesktopMode, EditIcon, ErrorIcon, LeftArrow, LightMode, LockIcon, OpenNewPage, PanoramaIcon, RightArrow, TrashCanIcon, } from "@app/assets/images/icons"; import PlatformIcon, { PLATFORM_ICON_OPTIONS, } from "@app/components/platform-icon/PlatformIcon"; import Avatar from "@app/components/avatar/Avatar"; import UpgradePopover from "@app/components/UpgradePopover/UpgradePopover"; import FeatureLockedContent from "@app/components/UpgradePopover/FeatureLockedContent"; import { ActivePopover, useUpgradePopover, } from "@settings/contexts/UpgradePopoverContext"; import Toggle from "@app/components/toggle/Toggle"; import InteractiveCard from "@app/components/interactive-card/InteractiveCard"; import { mapSettingToLabel } from "@app/services/utilities"; // Derived from PLATFORM_ICON_OPTIONS rather than hand-maintained separately - // the two lists silently drifting apart is exactly how this repo already // ended up with one duplicate copy of the platform->label mapping. const PLATFORM_LABELS: Record = PLATFORM_ICON_OPTIONS.reduce( (labels, option) => ({ ...labels, [option.platform]: option.label }), {} as Record ); const ConfigurationDetail: React.FC = () => { const { id: idParam } = useParams(); const navigate = useNavigate(); const { is_premium: isPremium } = sfsyncData; const initialConfigValues: SfSyncConfigListExpanded = { ig_user_id: "", media_limit: isPremium ? 30 : 3, page_slug: "", language: sfsyncData?.defaultLanguage ?? "", posts: [], scope: "post", page_header: { title: "", image_url: "", image_id: "", action_button: { text_color: "", bg_color: "", text: "", action_url: "", }, socialIcons: [], }, show_footer: "on", }; const [initialConfig, setInitialConfig] = useState( structuredClone(initialConfigValues) ); const [config, setConfig] = useState( structuredClone(initialConfigValues) ); const [showSelectOptions, setShowSelectOptions] = useState(false); const [isSaving, setIsSaving] = useState(false); const [configHasChanges, setConfigHasChanges] = useState(false); const [btnHasChanges, setBtnHasChanges] = useState(false); const [isBtnModalOpen, setIsBtnModalOpen] = useState(false); const [actionButton, setActionButton] = useState({ ...initialConfigValues?.page_header?.action_button, }); const [isSocialIconsModalOpen, setIsSocialIconsModalOpen] = useState(false); const [socialIconsHasChanges, setSocialIconsHasChanges] = useState(false); const [socialIcon, setSocialIcon] = useState({ title: "", action_url: "", image_url: "", image_id: "", }); const [isRemoveSocialIconsModalOpen, setIsRemoveSocialIconModalOpen] = useState(false); const [mode, setMode] = useState(""); const [index, setIndex] = useState(-1); const [isSocialIconsEmpty, setIsSocialIconsEmpty] = useState(true); const [mediaError, setMediaError] = useState(null); const [saveNotice, setSaveNotice] = useState(null); // Remove Account — scoped to this one connected account only; the // other accounts on this install are unaffected. const [isOpenRemoveAccountModal, setIsOpenRemoveAccountModal] = useState(false); const [isRemovingAccount, setIsRemovingAccount] = useState(false); const [removeAccountError, setRemoveAccountError] = useState(null); const { activePopover, setActivePopover } = useUpgradePopover(); const limitRef = useRef(null); const scopeRef = useRef(null); const showFooterRef = useRef(null); const localization = sfsyncI18n.data; useEffect(() => { const handleClickOutside = (event: MouseEvent) => { const refs = [limitRef, scopeRef, showFooterRef]; const isClickOutside = refs.every( (ref) => ref.current && !ref.current.contains(event.target as Node) ); if (isClickOutside) { setActivePopover(ActivePopover.None); } }; document.addEventListener("mousedown", handleClickOutside); return () => { document.removeEventListener("mousedown", handleClickOutside); }; }, [setActivePopover]); const activeLanguage = sfsyncData?.languages?.length ? config?.language || (sfsyncData?.defaultLanguage ?? "") : "default"; const handleOpenRemoveSocialIconsModal = (index: number) => { setIsRemoveSocialIconModalOpen(true); setIndex(index); }; const handleCloseRemoveSocialIconsModal = () => { setIsRemoveSocialIconModalOpen(false); }; const handleOnSocialIconClick = (index: number) => { setIsSocialIconsModalOpen(true); setIndex(index); const newSocialIcons = index === -1 ? { title: "", action_url: "", image_url: "" } : config?.page_header?.socialIcons?.[index] ?? socialIcon; setSocialIcon(newSocialIcons); }; const handleCloseSocialIconsModal = () => { setIsSocialIconsModalOpen(false); }; const checkSocialIconsEmpty = () => { // Check if any field in the socialIcon object is empty. An icon is // considered to have an image source either via an uploaded image_url // (the "Custom" path) or via a selected preset platform. const hasIconSource = socialIcon?.image_url !== "" || (!!socialIcon?.platform && socialIcon.platform !== "custom"); const socialIconsEmpty = socialIcon?.title === "" || socialIcon?.action_url === "" || !hasIconSource; setIsSocialIconsEmpty(socialIconsEmpty); }; // useEffect to monitor changes in the socialIcons object useEffect(() => { checkSocialIconsEmpty(); }, [socialIcon]); const { control, handleSubmit, formState: { errors }, reset, setError, } = useForm({ defaultValues: initialConfigValues, }); const { initialSettings, setInitialSettings, scopeOptions, emptyConfigList, homeURLs, handleChangeAdminTheme, isSavingAdminTheme, } = useSettings(); // "/configuration" (no :id) opens the plugin's single configured account. const id = idParam ?? initialSettings.selected_config ?? Object.keys(initialSettings.config_list ?? {})[0] ?? ""; const handleSelectAll = () => { setActivePopover(ActivePopover.Scope); }; const footerModeOption: SelectOption[] = [ { text: "Device default", value: "automatic", icon: DesktopMode, iconPosition: "start", }, { text: "Light", value: "light", icon: LightMode, iconPosition: "start", }, { text: "Dark", value: "dark", icon: DarkMode, iconPosition: "start", }, ]; const pageFooterOptions: ToggleOption[] = [ { label: "On", value: "on", }, { label: "Off", value: "off", }, ]; const slugHasChanged = () => { const initialSlug = initialSettings.config_list?.[id || ""]?.page_slug; const currentSlug = config.page_slug; return initialSlug !== currentSlug; }; const prepareSelectOptions = () => { return sfsyncData.languages?.map((lang: Language) => { return { value: lang.code, text: lang.native_name, }; }); }; const handleInputSocialIconsChange = (name: string, value: string) => { setSocialIcon((prevSocialIcon) => ({ ...prevSocialIcon, [name]: value, })); }; const handleSelectPlatform = (platform: SfSyncSocialIconPlatform) => { if (platform === "custom") { setSocialIcon((prevSocialIcon) => ({ ...prevSocialIcon, platform: "custom", })); return; } setSocialIcon((prevSocialIcon) => { // Only auto-fill the title when it's still whatever the previously // selected platform auto-filled (or empty) - once the admin has typed // their own title, switching (or re-clicking the same) preset must not // silently overwrite it. const previousAutoFilledTitle = prevSocialIcon.platform ? PLATFORM_LABELS[prevSocialIcon.platform] : undefined; const titleIsUntouched = !prevSocialIcon.title || prevSocialIcon.title === previousAutoFilledTitle; return { ...prevSocialIcon, platform, title: titleIsUntouched ? PLATFORM_LABELS[platform] : prevSocialIcon.title, }; }); }; const handleUpdateSocialImage = () => { setMediaError(null); if (!wp?.media) { setMediaError(localization.error_opening_media_modal_message); return; } const custom_uploader = wp.media({ title: localization.edit_image, button: { text: localization.use_this_image, }, multiple: false, library: { type: "image" }, }); custom_uploader.on("select", function () { const attachment = custom_uploader.state().get("selection").first(); if (attachment) { const url = attachment.attributes.url; const id = attachment.attributes.id; handleInputSocialIconsChange("image_url", url); handleInputSocialIconsChange("image_id", id); } }); custom_uploader.on("open", function () { if (socialIcon.image_id) { const initialAttachmentId = socialIcon.image_id; const selection = custom_uploader.state().get("selection"); const attachment = wp.media.attachment(initialAttachmentId); attachment.fetch(); selection.add(attachment ? [attachment] : []); } }); custom_uploader.open(); }; const handleApplySocialIcons = () => { const updatedSocialIcons = [...(config?.page_header?.socialIcons ?? [])]; if (index !== -1) { updatedSocialIcons[index] = socialIcon; } else { updatedSocialIcons.push(socialIcon); } const updatedPageHeader = { ...config?.page_header, socialIcons: updatedSocialIcons, }; updateConfig("page_header", updatedPageHeader); setIsSocialIconsModalOpen(false); }; // Reorders the icon currently open in the Add/Edit modal by swapping it // with its immediate neighbor - takes effect immediately (like Remove), // independent of the modal's own pending title/url/platform edits, since // position isn't a field of the icon being edited (WP-4955). const handleMoveSocialIcon = (direction: "earlier" | "later") => { const icons = [...(config?.page_header?.socialIcons ?? [])]; const targetIndex = direction === "earlier" ? index - 1 : index + 1; if (index === -1 || targetIndex < 0 || targetIndex >= icons.length) { return; } [icons[index], icons[targetIndex]] = [icons[targetIndex], icons[index]]; updateConfig("page_header", { ...config.page_header, socialIcons: icons, }); setIndex(targetIndex); }; const handleRemoveSocialIcon = (indexToRemove: number) => { const updatedSocialIcons = config?.page_header?.socialIcons?.filter( (_, index) => index !== indexToRemove ); updateConfig("page_header", { ...config.page_header, socialIcons: updatedSocialIcons, }); setIsRemoveSocialIconModalOpen(false); }; const handleRemoveSocialIconImage = () => { setSocialIcon((prevSocialIcons) => ({ ...prevSocialIcons, image_url: "", image_id: "", })); }; const handleClearLanguage = () => { // Reset the language when cleared updateConfig("language", ""); }; const updateConfig = ( name: string, value: string | number | null | Record ) => { setConfig({ ...config, [name]: value }); }; const handlePageHeaderChange = (name: string, value: string) => { setConfig((prevConfig) => ({ ...prevConfig, page_header: { ...prevConfig.page_header, [name]: value, }, })); }; const handleActionButtonChange = (name: string, value: string) => { const updatedActionButton = { ...actionButton, [name]: value, }; setActionButton({ ...updatedActionButton }); }; const handleInputChange = (name: string, value: string) => { if (!isPremium && name == "show_footer") { setActivePopover(ActivePopover.ShowFooter); return; } updateConfig(name, value); }; const handleScopeChange = (name: string, value: string) => { const selectedValues = value.split(","); const currentSelectedValue = selectedValues[selectedValues.length - 1]; // Last selected value if (!isPremium) { if (value === "") { updateConfig(name, value); setActivePopover(ActivePopover.None); return; } if (currentSelectedValue !== value) { const newValue = selectedValues[selectedValues.length - 1]; updateConfig(name, newValue); setActivePopover(ActivePopover.Scope); } else { updateConfig(name, value); } return; } updateConfig(name, value); }; const updateInitialSettings = (newSettings: SfSyncSettings) => { setInitialSettings(newSettings); }; const discardChanges = () => { setConfig(initialConfig); setActionButton(initialConfig?.page_header?.action_button ?? {}); }; const handleRemoveAccount = async () => { setIsRemovingAccount(true); setRemoveAccountError(null); const resp = await removeAccount(id); setIsRemovingAccount(false); if (resp?.error) { setRemoveAccountError( resp?.message || localization.remove_account_error_message ); return; } setInitialSettings({ ...initialSettings, config_list: resp.config_list ?? {}, selected_config: resp.selected_config ?? "", api_key_verified: resp.api_key_verified ?? false, }); setIsOpenRemoveAccountModal(false); navigate("/grid-manager", { replace: true }); }; const handleUpdateImage = () => { setMediaError(null); if (!wp?.media) { setMediaError(localization.error_opening_media_modal_message); return; } const custom_uploader = wp.media({ title: `${ config?.page_header?.image_url ? localization.update_image : localization.add_image }`, button: { text: localization.use_this_image, }, multiple: false, }); custom_uploader.on("select", function () { const attachment = custom_uploader.state().get("selection").first(); if (attachment) { const url = attachment.attributes.url; const id = attachment.attributes.id; handlePageHeaderChange("image_id", id); handlePageHeaderChange("image_url", url); } }); custom_uploader.on("open", function () { if (config.page_header?.image_url) { const initialAttachmentId = config.page_header?.image_id; const selection = custom_uploader.state().get("selection"); const attachment = wp.media.attachment(initialAttachmentId); attachment.fetch(); selection.add(attachment ? [attachment] : []); } }); custom_uploader.open(); }; const handleRemoveImage = () => { handlePageHeaderChange("image_url", ""); handlePageHeaderChange("image_id", ""); }; const handleCloseBtnModal = () => { if (btnHasChanges) { setActionButton(config?.page_header?.action_button ?? {}); } setIsBtnModalOpen(false); }; const handleOpenBtnModal = () => { setIsBtnModalOpen(true); }; const handleApplyCustomization = () => { const updatedConfig = { ...config.page_header, action_button: { ...actionButton, }, }; updateConfig("page_header", updatedConfig); setIsBtnModalOpen(false); }; const handleSaveConfig = async ( currentConfig?: SfSyncConfigListExpanded ): Promise => { const configToUse = currentConfig ?? config; const configPayload = { biography: configToUse.biography, name: configToUse.name, username: configToUse.username ?? "", profile_picture_url: configToUse.profile_picture_url, media_limit: configToUse.media_limit, page_slug: configToUse.page_slug, language: configToUse.language, page_header: configToUse.page_header, scope: configToUse?.scope, google_analytics_id: configToUse.google_analytics_id, footer_mode: configToUse.footer_mode, show_footer: configToUse.show_footer, }; const resp = await saveConfig(configToUse.ig_user_id, configPayload); if (resp?.error) { if (resp.status === 409) { setError("page_slug", { type: "server", message: localization.page_slug_taken_error_message, }); } return false; } const updatedConfigEntry = { ...initialSettings.config_list?.[configToUse.ig_user_id], ...configPayload, ...(resp.page_url ? { page_url: resp.page_url } : {}), }; const updatedSettings = { ...initialSettings, config_list: { ...initialSettings.config_list, [configToUse.ig_user_id]: updatedConfigEntry, }, selected_config: initialSettings.selected_config || configToUse.ig_user_id, }; updateInitialSettings(structuredClone(updatedSettings)); setInitialConfig({ ...structuredClone(configToUse) }); return true; }; const handleFormSubmit = async () => { // event.preventDefault(); setIsSaving(true); setSaveNotice(null); /** * Save settings */ const saveConfigSuccess = await handleSaveConfig(); if (!saveConfigSuccess) { setIsSaving(false); return; } setIsSaving(false); setSaveNotice(localization.configuration_updated); }; useEffect(() => { const configOfID = initialSettings?.config_list?.[id ?? ""]; if (!configOfID) return; const mergedConfig = { ...initialConfigValues, ...configOfID, ig_user_id: id ?? "", }; setInitialConfig(structuredClone(mergedConfig)); setConfig(structuredClone(mergedConfig)); reset(structuredClone(mergedConfig)); setActionButton({ ...mergedConfig?.page_header?.action_button }); }, []); useEffect(() => { // Check if the current data is different from the initial data const configHasChanges = JSON.stringify(initialConfig) !== JSON.stringify(config); setConfigHasChanges(configHasChanges); }, [initialConfig, config]); useEffect(() => { // Check if the current data is different from the initial data let btnHasChanges = JSON.stringify(config?.page_header?.action_button) !== JSON.stringify(actionButton); setBtnHasChanges(btnHasChanges); }, [config, actionButton]); useEffect(() => { let socialIconsHasChanges = JSON.stringify(config?.page_header?.socialIcons?.[index]) !== JSON.stringify(socialIcon); setSocialIconsHasChanges(socialIconsHasChanges); }, [config, socialIcon]); const handleFieldChange = (value: string, field: any) => { field.onChange(value); handleInputChange(field.name, value); }; useEffect(() => { if (config.footer_mode === "automatic" || !config.footer_mode) { const mediaQuery = window.matchMedia("(prefers-color-scheme: dark)"); const handleSystemPreference = () => { setMode(mediaQuery.matches ? "dark" : "light"); }; handleSystemPreference(); mediaQuery.addEventListener("change", handleSystemPreference); return () => mediaQuery.removeEventListener("change", handleSystemPreference); } else { setMode(config.footer_mode ?? "light"); } }, [config.footer_mode]); const getFooterActionBtnProps = (): ButtonProps | undefined => { return { text: localization.get_it_now, onClickHandler: () => {}, style: { fontSize: "1rem", padding: "1.5rem 2rem", backgroundColor: "#fff", color: "#474747", border: "1px solid #474747", }, type: "button", }; }; const getModeIcon = () => { if (config.footer_mode == "light") { return LightMode; } else if (config.footer_mode === "dark") { return DarkMode; } else { return DesktopMode; } }; const getAdminThemeIcon = () => { if (initialSettings.admin_theme === "light") { return LightMode; } else if (initialSettings.admin_theme === "dark") { return DarkMode; } else { return DesktopMode; } }; const formatMetaValue = (setting: SfSyncConfigListKey, value: string) => { if (setting === "language") { const languageInfo = sfsyncData.languages.find( (lang: Language) => lang.code === value ); return languageInfo ? languageInfo.native_name : value; } return value; }; const getMetaData = ( id: string ): Array | undefined => { if (emptyConfigList) return undefined; let metaData: Array = [ { label: mapSettingToLabel("ig_user_id"), value: id, }, ]; const supportedMeta = [ "media_limit", "language", "page_slug", ] satisfies Array; supportedMeta.forEach((setting) => { if (!config[setting]) { return; } if (setting === "language" && !sfsyncData.languages.length) { return; } let metaItem: InteractiveCardMetaItem = { label: mapSettingToLabel(setting), value: "", }; if (setting === "page_slug") { metaItem.label = "URL"; metaItem.hideLabel = true; metaItem.value = ( {config.page_url} ); } else { metaItem.value = formatMetaValue( setting, config[setting]?.toString() ?? "" ); } metaData.push(metaItem); }); return metaData; }; const configSectionProps: { [key: string]: any } = { "config-details": { key: "config-details", sectionID: "config-details", sectionTitle: "", sectionSubtitle: "", }, "link-content": { key: "link-content", sectionID: "link-content", sectionTitle: localization.link_content_section_title, sectionSubtitle: localization.link_content_section_subtitle, }, "bio-page-header": { key: "bio-page-header", sectionID: "bio-page-header", sectionTitle: localization.bio_page_header_section_title, sectionSubtitle: localization.bio_page_header_section_subtitle, }, "appearance-branding": { key: "appearance-branding", sectionID: "appearance-branding", sectionTitle: localization.appearance_branding_section_title, sectionSubtitle: localization.appearance_branding_section_subtitle, }, analytics: { key: "analytics", sectionID: "analytics", sectionTitle: localization.analytics_section_title, sectionSubtitle: localization.analytics_section_subtitle, }, }; const configSectionContent: { [key: string]: any[] } = { "config-details": [ , ], "link-content": [
{ return ( { handleFieldChange(value, field); }} concatenatedString={ activeLanguage && (homeURLs?.[activeLanguage] || sfsyncData?.homeURL || "") } errorMessage={ errors.page_slug && (errors.page_slug.message || localization.page_slug_error_message) } /> ); }} /> {initialSettings.config_list?.[id || ""]?.page_url && !slugHasChanged() && (
{" "}
)}
, sfsyncData.languages && sfsyncData.languages?.length > 0 && ( { setShowSelectOptions(false); handleScopeChange(name, value); }} placeholder={localization.scope_placeholder} options={scopeOptions} multiple //defaultValue={localization.post} externalShowOptions={showSelectOptions} handleSelectAll={handleSelectAll} /> ) : (

{localization.live_preview}

{localization.live_preview_description}

{config.show_footer === "off" && (

{localization.branding_off_note}

)}
, ], analytics: [ , ], }; let configName = config?.name || config?.username || id; let headerPropsTitle = configName ? `${localization.settings_for} ${configName}` : localization.settings; const livePageUrl = initialSettings.config_list?.[id || ""]?.page_url; const headerProps: PageHeaderProps = { title: headerPropsTitle, subtitle: ( <> {localization.manage_settings} {configName || id}. ), breadcrumb: [ { label: localization.accounts, href: "#/grid-manager" }, { label: configName || "" }, { label: localization.settings }, ], actionButtons: livePageUrl && !slugHasChanged() ? [ { type: "link", href: livePageUrl, target: "_blank", text: localization.view_live_page, icon: OpenNewPage, variant: "secondary", }, ] : [], }; if (emptyConfigList) { return ( {localization.add_your_api_key_from_your}{" "} {localization.dashboard} {" "} {localization.to_activate_this_plugin} } /> ); } return ( {saveNotice && ( setSaveNotice(null)} /> )} {mediaError && ( setMediaError(null)} /> )}
{Object.keys(configSectionProps).map((key: string) => ( {configSectionContent[key]} ))}
{/* Dashboard theme — plugin-wide (applies to every account's admin UI, and the pre-connection splash screen), so it lives outside the per-account save/discard
above, same as Remove Account below. Saves immediately on change rather than joining the form's dirty/save-changes flow, since it isn't part of that account's config. Temporarily hidden - see DASHBOARD_APPEARANCE_ENABLED in constants.ts. */} {DASHBOARD_APPEARANCE_ENABLED && (