@1urso/generic-editor 0.1.9 → 0.1.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/README.md +129 -129
  2. package/package.json +1 -1
package/README.md CHANGED
@@ -1,141 +1,141 @@
1
1
  # Generic Editor
2
2
 
3
- Uma biblioteca React poderosa, agnóstica de framework e **100% personalizável** para criação de layouts dinâmicos, geração de templates e edição visual. Projetada para ser o motor de design dentro da sua aplicação (Web, Electron, Tauri, Next.js, etc.).
3
+ A powerful, framework-agnostic, and **100% customizable** React library for creating dynamic layouts, template generation, and visual editing. Designed to be the design engine within your application (Web, Electron, Tauri, Next.js, etc.).
4
4
 
5
5
  ---
6
6
 
7
- ## 📚 Índice
8
-
9
- 1. [Instalação e Configuração](#instalação-e-configuração)
10
- 2. [Guia do Usuário (Interface Visual)](#guia-do-usuário-interface-visual)
11
- - [Manipulação Básica](#manipulação-básica)
12
- - [Menu de Contexto e Estilização](#menu-de-contexto-e-estilização)
13
- - [Trabalhando com Textos e Fontes](#trabalhando-com-textos-e-fontes)
14
- - [Trabalhando com Imagens](#trabalhando-com-imagens)
15
- 3. [Guia do Desenvolvedor (Integração)](#guia-do-desenvolvedor-integração)
16
- - [Inicialização e Props](#inicialização-e-props)
17
- - [Data Binding e Variáveis](#data-binding-e-variáveis)
18
- - [Modos: Item Único vs. Lista](#modos-item-único-vs-lista)
19
- - [Estrutura do JSON](#estrutura-do-json)
20
- - [Gerando HTML (Backend/Print)](#gerando-html-backendprint)
7
+ ## 📚 Table of Contents
8
+
9
+ 1. [Installation and Configuration](#installation-and-configuration)
10
+ 2. [User Guide (Visual Interface)](#user-guide-visual-interface)
11
+ - [Basic Manipulation](#basic-manipulation)
12
+ - [Context Menu and Styling](#context-menu-and-styling)
13
+ - [Working with Text and Fonts](#working-with-text-and-fonts)
14
+ - [Working with Images](#working-with-images)
15
+ 3. [Developer Guide (Integration)](#developer-guide-integration)
16
+ - [Initialization and Props](#initialization-and-props)
17
+ - [Data Binding and Variables](#data-binding-and-variables)
18
+ - [Modes: Single Item vs. List](#modes-single-item-vs-list)
19
+ - [JSON Structure](#json-structure)
20
+ - [Generating HTML (Backend/Print)](#generating-html-backendprint)
21
21
  4. [API Reference](#api-reference)
22
22
 
23
23
  ---
24
24
 
25
- ## Instalação e Configuração
25
+ ## Installation and Configuration
26
26
 
27
- ### 1. Instale o pacote
27
+ ### 1. Install the package
28
28
 
29
29
  ```bash
30
30
  npm install @1urso/generic-editor
31
- # ou
31
+ # or
32
32
  yarn add @1urso/generic-editor
33
33
  ```
34
34
 
35
- ### 2. Instale as dependências (Peer Dependencies)
35
+ ### 2. Install Peer Dependencies
36
36
 
37
- O editor utiliza bibliotecas modernas para garantir performance e acessibilidade. Você precisa instalá-las no seu projeto:
37
+ The editor uses modern libraries to ensure performance and accessibility. You need to install them in your project:
38
38
 
39
39
  ```bash
40
40
  npm install @radix-ui/themes @radix-ui/react-icons react-resizable-panels re-resizable framer-motion @dnd-kit/core
41
41
  ```
42
42
 
43
- ### 3. Importe os Estilos
43
+ ### 3. Import Styles
44
44
 
45
- No arquivo de entrada da sua aplicação (ex: `main.tsx`, `App.tsx` ou `layout.tsx` no Next.js), importe o CSS do editor (obrigatório para o menu de contexto) e do Radix UI:
45
+ In your application entry file (e.g., `main.tsx`, `App.tsx`, or `layout.tsx` in Next.js), import the editor's CSS (required for the context menu) and Radix UI:
46
46
 
47
47
  ```tsx
48
- import "@1urso/generic-editor/dist/generic-editor.css"; // Essencial para o funcionamento do editor
48
+ import "@1urso/generic-editor/dist/generic-editor.css"; // Essential for the editor to work
49
49
  import "@radix-ui/themes/styles.css";
50
50
  ```
51
51
 
52
52
  ---
53
53
 
54
- ## Guia do Usuário (Interface Visual)
54
+ ## User Guide (Visual Interface)
55
55
 
56
- Esta seção descreve as funcionalidades disponíveis para o **usuário final** que utilizará o editor na sua plataforma.
56
+ This section describes the features available to the **end user** who will use the editor on your platform.
57
57
 
58
- ### Manipulação Básica
58
+ ### Basic Manipulation
59
59
 
60
- O editor oferece uma experiência similar a ferramentas de design como Canva ou Figma:
60
+ The editor offers an experience similar to design tools like Canva or Figma:
61
61
 
62
- - **Adicionar Elementos**: Utilize a barra lateral (ou botões que você implementar) para arrastar ou clicar e adicionar Textos, Imagens ou Caixas.
63
- - **Mover**: Clique e arraste qualquer elemento para reposicioná-lo.
64
- - **Redimensionar**: Clique no elemento para selecioná-lo. Puxe as alças (quadrados azuis) nas bordas ou cantos para alterar o tamanho.
65
- - **Rotacionar**: Ao selecionar um elemento, uma alça circular aparecerá acima dele. Clique e arraste para girar livremente.
66
- - **Deletar**: Selecione um elemento e pressione a tecla `Delete` ou use o menu de contexto.
62
+ - **Add Elements**: Use the sidebar (or buttons you implement) to drag or click and add Texts, Images, or Boxes.
63
+ - **Move**: Click and drag any element to reposition it.
64
+ - **Resize**: Click on the element to select it. Pull the handles (blue squares) on the edges or corners to change the size.
65
+ - **Rotate**: When selecting an element, a circular handle will appear above it. Click and drag to rotate freely.
66
+ - **Delete**: Select an element and press the `Delete` key or use the context menu.
67
67
 
68
- ### Menu de Contexto e Estilização
68
+ ### Context Menu and Styling
69
69
 
70
- **Clique com o botão direito** em qualquer elemento para abrir o menu de opções avançadas.
70
+ **Right-click** on any element to open the advanced options menu.
71
71
 
72
- #### Opções Gerais (Todos os Elementos)
72
+ #### General Options (All Elements)
73
73
 
74
- - **Duplicar**: Cria uma cópia exata do elemento próximo ao original.
75
- - **Remover**: Exclui o elemento.
76
- - **Camadas**:
77
- - _Trazer para frente_: Coloca o elemento sobre todos os outros.
78
- - _Enviar para trás_: Coloca o elemento atrás de todos.
79
- - **Cor de Fundo**: Altera a cor de fundo do elemento (inclui transparente).
80
- - **Bordas**:
81
- - _Arredondamento_: De 0px (quadrado) até 50% (círculo/oval).
82
- - _Espessura_: Adiciona borda sólida de 1px a 4px.
74
+ - **Duplicate**: Creates an exact copy of the element next to the original.
75
+ - **Remove**: Deletes the element.
76
+ - **Layers**:
77
+ - _Bring to front_: Places the element above all others.
78
+ - _Send to back_: Places the element behind all others.
79
+ - **Background Color**: Changes the background color of the element (includes transparent).
80
+ - **Borders**:
81
+ - _Radius_: From 0px (square) to 50% (circle/oval).
82
+ - _Thickness_: Adds a solid border from 1px to 4px.
83
83
 
84
- ### Configurações e Dados de Teste
84
+ ### Settings and Test Data
85
85
 
86
- No topo da barra lateral esquerda, o botão **Configurações** (ícone de engrenagem) permite simular como o layout ficará com dados reais.
86
+ At the top of the left sidebar, the **Settings** button (gear icon) allows you to simulate how the layout will look with real data.
87
87
 
88
- - **Aba Configuração da Lista**:
89
- - _Propriedade para Ordenar_: Define qual campo será usado para ordenar a lista (ex: `preco`, `nome`).
90
- - _Ordem_: Crescente ou Decrescente.
91
- - **Aba Dados Mockados**:
92
- - _Dados para Lista_: Um array JSON `[...]` para testar o modo lista.
93
- - _Dados Únicos_: Um objeto JSON `{...}` para testar o modo único.
94
- > Edite esses JSONs para ver o layout reagir em tempo real às suas variáveis.
88
+ - **List Configuration Tab**:
89
+ - _Sort Property_: Defines which field will be used to sort the list (e.g., `price`, `name`).
90
+ - _Order_: Ascending or Descending.
91
+ - **Mock Data Tab**:
92
+ - _List Data_: A JSON array `[...]` to test list mode.
93
+ - _Single Data_: A JSON object `{...}` to test single mode.
94
+ > Edit these JSONs to see the layout react in real-time to your variables.
95
95
 
96
- ### Trabalhando com Textos e Fontes
96
+ ### Working with Text and Fonts
97
97
 
98
- Ao clicar com o botão direito em um elemento de **Texto**:
98
+ When right-clicking on a **Text** element:
99
99
 
100
- - **Editar Texto**: Abre uma janela para digitar o conteúdo. É aqui que você insere variáveis (ex: Nome do Cliente) clicando nos botões disponíveis.
101
- - **Fonte**: Selecione entre diversas fontes seguras para web (Arial, Helvetica, etc) e Google Fonts populares (Roboto, Open Sans, Montserrat).
102
- - _Importar Google Font_: Permite digitar o nome de qualquer fonte do Google Fonts (ex: "Pacifico") e o editor a carregará automaticamente.
103
- - **Tamanho**: Ajuste de 12px a 64px.
104
- - **Cor do Texto**: Paleta de cores pré-definida.
105
- - **Peso**: Normal ou Negrito.
106
- - **Alinhamento**: Esquerda, Centro ou Direita.
100
+ - **Edit Text**: Opens a window to type content. This is where you insert variables (e.g., Customer Name) by clicking on the available buttons.
101
+ - **Font**: Select from various web-safe fonts (Arial, Helvetica, etc.) and popular Google Fonts (Roboto, Open Sans, Montserrat).
102
+ - _Import Google Font_: Allows you to type the name of any Google Fonts font (e.g., "Pacifico") and the editor will automatically load it.
103
+ - **Size**: Adjust from 12px to 64px.
104
+ - **Text Color**: Pre-defined color palette.
105
+ - **Weight**: Normal or Bold.
106
+ - **Alignment**: Left, Center, or Right.
107
107
 
108
- ### Trabalhando com Imagens
108
+ ### Working with Images
109
109
 
110
- Ao clicar com o botão direito em um elemento de **Imagem**:
110
+ When right-clicking on an **Image** element:
111
111
 
112
- - **Alterar Imagem**:
113
- - _Upload_: Carregue uma imagem do seu computador.
114
- - _URL_: Cole um link direto para uma imagem da web.
115
- - **Ajuste (Object Fit)**:
116
- - _Ajustar (Contain)_: A imagem inteira é mostrada dentro da caixa, mantendo a proporção (pode sobrar espaço em branco).
117
- - _Esticar (Fill)_: A imagem preenche toda a caixa, podendo ser cortada ou distorcida dependendo da proporção.
118
- - **Vincular Dados**: Conecta a imagem a uma variável dinâmica (ex: Foto do Produto).
112
+ - **Change Image**:
113
+ - _Upload_: Upload an image from your computer.
114
+ - _URL_: Paste a direct link to an image from the web.
115
+ - **Fit (Object Fit)**:
116
+ - _Fit (Contain)_: The entire image is shown inside the box, maintaining proportions (may leave white space).
117
+ - _Stretch (Fill)_: The image fills the entire box, potentially being cropped or distorted depending on the aspect ratio.
118
+ - **Bind Data**: Connects the image to a dynamic variable (e.g., Product Photo).
119
119
 
120
120
  ---
121
121
 
122
- ## Guia do Desenvolvedor (Integração)
122
+ ## Developer Guide (Integration)
123
123
 
124
- ### Inicialização e Props
124
+ ### Initialization and Props
125
125
 
126
- Para iniciar o editor, você deve fornecer a configuração de `layout` que dita quais dados (variáveis) estarão disponíveis para o usuário.
126
+ To start the editor, you must provide the `layout` configuration which dictates what data (variables) will be available to the user.
127
127
 
128
128
  ```tsx
129
129
  import { EditorContent } from "@1urso/generic-editor";
130
130
 
131
131
  const config = {
132
- isList: false, // Modo único (ex: Crachá) ou Lista (ex: Catálogo)
133
- name: "Crachá de Funcionário",
132
+ isList: false, // Single mode (e.g., ID Card) or List (e.g., Catalog)
133
+ name: "Employee ID Card",
134
134
  props: [
135
- // Define as variáveis que aparecerão no botão "Inserir Variável"
136
- { name: "Nome Completo", dataName: "nome" },
137
- { name: "Cargo", dataName: "cargo" },
138
- { name: "Foto de Perfil", dataName: "fotoUrl" },
135
+ // Define the variables that will appear in the "Insert Variable" button
136
+ { name: "Full Name", dataName: "nome" },
137
+ { name: "Role", dataName: "cargo" },
138
+ { name: "Profile Picture", dataName: "fotoUrl" },
139
139
  ],
140
140
  };
141
141
 
@@ -145,44 +145,44 @@ function App() {
145
145
  <EditorContent
146
146
  layout={config}
147
147
  onSave={(json) => saveToBackend(json)}
148
- theme="light" // Opcional: 'light' ou 'dark'
148
+ theme="light" // Optional: 'light' or 'dark'
149
149
  />
150
150
  </div>
151
151
  );
152
152
  }
153
153
  ```
154
154
 
155
- ### Data Binding e Variáveis
155
+ ### Data Binding and Variables
156
156
 
157
- O editor utiliza um sistema de interpolação baseado em chaves duplas `{{chave}}`.
157
+ The editor uses an interpolation system based on double braces `{{key}}`.
158
158
 
159
- 1. **Inserção**: O usuário não precisa digitar `{{...}}` manualmente. Na janela de edição de texto, ele verá botões (badges) com os nomes amigáveis (ex: "Nome Completo"). Ao clicar, o código `{{nome}}` é inserido.
160
- 2. **Renderização**:
161
- - Se `data = { nome: "Maria" }`, o texto "Olá {{nome}}" vira "Olá Maria".
162
- - Se a variável não existir nos dados, o editor mantém o texto original `{{nome}}` ou exibe vazio, dependendo da configuração.
159
+ 1. **Insertion**: The user does not need to type `{{...}}` manually. In the text edit window, they will see buttons (badges) with friendly names (e.g., "Full Name"). Clicking them inserts the `{{nome}}` code.
160
+ 2. **Rendering**:
161
+ - If `data = { nome: "Maria" }`, the text "Hello {{nome}}" becomes "Hello Maria".
162
+ - If the variable does not exist in the data, the editor keeps the original text `{{nome}}` or displays empty, depending on the configuration.
163
163
 
164
- ### Modos: Item Único vs. Lista
164
+ ### Modes: Single Item vs. List
165
165
 
166
- A propriedade `isList` muda drasticamente como o editor e o gerador de HTML se comportam.
166
+ The `isList` property drastically changes how the editor and HTML generator behave.
167
167
 
168
- #### `isList: false` (Modo Único)
168
+ #### `isList: false` (Single Mode)
169
169
 
170
- - **Uso**: Certificados, Crachás, Banners, Capas.
171
- - **Dados**: Espera um **Objeto Único** `{ nome: 'João', cargo: 'Dev' }`.
172
- - **Canvas**: Mostra uma única página/arte.
170
+ - **Usage**: Certificates, ID Cards, Banners, Covers.
171
+ - **Data**: Expects a **Single Object** `{ nome: 'John', cargo: 'Dev' }`.
172
+ - **Canvas**: Shows a single page/art.
173
173
 
174
- #### `isList: true` (Modo Lista)
174
+ #### `isList: true` (List Mode)
175
175
 
176
- - **Uso**: Listas de Preços, Catálogos, Etiquetas de Gôndola, Relatórios.
177
- - **Dados**: Espera um **Array de Objetos** `[{ nome: 'A' }, { nome: 'B' }]`.
176
+ - **Usage**: Price Lists, Catalogs, Shelf Labels, Reports.
177
+ - **Data**: Expects an **Array of Objects** `[{ nome: 'A' }, { nome: 'B' }]`.
178
178
  - **Canvas**:
179
- - O usuário desenha o "Item Modelo" (Template).
180
- - O editor repete esse modelo verticalmente para cada item do array de dados mockados.
181
- - Permite visualizar como a lista se comporta com múltiplos itens.
179
+ - The user designs the "Template Item".
180
+ - The editor repeats this model vertically for each item in the mock data array.
181
+ - Allows visualization of how the list behaves with multiple items.
182
182
 
183
- ### Estrutura do JSON
183
+ ### JSON Structure
184
184
 
185
- O output do `onSave` é um JSON pronto para ser armazenado.
185
+ The output of `onSave` is a JSON ready to be stored.
186
186
 
187
187
  ```json
188
188
  {
@@ -191,7 +191,7 @@ O output do `onSave` é um JSON pronto para ser armazenado.
191
191
  {
192
192
  "id": "uuid-v4",
193
193
  "type": "text", // 'text' | 'image' | 'box'
194
- "content": "Nome: {{nome}}",
194
+ "content": "Name: {{nome}}",
195
195
  "x": 50,
196
196
  "y": 100,
197
197
  "width": 200,
@@ -203,7 +203,7 @@ O output do `onSave` é um JSON pronto para ser armazenado.
203
203
  "fontFamily": "Roboto",
204
204
  "textAlign": "center"
205
205
  },
206
- "dataBinding": "nome" // Opcional, usado para vínculo direto
206
+ "dataBinding": "nome" // Optional, used for direct binding
207
207
  }
208
208
  ],
209
209
  "listSettings": {
@@ -213,24 +213,24 @@ O output do `onSave` é um JSON pronto para ser armazenado.
213
213
  }
214
214
  ```
215
215
 
216
- ### Gerando HTML (Backend/Print)
216
+ ### Generating HTML (Backend/Print)
217
217
 
218
- Para gerar o resultado final (para imprimir, salvar PDF ou enviar por email), use a função `generateHTML`. Ela roda em qualquer ambiente JS (Node, Browser, etc).
218
+ To generate the final result (for printing, saving as PDF, or sending via email), use the `generateHTML` function. It runs in any JS environment (Node, Browser, etc.).
219
219
 
220
220
  ```typescript
221
221
  import { generateHTML } from "@1urso/generic-editor";
222
222
 
223
- // 1. Carregue o layout e os dados
223
+ // 1. Load layout and data
224
224
  const layout = JSON.parse(db.getLayout());
225
- const dados = db.getFuncionarios(); // Array ou Objeto
225
+ const dados = db.getFuncionarios(); // Array or Object
226
226
 
227
- // 2. Gere o HTML
227
+ // 2. Generate HTML
228
228
  const htmlString = generateHTML(layout.elements, dados, {
229
- isList: layout.isList, // Importante passar o modo correto
229
+ isList: layout.isList, // Important to pass the correct mode
230
230
  listSettings: layout.listSettings,
231
231
  });
232
232
 
233
- // 3. Injete onde precisar
233
+ // 3. Inject where needed
234
234
  document.getElementById("preview").innerHTML = htmlString;
235
235
  ```
236
236
 
@@ -238,24 +238,24 @@ document.getElementById("preview").innerHTML = htmlString;
238
238
 
239
239
  ## API Reference
240
240
 
241
- ### Componente `<EditorContent />`
241
+ ### Component `<EditorContent />`
242
242
 
243
- | Propriedade | Tipo | Obrigatório | Padrão | Descrição |
244
- | -------------- | ------------------------ | ----------- | ------ | --------------------------------------------- |
245
- | `layout` | `ILayout` | **Sim** | - | Configuração inicial das variáveis e modo. |
246
- | `initialState` | `any` | Não | `null` | Estado JSON para carregar um layout salvo. |
247
- | `onSave` | `(json: string) => void` | Não | - | Callback acionado ao clicar no botão Salvar. |
248
- | `mockData` | `any[]` | Não | `[]` | Dados para preview imediato durante a edição. |
243
+ | Property | Type | Required | Default | Description |
244
+ | -------------- | ------------------------ | -------- | ------- | --------------------------------------------- |
245
+ | `layout` | `ILayout` | **Yes** | - | Initial configuration of variables and mode. |
246
+ | `initialState` | `any` | No | `null` | JSON state to load a saved layout. |
247
+ | `onSave` | `(json: string) => void` | No | - | Callback triggered when clicking Save button. |
248
+ | `mockData` | `any[]` | No | `[]` | Data for immediate preview during editing. |
249
249
 
250
- ### Tipos TypeScript
250
+ ### TypeScript Types
251
251
 
252
252
  #### `ILayout`
253
253
 
254
254
  ```typescript
255
255
  interface ILayout {
256
- name: string; // Nome do layout (metadado)
257
- isList?: boolean; // Define o comportamento padrão (Lista ou Único)
258
- props: IProp[]; // Lista de variáveis disponíveis
256
+ name: string; // Layout name (metadata)
257
+ isList?: boolean; // Defines default behavior (List or Single)
258
+ props: IProp[]; // List of available variables
259
259
  }
260
260
  ```
261
261
 
@@ -263,16 +263,16 @@ interface ILayout {
263
263
 
264
264
  ```typescript
265
265
  interface IProp {
266
- name: string; // Rótulo visível (ex: "Preço do Produto")
267
- dataName: string; // Chave do objeto (ex: "product_price")
266
+ name: string; // Visible label (e.g., "Product Price")
267
+ dataName: string; // Object key (e.g., "product_price")
268
268
  }
269
269
  ```
270
270
 
271
271
  #### `EditorProps`
272
272
 
273
- | Prop | Tipo | Obrigatório | Descrição |
274
- | -------------- | ------------------------ | ----------- | ------------------------------------------- |
275
- | `layout` | `ILayout` | Sim | Configuração inicial e metadados. |
276
- | `onSave` | `(json: string) => void` | Não | Callback disparado ao salvar. |
277
- | `initialState` | `any` | Não | Estado salvo anteriormente (JSON parseado). |
278
- | `theme` | `'light' \| 'dark'` | Não | Tema da interface (padrão: `'light'`). |
273
+ | Prop | Type | Required | Description |
274
+ | -------------- | ------------------------ | -------- | ------------------------------------- |
275
+ | `layout` | `ILayout` | Yes | Initial configuration and metadata. |
276
+ | `onSave` | `(json: string) => void` | No | Callback triggered on save. |
277
+ | `initialState` | `any` | No | Previously saved state (parsed JSON). |
278
+ | `theme` | `'light' \| 'dark'` | No | Interface theme (default: `'light'`). |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@1urso/generic-editor",
3
- "version": "0.1.9",
3
+ "version": "0.1.10",
4
4
  "publishConfig": {
5
5
  "access": "public"
6
6
  },