358 lines
18 KiB
Plaintext
358 lines
18 KiB
Plaintext
<%# Editor de blocos de UM evento em UM canal.
|
|
O estado vive num array JS; o HTML dos cards é desenhado a partir dele e
|
|
serializado num hidden ao salvar. Desenhar a partir do estado (em vez de ler
|
|
o DOM) é o que faz arrastar, remover e reordenar não perderem conteúdo. %>
|
|
<% outro_canal = @canal == 'email' ? 'whatsapp' : 'email' %>
|
|
<div class="space-y-6" id="editor-mensagem"
|
|
data-preview-url="<%= preview_template_admin_evento_path(@evento, canal: @canal) %>">
|
|
|
|
<div class="flex flex-col lg:flex-row lg:items-center justify-between gap-4">
|
|
<div class="min-w-0">
|
|
<h1 class="text-2xl font-bold text-white flex items-center gap-2">
|
|
<%= icone :editar, espaco: false %> Mensagem — <%= @evento.nome %>
|
|
</h1>
|
|
<div class="flex flex-wrap items-center gap-2 mt-2">
|
|
<% wpp = @canal != 'email' %>
|
|
<span class="inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-xs font-bold
|
|
<%= wpp ? 'bg-green-500/15 border border-green-500/30 text-green-300'
|
|
: 'bg-blue-500/15 border border-blue-500/30 text-blue-300' %>">
|
|
<%= icone(wpp ? :telefone : :email, cor: nil, tamanho: 'w-3.5 h-3.5', espaco: false) %>
|
|
<%= wpp ? 'WhatsApp' : 'E-mail' %>
|
|
</span>
|
|
<span class="inline-flex items-center px-2.5 py-1 rounded-full text-xs
|
|
bg-white/5 border border-white/10 text-gray-400">
|
|
<%= @evento.gatilho_label %>
|
|
</span>
|
|
</div>
|
|
</div>
|
|
<div class="flex items-center gap-2 flex-shrink-0">
|
|
<%= link_to template_admin_evento_path(@evento, canal: outro_canal), data: { turbo: false },
|
|
class: 'inline-flex items-center gap-2 px-4 py-2.5 rounded-xl text-sm border
|
|
border-white/10 text-gray-300 hover:border-white/20 hover:text-white
|
|
transition-colors whitespace-nowrap' do %>
|
|
<%= icone(outro_canal == 'email' ? :email : :telefone, cor: nil, tamanho: 'w-4 h-4', espaco: false) %>
|
|
Editar <%= outro_canal == 'email' ? 'e-mail' : 'WhatsApp' %>
|
|
<% end %>
|
|
<%= link_to admin_eventos_path, data: { turbo: false },
|
|
class: 'inline-flex items-center gap-2 px-4 py-2.5 rounded-xl text-sm border
|
|
border-white/10 text-gray-300 hover:border-white/20 hover:text-white
|
|
transition-colors whitespace-nowrap' do %>
|
|
<%= icone :voltar, cor: nil, tamanho: 'w-4 h-4', espaco: false %> Voltar
|
|
<% end %>
|
|
</div>
|
|
</div>
|
|
|
|
<%= render 'shared/flash' %>
|
|
|
|
<% if @template.errors.any? %>
|
|
<div class="p-4 bg-red-900/30 border border-red-500/40 rounded-xl">
|
|
<p class="text-red-400 text-sm font-medium mb-2">
|
|
<%= pluralize(@template.errors.count, 'erro', 'erros') %> encontrado<%= @template.errors.count > 1 ? 's' : '' %>:
|
|
</p>
|
|
<ul class="list-disc list-inside space-y-1">
|
|
<% @template.errors.full_messages.each do |msg| %>
|
|
<li class="text-red-300 text-sm"><%= msg %></li>
|
|
<% end %>
|
|
</ul>
|
|
</div>
|
|
<% end %>
|
|
|
|
<%= form_with url: template_admin_evento_path(@evento, canal: @canal), method: :patch,
|
|
data: { turbo: false }, id: 'form-template' do |f| %>
|
|
<%= hidden_field_tag :blocos, @template.blocos.to_json, id: 'campo-blocos' %>
|
|
|
|
<div class="grid grid-cols-1 xl:grid-cols-[16rem_minmax(0,1fr)_22rem] gap-4">
|
|
|
|
<%# ── Paleta ──────────────────────────────────────────── %>
|
|
<div class="space-y-4">
|
|
<div class="bg-[#1a1a1a] rounded-2xl border border-white/5 p-4">
|
|
<p class="text-xs font-semibold text-gray-400 uppercase tracking-wider mb-3">Blocos</p>
|
|
<p class="text-xs text-gray-500 mb-3">Arraste para a mensagem — ou clique.</p>
|
|
<div id="paleta" class="space-y-2">
|
|
<% Notificacao::Blocos::CATALOGO.each do |tipo, meta| %>
|
|
<div class="cursor-grab select-none bg-[#0a0a0a] border border-white/10 rounded-xl
|
|
px-3 py-2.5 hover:border-[#f97316] hover:bg-white/5 transition-colors"
|
|
data-tipo="<%= tipo %>" title="<%= meta[:dica] %>">
|
|
<span class="text-gray-500 mr-1">⠿</span>
|
|
<span class="text-sm text-white"><%= meta[:rotulo] %></span>
|
|
<span class="block text-xs text-gray-500 mt-0.5"><%= meta[:dica] %></span>
|
|
</div>
|
|
<% end %>
|
|
</div>
|
|
</div>
|
|
|
|
<%# ── Variáveis ─────────────────────────────────────── %>
|
|
<div class="bg-[#1a1a1a] rounded-2xl border border-white/5 p-4">
|
|
<p class="text-xs font-semibold text-gray-400 uppercase tracking-wider mb-3">Variáveis</p>
|
|
<p class="text-xs text-gray-500 mb-3">
|
|
Clique num campo da mensagem e depois numa variável para inseri-la ali.
|
|
</p>
|
|
<div class="flex flex-wrap gap-1.5">
|
|
<% @variaveis.each do |nome, meta| %>
|
|
<button type="button" title="<%= meta[:descricao] %> (ex.: <%= meta[:amostra] %>)"
|
|
class="chip-variavel px-2.5 py-1 rounded-full bg-[#f97316]/10 border border-[#f97316]/30
|
|
text-xs font-mono text-[#f97316] hover:bg-[#f97316]/20 hover:border-[#f97316]
|
|
transition-colors cursor-pointer"
|
|
data-variavel="<%= nome %>">
|
|
<%= "{{#{nome}}}" %>
|
|
</button>
|
|
<% end %>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
|
|
<%# ── Mensagem ────────────────────────────────────────── %>
|
|
<div class="space-y-4">
|
|
<% if @canal == 'email' %>
|
|
<div class="bg-[#1a1a1a] rounded-2xl border border-white/5 p-4">
|
|
<label class="block text-sm font-medium text-gray-300 mb-1.5" for="assunto">Assunto</label>
|
|
<%= text_field_tag :assunto, @template.assunto, id: 'assunto',
|
|
class: 'campo-editavel w-full px-4 py-3 bg-[#0a0a0a] border border-white/10 rounded-xl
|
|
text-white placeholder-gray-600 focus:outline-none focus:border-[#f97316]
|
|
focus:ring-1 focus:ring-[#f97316] transition-colors text-sm' %>
|
|
</div>
|
|
<% end %>
|
|
|
|
<div class="bg-[#1a1a1a] rounded-2xl border border-white/5 p-4">
|
|
<p class="text-xs font-semibold text-gray-400 uppercase tracking-wider mb-3">Mensagem</p>
|
|
<div id="canvas" class="space-y-3 min-h-[8rem]"></div>
|
|
<div id="canvas-vazio" class="text-center py-10 border border-dashed border-white/10 rounded-xl">
|
|
<div class="mb-2"><%= icone :vazio, tamanho: 'w-8 h-8', cor: 'text-gray-600', espaco: false %></div>
|
|
<p class="text-sm text-gray-500 max-w-xs mx-auto">
|
|
Arraste um bloco para cá. Sem blocos, o evento continua usando o texto padrão do sistema.
|
|
</p>
|
|
</div>
|
|
</div>
|
|
|
|
<div class="bg-[#1a1a1a] rounded-2xl border border-white/5 p-4 flex flex-wrap items-center gap-3">
|
|
<%= submit_tag 'Salvar mensagem',
|
|
class: 'px-6 py-3 bg-[#f97316] hover:bg-orange-500 text-white font-semibold
|
|
rounded-xl transition-colors cursor-pointer min-h-[48px]' %>
|
|
<button type="button" id="btn-preview"
|
|
class="inline-flex items-center gap-2 px-5 py-3 rounded-xl text-sm border
|
|
border-white/10 text-gray-300 hover:border-white/20 hover:text-white
|
|
transition-colors cursor-pointer min-h-[48px]">
|
|
<%= icone :restaurar, cor: nil, tamanho: 'w-4 h-4', espaco: false %> Atualizar preview
|
|
</button>
|
|
<label class="flex items-center gap-2.5 text-sm text-gray-300 ml-auto cursor-pointer">
|
|
<%= check_box_tag :ativo, '1', @template.ativo,
|
|
class: 'w-4 h-4 rounded border-white/20 bg-[#0a0a0a] text-[#f97316]
|
|
focus:ring-[#f97316] focus:ring-offset-0 cursor-pointer' %>
|
|
Usar esta mensagem
|
|
</label>
|
|
</div>
|
|
</div>
|
|
|
|
<%# ── Preview ─────────────────────────────────────────── %>
|
|
<div class="bg-[#1a1a1a] rounded-2xl border border-white/5 p-4 space-y-3">
|
|
<p class="text-xs font-semibold text-gray-400 uppercase tracking-wider">Preview</p>
|
|
<p class="text-xs text-gray-500">
|
|
Com valores de exemplo, renderizado pelo mesmo código do envio.
|
|
</p>
|
|
<p id="preview-assunto" class="text-sm text-white font-semibold break-words"></p>
|
|
<%# iframe sandbox: o HTML do e-mail é montado pelo nosso renderizador
|
|
(que escapa tudo), mas exibir dentro de um sandbox sem scripts evita
|
|
que os estilos do e-mail vazem para o admin — e vice-versa. %>
|
|
<iframe id="preview-email" class="w-full h-[26rem] rounded-xl bg-white border-0 <%= 'hidden' unless @canal == 'email' %>"
|
|
sandbox="" title="Preview do e-mail"></iframe>
|
|
<pre id="preview-whatsapp" class="whitespace-pre-wrap break-words text-sm text-gray-200 bg-[#0b141a] rounded-xl p-4 min-h-[10rem] <%= 'hidden' if @canal == 'email' %>"></pre>
|
|
</div>
|
|
</div>
|
|
<% end %>
|
|
</div>
|
|
|
|
<script src="https://cdn.jsdelivr.net/npm/sortablejs@1.15.2/Sortable.min.js"></script>
|
|
<script>
|
|
(function () {
|
|
var raiz = document.getElementById('editor-mensagem');
|
|
if (!raiz) return;
|
|
|
|
var CATALOGO = <%= raw Notificacao::Blocos::CATALOGO.to_json %>;
|
|
var CANAL = <%= raw @canal.to_json %>;
|
|
var campo = document.getElementById('campo-blocos');
|
|
var canvas = document.getElementById('canvas');
|
|
var vazio = document.getElementById('canvas-vazio');
|
|
|
|
var blocos;
|
|
try { blocos = JSON.parse(campo.value) || []; } catch (e) { blocos = []; }
|
|
|
|
// Último campo focado: é nele que a variável clicada é inserida.
|
|
var ultimoCampo = null;
|
|
document.addEventListener('focusin', function (e) {
|
|
if (e.target.classList && e.target.classList.contains('campo-editavel')) ultimoCampo = e.target;
|
|
});
|
|
|
|
function escapar(t) {
|
|
return String(t == null ? '' : t)
|
|
.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');
|
|
}
|
|
|
|
function blocoVazio(tipo) {
|
|
var b = { tipo: tipo };
|
|
var campos = (CATALOGO[tipo] || {}).campos || {};
|
|
Object.keys(campos).forEach(function (c) { b[c] = campos[c] === 'lista' ? [] : ''; });
|
|
return b;
|
|
}
|
|
|
|
function campoHtml(indice, chave, especie, valor) {
|
|
var id = 'b' + indice + '_' + chave;
|
|
var rotulo = chave.charAt(0).toUpperCase() + chave.slice(1);
|
|
if (especie === 'multilinha') {
|
|
return '<label class="block text-xs text-gray-500 mb-1" for="' + id + '">' + rotulo + '</label>' +
|
|
'<textarea id="' + id + '" rows="3" data-indice="' + indice + '" data-campo="' + chave + '"' +
|
|
' class="campo-editavel campo-bloco w-full bg-[#0a0a0a] border border-white/10 rounded-xl text-white text-sm px-3 py-2 focus:outline-none focus:border-[#f97316]">' +
|
|
escapar(valor) + '</textarea>';
|
|
}
|
|
return '<label class="block text-xs text-gray-500 mb-1" for="' + id + '">' + rotulo + '</label>' +
|
|
'<input id="' + id + '" type="text" value="' + escapar(valor) + '" data-indice="' + indice + '" data-campo="' + chave + '"' +
|
|
' class="campo-editavel campo-bloco w-full bg-[#0a0a0a] border border-white/10 rounded-xl text-white text-sm px-3 py-2 focus:outline-none focus:border-[#f97316]">';
|
|
}
|
|
|
|
function listaHtml(indice, linhas) {
|
|
var html = '<p class="text-xs text-gray-500 mb-1">Linhas da tabela</p>';
|
|
(linhas || []).forEach(function (linha, j) {
|
|
html += '<div class="flex gap-2 mb-2">' +
|
|
'<input type="text" value="' + escapar(linha.rotulo) + '" placeholder="Rótulo" data-indice="' + indice + '" data-linha="' + j + '" data-parte="rotulo"' +
|
|
' class="campo-editavel campo-linha flex-1 bg-[#0a0a0a] border border-white/10 rounded-xl text-white text-sm px-3 py-2 focus:outline-none focus:border-[#f97316]">' +
|
|
'<input type="text" value="' + escapar(linha.valor) + '" placeholder="Valor" data-indice="' + indice + '" data-linha="' + j + '" data-parte="valor"' +
|
|
' class="campo-editavel campo-linha flex-1 bg-[#0a0a0a] border border-white/10 rounded-xl text-white text-sm px-3 py-2 focus:outline-none focus:border-[#f97316]">' +
|
|
'<button type="button" class="btn-remove-linha px-2 text-red-400 hover:text-red-300" data-indice="' + indice + '" data-linha="' + j + '" title="Remover linha">✕</button>' +
|
|
'</div>';
|
|
});
|
|
html += '<button type="button" class="btn-add-linha text-xs text-orange-400 hover:text-orange-300" data-indice="' + indice + '">+ linha</button>';
|
|
return html;
|
|
}
|
|
|
|
function desenhar() {
|
|
canvas.innerHTML = '';
|
|
vazio.classList.toggle('hidden', blocos.length > 0);
|
|
|
|
blocos.forEach(function (bloco, i) {
|
|
var meta = CATALOGO[bloco.tipo] || { rotulo: bloco.tipo, campos: {} };
|
|
var card = document.createElement('div');
|
|
card.className = 'bg-[#0a0a0a] border border-white/10 rounded-xl p-3 hover:border-white/20 transition-colors';
|
|
card.dataset.indice = i;
|
|
|
|
var corpo = '<div class="flex items-center justify-between mb-2">' +
|
|
'<span class="text-sm text-white"><span class="alca cursor-grab text-gray-500 mr-1">⠿</span>' + escapar(meta.rotulo) + '</span>' +
|
|
'<button type="button" class="btn-remove text-red-400 hover:text-red-300 text-sm" data-indice="' + i + '" title="Remover bloco">✕</button>' +
|
|
'</div>';
|
|
|
|
var campos = meta.campos || {};
|
|
Object.keys(campos).forEach(function (chave) {
|
|
corpo += '<div class="mb-2">' +
|
|
(campos[chave] === 'lista' ? listaHtml(i, bloco[chave]) : campoHtml(i, chave, campos[chave], bloco[chave])) +
|
|
'</div>';
|
|
});
|
|
if (!Object.keys(campos).length) {
|
|
corpo += '<p class="text-xs text-gray-500">Sem campos — só a linha separadora.</p>';
|
|
}
|
|
|
|
card.innerHTML = corpo;
|
|
canvas.appendChild(card);
|
|
});
|
|
|
|
campo.value = JSON.stringify(blocos);
|
|
}
|
|
|
|
// ── Edição dos campos ──────────────────────────────────────
|
|
canvas.addEventListener('input', function (e) {
|
|
var alvo = e.target;
|
|
if (alvo.classList.contains('campo-bloco')) {
|
|
blocos[+alvo.dataset.indice][alvo.dataset.campo] = alvo.value;
|
|
} else if (alvo.classList.contains('campo-linha')) {
|
|
var bloco = blocos[+alvo.dataset.indice];
|
|
bloco.linhas = bloco.linhas || [];
|
|
bloco.linhas[+alvo.dataset.linha][alvo.dataset.parte] = alvo.value;
|
|
} else { return; }
|
|
campo.value = JSON.stringify(blocos); // sem redesenhar: perderia o cursor
|
|
});
|
|
|
|
canvas.addEventListener('click', function (e) {
|
|
var alvo = e.target;
|
|
if (alvo.classList.contains('btn-remove')) {
|
|
blocos.splice(+alvo.dataset.indice, 1); desenhar();
|
|
} else if (alvo.classList.contains('btn-add-linha')) {
|
|
var b = blocos[+alvo.dataset.indice];
|
|
b.linhas = (b.linhas || []).concat([{ rotulo: '', valor: '' }]); desenhar();
|
|
} else if (alvo.classList.contains('btn-remove-linha')) {
|
|
blocos[+alvo.dataset.indice].linhas.splice(+alvo.dataset.linha, 1); desenhar();
|
|
}
|
|
});
|
|
|
|
// ── Paleta: clicar adiciona, arrastar insere na posição ────
|
|
document.getElementById('paleta').addEventListener('click', function (e) {
|
|
var item = e.target.closest('[data-tipo]');
|
|
if (!item) return;
|
|
blocos.push(blocoVazio(item.dataset.tipo));
|
|
desenhar();
|
|
});
|
|
|
|
if (window.Sortable) {
|
|
Sortable.create(document.getElementById('paleta'), {
|
|
group: { name: 'blocos', pull: 'clone', put: false },
|
|
sort: false
|
|
});
|
|
Sortable.create(canvas, {
|
|
group: 'blocos',
|
|
handle: '.alca',
|
|
animation: 150,
|
|
onAdd: function (evt) {
|
|
// O clone da paleta é DOM sem estado: converte em bloco e redesenha.
|
|
var tipo = evt.item.dataset.tipo;
|
|
evt.item.parentNode.removeChild(evt.item);
|
|
blocos.splice(evt.newIndex, 0, blocoVazio(tipo));
|
|
desenhar();
|
|
},
|
|
onUpdate: function (evt) {
|
|
var movido = blocos.splice(evt.oldIndex, 1)[0];
|
|
blocos.splice(evt.newIndex, 0, movido);
|
|
desenhar();
|
|
}
|
|
});
|
|
}
|
|
|
|
// ── Variáveis: insere no cursor do último campo focado ─────
|
|
document.querySelectorAll('.chip-variavel').forEach(function (chip) {
|
|
chip.addEventListener('click', function () {
|
|
var texto = '{{' + chip.dataset.variavel + '}}';
|
|
if (!ultimoCampo) { alert('Clique primeiro no campo onde a variável deve entrar.'); return; }
|
|
var ini = ultimoCampo.selectionStart != null ? ultimoCampo.selectionStart : ultimoCampo.value.length;
|
|
var fim = ultimoCampo.selectionEnd != null ? ultimoCampo.selectionEnd : ini;
|
|
ultimoCampo.value = ultimoCampo.value.slice(0, ini) + texto + ultimoCampo.value.slice(fim);
|
|
ultimoCampo.dispatchEvent(new Event('input', { bubbles: true }));
|
|
ultimoCampo.focus();
|
|
ultimoCampo.selectionStart = ultimoCampo.selectionEnd = ini + texto.length;
|
|
});
|
|
});
|
|
|
|
// ── Preview: renderizado no servidor, pelo mesmo código do envio ──
|
|
var token = document.querySelector('meta[name="csrf-token"]');
|
|
document.getElementById('btn-preview').addEventListener('click', function () {
|
|
var assunto = document.getElementById('assunto');
|
|
fetch(raiz.dataset.previewUrl, {
|
|
method: 'POST',
|
|
headers: {
|
|
'Content-Type': 'application/json',
|
|
'Accept': 'application/json',
|
|
'X-CSRF-Token': token ? token.content : ''
|
|
},
|
|
body: JSON.stringify({ blocos: campo.value, assunto: assunto ? assunto.value : '' })
|
|
})
|
|
.then(function (r) { return r.json(); })
|
|
.then(function (dados) {
|
|
document.getElementById('preview-assunto').textContent = dados.assunto || '';
|
|
if (CANAL === 'email') {
|
|
document.getElementById('preview-email').srcdoc = dados.html || '';
|
|
} else {
|
|
document.getElementById('preview-whatsapp').textContent = dados.html || '';
|
|
}
|
|
})
|
|
.catch(function () { alert('Não foi possível gerar o preview agora.'); });
|
|
});
|
|
|
|
desenhar();
|
|
document.getElementById('btn-preview').click();
|
|
})();
|
|
</script>
|