forked from WordPress/ai
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAltTextControls.tsx
More file actions
238 lines (221 loc) · 6 KB
/
AltTextControls.tsx
File metadata and controls
238 lines (221 loc) · 6 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
/**
* Alt text generation controls for the image block inspector.
*/
/**
* WordPress dependencies
*/
import {
Button,
TextareaControl,
Spinner,
Notice,
} from '@wordpress/components';
import { InspectorControls } from '@wordpress/block-editor';
import { useState } from '@wordpress/element';
import { __ } from '@wordpress/i18n';
import { dispatch, select } from '@wordpress/data';
import { store as noticesStore } from '@wordpress/notices';
import { store as editorStore } from '@wordpress/editor';
/**
* Internal dependencies
*/
import type { ImageBlockAttributes } from '../types';
import { generateAltText } from '../../../utils/generate-alt-text';
interface AltTextControlsProps {
clientId: string;
attributes: ImageBlockAttributes;
setAttributes: ( attributes: Partial< ImageBlockAttributes > ) => void;
}
/**
* Returns the appropriate button label based on state.
*
* @param {boolean} hasExistingAlt Whether the image has existing alt text.
* @return {string} The button label.
*/
function getButtonLabel( hasExistingAlt: boolean ): string {
return hasExistingAlt
? __( 'Regenerate Alt Text', 'ai' )
: __( 'Generate Alt Text', 'ai' );
}
/**
* AltTextControls component.
*
* Adds a "Generate Alt Text" button to the image block inspector panel.
*
* @param {AltTextControlsProps} props The component props.
* @param {string} props.clientId The block client ID.
* @param {ImageBlockAttributes} props.attributes The block attributes.
* @param {Function} props.setAttributes The function to set the block attributes.
* @return {JSX.Element|null} The component.
*/
export function AltTextControls( {
clientId,
attributes,
setAttributes,
}: AltTextControlsProps ): JSX.Element | null {
const { id: attachmentId, url: imageUrl, alt } = attributes;
const [ isGenerating, setIsGenerating ] = useState< boolean >( false );
const [ generatedAlt, setGeneratedAlt ] = useState< string | null >( null );
const [ isDecorative, setIsDecorative ] = useState< boolean >( false );
// Don't show controls if there's no image.
if ( ! attachmentId && ! imageUrl ) {
return null;
}
const hasExistingAlt = alt && alt.trim().length > 0;
const hasGeneratedAlt = generatedAlt !== null;
/**
* Handles the generate button click.
*/
const handleGenerate = async () => {
setIsGenerating( true );
setGeneratedAlt( null );
setIsDecorative( false );
// Clear any previous notices.
( dispatch( noticesStore ) as any ).removeNotice(
'ai_alt_text_generation_error'
);
try {
const content = select( editorStore ).getEditedPostContent();
const result = await generateAltText(
attachmentId,
imageUrl,
content,
clientId,
{
linkDestination: attributes?.linkDestination,
href: attributes?.href,
linkTarget: attributes?.linkTarget,
caption:
typeof attributes?.caption === 'string'
? attributes.caption
: ( attributes?.caption as any )?.text,
}
);
if ( result.is_decorative ) {
setIsDecorative( true );
setGeneratedAlt( '' );
} else {
setGeneratedAlt( result.alt_text );
}
} catch ( err: any ) {
const errorMessage =
err?.message ||
__( 'An error occurred while generating alt text.', 'ai' );
( dispatch( noticesStore ) as any ).createErrorNotice(
errorMessage,
{
id: 'ai_alt_text_generation_error',
isDismissible: true,
}
);
} finally {
setIsGenerating( false );
}
};
/**
* Applies the generated alt text to the image block.
*/
const handleApply = () => {
if ( isDecorative ) {
setAttributes( { alt: '' } );
} else if ( generatedAlt ) {
setAttributes( { alt: generatedAlt } );
}
setGeneratedAlt( null );
setIsDecorative( false );
};
/**
* Dismisses the generated alt text suggestion.
*/
const handleDismiss = () => {
setGeneratedAlt( null );
setIsDecorative( false );
};
return (
<InspectorControls group="content">
<div
className="ai-alt-text-controls"
style={ { padding: '0 16px' } }
>
{ /* Generated alt text preview */ }
{ hasGeneratedAlt && ! isDecorative && (
<div style={ { marginBottom: '12px' } }>
<TextareaControl
label={ __( 'Generated Alt Text', 'ai' ) }
hideLabelFromVision
value={ generatedAlt || '' }
onChange={ ( value ) => setGeneratedAlt( value ) }
rows={ 3 }
__nextHasNoMarginBottom
/>
<div
style={ {
display: 'flex',
gap: '8px',
marginTop: '8px',
} }
>
<Button variant="primary" onClick={ handleApply }>
{ __( 'Apply', 'ai' ) }
</Button>
<Button
variant="secondary"
onClick={ handleDismiss }
>
{ __( 'Dismiss', 'ai' ) }
</Button>
</div>
</div>
) }
{ /* Decorative image notice */ }
{ isDecorative && (
<div style={ { marginBottom: '12px' } }>
<Notice status="info" isDismissible={ false }>
{ __(
'This image appears to be decorative. Applying will set an empty alt attribute, which tells screen readers to skip it.',
'ai'
) }
</Notice>
<div
style={ {
display: 'flex',
gap: '8px',
marginTop: '8px',
} }
>
<Button variant="primary" onClick={ handleApply }>
{ __( 'Apply', 'ai' ) }
</Button>
<Button
variant="secondary"
onClick={ handleDismiss }
>
{ __( 'Dismiss', 'ai' ) }
</Button>
</div>
</div>
) }
{ /* Generate button */ }
{ ! hasGeneratedAlt && ! isDecorative && (
<Button
variant="secondary"
onClick={ handleGenerate }
disabled={ isGenerating }
style={ { width: '100%', justifyContent: 'center' } }
>
{ isGenerating ? (
<>
<Spinner />
<span style={ { marginLeft: '8px' } }>
{ __( 'Generating…', 'ai' ) }
</span>
</>
) : (
getButtonLabel( !! hasExistingAlt )
) }
</Button>
) }
</div>
</InspectorControls>
);
}