From 4ea2b4d5555a2f8ceb5bf0d7100d7581b275ae41 Mon Sep 17 00:00:00 2001 From: KMchaudhary Date: Fri, 14 Aug 2026 15:59:51 +0530 Subject: [PATCH 1/8] feat: support Office, OpenDocument and text files in the Document block Extend the Document block beyond PDF to docx/doc, xlsx/xls, pptx/ppt, odt/ods/odp, txt and csv. These are sent to GoDAM Central as job_type=document, and the preview PDF it returns is stored in new rtgodam_preview_pdf_url meta. - Render every document through a chrome-less pdf.js viewer (react-pdf), loaded as a lazy chunk. Downloads always serve the original upload, never the generated preview. - Add rtgodam_get_supported_document_types() as the single source of truth, mirrored in the editor by constants.js and kept in sync by test. - Classify documents by MIME *and* extension: text/plain also covers .srt/.asc/.c/.cc/.h, which have no conversion path and would otherwise be dispatched as video transcodes and show a stuck progress spinner. - Extend the GoDAM media tab (job_type=pdf,document), the Elementor, WPBakery and shortcode pickers, and the Retranscode Media row action. - Keep the viewer CSS in the block style rather than the lazy chunk, so it reaches the editor canvas iframe; a runtime-injected stylesheet lands in the outer admin document and never arrives. - Drop the client-side page-count regex; pdf.js reports numPages, which works cross-origin and handles PDF 1.5+ object streams. Only written while the block is selected, so opening a post does not dirty it. - Wait for the attachment record to resolve before deciding a document has no preview, so the block no longer flashes the unavailable panel. --- admin/class-rtgodam-retranscodemedia.php | 7 +- admin/class-rtgodam-transcoder-handler.php | 70 +- .../class-rtgodam-transcoder-rest-routes.php | 69 +- admin/godam-transcoder-actions.php | 4 +- assets/src/blocks/godam-pdf/block.json | 4 +- assets/src/blocks/godam-pdf/constants.js | 117 ++ assets/src/blocks/godam-pdf/edit.js | 421 +++++-- assets/src/blocks/godam-pdf/editor.scss | 356 ++++-- assets/src/blocks/godam-pdf/render.php | 127 +- assets/src/blocks/godam-pdf/style.scss | 73 ++ assets/src/blocks/godam-pdf/view.js | 379 +++--- assets/src/blocks/godam-pdf/viewer/index.js | 200 +++ .../src/blocks/godam-pdf/viewer/viewer.scss | 45 + assets/src/blocks/godam-pdf/viewer/worker.js | 32 + .../src/js/elementor/controls/godam-media.js | 34 +- .../views/godam-media-frame-shared.js | 42 +- .../wpbakery-document-selector-param.js | 9 +- inc/classes/class-media-library-ajax.php | 40 +- inc/classes/class-video-metadata.php | 10 +- .../class-godam-document.php | 19 +- inc/classes/rest-api/class-media-library.php | 40 +- .../rest-api/class-meta-rest-fields.php | 52 + .../shortcodes/class-godam-document.php | 10 +- .../class-wpb-godam-document.php | 8 +- inc/helpers/custom-functions.php | 267 +++- package-lock.json | 1082 +++++++---------- package.json | 2 + tests/php/DocumentSupportTest.php | 492 +++++++- 28 files changed, 2707 insertions(+), 1304 deletions(-) create mode 100644 assets/src/blocks/godam-pdf/constants.js create mode 100644 assets/src/blocks/godam-pdf/viewer/index.js create mode 100644 assets/src/blocks/godam-pdf/viewer/viewer.scss create mode 100644 assets/src/blocks/godam-pdf/viewer/worker.js diff --git a/admin/class-rtgodam-retranscodemedia.php b/admin/class-rtgodam-retranscodemedia.php index f276eb4ea4..e7e5d770ea 100644 --- a/admin/class-rtgodam-retranscodemedia.php +++ b/admin/class-rtgodam-retranscodemedia.php @@ -240,10 +240,15 @@ public function admin_enqueues( $hook_suffix ) { */ public function add_media_row_action( $actions, $post ) { + // Documents are included so files already in the library — which predate document + // support and so were never sent to GoDAM Central — can have a preview generated + // without re-uploading them. Tested against the attachment rather than its MIME alone, + // so the action is not offered on the .srt/.asc/.c/.h files that share text/plain and + // have no conversion path. if ( ( 'audio/' !== substr( $post->post_mime_type, 0, 6 ) && 'video/' !== substr( $post->post_mime_type, 0, 6 ) && - 'application/pdf' !== $post->post_mime_type + ! rtgodam_is_supported_document_attachment( $post->ID ) ) || // Safe fallback via filter; PHPCS can't resolve dynamic capability. // phpcs:ignore WordPress.WP.Capabilities.Undetermined diff --git a/admin/class-rtgodam-transcoder-handler.php b/admin/class-rtgodam-transcoder-handler.php index 0876069013..2ae3fcc156 100644 --- a/admin/class-rtgodam-transcoder-handler.php +++ b/admin/class-rtgodam-transcoder-handler.php @@ -92,6 +92,20 @@ class RTGODAM_Transcoder_Handler { */ public $other_extensions = ',pdf'; + /** + * Document extensions with comma separated. + * + * Office / OpenDocument / plain-text formats, which GoDAM Central converts to a preview + * PDF. They are kept apart from $other_extensions because those map the extension + * straight onto the job type ('pdf' => job_type 'pdf'), whereas every format here shares + * the single job type 'document'. + * + * @since 2.2.0 + * @access public + * @var string $document_extensions Document extensions with comma separated. + */ + public $document_extensions = ',docx,doc,xlsx,xls,pptx,ppt,odt,ods,odp,txt,csv'; + /** * Allowed mimetypes. * @@ -101,7 +115,6 @@ class RTGODAM_Transcoder_Handler { */ public $allowed_mimetypes = array( 'application/ogg', - 'application/pdf', ); /** @@ -125,6 +138,21 @@ public function __construct( $no_init = false ) { $this->api_key = get_option( 'rtgodam-api-key' ); $this->easydam_settings = get_option( 'rtgodam-settings', array() ); + /* + * Document MIME types come from the shared helper rather than being duplicated in + * the property default, so the transcoder and the Document block can never disagree + * about which formats are supported. Anything not listed here is dropped by the + * mime gate in wp_media_transcoding() and never reaches GoDAM Central. + */ + $this->allowed_mimetypes = array_values( + array_unique( + array_merge( + $this->allowed_mimetypes, + array_keys( rtgodam_get_supported_document_types() ) + ) + ) + ); + $default_settings = array( 'video' => array( 'adaptive_bitrate' => false, @@ -308,11 +336,31 @@ public function wp_media_transcoding( $wp_metadata, $attachment_id, $autoformat $metadata = $wp_metadata; - $type_arry = explode( '.', $url ); - $type = strtolower( $type_arry[ count( $type_arry ) - 1 ] ); - $extension = pathinfo( $path, PATHINFO_EXTENSION ); + $type_arry = explode( '.', $url ); + $type = strtolower( $type_arry[ count( $type_arry ) - 1 ] ); + // Lowercased because the extension lists below are all lowercase: an upload named + // REPORT.PDF would otherwise miss its branch and be sent as a video stream job. + $extension = strtolower( pathinfo( $path, PATHINFO_EXTENSION ) ); $not_allowed_type = array(); + /* + * A document MIME type is not sufficient on its own, because several of them are + * shared with formats that have no conversion path. WordPress maps .srt, .asc, .c, + * .cc and .h to text/plain exactly as it maps .txt, so without this a subtitle file + * would satisfy the MIME gate below, find no matching extension in any of the job + * type branches, and fall through to the default 'stream' — dispatching every + * caption upload to GoDAM Central as a video transcode that can only fail. + * + * Checked here rather than inside the gate so audio/video and application/ogg keep + * matching on MIME alone, exactly as they did before documents were supported. + */ + if ( + array_key_exists( $metadata['mime_type'], rtgodam_get_supported_document_types() ) + && ! in_array( $extension, rtgodam_get_supported_document_extensions(), true ) + ) { + return $wp_metadata; + } + if ( ( preg_match( '/video|audio/i', $metadata['mime_type'], $type_array ) || in_array( $metadata['mime_type'], $this->allowed_mimetypes, true ) @@ -334,6 +382,20 @@ public function wp_media_transcoding( $wp_metadata, $attachment_id, $autoformat $job_type = $extension; $autoformat = $extension; $options_video_thumb = 0; + } elseif ( in_array( $extension, explode( ',', $this->document_extensions ), true ) ) { + /* + * Office / OpenDocument / text files all share one job type. GoDAM Central + * converts them to a preview PDF (job_type 'document' routes to its document + * queue), and returns that PDF separately as `preview_pdf_url` — `download_url` + * stays the original file. `formats` names the conversion target rather than + * the source extension, unlike the 'pdf' branch above where the two coincide. + * + * Thumbnails are rasterised from page 0 of the preview by Central itself, so + * no thumbnail count is requested here. + */ + $job_type = 'document'; + $autoformat = 'pdf'; + $options_video_thumb = 0; } /** Figure out who is requesting this job */ diff --git a/admin/class-rtgodam-transcoder-rest-routes.php b/admin/class-rtgodam-transcoder-rest-routes.php index f3b7113b56..c9b86df5f8 100644 --- a/admin/class-rtgodam-transcoder-rest-routes.php +++ b/admin/class-rtgodam-transcoder-rest-routes.php @@ -122,6 +122,33 @@ public function register_routes() { 'type' => 'string', 'sanitize_callback' => 'sanitize_text_field', ), + + /* + * Machine-readable failure reason (DOCUMENT_TOO_LARGE, + * DOCUMENT_UNSUPPORTED_TYPE, DOCUMENT_PROCESSING_FAILED, ...). Unlike + * error_msg it is safe to surface, since it carries no file paths or + * internal detail. + */ + 'error_code' => array( + 'required' => false, + 'type' => 'string', + 'sanitize_callback' => 'sanitize_text_field', + ), + + /* + * The converted preview PDF for a `document` job. Read from the top-level + * field rather than from files['preview_pdf']: the callback is form-encoded, + * and a nested array does not survive that encoding reliably. + * + * Absent — not empty — for job types that have no conversion step, and + * empty for a password protected document, which Central stores and + * reports as Transcoded but deliberately generates no preview for. + */ + 'preview_pdf_url' => array( + 'required' => false, + 'type' => 'string', + 'sanitize_callback' => 'esc_url_raw', + ), 'job_manager_form' => array( 'required' => false, 'type' => 'string', @@ -227,6 +254,7 @@ public function handle_callback( WP_REST_Request $request ) { $job_id = $request->get_param( 'job_id' ); $file_status = $request->get_param( 'file_status' ); $error_msg = $request->get_param( 'error_msg' ); + $error_code = $request->get_param( 'error_code' ); $job_for = $request->get_param( 'job_for' ); $thumbnail = $request->get_param( 'thumbnail' ); $format = $request->get_param( 'format' ); @@ -244,6 +272,16 @@ public function handle_callback( WP_REST_Request $request ) { if ( ! empty( $error_msg ) ) { update_post_meta( $failed_id, 'rtgodam_transcoding_error_msg', sanitize_textarea_field( $error_msg ) ); } + + /* + * The status callback stores this too, but a job that fails outright may + * never send one, and the code is what distinguishes a retryable failure + * (DOCUMENT_PROCESSING_FAILED) from a permanent one (DOCUMENT_TOO_LARGE, + * DOCUMENT_UNSUPPORTED_TYPE) that should not offer a retry. + */ + if ( ! empty( $error_code ) ) { + update_post_meta( $failed_id, 'rtgodam_transcoding_error_code', sanitize_text_field( $error_code ) ); + } } } return new WP_REST_Response( @@ -306,11 +344,38 @@ public function handle_callback( WP_REST_Request $request ) { } } - if ( 'pdf' === $job_type && isset( $post_array['download_url'] ) && ! empty( $post_array['download_url'] ) ) { - // Setting the transcoded PDF URL. + /* + * Documents. `pdf` is a file that needed no conversion; `document` is an + * Office / OpenDocument / text file that GoDAM Central rendered to a preview + * PDF. For both, `download_url` is the file the author uploaded, on the CDN. + * + * The two URLs are NOT interchangeable for a `document`: only the preview may + * be rendered, and only the original may be offered as a download. Somebody + * who uploads report.xlsx and downloads preview.pdf will think something broke. + */ + if ( in_array( $job_type, array( 'pdf', 'document' ), true ) && ! empty( $post_array['download_url'] ) ) { update_post_meta( $attachment_id, 'rtgodam_transcoded_url', esc_url_raw( $post_array['download_url'] ) ); } + if ( 'document' === $job_type ) { + if ( ! empty( $post_array['preview_pdf_url'] ) ) { + update_post_meta( $attachment_id, 'rtgodam_preview_pdf_url', esc_url_raw( $post_array['preview_pdf_url'] ) ); + } else { + /* + * No preview: the document is password protected, so Central stored it + * as-is and generated nothing to render. Deleting rather than skipping + * matters — a retranscode or in-place replace reuses the same job row, + * and leaving the key alone would keep serving the *previous* render's + * preview for a file that no longer has one. + */ + delete_post_meta( $attachment_id, 'rtgodam_preview_pdf_url' ); + } + } elseif ( 'pdf' === $job_type && ! empty( $post_array['download_url'] ) ) { + // A PDF is its own preview, so both keys point at the same file. Storing it + // here as well means every reader has a single key to consult. + update_post_meta( $attachment_id, 'rtgodam_preview_pdf_url', esc_url_raw( $post_array['download_url'] ) ); + } + if ( 'image' === $job_type && isset( $post_array['download_url'] ) && ! empty( $post_array['download_url'] ) ) { // Setting the transcoded Image URL. update_post_meta( $attachment_id, 'rtgodam_transcoded_url', esc_url_raw( $post_array['download_url'] ) ); diff --git a/admin/godam-transcoder-actions.php b/admin/godam-transcoder-actions.php index 571101a07d..e2b09511f1 100644 --- a/admin/godam-transcoder-actions.php +++ b/admin/godam-transcoder-actions.php @@ -29,11 +29,13 @@ function rtgodam_add_transcoded_url_field( $form_fields, $post ) { // Check if attachment is of type video. $mime_type = get_post_mime_type( $post->ID ); + // The document test goes through the attachment, not the MIME alone: text/plain also + // covers .srt/.asc/.c/.h, which are never transcoded and so have no CDN URL to show. $is_allowed = ( str_starts_with( $mime_type, 'video/' ) || str_starts_with( $mime_type, 'audio/' ) || str_starts_with( $mime_type, 'image/' ) || - 'application/pdf' === $mime_type + rtgodam_is_supported_document_attachment( $post->ID ) ); if ( ! $is_allowed ) { diff --git a/assets/src/blocks/godam-pdf/block.json b/assets/src/blocks/godam-pdf/block.json index 3be7ebf842..7d7cb3e0cf 100644 --- a/assets/src/blocks/godam-pdf/block.json +++ b/assets/src/blocks/godam-pdf/block.json @@ -4,8 +4,8 @@ "name": "godam/pdf", "title": "Document", "category": "media", - "description": "Embed a PDF file with preview.", - "keywords": [ "document", "pdf", "file", "preview", "godam" ], + "description": "Embed a document with a preview. Supports PDF, Word, Excel, PowerPoint, OpenDocument, TXT and CSV.", + "keywords": [ "document", "pdf", "doc", "docx", "word", "excel", "xlsx", "powerpoint", "pptx", "spreadsheet", "csv", "file", "preview", "godam" ], "textdomain": "godam", "attributes": { "blob": { diff --git a/assets/src/blocks/godam-pdf/constants.js b/assets/src/blocks/godam-pdf/constants.js new file mode 100644 index 0000000000..cb3e739a2d --- /dev/null +++ b/assets/src/blocks/godam-pdf/constants.js @@ -0,0 +1,117 @@ +/** + * Document formats the Document block accepts. + * + * Mirror of rtgodam_get_supported_document_types() in inc/helpers/custom-functions.php, + * which is the source of truth. tests/php/DocumentSupportTest.php parses this file and + * asserts the two lists stay identical, so edit both together. + * + * Everything except PDF is converted to a preview PDF by GoDAM Central, so the block only + * ever renders a PDF — but the media library has to accept the original upload first. + */ +export const SUPPORTED_DOCUMENT_TYPES = { + 'application/pdf': 'pdf', + 'application/vnd.openxmlformats-officedocument.wordprocessingml.document': 'docx', + 'application/msword': 'doc', + 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet': 'xlsx', + 'application/vnd.ms-excel': 'xls', + 'application/vnd.openxmlformats-officedocument.presentationml.presentation': 'pptx', + 'application/vnd.ms-powerpoint': 'ppt', + 'application/vnd.oasis.opendocument.text': 'odt', + 'application/vnd.oasis.opendocument.spreadsheet': 'ods', + 'application/vnd.oasis.opendocument.presentation': 'odp', + 'text/plain': 'txt', + 'text/csv': 'csv', + // Some servers report .csv as application/csv; Central accepts both. + 'application/csv': 'csv', +}; + +/** + * MIME types, for MediaUpload's `allowedTypes`. + */ +export const ALLOWED_MEDIA_TYPES = Object.keys( SUPPORTED_DOCUMENT_TYPES ); + +/** + * Transcoding statuses that mean a job is genuinely in flight. + * + * Lowercased mirror of the $status_messages map in inc/classes/rest-api/class-transcoding.php + * — the only enumeration of what GoDAM Central's status_callback sends — minus the terminal + * 'Transcoded'. 'Queued' is also written locally the moment Central accepts a job, in + * RTGODAM_Transcoder_Handler::wp_media_transcoding(). + * + * Deliberately an allow-list. Central's value is stored verbatim with no enum or validation, + * so treating everything else as "still working" would leave a document that was never + * dispatched (no API key) promising a preview forever. An unrecognised status therefore falls + * through to the download-only panel — if Central adds a stage, add it here. + * + * Statuses are lowercased before comparison because casing is mixed: Central and + * wp_media_transcoding() use Title Case ('Queued', 'Transcoding'), while plugin-authored + * values are lowercase ('failed', 'blocked', 'not_started', 'transcoded'). + */ +export const IN_PROGRESS_TRANSCODING_STATUSES = [ + 'queued', + 'downloading', + 'downloaded', + 'transcoding', +]; + +/** + * Distinct file extensions, without the leading dot. + */ +export const SUPPORTED_DOCUMENT_EXTENSIONS = [ + ...new Set( Object.values( SUPPORTED_DOCUMENT_TYPES ) ), +]; + +/** + * Value for the file input's `accept` attribute. + * + * Extensions rather than MIME types: browsers are inconsistent about the MIME they report + * for Office files (a .docx often arrives as application/zip or application/octet-stream), + * and an accept list of MIME types alone hides those files in the OS picker. + */ +export const DOCUMENT_ACCEPT = SUPPORTED_DOCUMENT_EXTENSIONS.map( + ( extension ) => `.${ extension }`, +).join( ',' ); + +/** + * Whether a media object selected in the editor is a format the block can display. + * + * The MIME type is authoritative when present. Uploads in flight and some library + * selections have no MIME yet, so the extension is the fallback — the same order of + * preference as godam_is_supported_document() on the server. + * + * @param {Object} media Media object from MediaUpload / MediaReplaceFlow. + * @return {boolean} True when the format is supported. + */ +export function isSupportedDocument( media ) { + if ( ! media ) { + return false; + } + + // Library selections expose `mime`, uploads expose `mime_type`. `media.type` is the + // REST post type ("attachment") for uploads, so it must not be consulted here. + const mime = media.mime || media.mime_type || ''; + + if ( mime ) { + return Object.prototype.hasOwnProperty.call( SUPPORTED_DOCUMENT_TYPES, mime ); + } + + return isSupportedDocumentUrl( media.url || '' ); +} + +/** + * Whether a URL points at a format the block can display, judged by extension alone. + * + * @param {string} url Document URL. + * @return {boolean} True when the extension is supported. + */ +export function isSupportedDocumentUrl( url ) { + if ( ! url || typeof url !== 'string' ) { + return false; + } + + // Strip the query string / fragment before reading the extension. + const path = url.split( /[?#]/ )[ 0 ]; + const extension = path.split( '.' ).pop().toLowerCase(); + + return SUPPORTED_DOCUMENT_EXTENSIONS.includes( extension ); +} diff --git a/assets/src/blocks/godam-pdf/edit.js b/assets/src/blocks/godam-pdf/edit.js index 98d534a1dc..1db60d7c19 100644 --- a/assets/src/blocks/godam-pdf/edit.js +++ b/assets/src/blocks/godam-pdf/edit.js @@ -9,7 +9,6 @@ import clsx from 'clsx'; import { isBlobURL } from '@wordpress/blob'; import { Button, - Disabled, PanelBody, RangeControl, TextControl, @@ -30,16 +29,28 @@ import { __ } from '@wordpress/i18n'; import { useDispatch, useSelect } from '@wordpress/data'; import { store as noticesStore } from '@wordpress/notices'; import { store as coreStore } from '@wordpress/core-data'; -import { useState, useEffect } from '@wordpress/element'; +import { useState, lazy, Suspense } from '@wordpress/element'; import { trash } from '@wordpress/icons'; /** * Internal dependencies */ import { Caption } from './caption'; +import { + ALLOWED_MEDIA_TYPES, + DOCUMENT_ACCEPT, + IN_PROGRESS_TRANSCODING_STATUSES, + isSupportedDocument, + isSupportedDocumentUrl, +} from './constants'; import './editor.scss'; -const ALLOWED_MEDIA_TYPES = [ 'application/pdf' ]; +// pdf.js is heavy, and most posts being edited contain no document at all. Loading it only +// when a document is actually on the canvas keeps it out of the editor's initial bundle — +// and it is the same chunk the front end uses, so it is usually already cached. +const DocumentViewer = lazy( () => + import( /* webpackChunkName: "godam-pdf-viewer" */ './viewer' ), +); /** * Format bytes → human-readable KB / MB. @@ -95,82 +106,117 @@ function PdfEdit( { const [ uploadingFile, setUploadingFile ] = useState( null ); const { createErrorNotice, createWarningNotice } = useDispatch( noticesStore ); - // Fetch attachment metadata: auto-generated cover, file size and MIME type. - const { autoGeneratedCover, fileSize, mimeType } = useSelect( ( select ) => { - if ( ! id ) { - return { autoGeneratedCover: '', fileSize: 0, mimeType: '' }; - } - const media = select( coreStore ).getEntityRecord( 'postType', 'attachment', id ); - return { - // Mirror set_media_library_thumbnail(): check video thumbnail first (set by - // GoDAM transcoding callback for WP-uploaded PDFs), then the PDF-specific key - // (set by GoDAM tab import). Both are registered show_in_rest:true. - autoGeneratedCover: media?.meta?.rtgodam_media_video_thumbnail || - media?.meta?.rtgodam_media_pdf_thumbnail || - '', - fileSize: media?.media_details?.filesize || 0, - mimeType: media?.mime_type || '', - }; - }, [ id ] ); - - // Count PDF pages client-side by fetching the raw file and scanning for - // page dictionary entries. Runs once when src is first set (or changes). - // Result is stored as a block attribute so it persists on save. - // Count pages every time src is set — this ensures previously-uploaded PDFs - // also get counted when the editor opens, not only on new uploads. - // The result is stored as an attribute so it persists after the post is saved. - useEffect( () => { - // Skip if src isn't set, or if we already have a page count (avoids - // re-downloading the file on every editor open and marking the post dirty). - // pageCount is reset to 0 in onSelectPdf when a new file is chosen, - // so a fresh count will still run after the user swaps the document. - if ( ! src || pageCount > 0 ) { - return; - } - - // NOTE: fetch only works for same-origin PDFs. Cross-origin / CDN files - // are blocked by CORS and will silently leave pageCount at 0. - // For production CDN setups, consider computing the page count server-side - // at upload/transcode time and storing it in post meta instead. - const controller = new AbortController(); + // Fetch attachment metadata: auto-generated cover, file size, MIME type, and the + // transcoding state needed to tell "preview on its way" from "there will never be one". + const { + autoGeneratedCover, + fileSize, + hasResolvedMedia, + mimeType, + previewPdfUrl, + sourceUrl, + transcodingStatus, + } = useSelect( + ( select ) => { + if ( ! id ) { + // A document added by URL alone has no record to wait for. + return { + autoGeneratedCover: '', + fileSize: 0, + hasResolvedMedia: true, + mimeType: '', + previewPdfUrl: '', + sourceUrl: '', + transcodingStatus: '', + }; + } + const media = select( coreStore ).getEntityRecord( 'postType', 'attachment', id ); + return { + /* + * Whether the record above has actually been fetched yet, as opposed to simply + * being absent. Every field here reads as empty until the request resolves, and + * an empty transcoding status is meaningful — it is what "no job was ever + * dispatched" looks like — so without this the canvas would classify the + * document from placeholder values and show the download-only panel for a moment + * before the real data arrived. + */ + hasResolvedMedia: select( coreStore ).hasFinishedResolution( + 'getEntityRecord', + [ 'postType', 'attachment', id ], + ), + // Mirror set_media_library_thumbnail(): check video thumbnail first (set by + // GoDAM transcoding callback for WP-uploaded PDFs), then the PDF-specific key + // (set by GoDAM tab import). Both are registered show_in_rest:true. + autoGeneratedCover: media?.meta?.rtgodam_media_video_thumbnail || + media?.meta?.rtgodam_media_pdf_thumbnail || + '', + fileSize: media?.media_details?.filesize || 0, + mimeType: media?.mime_type || '', + previewPdfUrl: media?.meta?.rtgodam_preview_pdf_url || '', + // REST runs source_url through wp_get_attachment_url(), so GoDAM-tab media + // resolves to its CDN URL here just as it does server-side. + sourceUrl: media?.source_url || '', + transcodingStatus: ( media?.meta?.rtgodam_transcoding_status || '' ).toLowerCase(), + }; + }, + [ id ], + ); - fetch( src, { credentials: 'same-origin', signal: controller.signal } ) - .then( ( res ) => { - if ( ! res.ok ) { - throw new Error( 'fetch failed' ); - } - return res.arrayBuffer(); - } ) - .then( ( buffer ) => { - // Decode as latin-1 so every byte is preserved as a character. - const text = new TextDecoder( 'latin1' ).decode( buffer ); - - // Primary: /Count N inside any /Pages dictionary. - // The root /Pages node always has the highest count value. - // Note: PDF 1.5+ object streams compress the page tree, so this - // regex may not find /Count in all modern PDFs. - const countMatches = [ ...text.matchAll( /\/Count\s+(\d+)/g ) ]; - let count = countMatches.reduce( ( max, m ) => { - const n = parseInt( m[ 1 ], 10 ); - return n > max ? n : max; - }, 0 ); - - // Fallback: count leaf /Page objects (works for older/uncompressed PDFs). - if ( ! count ) { - const pageMatches = text.match( /\/Type\s*\/Page[\s/<[]/g ); - count = pageMatches ? pageMatches.length : 0; - } + /* + * The PDF to render. Mirrors rtgodam_get_document_preview_url() on the server, so the + * canvas shows exactly what a visitor will see: + * + * - the preview PDF once Central has produced one; + * - for a plain PDF, the file itself, which needs no conversion and lets the editor + * render immediately rather than waiting on a transcode. + * + * Anything else has nothing to show yet. + */ + const isPdfSource = mimeType + ? 'application/pdf' === mimeType + : /\.pdf(?:[?#]|$)/i.test( src || '' ); + const resolvedPreviewUrl = previewPdfUrl || ( isPdfSource ? src : '' ); + + /* + * The file to offer for download, mirroring rtgodam_get_document_download_url(). Always + * the original upload, never the generated preview — somebody who uploaded report.xlsx + * and got preview.pdf back will think something broke. + * + * The attachment's own URL wins over the stored `src`, which was captured when the block + * was inserted and can be stale if the file was later offloaded to a CDN. + */ + const resolvedDownloadUrl = sourceUrl || src || ''; - if ( count > 0 ) { - setAttributes( { pageCount: count } ); - } - } ) - .catch( () => {} ); // Silently ignore network / CORS / abort errors. + /** + * Record the page count reported by pdf.js. + * + * This replaces an earlier hand-rolled count that fetched the raw file and regex-scanned + * it for `/Count` entries. That could not see cross-origin CDN files (blocked by CORS) + * and missed PDF 1.5+ files whose page tree lives in a compressed object stream. pdf.js + * has already parsed the document properly by the time it tells us, so this is both + * cheaper and correct. + * + * Written only while the block is selected, and only when the number actually changes. + * Both guards matter: any attribute write during a passive page load flags the post as + * having unsaved changes, so an author who merely opened a post to read it would be met + * with the browser's "Leave site?" prompt. Blocks saved before pdf.js was introduced hold + * pageCount: 0 — the old counter could not read cross-origin files — so without the + * selection guard every one of them would rewrite itself on open. + * + * The count is therefore refreshed the moment the author touches the block, which is also + * the only point at which they could act on it. + * + * @param {Object} pdf pdf.js document proxy. + */ + function onPreviewLoaded( pdf ) { + if ( ! isSingleSelected ) { + return; + } - return () => { - controller.abort(); - }; - }, [ src ] ); // eslint-disable-line react-hooks/exhaustive-deps + if ( pdf?.numPages > 0 && pdf.numPages !== pageCount ) { + setAttributes( { pageCount: pdf.numPages } ); + } + } function onUploadError( message ) { createErrorNotice( message, { type: 'snackbar' } ); @@ -201,23 +247,13 @@ function PdfEdit( { return; } - // Validate the format: reject anything that isn't a PDF. - // The MediaUpload allowedTypes filter restricts the library UI, but a - // runtime check is needed as a safety net (e.g. drag-and-drop bypasses it). - // Use the MIME string, not `media.type`: library selections expose - // `mime` ("application/pdf") while uploads expose `mime_type`; `media.type` - // is the REST post type ("attachment") for uploads and would wrongly reject them. - // Testing for equality (rather than inequality) matters: a missing MIME type - // used to pass straight through, so fall back to the extension instead of - // letting an unknown format in. - const mime = media.mime || media.mime_type || ''; - const isPdf = mime - ? 'application/pdf' === mime - : /\.pdf(?:[?#]|$)/i.test( media.url || '' ); - - if ( ! isPdf ) { + // Validate the format. The MediaUpload allowedTypes filter restricts the library UI, + // but a runtime check is needed as a safety net (e.g. drag-and-drop bypasses it). + // isSupportedDocument() prefers the MIME type and falls back to the extension, so an + // unknown format is rejected rather than passed straight through. + if ( ! isSupportedDocument( media ) ) { createWarningNotice( - __( 'Only PDF files can be attached to this block. Please select a PDF document.', 'godam' ), + __( 'That file type is not supported. Choose a PDF, Word, Excel, PowerPoint, OpenDocument, TXT or CSV file.', 'godam' ), { type: 'snackbar', isDismissible: true }, ); return; @@ -295,25 +331,54 @@ function PdfEdit( { const isCardView = previewMode === 'card'; const hasDocument = !! ( src || temporaryURL ); - // Content saved before the format was validated (or added by URL) can still hold - // a non-PDF. The front end renders nothing for those, so flag it here rather than - // showing an that just paints blank. - // Decided from the stored URL first, because that is the only signal available - // on the very first render. The attachment's MIME type arrives asynchronously, - // and waiting for it means rendering the speculatively: the browser - // fetches the file, and for a non-PDF that alone raises a download prompt - // before any notice can replace it. The MIME type still overrides the URL once - // present, since it is the authoritative answer. + // Content saved before the format was validated (or added by URL) can still hold an + // unsupported file. The front end renders nothing for those, so flag it here rather than + // showing an empty frame. // - // Trade-off: a PDF served from an extension-less URL is flagged until its MIME - // arrives. Erring that way is deliberate, because the opposite error hands the - // visitor's browser a file to download. + // Decided from the stored URL first, because that is the only signal available on the + // very first render; the attachment's MIME type arrives asynchronously and overrides it + // once present, since it is the authoritative answer. + // + // Trade-off: a supported file served from an extension-less URL is flagged until its MIME + // arrives. Erring that way is deliberate — the opposite error would show the author a + // broken preview and imply the page is fine. const isUnsupported = hasDocument && ! temporaryURL && ( mimeType - ? 'application/pdf' !== mimeType - : ! /\.pdf(?:[?#]|$)/i.test( src || '' ) + ? ! ALLOWED_MEDIA_TYPES.includes( mimeType ) + : ! isSupportedDocumentUrl( src || '' ) ); + /* + * No preview yet. Two situations, and the author needs to be able to tell them apart + * because only one of them resolves on its own: + * + * - a transcoding job is in flight — a preview is coming, so the canvas says so and the + * author has no reason to go looking for a fix; + * - no job is running, so no preview is coming. Either one finished without producing + * anything (it failed, or the document is password protected — GoDAM Central stores + * those as-is and reports success, because it cannot convert a file it cannot open), or + * one was never dispatched at all, which is what an absent status means. A visitor sees + * the download-only panel in every one of those cases, so the canvas shows that same + * panel rather than inventing editor-only copy for a distinction the page does not draw. + * + * Judged by an allow-list of in-flight statuses, so an absent status and anything + * unrecognised land in the second bucket rather than promising a preview forever. + */ + const missingPreview = + hasDocument && ! temporaryURL && ! isUnsupported && ! resolvedPreviewUrl; + /* + * Nothing can be classified until the attachment record has been fetched: until then every + * field reads empty, which is indistinguishable from a document that genuinely has no + * preview. Judging it early made the block open on the download-only panel and then swap to + * the document a moment later. Show the same "Loading preview…" the viewer itself uses, so + * the wait reads as one continuous load rather than a wrong answer being corrected. + */ + const isResolvingMedia = missingPreview && ! hasResolvedMedia; + const isAwaitingPreview = + missingPreview && ! isResolvingMedia && + IN_PROGRESS_TRANSCODING_STATUSES.includes( transcodingStatus ); + const hasNoPreview = missingPreview && ! isResolvingMedia && ! isAwaitingPreview; + const classes = clsx( className, { 'is-transient': !! temporaryURL, [ `is-preview-${ previewMode || 'default' }` ]: true, @@ -339,7 +404,7 @@ function PdfEdit( { (