feat(documents): editor de texto rico (Tiptap) para templates de documento
Substitui o textarea de texto puro por um editor visual real, seguindo o
print de referência do usuário do editor "Contrato de Software" do
OrçaFácil legado: toolbar completa (negrito/itálico/sublinhado/tachado,
alinhamento, listas, tabela, imagem, quebra de página), variáveis inseridas
como chip inline via catálogo fechado (nunca {{texto livre}}), painel
"Variáveis usadas neste modelo" (com badge obrigatório ao vivo) e
"Histórico de versões".
Backend: editor-content-renderer.ts e merge-engine.ts portados/reescritos
a partir do renderEditorContent.js/variableRegistry.js reais do legado
(achados em .tmp/orcafacil-reference) — resolve a árvore Tiptap
diretamente em vez de regex sobre HTML cacheado. Novo catálogo de
variáveis + GET /documents/variable-catalog.
Fora de escopo desta leva (documentado em docs/progress.md): nó
`conditional`, repetição de linha de tabela, bloqueio por variável
obrigatória ausente, e auto-resolução de dados reais do cadastro na hora
de gerar o documento.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
@@ -2,12 +2,12 @@
|
||||
* Client for `apps/api` `/v1/documents/templates` and `/v1/documents/generations`
|
||||
* — the "templates + generation" half of Documents (eden.md módulo 4, §1.1-1.3).
|
||||
*
|
||||
* This leva has NO real visual editor: `editorContent` is a simplified
|
||||
* JSONB with a single root-level `plainText` string carrying
|
||||
* `{{variavel}}` placeholders (no rich node tree). PDF generation itself
|
||||
* IS real (Chromium via packages/integrations/src/pdf/renderer.ts) —
|
||||
* `pdf_s3_key`/`pdf_sha256`/`pdf_size_bytes` are populated on every
|
||||
* `status: 'final'` generation.
|
||||
* `editorContent` is a real Tiptap document tree (`JSONContent`), edited via
|
||||
* the rich editor in `./documents/editor` — resolved server-side by
|
||||
* `apps/api/src/documents/editor-content-renderer.ts` (ported from the
|
||||
* legacy `renderEditorContent.js`). PDF generation is real (Chromium via
|
||||
* packages/integrations/src/pdf/renderer.ts) — `pdf_s3_key`/`pdf_sha256`/
|
||||
* `pdf_size_bytes` are populated on every `status: 'final'` generation.
|
||||
*
|
||||
* Like Contracts/Resellers, template/version/generation responses are
|
||||
* snake_case straight off the DB row — except the two computed fields on a
|
||||
@@ -15,6 +15,7 @@
|
||||
* camelCase exactly as documented in the task brief; mirrored as-is below,
|
||||
* not "fixed" to snake_case.
|
||||
*/
|
||||
import type { JSONContent } from "@tiptap/core";
|
||||
import { API_BASE_URL, apiRequest } from "./http.js";
|
||||
|
||||
export type DocGroup = "cliente" | "revenda";
|
||||
@@ -30,10 +31,15 @@ export type GenerationStatus = "generating" | "final" | "error";
|
||||
*/
|
||||
export const DOCUMENT_TEMPLATE_KEY_PATTERN = /^[a-z][a-z0-9_]*$/;
|
||||
|
||||
/** Simplified editor content for this leva — always `{ type: "doc", plainText }`, never a rich node tree. */
|
||||
export interface SimpleEditorContent {
|
||||
type: "doc";
|
||||
plainText: string;
|
||||
/** Empty Tiptap doc — mirrors `EMPTY_DOC_CONTENT` in packages/database/src/repositories/documents.ts. */
|
||||
export const EMPTY_EDITOR_CONTENT: JSONContent = { type: "doc", content: [{ type: "paragraph", content: [] }] };
|
||||
|
||||
/** Uma entrada do catálogo fechado de variáveis — `GET /documents/variable-catalog`. */
|
||||
export interface VariableCatalogEntry {
|
||||
key: string;
|
||||
label: string;
|
||||
category: string;
|
||||
required: boolean;
|
||||
}
|
||||
|
||||
/** Response shape for `GET /documents/templates` (list) and the bare fields of the detail response. */
|
||||
@@ -54,7 +60,7 @@ export interface DocumentTemplateVersion {
|
||||
template_id: string;
|
||||
version: number;
|
||||
status: DocumentVersionStatus;
|
||||
editor_content: SimpleEditorContent | Record<string, unknown>;
|
||||
editor_content: JSONContent;
|
||||
html_content: string | null;
|
||||
css_content: string | null;
|
||||
page_config: Record<string, unknown> | null;
|
||||
@@ -78,7 +84,7 @@ export interface CreateDocumentTemplateInput {
|
||||
|
||||
/** Body of `PATCH /documents/templates/:id/draft` — matches `UpdateDraftDto`. `pageConfig` is deliberately omitted from the UI. */
|
||||
export interface UpdateDraftInput {
|
||||
editorContent?: SimpleEditorContent;
|
||||
editorContent?: JSONContent;
|
||||
cssContent?: string;
|
||||
pageConfig?: Record<string, unknown>;
|
||||
}
|
||||
@@ -212,7 +218,7 @@ export async function downloadGenerationPdf(id: string, accessToken: string, fil
|
||||
* Renders the CURRENT (possibly unsaved) draft content to PDF via Chromium
|
||||
* — nothing is persisted server-side. Same raw-fetch pattern as
|
||||
* `downloadGenerationPdf` (binary response, still needs the bearer token).
|
||||
* Every `{{variavel}}` shows as `[variavel]` in the result (no real
|
||||
* Every `mergeField` shows as `[chave]` in the result (no real
|
||||
* client/reseller context at this stage).
|
||||
*
|
||||
* Returns an object URL for the caller to show inline (`<iframe>`), rather
|
||||
@@ -228,13 +234,13 @@ export async function downloadGenerationPdf(id: string, accessToken: string, fil
|
||||
*/
|
||||
export async function previewDraft(
|
||||
templateId: string,
|
||||
input: { plainText: string; cssContent?: string },
|
||||
input: { editorContent: JSONContent; cssContent?: string },
|
||||
accessToken: string,
|
||||
): Promise<string> {
|
||||
const response = await fetch(`${API_BASE_URL}/documents/templates/${templateId}/draft/preview`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json", Authorization: `Bearer ${accessToken}` },
|
||||
body: JSON.stringify({ editorContent: { plainText: input.plainText }, cssContent: input.cssContent }),
|
||||
body: JSON.stringify({ editorContent: input.editorContent, cssContent: input.cssContent }),
|
||||
});
|
||||
if (!response.ok) {
|
||||
throw new Error("Não foi possível gerar a pré-visualização.");
|
||||
@@ -243,14 +249,33 @@ export async function previewDraft(
|
||||
return URL.createObjectURL(blob);
|
||||
}
|
||||
|
||||
/** Extracts `{{variavel}}` references from a plain-text template body — used to auto-build the generation context form. */
|
||||
export function extractTemplateVariables(plainText: string): string[] {
|
||||
const found = new Set<string>();
|
||||
const pattern = /\{\{(\w+)\}\}/g;
|
||||
let match: RegExpExecArray | null;
|
||||
while ((match = pattern.exec(plainText)) !== null) {
|
||||
const variable = match[1];
|
||||
if (variable) found.add(variable);
|
||||
}
|
||||
return Array.from(found);
|
||||
export function getVariableCatalog(accessToken: string): Promise<VariableCatalogEntry[]> {
|
||||
return apiRequest<VariableCatalogEntry[]>("/documents/variable-catalog", { method: "GET" }, { accessToken });
|
||||
}
|
||||
|
||||
/**
|
||||
* Varre a árvore Tiptap e devolve as chaves de `mergeField` usadas —
|
||||
* espelha `collectMergeFieldKeys` em
|
||||
* apps/api/src/documents/editor-content-renderer.ts (duplicado de
|
||||
* propósito: o editor não pode depender do backend, e vice-versa, mesma
|
||||
* lógica do legado). Usado tanto no painel "Variáveis usadas neste modelo"
|
||||
* quanto para auto-detectar o formulário de contexto em
|
||||
* `GenerationFormPage.tsx`.
|
||||
*/
|
||||
export function collectMergeFieldKeys(editorContent: JSONContent | null | undefined): string[] {
|
||||
const keys = new Set<string>();
|
||||
|
||||
function walk(node: JSONContent | undefined): void {
|
||||
if (!node) return;
|
||||
if (node.type === "mergeField" && typeof node.attrs?.key === "string") {
|
||||
keys.add(node.attrs.key);
|
||||
return;
|
||||
}
|
||||
(node.content ?? []).forEach(walk);
|
||||
}
|
||||
|
||||
if (editorContent?.type === "doc") {
|
||||
(editorContent.content ?? []).forEach(walk);
|
||||
}
|
||||
return [...keys];
|
||||
}
|
||||
|
||||
@@ -5,8 +5,8 @@ import { Alert, Button, Card, Input, PageHeader, Select } from "@eden/ui";
|
||||
import { useAuth } from "../../lib/auth/AuthContext.js";
|
||||
import { ApiError } from "../../lib/api/http.js";
|
||||
import {
|
||||
collectMergeFieldKeys,
|
||||
createGeneration,
|
||||
extractTemplateVariables,
|
||||
getDocumentTemplate,
|
||||
listDocumentTemplates,
|
||||
} from "../../lib/api/documents.js";
|
||||
@@ -92,8 +92,7 @@ export function GenerationFormPage() {
|
||||
.then((detail) => {
|
||||
if (cancelled) return;
|
||||
const published = detail.versions.find((v) => v.id === detail.current_version_id);
|
||||
const content = published?.editor_content as { plainText?: string } | undefined;
|
||||
const variables = content?.plainText ? extractTemplateVariables(content.plainText) : [];
|
||||
const variables = published ? collectMergeFieldKeys(published.editor_content) : [];
|
||||
setTemplateVariables(variables);
|
||||
setVariableValues(Object.fromEntries(variables.map((v) => [v, ""])));
|
||||
})
|
||||
|
||||
@@ -1,34 +1,36 @@
|
||||
import { useCallback, useEffect, useState } from "react";
|
||||
import type { FormEvent } from "react";
|
||||
import { useParams } from "react-router-dom";
|
||||
import type { JSONContent } from "@tiptap/react";
|
||||
import { Alert, Badge, Button, Card, PageHeader } from "@eden/ui";
|
||||
import { useAuth } from "../../lib/auth/AuthContext.js";
|
||||
import { ApiError } from "../../lib/api/http.js";
|
||||
import {
|
||||
EMPTY_EDITOR_CONTENT,
|
||||
collectMergeFieldKeys,
|
||||
createDraft,
|
||||
getDocumentTemplate,
|
||||
getVariableCatalog,
|
||||
previewDraft,
|
||||
publishDraft,
|
||||
updateDraft,
|
||||
} from "../../lib/api/documents.js";
|
||||
import type { DocumentTemplateVersion, DocumentTemplateWithVersions } from "../../lib/api/documents.js";
|
||||
import type { DocumentTemplateVersion, DocumentTemplateWithVersions, VariableCatalogEntry } from "../../lib/api/documents.js";
|
||||
import { formatDateTimeBR } from "../../lib/format.js";
|
||||
import { Breadcrumb } from "../../components/Breadcrumb.js";
|
||||
import { DOC_GROUP_LABEL, DOC_GROUP_VARIANT } from "./documentLabels.js";
|
||||
import { DocumentEditor } from "./editor/DocumentEditor.js";
|
||||
|
||||
/**
|
||||
* Layout reference: DreamsERP theme `.tmp/theme-reference/documentRepository.tsx`
|
||||
* (breadcrumb + title/status-badge header, bordered white "detail" cards)
|
||||
* and `.tmp/theme-reference/documentWorkflows.tsx` for the
|
||||
* draft-in-progress/active status pill language — the theme's Ant Design
|
||||
* table + off-canvas modals were not usable here, so the draft editor is a
|
||||
* plain in-page card (textarea + Save/Publish), same composition style as
|
||||
* `ContractDetailPage`'s `StatusTransitionCard`.
|
||||
* Layout de referência: print do usuário (`/home/handix/editortexto.png`,
|
||||
* editor de "Contrato de Software" do OrçaFácil legado) — header com
|
||||
* título/badge de versão + ações, tabs "Editor" / "Pré-visualização (PDF)",
|
||||
* toolbar rica com variáveis inseridas como chip (nunca `{{texto livre}}`),
|
||||
* painel "Variáveis usadas neste modelo" e "Histórico de versões".
|
||||
*
|
||||
* No rich Tiptap editor and no PDF in this leva: `editorContent` is always
|
||||
* `{ type: "doc", plainText }` and the only free-form field is a `<textarea>`
|
||||
* with `{{variavel}}` placeholders. `html_content` is the server-computed
|
||||
* preview of that merge, rendered read-only.
|
||||
* A tab "Pré-visualização (PDF)" é nomeada diferente do print
|
||||
* ("Visualizar com dados") de propósito: não resolve dado real de
|
||||
* cliente/revenda nesta leva, só o placeholder `[chave]` — ver
|
||||
* apps/api/src/documents/documents.service.ts#previewDraft.
|
||||
*/
|
||||
export function TemplateDetailPage() {
|
||||
const { id } = useParams<{ id: string }>();
|
||||
@@ -37,6 +39,7 @@ export function TemplateDetailPage() {
|
||||
const [template, setTemplate] = useState<DocumentTemplateWithVersions | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [editorOpen, setEditorOpen] = useState(false);
|
||||
|
||||
const load = useCallback(() => {
|
||||
if (!id || !accessToken) return;
|
||||
@@ -73,6 +76,23 @@ export function TemplateDetailPage() {
|
||||
const publishedVersion = template.versions.find((v) => v.id === template.current_version_id) ?? null;
|
||||
const draftVersion = template.versions.find((v) => v.status === "draft") ?? null;
|
||||
|
||||
if (editorOpen && draftVersion) {
|
||||
return (
|
||||
<div>
|
||||
<Breadcrumb items={[{ label: "Documentos", href: "/documents/templates" }, { label: template.name }]} />
|
||||
<DraftEditorScreen
|
||||
templateId={template.id}
|
||||
templateName={template.name}
|
||||
draftVersion={draftVersion}
|
||||
versions={template.versions}
|
||||
accessToken={accessToken}
|
||||
onClose={() => setEditorOpen(false)}
|
||||
onChanged={load}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div>
|
||||
<Breadcrumb items={[{ label: "Documentos", href: "/documents/templates" }, { label: template.name }]} />
|
||||
@@ -115,7 +135,7 @@ export function TemplateDetailPage() {
|
||||
<Card title="Preview da versão publicada">
|
||||
{publishedVersion?.html_content ? (
|
||||
<div
|
||||
className="rounded-md border border-border-color p-4 text-sm leading-relaxed text-title [&_p]:mb-2"
|
||||
className="rounded-md border border-border-color p-4 text-sm leading-relaxed text-title [&_p]:mb-2 [&_.merge-field-chip]:rounded [&_.merge-field-chip]:bg-primary/10 [&_.merge-field-chip]:px-1 [&_.merge-field-chip]:text-primary"
|
||||
dangerouslySetInnerHTML={{ __html: publishedVersion.html_content }}
|
||||
/>
|
||||
) : (
|
||||
@@ -125,12 +145,19 @@ export function TemplateDetailPage() {
|
||||
)}
|
||||
</Card>
|
||||
|
||||
<DraftCard
|
||||
templateId={template.id}
|
||||
draftVersion={draftVersion}
|
||||
accessToken={accessToken}
|
||||
onChanged={load}
|
||||
/>
|
||||
<Card title="Rascunho">
|
||||
{draftVersion ? (
|
||||
<div className="space-y-3">
|
||||
<p className="text-sm text-default">
|
||||
Existe um rascunho em edição (v{draftVersion.version}, criado em{" "}
|
||||
{formatDateTimeBR(draftVersion.created_at)}).
|
||||
</p>
|
||||
<Button onClick={() => setEditorOpen(true)}>Editar rascunho existente</Button>
|
||||
</div>
|
||||
) : (
|
||||
<CreateDraftPrompt templateId={template.id} accessToken={accessToken} onCreated={() => { load(); setEditorOpen(true); }} />
|
||||
)}
|
||||
</Card>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -146,79 +173,98 @@ function Row({ label, value }: { label: string; value: string }) {
|
||||
);
|
||||
}
|
||||
|
||||
function DraftCard({
|
||||
function CreateDraftPrompt({
|
||||
templateId,
|
||||
draftVersion,
|
||||
accessToken,
|
||||
onChanged,
|
||||
onCreated,
|
||||
}: {
|
||||
templateId: string;
|
||||
draftVersion: DocumentTemplateVersion | null;
|
||||
accessToken: string | null;
|
||||
onChanged: () => void;
|
||||
onCreated: () => void;
|
||||
}) {
|
||||
const [editorOpen, setEditorOpen] = useState(false);
|
||||
const [plainText, setPlainText] = useState("");
|
||||
const [cssContent, setCssContent] = useState("");
|
||||
const [creating, setCreating] = useState(false);
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [confirmingPublish, setConfirmingPublish] = useState(false);
|
||||
const [publishing, setPublishing] = useState(false);
|
||||
const [previewing, setPreviewing] = useState(false);
|
||||
const [previewUrl, setPreviewUrl] = useState<string | null>(null);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [saveSuccess, setSaveSuccess] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
// Revoga a URL antiga sempre que uma nova pré-visualização substitui a
|
||||
// anterior, e ao fechar o editor/desmontar — sem isso o blob fica
|
||||
// retido na memória do navegador indefinidamente.
|
||||
return () => {
|
||||
if (previewUrl) URL.revokeObjectURL(previewUrl);
|
||||
};
|
||||
}, [previewUrl]);
|
||||
|
||||
function openEditorFor(version: DocumentTemplateVersion) {
|
||||
const content = version.editor_content as { plainText?: string } | undefined;
|
||||
setPlainText(content?.plainText ?? "");
|
||||
setCssContent(version.css_content ?? "");
|
||||
setEditorOpen(true);
|
||||
setError(null);
|
||||
setSaveSuccess(false);
|
||||
}
|
||||
|
||||
async function handleCreateDraft() {
|
||||
if (!accessToken) return;
|
||||
setError(null);
|
||||
setCreating(true);
|
||||
try {
|
||||
const version = await createDraft(templateId, accessToken);
|
||||
openEditorFor(version);
|
||||
onChanged();
|
||||
await createDraft(templateId, accessToken);
|
||||
onCreated();
|
||||
} catch (err) {
|
||||
if (err instanceof ApiError && err.status === 409) {
|
||||
setError("Já existe um rascunho para este template — recarregando para editá-lo.");
|
||||
onChanged();
|
||||
} else {
|
||||
setError(err instanceof ApiError ? err.message : "Não foi possível criar o rascunho.");
|
||||
}
|
||||
setError(err instanceof ApiError ? err.message : "Não foi possível criar o rascunho.");
|
||||
} finally {
|
||||
setCreating(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function handleSave(event: FormEvent) {
|
||||
event.preventDefault();
|
||||
return (
|
||||
<div className="space-y-3">
|
||||
{error ? <Alert variant="error">{error}</Alert> : null}
|
||||
<p className="text-sm text-default">Nenhum rascunho em edição no momento.</p>
|
||||
<Button onClick={handleCreateDraft} loading={creating}>
|
||||
Criar rascunho
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
type PreviewTab = "editor" | "preview";
|
||||
|
||||
function DraftEditorScreen({
|
||||
templateId,
|
||||
templateName,
|
||||
draftVersion,
|
||||
versions,
|
||||
accessToken,
|
||||
onClose,
|
||||
onChanged,
|
||||
}: {
|
||||
templateId: string;
|
||||
templateName: string;
|
||||
draftVersion: DocumentTemplateVersion;
|
||||
versions: DocumentTemplateVersion[];
|
||||
accessToken: string | null;
|
||||
onClose: () => void;
|
||||
onChanged: () => void;
|
||||
}) {
|
||||
const [content, setContent] = useState<JSONContent>((draftVersion.editor_content as JSONContent) ?? EMPTY_EDITOR_CONTENT);
|
||||
const [cssContent, setCssContent] = useState(draftVersion.css_content ?? "");
|
||||
const [tab, setTab] = useState<PreviewTab>("editor");
|
||||
const [catalog, setCatalog] = useState<VariableCatalogEntry[]>([]);
|
||||
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [saveSuccess, setSaveSuccess] = useState(false);
|
||||
const [previewing, setPreviewing] = useState(false);
|
||||
const [previewUrl, setPreviewUrl] = useState<string | null>(null);
|
||||
const [confirmingPublish, setConfirmingPublish] = useState(false);
|
||||
const [publishing, setPublishing] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (!accessToken) return;
|
||||
getVariableCatalog(accessToken)
|
||||
.then(setCatalog)
|
||||
.catch(() => setCatalog([]));
|
||||
}, [accessToken]);
|
||||
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
if (previewUrl) URL.revokeObjectURL(previewUrl);
|
||||
};
|
||||
}, [previewUrl]);
|
||||
|
||||
const usedKeys = collectMergeFieldKeys(content);
|
||||
const usedEntries = usedKeys.map((key) => catalog.find((entry) => entry.key === key) ?? { key, label: key, category: "Outra", required: false });
|
||||
|
||||
async function handleSave() {
|
||||
if (!accessToken) return;
|
||||
setError(null);
|
||||
setSaveSuccess(false);
|
||||
setSaving(true);
|
||||
try {
|
||||
await updateDraft(
|
||||
templateId,
|
||||
{ editorContent: { type: "doc", plainText }, cssContent: cssContent || undefined },
|
||||
accessToken,
|
||||
);
|
||||
await updateDraft(templateId, { editorContent: content, cssContent: cssContent || undefined }, accessToken);
|
||||
setSaveSuccess(true);
|
||||
onChanged();
|
||||
} catch (err) {
|
||||
@@ -233,7 +279,7 @@ function DraftCard({
|
||||
setError(null);
|
||||
setPreviewing(true);
|
||||
try {
|
||||
const url = await previewDraft(templateId, { plainText, cssContent: cssContent || undefined }, accessToken);
|
||||
const url = await previewDraft(templateId, { editorContent: content, cssContent: cssContent || undefined }, accessToken);
|
||||
setPreviewUrl((prev) => {
|
||||
if (prev) URL.revokeObjectURL(prev);
|
||||
return url;
|
||||
@@ -251,9 +297,9 @@ function DraftCard({
|
||||
setPublishing(true);
|
||||
try {
|
||||
await publishDraft(templateId, accessToken);
|
||||
setEditorOpen(false);
|
||||
setConfirmingPublish(false);
|
||||
onChanged();
|
||||
onClose();
|
||||
} catch (err) {
|
||||
setError(err instanceof ApiError ? err.message : "Não foi possível publicar o rascunho.");
|
||||
} finally {
|
||||
@@ -261,36 +307,28 @@ function DraftCard({
|
||||
}
|
||||
}
|
||||
|
||||
if (!editorOpen) {
|
||||
return (
|
||||
<Card title="Rascunho">
|
||||
{error ? (
|
||||
<Alert variant="error" className="mb-3">
|
||||
{error}
|
||||
</Alert>
|
||||
) : null}
|
||||
{draftVersion ? (
|
||||
<div className="space-y-3">
|
||||
<p className="text-sm text-default">
|
||||
Existe um rascunho em edição (v{draftVersion.version}, criado em{" "}
|
||||
{formatDateTimeBR(draftVersion.created_at)}).
|
||||
</p>
|
||||
<Button onClick={() => openEditorFor(draftVersion)}>Editar rascunho existente</Button>
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-3">
|
||||
<p className="text-sm text-default">Nenhum rascunho em edição no momento.</p>
|
||||
<Button onClick={handleCreateDraft} loading={creating}>
|
||||
Criar rascunho
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<Card title="Editar rascunho">
|
||||
<div>
|
||||
<div className="mb-4 flex flex-wrap items-center justify-between gap-3">
|
||||
<div className="flex items-center gap-3">
|
||||
<h1 className="text-lg font-bold text-title">{templateName}</h1>
|
||||
<Badge variant="warning">Rascunho (v{draftVersion.version})</Badge>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<Button type="button" variant="secondary" onClick={onClose}>
|
||||
Fechar
|
||||
</Button>
|
||||
<Button type="button" variant="secondary" loading={saving} onClick={handleSave}>
|
||||
Salvar rascunho
|
||||
</Button>
|
||||
{!confirmingPublish ? (
|
||||
<Button type="button" variant="danger" onClick={() => setConfirmingPublish(true)}>
|
||||
Publicar
|
||||
</Button>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{error ? (
|
||||
<Alert variant="error" className="mb-3">
|
||||
{error}
|
||||
@@ -301,92 +339,119 @@ function DraftCard({
|
||||
Rascunho salvo.
|
||||
</Alert>
|
||||
) : null}
|
||||
|
||||
<form className="space-y-4" onSubmit={handleSave}>
|
||||
<div>
|
||||
<label className="mb-1 block text-sm font-semibold text-gray-900" htmlFor="draft-plain-text">
|
||||
Conteúdo do documento
|
||||
</label>
|
||||
<textarea
|
||||
id="draft-plain-text"
|
||||
className="w-full rounded-md border border-border-color bg-white px-3 py-2.5 font-mono text-sm text-title focus:outline-none focus:ring-2 focus:ring-primary/30"
|
||||
rows={14}
|
||||
value={plainText}
|
||||
onChange={(e) => setPlainText(e.target.value)}
|
||||
placeholder={"Prezado(a) {{nome_cliente}},\n\nEste contrato refere-se a {{plano_contratado}}..."}
|
||||
/>
|
||||
<p className="mt-1 text-xs text-default">
|
||||
Use <code>{"{{variavel}}"}</code> para marcar trechos que serão substituídos na geração do documento. Use
|
||||
"Pré-visualizar (PDF)" abaixo pra ver o resultado real (renderizado no servidor) antes de publicar — cada
|
||||
variável aparece como <code>[variavel]</code>, já que ainda não há um cliente/revenda selecionado nesta
|
||||
tela.
|
||||
{confirmingPublish ? (
|
||||
<Alert variant="warning" title="Publicar esta versão?" className="mb-3">
|
||||
<p className="mb-3">
|
||||
Ao publicar, esta versão passa a ser a versão ativa do template e não poderá mais ser editada — a
|
||||
publicação é permanente.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<details>
|
||||
<summary className="cursor-pointer text-sm font-semibold text-title">CSS (avançado, opcional)</summary>
|
||||
<textarea
|
||||
className="mt-2 w-full rounded-md border border-border-color bg-white px-3 py-2.5 font-mono text-sm text-title focus:outline-none focus:ring-2 focus:ring-primary/30"
|
||||
rows={6}
|
||||
value={cssContent}
|
||||
onChange={(e) => setCssContent(e.target.value)}
|
||||
/>
|
||||
</details>
|
||||
|
||||
<div className="flex flex-wrap items-center gap-2 border-t border-border-color pt-4">
|
||||
<Button type="submit" loading={saving}>
|
||||
Salvar rascunho
|
||||
</Button>
|
||||
<Button type="button" variant="secondary" loading={previewing} onClick={handlePreview}>
|
||||
Pré-visualizar (PDF)
|
||||
</Button>
|
||||
<Button type="button" variant="secondary" onClick={() => setEditorOpen(false)}>
|
||||
Fechar
|
||||
</Button>
|
||||
{!confirmingPublish ? (
|
||||
<Button type="button" variant="danger" onClick={() => setConfirmingPublish(true)}>
|
||||
Publicar
|
||||
<div className="flex items-center gap-2">
|
||||
<Button type="button" variant="danger" onClick={handlePublish} loading={publishing}>
|
||||
Confirmar publicação
|
||||
</Button>
|
||||
) : null}
|
||||
<Button type="button" variant="secondary" onClick={() => setConfirmingPublish(false)}>
|
||||
Cancelar
|
||||
</Button>
|
||||
</div>
|
||||
</Alert>
|
||||
) : null}
|
||||
|
||||
<div className="mb-3 flex gap-1 border-b border-border-color">
|
||||
<TabButton active={tab === "editor"} onClick={() => setTab("editor")}>
|
||||
Editor / com variáveis
|
||||
</TabButton>
|
||||
<TabButton active={tab === "preview"} onClick={() => setTab("preview")}>
|
||||
Pré-visualização (PDF)
|
||||
</TabButton>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 gap-4 lg:grid-cols-4">
|
||||
<div className="lg:col-span-3">
|
||||
{tab === "editor" ? (
|
||||
<>
|
||||
<DocumentEditor content={content} onChange={setContent} catalog={catalog} />
|
||||
<details className="mt-3">
|
||||
<summary className="cursor-pointer text-sm font-semibold text-title">CSS (avançado, opcional)</summary>
|
||||
<textarea
|
||||
className="mt-2 w-full rounded-md border border-border-color bg-white px-3 py-2.5 font-mono text-sm text-title focus:outline-none focus:ring-2 focus:ring-primary/30"
|
||||
rows={6}
|
||||
value={cssContent}
|
||||
onChange={(e) => setCssContent(e.target.value)}
|
||||
/>
|
||||
</details>
|
||||
</>
|
||||
) : (
|
||||
<Card>
|
||||
<div className="mb-3 flex items-center justify-between">
|
||||
<p className="text-sm text-default">
|
||||
Renderização real via Chromium do conteúdo atual (ainda não salvo) — cada variável aparece como{" "}
|
||||
<code>[chave]</code>, já que não há cliente/revenda selecionado nesta tela.
|
||||
</p>
|
||||
<Button type="button" variant="secondary" loading={previewing} onClick={handlePreview}>
|
||||
Gerar pré-visualização
|
||||
</Button>
|
||||
</div>
|
||||
{previewUrl ? (
|
||||
<iframe
|
||||
src={previewUrl}
|
||||
title="Pré-visualização do documento"
|
||||
className="h-[600px] w-full rounded-md border border-border-color"
|
||||
/>
|
||||
) : (
|
||||
<p className="text-sm text-default">Clique em "Gerar pré-visualização" para ver o PDF.</p>
|
||||
)}
|
||||
</Card>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{previewUrl ? (
|
||||
<div>
|
||||
<div className="mb-2 flex items-center justify-between">
|
||||
<p className="text-sm font-semibold text-title">Pré-visualização</p>
|
||||
<Button
|
||||
type="button"
|
||||
variant="secondary"
|
||||
size="sm"
|
||||
onClick={() => {
|
||||
URL.revokeObjectURL(previewUrl);
|
||||
setPreviewUrl(null);
|
||||
}}
|
||||
>
|
||||
Fechar pré-visualização
|
||||
</Button>
|
||||
</div>
|
||||
<iframe src={previewUrl} title="Pré-visualização do documento" className="h-[600px] w-full rounded-md border border-border-color" />
|
||||
</div>
|
||||
) : null}
|
||||
<div className="space-y-4 lg:col-span-1">
|
||||
<Card title="Variáveis usadas neste modelo">
|
||||
{usedEntries.length === 0 ? (
|
||||
<p className="text-xs text-default">Nenhuma variável inserida ainda.</p>
|
||||
) : (
|
||||
<ul className="space-y-2 text-xs">
|
||||
{usedEntries.map((entry) => (
|
||||
<li key={entry.key} className="flex items-center justify-between gap-2">
|
||||
<span className="flex items-center gap-1.5 text-title">
|
||||
<span className="text-success">✓</span> {entry.label}
|
||||
</span>
|
||||
{entry.required ? <span className="font-semibold text-warning">obrigatório</span> : null}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</Card>
|
||||
|
||||
{confirmingPublish ? (
|
||||
<Alert variant="warning" title="Publicar esta versão?">
|
||||
<p className="mb-3">
|
||||
Ao publicar, esta versão passa a ser a versão ativa do template e não poderá mais ser editada — a
|
||||
publicação é permanente.
|
||||
</p>
|
||||
<div className="flex items-center gap-2">
|
||||
<Button type="button" variant="danger" onClick={handlePublish} loading={publishing}>
|
||||
Confirmar publicação
|
||||
</Button>
|
||||
<Button type="button" variant="secondary" onClick={() => setConfirmingPublish(false)}>
|
||||
Cancelar
|
||||
</Button>
|
||||
</div>
|
||||
</Alert>
|
||||
) : null}
|
||||
</form>
|
||||
</Card>
|
||||
<Card title="Histórico de versões">
|
||||
<ul className="space-y-2 text-xs">
|
||||
{[...versions]
|
||||
.sort((a, b) => b.version - a.version)
|
||||
.map((version) => (
|
||||
<li key={version.id} className="flex items-center justify-between gap-2">
|
||||
<span className="text-title">v{version.version}</span>
|
||||
<Badge variant={version.status === "draft" ? "warning" : "success"}>
|
||||
{version.status === "draft" ? "Rascunho" : "Publicado"}
|
||||
</Badge>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</Card>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function TabButton({ active, onClick, children }: { active: boolean; onClick: () => void; children: React.ReactNode }) {
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
onClick={onClick}
|
||||
className={`-mb-px border-b-2 px-3 py-2 text-sm font-semibold transition-colors ${
|
||||
active ? "border-primary text-primary" : "border-transparent text-default hover:text-title"
|
||||
}`}
|
||||
>
|
||||
{children}
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
78
apps/core-web/src/routes/documents/editor/DocumentEditor.tsx
Normal file
78
apps/core-web/src/routes/documents/editor/DocumentEditor.tsx
Normal file
@@ -0,0 +1,78 @@
|
||||
import { useEffect } from "react";
|
||||
import { EditorContent, useEditor } from "@tiptap/react";
|
||||
import type { JSONContent } from "@tiptap/react";
|
||||
import StarterKit from "@tiptap/starter-kit";
|
||||
import Underline from "@tiptap/extension-underline";
|
||||
import TextAlign from "@tiptap/extension-text-align";
|
||||
import { TextStyle, FontSize } from "@tiptap/extension-text-style";
|
||||
import Image from "@tiptap/extension-image";
|
||||
import { Table } from "@tiptap/extension-table";
|
||||
import { TableRow } from "@tiptap/extension-table-row";
|
||||
import { TableHeader } from "@tiptap/extension-table-header";
|
||||
import { TableCell } from "@tiptap/extension-table-cell";
|
||||
import type { VariableCatalogEntry } from "../../../lib/api/documents.js";
|
||||
import { MergeField } from "./mergeFieldExtension.js";
|
||||
import { PageBreak } from "./pageBreakExtension.js";
|
||||
import { EditorToolbar } from "./EditorToolbar.js";
|
||||
|
||||
/**
|
||||
* Editor de rascunho real (Tiptap) — substitui o `<textarea>` de texto puro
|
||||
* das levas anteriores. `content` é só o valor INICIAL (Tiptap é
|
||||
* não-controlado por natureza); mudanças propagam via `onChange` chamado a
|
||||
* cada transação, devolvendo `editor.getJSON()` — o mesmo formato aceito
|
||||
* por `editor_content` no backend.
|
||||
*/
|
||||
export function DocumentEditor({
|
||||
content,
|
||||
onChange,
|
||||
catalog,
|
||||
}: {
|
||||
content: JSONContent;
|
||||
onChange: (content: JSONContent) => void;
|
||||
catalog: VariableCatalogEntry[];
|
||||
}) {
|
||||
const editor = useEditor({
|
||||
extensions: [
|
||||
StarterKit,
|
||||
Underline,
|
||||
TextStyle,
|
||||
FontSize,
|
||||
TextAlign.configure({ types: ["heading", "paragraph"] }),
|
||||
Image,
|
||||
Table.configure({ resizable: false }),
|
||||
TableRow,
|
||||
TableHeader,
|
||||
TableCell,
|
||||
MergeField,
|
||||
PageBreak,
|
||||
],
|
||||
content,
|
||||
onUpdate: ({ editor: updated }) => onChange(updated.getJSON()),
|
||||
editorProps: {
|
||||
attributes: {
|
||||
class: "prose prose-sm max-w-none rounded-b-md border border-border-color bg-white p-4 text-sm text-title focus:outline-none min-h-[420px] [&_table]:border-collapse [&_td]:border [&_td]:border-border-color [&_td]:p-1.5 [&_th]:border [&_th]:border-border-color [&_th]:bg-light [&_th]:p-1.5",
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
// Rascunhos diferentes abertos no mesmo componente montado (troca de
|
||||
// template sem desmontar a página) precisam resetar o conteúdo — Tiptap
|
||||
// não observa `content` depois do mount.
|
||||
useEffect(() => {
|
||||
if (editor && content) {
|
||||
const current = JSON.stringify(editor.getJSON());
|
||||
const next = JSON.stringify(content);
|
||||
if (current !== next) editor.commands.setContent(content);
|
||||
}
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [editor]);
|
||||
|
||||
if (!editor) return null;
|
||||
|
||||
return (
|
||||
<div>
|
||||
<EditorToolbar editor={editor} catalog={catalog} />
|
||||
<EditorContent editor={editor} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
225
apps/core-web/src/routes/documents/editor/EditorToolbar.tsx
Normal file
225
apps/core-web/src/routes/documents/editor/EditorToolbar.tsx
Normal file
@@ -0,0 +1,225 @@
|
||||
import type { Editor } from "@tiptap/react";
|
||||
import type { VariableCatalogEntry } from "../../../lib/api/documents.js";
|
||||
import { VariablePickerMenu } from "./VariablePickerMenu.js";
|
||||
|
||||
const FONT_SIZES = [
|
||||
{ label: "Padrão", value: "" },
|
||||
{ label: "Pequeno", value: "10px" },
|
||||
{ label: "Grande", value: "14px" },
|
||||
{ label: "Título", value: "18px" },
|
||||
];
|
||||
|
||||
function ToolbarButton({
|
||||
active,
|
||||
disabled,
|
||||
onClick,
|
||||
title,
|
||||
children,
|
||||
}: {
|
||||
active?: boolean;
|
||||
disabled?: boolean;
|
||||
onClick: () => void;
|
||||
title: string;
|
||||
children: React.ReactNode;
|
||||
}) {
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
title={title}
|
||||
disabled={disabled}
|
||||
onClick={onClick}
|
||||
className={`flex h-8 min-w-8 items-center justify-center rounded px-1.5 text-sm font-semibold transition-colors disabled:cursor-not-allowed disabled:opacity-40 ${
|
||||
active ? "bg-primary/15 text-primary" : "text-title hover:bg-light"
|
||||
}`}
|
||||
>
|
||||
{children}
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Toolbar fiel ao print de referência (`/home/handix/editortexto.png`):
|
||||
* desfazer/refazer · parágrafo/título · tamanho de fonte · negrito/itálico/
|
||||
* sublinhado/tachado · alinhamento · listas · tabela (+ controles quando o
|
||||
* cursor está dentro de uma) · imagem · quebra de página · inserir variável.
|
||||
*/
|
||||
export function EditorToolbar({
|
||||
editor,
|
||||
catalog,
|
||||
}: {
|
||||
editor: Editor;
|
||||
catalog: VariableCatalogEntry[];
|
||||
}) {
|
||||
const insideTable = editor.isActive("table");
|
||||
|
||||
function headingValue(): string {
|
||||
if (editor.isActive("heading", { level: 1 })) return "1";
|
||||
if (editor.isActive("heading", { level: 2 })) return "2";
|
||||
if (editor.isActive("heading", { level: 3 })) return "3";
|
||||
return "p";
|
||||
}
|
||||
|
||||
function fontSizeValue(): string {
|
||||
return (editor.getAttributes("textStyle").fontSize as string | undefined) ?? "";
|
||||
}
|
||||
|
||||
function insertImage() {
|
||||
const url = window.prompt("URL da imagem (https:// ou data:)");
|
||||
if (url) editor.chain().focus().setImage({ src: url, alt: "" }).run();
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex flex-wrap items-center gap-1 rounded-t-md border border-b-0 border-border-color bg-light/50 p-2">
|
||||
<ToolbarButton title="Desfazer" onClick={() => editor.chain().focus().undo().run()} disabled={!editor.can().undo()}>
|
||||
↶
|
||||
</ToolbarButton>
|
||||
<ToolbarButton title="Refazer" onClick={() => editor.chain().focus().redo().run()} disabled={!editor.can().redo()}>
|
||||
↷
|
||||
</ToolbarButton>
|
||||
|
||||
<div className="mx-1 h-5 w-px bg-border-color" />
|
||||
|
||||
<select
|
||||
title="Parágrafo/Título"
|
||||
value={headingValue()}
|
||||
onChange={(e) => {
|
||||
const v = e.target.value;
|
||||
if (v === "p") editor.chain().focus().setParagraph().run();
|
||||
else editor.chain().focus().toggleHeading({ level: Number(v) as 1 | 2 | 3 }).run();
|
||||
}}
|
||||
className="h-8 rounded border border-border-color bg-white px-2 text-xs text-title"
|
||||
>
|
||||
<option value="p">Parágrafo</option>
|
||||
<option value="1">Título 1</option>
|
||||
<option value="2">Título 2</option>
|
||||
<option value="3">Título 3</option>
|
||||
</select>
|
||||
|
||||
<select
|
||||
title="Tamanho da fonte"
|
||||
value={fontSizeValue()}
|
||||
onChange={(e) => {
|
||||
const v = e.target.value;
|
||||
if (v) editor.chain().focus().setFontSize(v).run();
|
||||
else editor.chain().focus().unsetFontSize().run();
|
||||
}}
|
||||
className="h-8 rounded border border-border-color bg-white px-2 text-xs text-title"
|
||||
>
|
||||
{FONT_SIZES.map((f) => (
|
||||
<option key={f.label} value={f.value}>
|
||||
{f.label}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
|
||||
<div className="mx-1 h-5 w-px bg-border-color" />
|
||||
|
||||
<ToolbarButton title="Negrito" active={editor.isActive("bold")} onClick={() => editor.chain().focus().toggleBold().run()}>
|
||||
B
|
||||
</ToolbarButton>
|
||||
<ToolbarButton title="Itálico" active={editor.isActive("italic")} onClick={() => editor.chain().focus().toggleItalic().run()}>
|
||||
<span className="italic">I</span>
|
||||
</ToolbarButton>
|
||||
<ToolbarButton
|
||||
title="Sublinhado"
|
||||
active={editor.isActive("underline")}
|
||||
onClick={() => editor.chain().focus().toggleUnderline().run()}
|
||||
>
|
||||
<span className="underline">U</span>
|
||||
</ToolbarButton>
|
||||
<ToolbarButton title="Tachado" active={editor.isActive("strike")} onClick={() => editor.chain().focus().toggleStrike().run()}>
|
||||
<span className="line-through">S</span>
|
||||
</ToolbarButton>
|
||||
|
||||
<div className="mx-1 h-5 w-px bg-border-color" />
|
||||
|
||||
<ToolbarButton
|
||||
title="Alinhar à esquerda"
|
||||
active={editor.isActive({ textAlign: "left" })}
|
||||
onClick={() => editor.chain().focus().setTextAlign("left").run()}
|
||||
>
|
||||
⯇
|
||||
</ToolbarButton>
|
||||
<ToolbarButton
|
||||
title="Centralizar"
|
||||
active={editor.isActive({ textAlign: "center" })}
|
||||
onClick={() => editor.chain().focus().setTextAlign("center").run()}
|
||||
>
|
||||
☰
|
||||
</ToolbarButton>
|
||||
<ToolbarButton
|
||||
title="Alinhar à direita"
|
||||
active={editor.isActive({ textAlign: "right" })}
|
||||
onClick={() => editor.chain().focus().setTextAlign("right").run()}
|
||||
>
|
||||
⯈
|
||||
</ToolbarButton>
|
||||
<ToolbarButton
|
||||
title="Justificar"
|
||||
active={editor.isActive({ textAlign: "justify" })}
|
||||
onClick={() => editor.chain().focus().setTextAlign("justify").run()}
|
||||
>
|
||||
☷
|
||||
</ToolbarButton>
|
||||
|
||||
<div className="mx-1 h-5 w-px bg-border-color" />
|
||||
|
||||
<ToolbarButton
|
||||
title="Lista com marcadores"
|
||||
active={editor.isActive("bulletList")}
|
||||
onClick={() => editor.chain().focus().toggleBulletList().run()}
|
||||
>
|
||||
•≡
|
||||
</ToolbarButton>
|
||||
<ToolbarButton
|
||||
title="Lista numerada"
|
||||
active={editor.isActive("orderedList")}
|
||||
onClick={() => editor.chain().focus().toggleOrderedList().run()}
|
||||
>
|
||||
1≡
|
||||
</ToolbarButton>
|
||||
|
||||
<div className="mx-1 h-5 w-px bg-border-color" />
|
||||
|
||||
<ToolbarButton
|
||||
title="Inserir tabela"
|
||||
onClick={() => editor.chain().focus().insertTable({ rows: 3, cols: 3, withHeaderRow: true }).run()}
|
||||
>
|
||||
▦
|
||||
</ToolbarButton>
|
||||
{insideTable ? (
|
||||
<>
|
||||
<ToolbarButton title="Adicionar linha" onClick={() => editor.chain().focus().addRowAfter().run()}>
|
||||
+L
|
||||
</ToolbarButton>
|
||||
<ToolbarButton title="Adicionar coluna" onClick={() => editor.chain().focus().addColumnAfter().run()}>
|
||||
+C
|
||||
</ToolbarButton>
|
||||
<ToolbarButton title="Remover linha" onClick={() => editor.chain().focus().deleteRow().run()}>
|
||||
-L
|
||||
</ToolbarButton>
|
||||
<ToolbarButton title="Remover coluna" onClick={() => editor.chain().focus().deleteColumn().run()}>
|
||||
-C
|
||||
</ToolbarButton>
|
||||
<ToolbarButton title="Remover tabela" onClick={() => editor.chain().focus().deleteTable().run()}>
|
||||
✕▦
|
||||
</ToolbarButton>
|
||||
</>
|
||||
) : null}
|
||||
|
||||
<ToolbarButton title="Inserir imagem" onClick={insertImage}>
|
||||
🖼
|
||||
</ToolbarButton>
|
||||
<ToolbarButton title="Quebra de página" onClick={() => editor.chain().focus().insertPageBreak().run()}>
|
||||
⇥|
|
||||
</ToolbarButton>
|
||||
|
||||
<div className="ml-auto">
|
||||
<VariablePickerMenu
|
||||
catalog={catalog}
|
||||
onSelect={(entry) => editor.chain().focus().insertMergeField({ key: entry.key, label: entry.label }).run()}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import type { VariableCatalogEntry } from "../../../lib/api/documents.js";
|
||||
|
||||
/**
|
||||
* "Inserir variável" — não existe um componente de menu/dropdown pronto em
|
||||
* packages/ui (só `Select`, um `<select>` nativo), então este painel é
|
||||
* construído aqui, seguindo as mesmas classes Tailwind já usadas no projeto
|
||||
* (border-border-color/rounded-md/shadow).
|
||||
*/
|
||||
export function VariablePickerMenu({
|
||||
catalog,
|
||||
onSelect,
|
||||
}: {
|
||||
catalog: VariableCatalogEntry[];
|
||||
onSelect: (entry: VariableCatalogEntry) => void;
|
||||
}) {
|
||||
const [open, setOpen] = useState(false);
|
||||
const ref = useRef<HTMLDivElement>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
function handleClickOutside(event: MouseEvent) {
|
||||
if (ref.current && !ref.current.contains(event.target as Node)) setOpen(false);
|
||||
}
|
||||
document.addEventListener("mousedown", handleClickOutside);
|
||||
return () => document.removeEventListener("mousedown", handleClickOutside);
|
||||
}, [open]);
|
||||
|
||||
const categories = [...new Set(catalog.map((entry) => entry.category))];
|
||||
|
||||
return (
|
||||
<div ref={ref} className="relative inline-block">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setOpen((v) => !v)}
|
||||
className="flex items-center gap-1.5 rounded-md border border-border-color bg-white px-3 py-1.5 text-xs font-semibold text-title hover:bg-light"
|
||||
>
|
||||
<span aria-hidden>(x)</span> Inserir variável
|
||||
</button>
|
||||
{open ? (
|
||||
<div className="absolute right-0 z-20 mt-1 max-h-80 w-72 overflow-y-auto rounded-md border border-border-color bg-white p-2 shadow-lg">
|
||||
{categories.map((category) => (
|
||||
<div key={category} className="mb-2 last:mb-0">
|
||||
<p className="mb-1 px-2 text-[11px] font-bold uppercase tracking-wide text-default">{category}</p>
|
||||
{catalog
|
||||
.filter((entry) => entry.category === category)
|
||||
.map((entry) => (
|
||||
<button
|
||||
key={entry.key}
|
||||
type="button"
|
||||
onClick={() => {
|
||||
onSelect(entry);
|
||||
setOpen(false);
|
||||
}}
|
||||
className="flex w-full items-center justify-between gap-2 rounded px-2 py-1.5 text-left text-xs text-title hover:bg-light"
|
||||
>
|
||||
<span>{entry.label}</span>
|
||||
{entry.required ? <span className="text-[10px] font-semibold text-warning">obrigatório</span> : null}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
import { mergeAttributes, Node } from "@tiptap/core";
|
||||
import { ReactNodeViewRenderer, NodeViewWrapper } from "@tiptap/react";
|
||||
import type { ReactNodeViewProps } from "@tiptap/react";
|
||||
|
||||
/**
|
||||
* Nó Tiptap customizado para variáveis inseridas via catálogo fechado
|
||||
* (`../variableCatalog.ts`) — nunca texto livre `{{variavel}}` digitado à
|
||||
* mão (eden.md §3.1). `attrs.key` é o que o backend resolve
|
||||
* (apps/api/src/documents/editor-content-renderer.ts); `attrs.label` é só
|
||||
* exibição, nunca interpretado no servidor.
|
||||
*/
|
||||
export interface MergeFieldAttrs {
|
||||
key: string;
|
||||
label: string;
|
||||
}
|
||||
|
||||
declare module "@tiptap/core" {
|
||||
interface Commands<ReturnType> {
|
||||
mergeField: {
|
||||
insertMergeField: (attrs: MergeFieldAttrs) => ReturnType;
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
function MergeFieldChip({ node }: ReactNodeViewProps<HTMLElement>) {
|
||||
const attrs = node.attrs as MergeFieldAttrs;
|
||||
return (
|
||||
<NodeViewWrapper as="span" className="inline-block align-baseline">
|
||||
<span className="rounded border border-primary/30 bg-primary/10 px-1.5 py-0.5 text-xs font-medium text-primary">
|
||||
{attrs.label || attrs.key}
|
||||
</span>
|
||||
</NodeViewWrapper>
|
||||
);
|
||||
}
|
||||
|
||||
export const MergeField = Node.create({
|
||||
name: "mergeField",
|
||||
group: "inline",
|
||||
inline: true,
|
||||
atom: true,
|
||||
selectable: true,
|
||||
|
||||
addAttributes() {
|
||||
return {
|
||||
key: { default: "" },
|
||||
label: { default: "" },
|
||||
};
|
||||
},
|
||||
|
||||
parseHTML() {
|
||||
return [{ tag: 'span[data-merge-field]' }];
|
||||
},
|
||||
|
||||
renderHTML({ HTMLAttributes }) {
|
||||
return ["span", mergeAttributes(HTMLAttributes, { "data-merge-field": HTMLAttributes.key }), HTMLAttributes.label];
|
||||
},
|
||||
|
||||
addNodeView() {
|
||||
return ReactNodeViewRenderer(MergeFieldChip);
|
||||
},
|
||||
|
||||
addCommands() {
|
||||
return {
|
||||
insertMergeField:
|
||||
(attrs: MergeFieldAttrs) =>
|
||||
({ commands }) =>
|
||||
commands.insertContent({ type: this.name, attrs }),
|
||||
};
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,37 @@
|
||||
import { mergeAttributes, Node } from "@tiptap/core";
|
||||
|
||||
/**
|
||||
* Nó de bloco "quebra de página" — vira `<div style="break-after:page;
|
||||
* page-break-after:always;">` no PDF final (ver renderBlock em
|
||||
* apps/api/src/documents/editor-content-renderer.ts, case 'pageBreak').
|
||||
* No editor, renderiza como uma régua tracejada não editável.
|
||||
*/
|
||||
declare module "@tiptap/core" {
|
||||
interface Commands<ReturnType> {
|
||||
pageBreak: {
|
||||
insertPageBreak: () => ReturnType;
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
export const PageBreak = Node.create({
|
||||
name: "pageBreak",
|
||||
group: "block",
|
||||
atom: true,
|
||||
selectable: true,
|
||||
|
||||
parseHTML() {
|
||||
return [{ tag: "div.page-break" }];
|
||||
},
|
||||
|
||||
renderHTML({ HTMLAttributes }) {
|
||||
return [
|
||||
"div",
|
||||
mergeAttributes(HTMLAttributes, {
|
||||
class: "page-break my-2 border-t-2 border-dashed border-border-color py-1 text-center text-[10px] uppercase tracking-wide text-default",
|
||||
"data-page-break": "true",
|
||||
}),
|
||||
"Quebra de página",
|
||||
];
|
||||
},
|
||||
});
|
||||
Reference in New Issue
Block a user