index.tsx
74 lines
| 1 | /** |
| 2 | * External dependencies |
| 3 | */ |
| 4 | import { createBlock, getBlockContent } from '@wordpress/blocks'; |
| 5 | import TurndownService from 'turndown'; |
| 6 | /** |
| 7 | * Internal dependencies |
| 8 | */ |
| 9 | import { blockName } from '..'; |
| 10 | import { |
| 11 | EXTENDED_BLOCKS, |
| 12 | ExtendedBlockProp, |
| 13 | isPossibleToExtendBlock, |
| 14 | } from '../extensions/ai-assistant'; |
| 15 | /** |
| 16 | * Types |
| 17 | */ |
| 18 | import { PromptItemProps } from '../lib/prompt'; |
| 19 | |
| 20 | const turndownService = new TurndownService( { emDelimiter: '_', headingStyle: 'atx' } ); |
| 21 | |
| 22 | const from = []; |
| 23 | |
| 24 | /** |
| 25 | * Return an AI Assistant block instance from a given block type. |
| 26 | * |
| 27 | * @param {object} attrs - Block attributes. |
| 28 | * @param {ExtendedBlockProp} blockType - Block type. |
| 29 | * @returns {object} AI Assistant block instance. |
| 30 | */ |
| 31 | export function transfromToAIAssistantBlock( attrs, blockType: ExtendedBlockProp ) { |
| 32 | const { content } = attrs; |
| 33 | // Create a temporary block to get the HTML content. |
| 34 | const temporaryBlock = createBlock( blockType, { content } ); |
| 35 | let htmlContent = getBlockContent( temporaryBlock ); |
| 36 | |
| 37 | // core/heading custom transform handling. |
| 38 | if ( blockType === 'core/heading' && attrs?.level ) { |
| 39 | // Replace the HTML tags with the block level. |
| 40 | htmlContent = htmlContent.replace( /<(\/?)h\d([^>]*)>/g, `<$1h${ attrs.level }$2>` ); |
| 41 | } |
| 42 | |
| 43 | // Convert the content to markdown. |
| 44 | const aiAssistantBlockcontent = turndownService.turndown( htmlContent ); |
| 45 | |
| 46 | // Create a pair of user/assistant messages. |
| 47 | const messages: Array< PromptItemProps > = [ |
| 48 | { |
| 49 | role: 'user', |
| 50 | content: 'Tell me some content for this block, please.', |
| 51 | }, |
| 52 | { |
| 53 | role: 'assistant', |
| 54 | content, |
| 55 | }, |
| 56 | ]; |
| 57 | |
| 58 | return createBlock( blockName, { content: aiAssistantBlockcontent, messages } ); |
| 59 | } |
| 60 | |
| 61 | /* |
| 62 | * Create individual transform handler for each block type. |
| 63 | */ |
| 64 | for ( const blockType of EXTENDED_BLOCKS ) { |
| 65 | from.push( { |
| 66 | type: 'block', |
| 67 | blocks: [ blockType ], |
| 68 | isMatch: () => isPossibleToExtendBlock(), |
| 69 | transform: attrs => transfromToAIAssistantBlock( attrs, blockType ), |
| 70 | } ); |
| 71 | } |
| 72 | |
| 73 | export default { from }; |
| 74 |