Your IP : 216.73.216.224


Current Path : /var/www/html/libraries/noboss/src/Form/Field/
Upload File :
Current File : /var/www/html/libraries/noboss/src/Form/Field/NbAutosaveField.php

<?php
/**
 * @package         No Boss Extensions
 * @subpackage      No Boss Library
 * @author          No Boss Technology <contact@nobosstechnology.com>
 * @copyright       Copyright (C) 2026 No Boss Technology. All rights reserved.
 * @license         GNU Lesser General Public License version 3 or later; see <https://www.gnu.org/licenses/lgpl-3.0.en.html>
 */

namespace Noboss\Library\Form\Field;

use Joomla\CMS\Form\FormField;
use Joomla\CMS\Factory;
use Joomla\CMS\Language\Text;
use Joomla\CMS\Uri\Uri;
use Joomla\CMS\Session\Session;
use Noboss\Library\Util\NbJsConstantsUtil;

// phpcs:disable PSR1.Files.SideEffects
\defined('_JEXEC') or die;
// phpcs:enable PSR1.Files.SideEffects

class NbAutosaveField extends FormField
{
    protected function getLabel(): string
    {
        return '';
    }

    protected function getInput(): string
    {
        $app = Factory::getApplication();

        // Somente disponível no painel administrativo e em modo edição (módulo já salvo no banco)
        if (!$app->isClient('administrator')) {
            return '';
        }

        $moduleId = $app->input->getInt('id', 0);

        if (empty($moduleId)) {
            return '';
        }

        NbJsConstantsUtil::addConstantsDefault();

        $wa    = $app->getDocument()->getWebAssetManager();
        $wa->useScript('jquery');
        $token = Session::getFormToken();

        // Carrega os params atuais do banco para usar como base segura no JS.
        // Isso evita que o autosave sobrescreva campos cujos valores não são
        // facilmente serializáveis a partir do DOM (campos com render complexo via JS).
        $existingParams = '{}';
        try {
            $db = Factory::getContainer()->get(\Joomla\Database\DatabaseInterface::class);
            $query = $db->getQuery(true)
                ->select($db->quoteName('params'))
                ->from($db->quoteName('#__modules'))
                ->where($db->quoteName('id') . ' = ' . $db->quote($moduleId));
            $db->setQuery($query);
            $raw = $db->loadResult();

            if (!empty($raw)) {
                // Valida que é JSON. Se não for, mantém '{}'
                $decoded = json_decode($raw, true);
                if (json_last_error() === JSON_ERROR_NONE) {
                    $existingParams = $raw;
                }
            }
        } catch (\Throwable $e) {
            $existingParams = '{}';
        }

        $labelEnable       = htmlspecialchars(Text::_('LIB_NOBOSS_FIELD_NBAUTOSAVE_ENABLE_LABEL'), ENT_QUOTES, 'UTF-8');
        $labelDisable      = htmlspecialchars(Text::_('LIB_NOBOSS_FIELD_NBAUTOSAVE_DISABLE_LABEL'), ENT_QUOTES, 'UTF-8');
        $labelEnableShort  = htmlspecialchars(Text::_('LIB_NOBOSS_FIELD_NBAUTOSAVE_ENABLE_LABEL_SHORT'), ENT_QUOTES, 'UTF-8');
        $labelDisableShort = htmlspecialchars(Text::_('LIB_NOBOSS_FIELD_NBAUTOSAVE_DISABLE_LABEL_SHORT'), ENT_QUOTES, 'UTF-8');
        $betaLabel         = htmlspecialchars(Text::_('LIB_NOBOSS_FIELD_NBAUTOSAVE_BETA_LABEL'), ENT_QUOTES, 'UTF-8');

        // data-existing-params usa aspas duplas; ENT_QUOTES escapa " → &quot; e ' → &#039;
        $existingParamsAttr = htmlspecialchars($existingParams, ENT_QUOTES, 'UTF-8');

        $html = "
            <div data-id='noboss-autosave'
                 data-module-id='{$moduleId}'
                 data-token='{$token}'
                 data-label-enable='{$labelEnable}'
                 data-label-disable='{$labelDisable}'
                 data-label-enable-short='{$labelEnableShort}'
                 data-label-disable-short='{$labelDisableShort}'
                 data-base-url='" . Uri::root() . "'
                 data-existing-params=\"{$existingParamsAttr}\">
                <button type='button'
                        class='noboss-autosave__toggle'
                        data-active='0'
                        aria-label='{$labelEnable}'>
                    <span class='noboss-autosave__icon icon-power-off' aria-hidden='true'></span>
                    <span class='noboss-autosave__labels'>
                        <span class='noboss-autosave__label-short'>" . Text::_('LIB_NOBOSS_FIELD_NBAUTOSAVE_ENABLE_LABEL_SHORT') . "</span>
                        <span class='noboss-autosave__label-full' aria-hidden='true'>" . Text::_('LIB_NOBOSS_FIELD_NBAUTOSAVE_ENABLE_LABEL') . "</span>
                    </span>
                    <span class='noboss-autosave__beta' aria-hidden='true'>{$betaLabel}</span>
                </button>
            </div>";

        $wa->addInline('script', '
            if (typeof translationConstants === "undefined") { var translationConstants = {}; }
            translationConstants.nobossautosave = {
                saving:   "' . addslashes(Text::_('LIB_NOBOSS_FIELD_NBAUTOSAVE_SAVING')) . '",
                success:  "' . addslashes(Text::_('LIB_NOBOSS_FIELD_NBAUTOSAVE_SUCCESS')) . '",
                error:    "' . addslashes(Text::_('LIB_NOBOSS_FIELD_NBAUTOSAVE_ERROR')) . '",
                required: "' . addslashes(Text::_('LIB_NOBOSS_FIELD_NBAUTOSAVE_REQUIRED_ERROR')) . '",
                enabled:  "' . addslashes(Text::_('LIB_NOBOSS_FIELD_NBAUTOSAVE_ENABLED_MSG')) . '",
                disabled: "' . addslashes(Text::_('LIB_NOBOSS_FIELD_NBAUTOSAVE_DISABLED_MSG')) . '"
            };
        ', ['name' => '.nobossautosave']);

        $wa->registerAndUseScript('nobossautosave', Uri::root() . 'libraries/noboss/src/Form/Field/assets/js/min/nobossautosave.min.js');
        $wa->registerAndUseStyle('nobossautosave', Uri::root() . 'libraries/noboss/src/Form/Field/assets/stylesheets/css/nobossautosave.min.css');

        return $html;
    }
}