api.js
62 lines
| 1 | import apiFetch from '@wordpress/api-fetch'; |
| 2 | import { API_PATH, VALID_SECTIONS } from '../constants'; |
| 3 | |
| 4 | /** |
| 5 | * Generate or improve guidelines for the given sections/blocks. |
| 6 | * |
| 7 | * Translates between the internal format used by our components and the |
| 8 | * API's categories-based format: |
| 9 | * |
| 10 | * API request: { categories: { site: {}, copy: { guidelines: "..." }, blocks: { "core/paragraph": {} } } } |
| 11 | * API response: { site: { guidelines: "..." }, blocks: { "core/paragraph": { guidelines: "..." } } } |
| 12 | * |
| 13 | * @param {string[]} slugs - Section slugs or block names to generate. |
| 14 | * @param {Object.<string, string>} [existingContent] - Existing content keyed by slug. |
| 15 | * @return {Promise<Object>} Response with `suggestions` keyed by slug. |
| 16 | */ |
| 17 | export async function suggestGuidelines( slugs, existingContent = {} ) { |
| 18 | // Build categories object for the API. |
| 19 | // Standard sections go as top-level keys, block names go under `blocks`. |
| 20 | const categories = {}; |
| 21 | const blockEntries = {}; |
| 22 | |
| 23 | for ( const slug of slugs ) { |
| 24 | const existing = existingContent[ slug ]; |
| 25 | const entry = existing ? { guidelines: existing } : {}; |
| 26 | |
| 27 | if ( VALID_SECTIONS.includes( slug ) ) { |
| 28 | categories[ slug ] = entry; |
| 29 | } else { |
| 30 | blockEntries[ slug ] = entry; |
| 31 | } |
| 32 | } |
| 33 | |
| 34 | if ( Object.keys( blockEntries ).length > 0 ) { |
| 35 | categories.blocks = blockEntries; |
| 36 | } |
| 37 | |
| 38 | const response = await apiFetch( { |
| 39 | path: API_PATH, |
| 40 | method: 'POST', |
| 41 | data: { categories }, |
| 42 | } ); |
| 43 | |
| 44 | // Normalize API response to { suggestions: { slug: text } }. |
| 45 | const suggestions = {}; |
| 46 | for ( const slug of slugs ) { |
| 47 | if ( VALID_SECTIONS.includes( slug ) ) { |
| 48 | const guidelines = response?.[ slug ]?.guidelines; |
| 49 | if ( guidelines ) { |
| 50 | suggestions[ slug ] = guidelines; |
| 51 | } |
| 52 | } else { |
| 53 | const guidelines = response?.blocks?.[ slug ]?.guidelines; |
| 54 | if ( guidelines ) { |
| 55 | suggestions[ slug ] = guidelines; |
| 56 | } |
| 57 | } |
| 58 | } |
| 59 | |
| 60 | return { suggestions }; |
| 61 | } |
| 62 |