@easyling/sanity-connector 0.0.2 → 0.0.3

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.
package/README.md CHANGED
@@ -1,19 +1,18 @@
1
1
  # Sanity Translation Plugin
2
2
 
3
- A Sanity Studio plugin that enables document translation functionality with support for single and bulk operations. The plugin extracts document content as HTML and prepares translation requests for external translation services.
3
+ A Sanity Studio plugin that enables seamless document translation workflows. It extracts content as HTML, manages translation requests to external services, and handles the re-import of translated content while preserving Portable Text structures.
4
4
 
5
5
  ## Features
6
6
 
7
- - **Single Document Translation**: Translate individual documents with user confirmation
8
- - **Bulk Translation**: Translate multiple documents in batch operations
9
- - **Document Creation**: Automatically create new translated documents
10
- - **HTML Content Extraction**: Convert Sanity portable text to HTML format
11
- - **Portable Text Conversion**: Convert HTML responses back to Sanity portable text
12
- - **Translation-Invariant Fields**: Mark specific fields as non-translatable using the `dnt` (Do Not Translate) flag
13
- - **DNT Field Management UI**: User-friendly document action to manage which fields should not be translated
14
- - **Comprehensive Validation**: Multi-layer validation and error handling
15
- - **Progress Tracking**: Real-time progress updates for bulk operations
16
- - **Error Handling**: Detailed error reporting and rollback support
7
+ - **Single Document Translation**: Translate individual documents directly from the document form.
8
+ - **Bulk Translation**: Batch process multiple documents via a dedicated tool.
9
+ - **Smart Content Extraction**: Converts Sanity Portable Text to HTML for translation and back again.
10
+ - **Translation Invariance**: granular control over what gets translated via "Do Not Translate" (DNT) flags.
11
+ - **Inline Badges**: Toggle translation status for individual fields directly in the editor.
12
+ - **Field Management**: dedicated action to manage DNT status across the whole document.
13
+ - **Authentication Support**: Secure OAuth integration with translation services, with a legacy mode for local testing.
14
+ - **Auto-Configuration**: Intelligent defaults for new installations to get you started quickly.
15
+ - **Progress Tracking**: Real-time feedback for long-running bulk operations.
17
16
 
18
17
  ## Installation
19
18
 
@@ -32,7 +31,7 @@ import translationPlugin from 'sanity-translation-plugin'
32
31
  export default defineConfig({
33
32
  // ... your other config
34
33
  plugins: [
35
- // ... your other plugins
34
+ // ... other plugins
36
35
  translationPlugin()
37
36
  ]
38
37
  })
@@ -40,443 +39,84 @@ export default defineConfig({
40
39
 
41
40
  ## Configuration
42
41
 
43
- The plugin works with a placeholder endpoint by default for testing purposes. In production, you'll need to configure it with your translation service endpoint.
42
+ ### Authentication & Connection
44
43
 
45
- ### Basic Configuration
44
+ The plugin supports two modes of operation:
46
45
 
47
- ```typescript
48
- import translationPlugin from 'sanity-translation-plugin'
49
-
50
- export default defineConfig({
51
- plugins: [
52
- translationPlugin({
53
- // Plugin configuration options will be available in future versions
54
- // Currently uses placeholder endpoint for testing
55
- })
56
- ]
57
- })
58
- ```
59
-
60
- ### Translation Service Requirements
61
-
62
- Your translation service should accept POST requests with the following payload structure:
63
-
64
- ```json
65
- {
66
- "content": "<h1>Document content in HTML format</h1>",
67
- "format": "html",
68
- "metadata": {
69
- "documentId": "document-id",
70
- "documentType": "document-type",
71
- "title": "Document Title",
72
- "sourceLanguage": "en",
73
- "targetLanguage": "es"
74
- }
75
- }
76
- ```
77
-
78
- And return responses in this format:
79
-
80
- ```json
81
- {
82
- "success": true,
83
- "translatedContent": {
84
- "body": "<h1>Translated HTML content</h1>",
85
- "title": "Translated Title",
86
- "slug": "translated-slug",
87
- "fields": {}
88
- },
89
- "requestId": "optional-request-id"
90
- }
91
- ```
46
+ 1. **OAuth Mode (Recommended for Production)**:
47
+ - Uses secure token-based authentication.
48
+ - Configurable via the **OAuth Configuration** tool within Sanity Studio.
49
+ - Supports project-specific access control.
92
50
 
93
- ## Translation Service Integration
51
+ 2. **Legacy/Development Mode**:
52
+ - Default behavior out of the box.
53
+ - Points to `http://app.easyling.com` by default.
54
+ - Useful for local development and testing without setting up full auth.
94
55
 
95
- This plugin requires an external translation service that implements the specified API format.
56
+ To configure the plugin for production use, navigate to the **Easyling Translation Plugin Configuration** document type in your Sanity Studio after installation, and create a new configuration. Enter your project code and access token (both are available in the Easyling platform), and publish your configuration.
96
57
 
97
- ### Quick Start with Example Service
58
+ Next, navigate to the **Locales** tab of the configuration, and add the locales you wish to handle. These are the ones you will be able to translate your content into.
98
59
 
99
- 1. **Start the example translation service:**
100
- ```bash
101
- cd examples
102
- npm install
103
- npm start
104
- ```
60
+ At this point, you're ready to begin processing content, but if you want, you can add translation-invariant fields for your content types, by toggling the badges on the individual fields.
105
61
 
106
- 2. **Configure the plugin** to use `http://localhost:8275/translate` as the endpoint
62
+ ### Defaults
107
63
 
108
- 3. **Test translation** using the document actions in Sanity Studio
109
-
110
- ### Documentation
111
-
112
- - **[Translation Service API Documentation](./docs/translation-service-api.md)** - Complete API specification
113
- - **[JSON Schema](./docs/translation-response-schema.json)** - Response format validation
114
- - **[Example Implementation](./examples/)** - Working example service
115
- - **[Documentation Overview](./docs/README.md)** - All documentation files
116
-
117
- ### Expected Response Format
118
-
119
- Your translation service must return responses in this format:
120
-
121
- **Success Response:**
122
- ```json
123
- {
124
- "success": true,
125
- "translatedContent": {
126
- "body": "<h1>Translated HTML content</h1>",
127
- "title": "Translated Title",
128
- "slug": "translated-slug",
129
- "fields": {}
130
- },
131
- "requestId": "optional-request-id"
132
- }
133
- ```
134
-
135
- **Error Response:**
136
- ```json
137
- {
138
- "success": false,
139
- "error": "Error message describing the failure",
140
- "requestId": "optional-request-id"
141
- }
142
- ```
64
+ The plugin comes with "Auto-Default" behavior. When you install it for the first time, it will automatically select sensible defaults (like "Draft" mode for new translated documents) so you can start using it immediately without manual configuration.
143
65
 
144
66
  ## Usage
145
67
 
146
68
  ### Single Document Translation
147
69
 
148
- 1. **Open a document** in Sanity Studio that you want to translate
149
- 2. **Click the "Translate" action** button in the document toolbar (appears as a translate icon)
150
- 3. **Review the confirmation dialog** showing the document details
151
- 4. **Click "Translate"** to proceed with the translation
152
- 5. **Monitor the progress** - the plugin will show loading states during processing
153
- 6. **View results** - translation requests are logged to the browser console for testing
154
-
155
- **Example workflow:**
156
- ```
157
- Document: "Welcome Post" (blog post)
158
- ↓ Extract content as HTML
159
- ↓ Prepare translation request
160
- ↓ Log request to console (for testing)
161
- ↓ Show success confirmation
162
- ```
70
+ 1. Open a document in Sanity Studio.
71
+ 2. Click the **Translate** icon in the document toolbar.
72
+ 3. Review the document details in the confirmation dialog.
73
+ 4. Click **Translate**.
74
+ 5. The plugin will process the translation and inform you when complete.
163
75
 
164
76
  ### Bulk Translation
165
77
 
166
- 1. **Open the "Bulk Translate" tool** from the Sanity Studio tools menu
167
- 2. **Select document types** you want to translate (e.g., "post", "page")
168
- 3. **Choose specific documents** from the filtered list
169
- 4. **Click "Translate X Documents"** where X is the number of selected documents
170
- 5. **Confirm the bulk operation** in the dialog
171
- 6. **Monitor progress** with the real-time progress indicator
172
- 7. **Review results** in the summary report
173
-
174
- **Example workflow:**
175
- ```
176
- Selected: 5 blog posts
177
- ↓ Extract content from each document
178
- ↓ Prepare 5 translation requests
179
- ↓ Process requests (logged to console)
180
- ↓ Show summary: "5 documents processed successfully"
181
- ```
182
-
183
- ### Testing the Plugin
184
-
185
- Since the plugin uses a placeholder endpoint for testing:
186
-
187
- 1. **Open browser developer tools** to view the console
188
- 2. **Perform translation actions** (single or bulk)
189
- 3. **Check console logs** to see the prepared translation requests
190
- 4. **Verify request format** matches your translation service expectations
191
-
192
- **Console output example:**
193
- ```javascript
194
- [Translation Plugin] Request prepared for document: welcome-post
195
- {
196
- "content": "<h1>Welcome to our blog</h1><p>This is our first post...</p>",
197
- "format": "html",
198
- "metadata": {
199
- "documentId": "welcome-post",
200
- "documentType": "post",
201
- "title": "Welcome to our blog"
202
- }
203
- }
204
- ```
205
-
206
- ## Development
207
-
208
- ### Building the Plugin
209
-
210
- ```bash
211
- # Install dependencies
212
- npm install
213
-
214
- # Build the plugin
215
- npm run build
216
-
217
- # Build and watch for changes
218
- npm run dev
219
-
220
- # Run tests
221
- npm run test
222
-
223
- # Run tests with coverage
224
- npm run test:coverage
225
-
226
- # Lint code
227
- npm run lint
228
-
229
- # Fix linting issues
230
- npm run lint:fix
231
- ```
232
-
233
- ### Project Structure
234
-
235
- ```
236
- sanity-translation-plugin/
237
- ├── src/
238
- │ ├── index.ts # Plugin entry point
239
- │ ├── plugin.ts # Main plugin definition
240
- │ ├── actions/
241
- │ │ ├── translateDocument.ts # Single document translation
242
- │ │ └── bulkTranslate.ts # Bulk translation tool
243
- │ ├── services/
244
- │ │ ├── contentExtractor.ts # HTML content extraction
245
- │ │ ├── translationService.ts # Translation request handling
246
- │ │ └── documentCreationService.ts # Document creation
247
- │ └── utils/
248
- │ ├── htmlFormatter.ts # HTML formatting utilities
249
- │ └── logger.ts # Logging utilities
250
- ├── dist/ # Built plugin files
251
- ├── docs/ # Documentation
252
- └── examples/ # Example implementations
253
- ```
254
-
255
- ## Architecture
256
-
257
- The plugin follows a modular architecture with clear separation of concerns:
258
-
259
- ### Core Services
260
-
261
- - **ContentExtractor** (`src/services/contentExtractor.ts`)
262
- - Extracts content from Sanity documents
263
- - Converts portable text to HTML format
264
- - Handles various field types (text, images, references)
265
-
266
- - **TranslationService** (`src/services/translationService.ts`)
267
- - Prepares translation request payloads
268
- - Handles request logging for testing
269
- - Manages bulk translation processing
78
+ 1. Open the **Bulk Translate** tool from the Sanity Studio tools menu.
79
+ 2. Select the document types you wish to translate.
80
+ 3. Filter and select specific documents from the list.
81
+ 4. Click the **Translate** button to process the batch.
82
+ 5. A summary report will be displayed upon completion.
270
83
 
271
- - **DocumentCreationService** (`src/services/documentCreationService.ts`)
272
- - Creates new Sanity documents from translation responses
273
- - Converts HTML back to portable text format
274
- - Handles document validation and error recovery
84
+ ### Managing Translatable Fields
275
85
 
276
- ### User Interface Components
86
+ Sometimes you need to keep specific fields (like product codes, technical IDs, or proper names) from being translated.
277
87
 
278
- - **Document Actions** (`src/actions/translateDocument.ts`)
279
- - Adds translate button to document toolbar
280
- - Handles single document translation workflow
281
- - Provides user feedback and error handling
88
+ **Method 1: Inline Badges**
89
+ In the document editor, you will see small badges below translatable fields:
90
+ - **Green "Will Translate"**: The field will be included in the translation request.
91
+ - **Red "Do Not Translate"**: The field will be skipped.
92
+ Click the badge to toggle the status.
282
93
 
283
- - **Bulk Translation Tool** (`src/actions/bulkTranslate.ts`)
284
- - Provides bulk translation interface
285
- - Document selection and filtering
286
- - Progress tracking and result reporting
287
-
288
- ### Utilities
289
-
290
- - **HTML Formatter** (`src/utils/htmlFormatter.ts`)
291
- - HTML formatting and validation utilities
292
- - Content structure preservation
293
-
294
- - **Logger** (`src/utils/logger.ts`)
295
- - Structured logging for debugging
296
- - Request/response tracking
297
-
298
- ## Requirements
299
-
300
- - **Sanity Studio**: v3.0.0 or higher
301
- - **Node.js**: 16.0.0 or higher
302
- - **React**: 18.0.0 or higher
303
- - **TypeScript**: 5.0.0 or higher (for development)
94
+ **Method 2: Field Management Action**
95
+ For a high-level view:
96
+ 1. Click the document menu (three dots) in the top right.
97
+ 2. Select **Manage Translation Fields**.
98
+ 3. View and toggle the translation status for all fields in the document.
304
99
 
305
100
  ## Troubleshooting
306
101
 
307
- ### Common Issues
308
-
309
102
  **Plugin not appearing in Studio**
310
- - Ensure the plugin is properly installed: `npm list sanity-translation-plugin`
311
- - Check that the plugin is added to your `sanity.config.ts` file
312
- - Restart your Sanity Studio development server
103
+ - Verify `npm install sanity-translation-plugin` completed successfully.
104
+ - Ensure `translationPlugin()` is in the `plugins` array in `sanity.config.ts`.
105
+ - Restart the Sanity Studio development server.
313
106
 
314
107
  **Translation action not visible**
315
- - The translate action only appears for documents with translatable content
316
- - Check browser console for any JavaScript errors
317
- - Ensure you're using Sanity Studio v3+
318
-
319
- **Console logs not appearing**
320
- - Open browser developer tools (F12)
321
- - Check the Console tab
322
- - Ensure log level is set to show all messages
323
-
324
- **Build errors during development**
325
- - Run `npm run clean` to clear build cache
326
- - Delete `node_modules` and run `npm install`
327
- - Check TypeScript version compatibility
328
-
329
- ### Getting Help
330
-
331
- - Check the [documentation](./docs/) for detailed API information
332
- - Review [example implementations](./examples/) for reference
333
- - Open an issue on GitHub for bug reports or feature requests
334
-
335
- ## API Reference
336
-
337
- ### Plugin Configuration
108
+ - The action only appears on documents that have translatable fields defined in their schema.
338
109
 
339
- ```typescript
340
- interface TranslationPluginConfig {
341
- // Future configuration options will be added here
342
- // Currently uses default placeholder endpoint
343
- }
344
- ```
345
-
346
- ### Content Extraction
347
-
348
- ```typescript
349
- interface DocumentContent {
350
- documentId: string;
351
- documentType: string;
352
- title: string;
353
- htmlContent: string;
354
- extractedAt: Date;
355
- }
356
- ```
110
+ **Authentication Issues**
111
+ - If using OAuth, check the **OAuth Configuration** tool to ensure your tokens are valid.
112
+ - If using local testing, ensure your mock translation service is running on the expected port.
357
113
 
358
- ### Translation Request Format
114
+ ## Support
359
115
 
360
- ```typescript
361
- interface TranslationRequest {
362
- content: string;
363
- format: 'html';
364
- metadata: {
365
- documentId: string;
366
- documentType: string;
367
- title: string;
368
- sourceLanguage?: string;
369
- targetLanguage?: string;
370
- };
371
- }
372
- ```
373
-
374
- ### Translation Response Format
375
-
376
- ```typescript
377
- interface TranslationResponse {
378
- success: boolean;
379
- translatedContent?: {
380
- body: string;
381
- title?: string;
382
- slug?: string;
383
- fields?: Record<string, any>;
384
- };
385
- error?: string;
386
- requestId?: string;
387
- }
388
- ```
116
+ Our support team can be reached at support@easyling.com.
389
117
 
390
- ### Translation-Invariant Fields
391
-
392
- The plugin now supports marking specific fields as translation-invariant using the `dnt` (Do Not Translate) flag. This is useful for fields that should not be translated, such as product IDs, dates, URLs, and other technical identifiers.
393
-
394
- ```typescript
395
- import { ExtendedDocumentContent, TranslatableField } from 'sanity-translation-plugin';
396
-
397
- const content: ExtendedDocumentContent = {
398
- documentId: 'product-123',
399
- title: 'Premium Headphones',
400
- htmlContent: '<p>High-quality wireless headphones</p>',
401
- slug: 'premium-headphones',
402
- fields: {
403
- // Translatable field
404
- description: {
405
- value: 'Premium audio quality',
406
- dnt: false
407
- },
408
- // Translation-invariant field
409
- sku: {
410
- value: 'HDPHN-001',
411
- dnt: true // This field will NOT be translated
412
- },
413
- price: {
414
- value: 299.99,
415
- dnt: true
416
- }
417
- }
418
- };
419
- ```
420
-
421
- For backward compatibility, flat field values are automatically converted to the new structure with `dnt: false`.
422
-
423
- **See the [Translation-Invariant Fields Guide](./docs/translation-invariant-fields.md) for detailed documentation and examples.**
424
-
425
- #### Managing DNT Fields via Inline Badges
426
-
427
- The plugin displays **inline badges** on each translatable field in the document editor, allowing you to toggle DNT status with a single click:
428
-
429
- **Visual indicators appear below each field:**
430
- - **Green "Will Translate" badge** - Field will be translated ✓
431
- - **Red "Do Not Translate" badge** - Field will NOT be translated ⊘
432
-
433
- Simply click the badge to toggle the DNT status. Changes save automatically and apply during translation.
434
-
435
- **Supported field types**: string, text, number, url, email
436
-
437
- **See the [Inline DNT Badges Guide](./docs/inline-dnt-badges.md) for visual examples and detailed instructions.**
438
-
439
- #### Additional DNT Management
440
-
441
- For bulk operations, use the **"Manage Translation Fields" document action**:
442
-
443
- 1. Open any document in Sanity Studio
444
- 2. Click the document menu (three dots)
445
- 3. Select "Manage Translation Fields"
446
- 4. View all fields and clear DNT preferences if needed
447
-
448
- **See the [DNT Field Management Guide](./docs/dnt-field-management.md) for complete documentation.**
449
-
450
- ## Contributing
451
-
452
- We welcome contributions! Please follow these steps:
453
-
454
- 1. **Fork the repository** and create a feature branch
455
- 2. **Install dependencies**: `npm install`
456
- 3. **Make your changes** with appropriate tests
457
- 4. **Run the test suite**: `npm test`
458
- 5. **Lint your code**: `npm run lint`
459
- 6. **Build the plugin**: `npm run build`
460
- 7. **Submit a pull request** with a clear description
461
-
462
- ### Development Guidelines
463
-
464
- - Follow TypeScript best practices
465
- - Add unit tests for new functionality
466
- - Update documentation for API changes
467
- - Use conventional commit messages
468
- - Ensure all tests pass before submitting
118
+ **Note:** In order to investigate compatibility or interoperability issues, we may need access to your Sanity data lake and Studio codebase. We are happy to work with you to establish secure access for debugging purposes.
469
119
 
470
120
  ## License
471
121
 
472
122
  MIT License - see [LICENSE](LICENSE) file for details.
473
-
474
- ## Changelog
475
-
476
- ### v1.0.0
477
- - Initial release
478
- - Single document translation support
479
- - Bulk translation functionality
480
- - HTML content extraction
481
- - Portable text conversion
482
- - Comprehensive test coverage