-
Notifications
You must be signed in to change notification settings - Fork 108
Expand file tree
/
Copy pathTitleToolbar.tsx
More file actions
266 lines (242 loc) · 6.53 KB
/
TitleToolbar.tsx
File metadata and controls
266 lines (242 loc) · 6.53 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
/**
* Title toolbar component for generating post titles.
*/
/**
* WordPress dependencies
*/
import {
Button,
Flex,
FlexItem,
Modal,
TextareaControl,
ToolbarGroup,
ToolbarButton,
} from '@wordpress/components';
import { dispatch, useDispatch, useSelect } from '@wordpress/data';
import { store as editorStore, PostTypeSupportCheck } from '@wordpress/editor';
import { useState } from '@wordpress/element';
import { update } from '@wordpress/icons';
import { __ } from '@wordpress/i18n';
import { store as noticesStore } from '@wordpress/notices';
/**
* Internal dependencies
*/
import { runAbility } from '../../../utils/run-ability';
import type { TitleGenerationAbilityInput, GeneratedTitleData } from '../types';
const { aiTitleGenerationData } = window as any;
/**
* Generates a title for the given post ID and content.
*
* @param {number} postId The ID of the post to generate a title for.
* @param {string} content The content of the post to generate a title for.
* @return {Promise<string>} A promise that resolves to the generated title.
*/
async function generateTitle(
postId: number,
content: string
): Promise< string > {
const params: TitleGenerationAbilityInput = {
context: postId.toString(),
content,
};
const response = await runAbility< GeneratedTitleData >(
'ai/title-generation',
params
);
if (
response &&
typeof response === 'object' &&
'title' in response &&
typeof response.title === 'string' &&
response.title.length > 0
) {
return response.title;
}
throw new Error( __( 'No title suggestion was generated.', 'ai' ) );
}
/**
* TitleToolbar component.
*
* Provides Generate/Regenerate button and a modal for reviewing and
* inserting the AI-generated title suggestion.
*
* @return {React.JSX.Element} The toolbar component.
*/
interface TitleToolbarProps {
isStandalone?: boolean;
}
export default function TitleToolbar( {
isStandalone = false,
}: TitleToolbarProps ): React.JSX.Element | null {
const { postId, content, title } = useSelect( ( select ) => {
const editor = select( editorStore );
return {
postId: editor.getCurrentPostId(),
content: editor.getEditedPostContent() || '',
title: editor.getEditedPostAttribute( 'title' ) || '',
};
}, [] );
const { editPost } = useDispatch( editorStore );
const [ isGenerating, setIsGenerating ] = useState< boolean >( false );
const [ isRegenerating, setIsRegenerating ] = useState< boolean >( false );
const [ isOpen, setOpen ] = useState< boolean >( false );
const [ generatedTitle, setGeneratedTitle ] = useState< string >( '' );
const openModal = () => setOpen( true );
const closeModal = () => {
setOpen( false );
setGeneratedTitle( '' );
};
const hasContent = content.trim().length > 0;
const hasTitle = title.trim().length > 0;
let buttonLabel: string = __( 'Generate', 'ai' );
if ( isGenerating || isRegenerating ) {
buttonLabel = __( 'Generating…', 'ai' );
} else if ( hasTitle ) {
buttonLabel = __( 'Regenerate', 'ai' );
}
/**
* Handles the toolbar Generate/Regenerate button click.
*/
const handleGenerate = async () => {
if ( isGenerating ) {
return;
}
setIsGenerating( true );
( dispatch( noticesStore ) as any ).removeNotice(
'ai_title_generation_error'
);
try {
const result = await generateTitle( postId as number, content );
setGeneratedTitle( result );
openModal();
} catch ( error: any ) {
const message =
typeof error === 'string'
? error
: error?.message ?? __( 'Failed to generate title.', 'ai' );
( dispatch( noticesStore ) as any ).createErrorNotice( message, {
id: 'ai_title_generation_error',
isDismissible: true,
} );
} finally {
setIsGenerating( false );
}
};
/**
* Handles the Regenerate button inside the modal.
* Fetches a new suggestion without closing the modal.
*/
const handleRegenerate = async () => {
setIsRegenerating( true );
( dispatch( noticesStore ) as any ).removeNotice(
'ai_title_generation_error'
);
try {
const result = await generateTitle( postId as number, content );
setGeneratedTitle( result );
} catch ( error: any ) {
const message =
typeof error === 'string'
? error
: error?.message ?? __( 'Failed to generate title.', 'ai' );
( dispatch( noticesStore ) as any ).createErrorNotice( message, {
id: 'ai_title_generation_error',
isDismissible: true,
} );
} finally {
setIsRegenerating( false );
}
};
/**
* Applies the generated title to the post and closes the modal.
*/
const handleInsert = () => {
editPost( { title: generatedTitle } );
closeModal();
};
// Don't render if disabled or there is no post content to generate from.
if ( ! aiTitleGenerationData?.enabled || ! hasContent ) {
return null;
}
return (
<PostTypeSupportCheck supportKeys="title">
{ isStandalone ? (
<Button
icon={ update }
variant="secondary"
label={ buttonLabel }
onClick={ handleGenerate }
disabled={ isGenerating }
isBusy={ isGenerating }
accessibleWhenDisabled
__next40pxDefaultSize
>
{ buttonLabel }
</Button>
) : (
<ToolbarGroup>
<ToolbarButton
icon={ update }
label={ buttonLabel }
onClick={ handleGenerate }
disabled={ isGenerating }
isBusy={ isGenerating }
>
{ buttonLabel }
</ToolbarButton>
</ToolbarGroup>
) }
{ isOpen && (
<Modal
title={ __( 'Title suggestion', 'ai' ) }
onRequestClose={ closeModal }
isFullScreen={ false }
size="medium"
className="ai-title-generation-modal"
>
<p className="ai-title-generation-subtitle">
{ __(
'Review, edit and insert the suggested title or regenerate a new one.',
'ai'
) }
</p>
<TextareaControl
rows={ 2 }
label={ __( 'Generated title', 'ai' ) }
hideLabelFromVision
value={ generatedTitle }
onChange={ setGeneratedTitle }
disabled={ isRegenerating }
__nextHasNoMarginBottom
/>
<Flex
justify="flex-end"
gap="3"
className="ai-title-generation-actions"
>
<FlexItem>
<Button
variant="secondary"
onClick={ handleRegenerate }
disabled={ isRegenerating }
isBusy={ isRegenerating }
>
{ buttonLabel }
</Button>
</FlexItem>
<FlexItem>
<Button
variant="primary"
onClick={ handleInsert }
disabled={ isRegenerating || ! generatedTitle }
>
{ __( 'Insert', 'ai' ) }
</Button>
</FlexItem>
</Flex>
</Modal>
) }
</PostTypeSupportCheck>
);
}