Created
August 6, 2025 14:04
-
-
Save cupertinobr/451de89d8e640db298206419dc415253 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /** | |
| * ScriptCase Field Visibility Manager | |
| * Biblioteca para controlar visibilidade de campos baseado em condições | |
| */ | |
| class SCFieldVisibility { | |
| constructor() { | |
| this.rules = []; | |
| this.observer = null; | |
| this.initialized = false; | |
| } | |
| /** | |
| * Adiciona uma regra de visibilidade | |
| * @param {Object} config - Configuração da regra | |
| * @param {string} config.triggerField - ID do campo que dispara a condição | |
| * @param {Array} config.targetFields - Array de IDs dos campos a serem controlados | |
| * @param {function} config.condition - Função que retorna true/false para mostrar/esconder | |
| * @param {Object} config.options - Opções adicionais | |
| */ | |
| addRule(config) { | |
| const rule = { | |
| triggerField: config.triggerField, | |
| targetFields: Array.isArray(config.targetFields) ? config.targetFields : [config.targetFields], | |
| condition: config.condition, | |
| options: { | |
| hideOnTrue: config.options?.hideOnTrue ?? true, | |
| includeLabels: config.options?.includeLabels ?? true, | |
| ...config.options | |
| } | |
| }; | |
| this.rules.push(rule); | |
| // Se já foi inicializado, aplica a regra imediatamente | |
| if (this.initialized) { | |
| this.applyRule(rule); | |
| } | |
| } | |
| /** | |
| * Aplica uma regra específica | |
| * @param {Object} rule - Regra a ser aplicada | |
| */ | |
| applyRule(rule) { | |
| const triggerElement = document.getElementById(rule.triggerField); | |
| if (!triggerElement) return; | |
| const triggerValue = triggerElement.value; | |
| const shouldHide = rule.options.hideOnTrue ? rule.condition(triggerValue) : !rule.condition(triggerValue); | |
| rule.targetFields.forEach(fieldId => { | |
| this.toggleFieldVisibility(fieldId, !shouldHide, rule.options.includeLabels); | |
| }); | |
| } | |
| /** | |
| * Aplica todas as regras | |
| */ | |
| applyAllRules() { | |
| this.rules.forEach(rule => { | |
| this.applyRule(rule); | |
| }); | |
| } | |
| /** | |
| * Controla a visibilidade de um campo | |
| * @param {string} fieldId - ID do campo | |
| * @param {boolean} show - true para mostrar, false para esconder | |
| * @param {boolean} includeLabel - Se deve incluir o label | |
| */ | |
| toggleFieldVisibility(fieldId, show, includeLabel = true) { | |
| const field = document.getElementById(fieldId); | |
| const label = document.getElementById(fieldId + '_label'); | |
| if (field) { | |
| field.style.display = show ? '' : 'none'; | |
| // Se usar jQuery | |
| if (typeof $ !== 'undefined') { | |
| show ? $('#' + fieldId).show() : $('#' + fieldId).hide(); | |
| } | |
| } | |
| if (label && includeLabel) { | |
| label.style.display = show ? '' : 'none'; | |
| // Se usar jQuery | |
| if (typeof $ !== 'undefined') { | |
| show ? $('#' + fieldId + '_label').show() : $('#' + fieldId + '_label').hide(); | |
| } | |
| } | |
| } | |
| /** | |
| * Inicializa o observer e aplica as regras | |
| */ | |
| init() { | |
| // Aplica regras quando documento estiver pronto | |
| if (typeof $ !== 'undefined') { | |
| $(document).ready(() => { | |
| this.applyAllRules(); | |
| this.initialized = true; | |
| }); | |
| } else { | |
| document.addEventListener('DOMContentLoaded', () => { | |
| this.applyAllRules(); | |
| this.initialized = true; | |
| }); | |
| } | |
| // Observer para detectar mudanças no DOM | |
| this.observer = new MutationObserver((mutations) => { | |
| let shouldUpdate = false; | |
| mutations.forEach(mutation => { | |
| if (mutation.type === 'childList' && mutation.addedNodes.length > 0) { | |
| shouldUpdate = true; | |
| } | |
| }); | |
| if (shouldUpdate) { | |
| this.applyAllRules(); | |
| } | |
| }); | |
| // Observar mudanças no body | |
| this.observer.observe(document.body, { | |
| childList: true, | |
| subtree: true | |
| }); | |
| } | |
| /** | |
| * Para o observer | |
| */ | |
| destroy() { | |
| if (this.observer) { | |
| this.observer.disconnect(); | |
| } | |
| this.rules = []; | |
| this.initialized = false; | |
| } | |
| } | |
| // Funções utilitárias para condições comuns | |
| const SCConditions = { | |
| /** | |
| * Verifica se o primeiro caractere é maior que um valor | |
| */ | |
| firstCharGreaterThan: (value) => (fieldValue) => { | |
| const firstChar = fieldValue ? fieldValue.charAt(0) : ''; | |
| return firstChar > value; | |
| }, | |
| /** | |
| * Verifica se o campo não está vazio | |
| */ | |
| notEmpty: (fieldValue) => { | |
| return fieldValue && fieldValue.toString().trim() !== ''; | |
| }, | |
| /** | |
| * Verifica se o campo está vazio | |
| */ | |
| isEmpty: (fieldValue) => { | |
| return !fieldValue || fieldValue.toString().trim() === ''; | |
| }, | |
| /** | |
| * Verifica se o valor é igual a um valor específico | |
| */ | |
| equals: (value) => (fieldValue) => { | |
| return fieldValue == value; | |
| }, | |
| /** | |
| * Verifica se o valor está em uma lista | |
| */ | |
| in: (values) => (fieldValue) => { | |
| return values.includes(fieldValue); | |
| }, | |
| /** | |
| * Condição customizada usando regex | |
| */ | |
| regex: (pattern) => (fieldValue) => { | |
| const regex = new RegExp(pattern); | |
| return regex.test(fieldValue); | |
| } | |
| }; | |
| // Instância global | |
| const scFieldVisibility = new SCFieldVisibility(); | |
| // EXEMPLOS DE USO: | |
| // 1. Exemplo do código original (esconder status quando primeiro char > 0) | |
| scFieldVisibility.addRule({ | |
| triggerField: 'SC_codiempr', | |
| targetFields: ['SC_status_label', 'id_hide_status'], | |
| condition: SCConditions.firstCharGreaterThan('0'), | |
| options: { | |
| hideOnTrue: true, | |
| includeLabels: true | |
| } | |
| }); | |
| // 2. Mostrar campos apenas quando um checkbox estiver marcado | |
| scFieldVisibility.addRule({ | |
| triggerField: 'SC_ativo', | |
| targetFields: ['SC_data_inicio', 'SC_data_fim'], | |
| condition: SCConditions.equals('S'), | |
| options: { | |
| hideOnTrue: false, // mostrar quando condição for true | |
| includeLabels: true | |
| } | |
| }); | |
| // 3. Esconder campos quando valor estiver em uma lista | |
| scFieldVisibility.addRule({ | |
| triggerField: 'SC_tipo', | |
| targetFields: ['SC_campo_especial'], | |
| condition: SCConditions.in(['A', 'B', 'C']), | |
| options: { | |
| hideOnTrue: true, | |
| includeLabels: true | |
| } | |
| }); | |
| // 4. Condição customizada | |
| scFieldVisibility.addRule({ | |
| triggerField: 'SC_codigo', | |
| targetFields: ['SC_detalhes'], | |
| condition: (value) => { | |
| // Lógica customizada | |
| return value && value.length >= 5 && value.startsWith('VIP'); | |
| }, | |
| options: { | |
| hideOnTrue: false, // mostrar quando for VIP com 5+ chars | |
| includeLabels: true | |
| } | |
| }); | |
| // Inicializar a biblioteca | |
| scFieldVisibility.init(); | |
| // MÉTODOS ÚTEIS: | |
| // Adicionar regra após inicialização | |
| // scFieldVisibility.addRule({...}); | |
| // Aplicar todas as regras manualmente | |
| // scFieldVisibility.applyAllRules(); | |
| // Controlar visibilidade manualmente | |
| // scFieldVisibility.toggleFieldVisibility('SC_campo', true); // mostrar | |
| // scFieldVisibility.toggleFieldVisibility('SC_campo', false); // esconder | |
| // Limpar todas as regras e parar observer | |
| // scFieldVisibility.destroy(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment