-
Notifications
You must be signed in to change notification settings - Fork 29
Expand file tree
/
Copy pathApp.js
More file actions
370 lines (327 loc) · 9.41 KB
/
App.js
File metadata and controls
370 lines (327 loc) · 9.41 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
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
/**
* Press This Main App Component
*
* The root component for the Press This application.
* Uses the native Gutenberg editor for a streamlined editing experience.
*
* @package
*/
/**
* WordPress dependencies
*/
import { useMemo, useState, useCallback, useEffect } from '@wordpress/element';
import { __ } from '@wordpress/i18n';
/**
* Internal dependencies
*/
import Header from './components/Header';
import PressThisEditor from './components/PressThisEditor';
import { buildSuggestedContentFromMetadata } from './utils';
/**
* Get initial data from PHP.
*
* @return {Object} Press This data from window.pressThisData.
*/
function getInitialData() {
return window.pressThisData || {};
}
/**
* Main App component.
*
* @return {JSX.Element} The App component.
*/
export default function App() {
const data = useMemo( () => getInitialData(), [] );
// State for pending scraped content to append.
const [ pendingScrape, setPendingScrape ] = useState( null );
// State for save handler from editor.
const [ saveState, setSaveState ] = useState( {
handleSave: null,
isSaving: false,
publishLabel: __( 'Publish', 'press-this' ),
} );
// Build initial post object for editor.
const post = useMemo(
() => ( {
id: data.postId,
title: data.title || '',
content: data.content || '',
} ),
[ data.postId, data.title, data.content ]
);
// Track additional scraped images/embeds.
const [ additionalMedia, setAdditionalMedia ] = useState( {
images: [],
embeds: [],
} );
// Build editor settings.
const settings = useMemo(
() => ( {
allowedBlocks: data.allowedBlocks || [],
isRTL: data.isRTL,
suggestedPostFormat: data.suggestedFormat || '',
postFormatOverride: data.postFormatOverride || '',
postFormatDefault: data.postFormatDefault || '',
} ),
[
data.allowedBlocks,
data.isRTL,
data.suggestedFormat,
data.postFormatOverride,
data.postFormatDefault,
]
);
// Build capabilities object.
const capabilities = useMemo(
() => ( {
canPublish: data.canPublish,
canUploadFiles: data.canUploadFiles,
canAssignCategories: data.canAssignCategories,
canEditCategories: data.canEditCategories,
canAssignTags: data.canAssignTags,
} ),
[
data.canPublish,
data.canUploadFiles,
data.canAssignCategories,
data.canEditCategories,
data.canAssignTags,
]
);
// Build REST config object.
const restConfig = useMemo(
() => ( {
restUrl: data.restUrl,
restNonce: data.restNonce,
redirInParent: data.redirInParent,
} ),
[ data.restUrl, data.restNonce, data.redirInParent ]
);
// Combine initial and additional scraped media.
const images = useMemo( () => {
const combined = [
...( data.images || [] ),
...additionalMedia.images,
];
// Deduplicate by URL.
return [ ...new Set( combined ) ];
}, [ data.images, additionalMedia.images ] );
const embeds = useMemo( () => {
const combined = [
...( data.embeds || [] ),
...additionalMedia.embeds,
];
return [ ...new Set( combined ) ];
}, [ data.embeds, additionalMedia.embeds ] );
const sourceUrl = additionalMedia.sourceUrl || data.sourceUrl || '';
// State to track if we've received postMessage data.
const [ postMessageReceived, setPostMessageReceived ] = useState( false );
// State for title/content that may come from postMessage.
const [ , setPostMessageData ] = useState( null );
/**
* Validate embed URLs through WordPress oEmbed providers.
*
* @param {Array} urls Array of embed URLs to validate.
* @return {Promise<Array>} Promise resolving to array of valid embed URLs.
*/
const validateEmbeds = useCallback(
async ( urls ) => {
if ( ! urls || urls.length === 0 ) {
return [];
}
try {
const response = await fetch(
`${ data.restUrl }validate-embeds`,
{
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-WP-Nonce': data.restNonce,
},
body: JSON.stringify( { urls } ),
}
);
if ( ! response.ok ) {
// On error, return empty array (fail safe).
return [];
}
const result = await response.json();
return result.embeds || [];
} catch {
// On network error, return empty array.
return [];
}
},
[ data.restUrl, data.restNonce ]
);
/**
* Listen for postMessage data from bookmarklet.
* This is used when the bookmarklet opens Press This via GET (to send cookies)
* and then sends scraped data via postMessage.
*/
useEffect( () => {
// Only listen if we're in postMessage mode and haven't received data yet.
if ( ! data.postMessageMode || postMessageReceived ) {
return;
}
async function handleMessage( event ) {
// Validate message structure.
if ( ! event.data || event.data.type !== 'press-this-data' ) {
return;
}
const messageData = event.data.data;
if ( ! messageData ) {
return;
}
// Mark as received so we stop listening.
setPostMessageReceived( true );
// Store the received data.
setPostMessageData( messageData );
// Process images (no validation needed).
const receivedImages = messageData._images || [];
const receivedSourceUrl = messageData.u || data.sourceUrl;
// Validate embeds through WordPress oEmbed providers.
const rawEmbeds = messageData._embeds || [];
const validatedEmbeds = await validateEmbeds( rawEmbeds );
// Update media state with validated embeds.
setAdditionalMedia( ( prev ) => ( {
images: [ ...prev.images, ...receivedImages ],
embeds: [ ...prev.embeds, ...validatedEmbeds ],
sourceUrl: receivedSourceUrl,
} ) );
// Build suggested content from bookmarklet metadata.
// Extract description from meta tags.
const meta = messageData._meta || {};
const description =
messageData.s || // User selection takes priority.
meta[ 'twitter:description' ] ||
meta[ 'og:description' ] ||
meta.description ||
'';
const title =
messageData.t ||
meta[ 'twitter:title' ] ||
meta[ 'og:title' ] ||
meta.title ||
'';
// Get canonical URL.
const links = messageData._links || {};
const canonical = links.canonical || receivedSourceUrl;
// Build suggested content using the same utility as Header.
const suggestedContent = buildSuggestedContentFromMetadata( {
title,
description,
siteName: meta[ 'og:site_name' ] || '',
canonical,
url: receivedSourceUrl,
} );
// Set as pending scrape so the editor will process it.
if ( title || suggestedContent ) {
setPendingScrape( {
title,
content: suggestedContent,
images: receivedImages,
embeds: validatedEmbeds,
sourceUrl: receivedSourceUrl,
} );
}
}
window.addEventListener( 'message', handleMessage );
return () => {
window.removeEventListener( 'message', handleMessage );
};
}, [
data.postMessageMode,
data.restUrl,
data.restNonce,
data.sourceUrl,
postMessageReceived,
validateEmbeds,
] );
/**
* Handle scrape completion from Header.
* Sets pending scrape data for the editor to process.
*
* @param {Object} result Scraped data.
*/
const handleScrapeComplete = useCallback( ( result ) => {
// Only set pending scrape if there's content to append (not media-only scans).
if ( ! result.mediaOnly && result.content ) {
setPendingScrape( result );
}
// Add new images/embeds to the media panel.
setAdditionalMedia( ( prev ) => ( {
images: [ ...prev.images, ...( result.images || [] ) ],
embeds: [ ...prev.embeds, ...( result.embeds || [] ) ],
sourceUrl: result.sourceUrl,
} ) );
}, [] );
/**
* Called by editor after it has processed the pending scrape.
*/
const handleScrapeProcessed = useCallback( () => {
setPendingScrape( null );
}, [] );
/**
* Handle save state updates from PressThisEditor.
*
* @param {Object} state Save state with handleSave, isSaving, publishLabel.
*/
const handleSaveReady = useCallback( ( state ) => {
setSaveState( state );
}, [] );
// State for undo/redo from editor.
const [ undoState, setUndoState ] = useState( {
handleUndo: null,
handleRedo: null,
hasUndo: false,
hasRedo: false,
} );
const handleUndoReady = useCallback( ( state ) => {
setUndoState( state );
}, [] );
return (
<div className="press-this-app">
<Header
siteName={ data.siteName }
siteUrl={ data.siteUrl }
sourceUrl={ data.sourceUrl }
isLegacyBookmarklet={ data.isLegacyBookmarklet }
hasBookmarkletContent={ !! data.content }
hasBookmarkletMedia={
!! ( data.images?.length || data.embeds?.length )
}
proxyEnabled={ data.proxyEnabled }
restUrl={ data.restUrl }
restNonce={ data.restNonce }
onScrapeComplete={ handleScrapeComplete }
onSave={ saveState.handleSave }
isSaving={ saveState.isSaving }
publishLabel={ saveState.publishLabel }
onUndo={ undoState.handleUndo }
onRedo={ undoState.handleRedo }
hasUndo={ undoState.hasUndo }
hasRedo={ undoState.hasRedo }
/>
<div className="press-this-app__body">
<PressThisEditor
post={ post }
settings={ settings }
images={ images }
embeds={ embeds }
categories={ data.categories || [] }
postFormats={ data.postFormats || [] }
capabilities={ capabilities }
restConfig={ restConfig }
sourceUrl={ sourceUrl }
pendingScrape={ pendingScrape }
onScrapeProcessed={ handleScrapeProcessed }
onSaveReady={ handleSaveReady }
onUndoReady={ handleUndoReady }
categoryNonce={ data.categoryNonce || '' }
ajaxUrl={ data.ajaxUrl || '' }
/>
</div>
</div>
);
}