Skip to content

Extend the Document block beyond PDF to docx/doc, xlsx/xls, pptx/ppt, odt/ods/odp, txt and csv. - #2079

Merged
subodhr258 merged 9 commits into
developfrom
feat/document-block-support-all-docs
Aug 20, 2026
Merged

subodhr258 merged 9 commits into
developfrom
feat/document-block-support-all-docs

Conversation

@KMchaudhary

@KMchaudhary KMchaudhary commented Aug 14, 2026 •

Copy link
Copy Markdown
Collaborator

Fixes: #2073

This pull request adds robust support for Office, OpenDocument, plain-text, and CSV files as previewable documents alongside PDFs. It ensures that only supported document formats are processed, both in the WordPress admin and in the block editor, and introduces new logic to handle document-specific transcoding, error reporting, and preview management. The changes also improve user feedback and maintain consistency between the client and server regarding supported formats.

Document Format Support and Consistency

  • Added a comprehensive list of supported document MIME types and extensions (including DOCX, XLSX, PPTX, ODT, CSV, TXT, etc.) in both the backend (RTGODAM_Transcoder_Handler and helpers) and frontend (SUPPORTED_DOCUMENT_TYPES in constants.js), ensuring the block and server always agree on which formats are allowed. [1] [2]
  • Updated the block description and keywords in block.json to reflect support for a wide range of document types, not just PDFs.

Transcoding Logic and Preview Handling

  • Modified transcoding logic so that Office/OpenDocument/text files are converted to a preview PDF by GoDAM Central, while PDFs are passed through directly. Only supported extensions are accepted for transcoding, preventing unsupported files (e.g., .srt, .c) from being misrouted. [1] [2]
  • Implemented logic to clear outdated previews when retranscoding or replacing a document, preventing stale previews from being shown if the file changes.
  • On callback, stores or deletes the preview PDF URL as appropriate, ensuring accurate rendering and download behavior for both PDFs and converted documents.

Error Reporting and Status Handling

  • Extended the REST API to accept and store a machine-readable error_code for failed transcodes, allowing the UI to distinguish between retryable and permanent errors. [1] [2] [3]
  • Defined a strict allow-list of in-progress transcoding statuses in the frontend, ensuring only recognized statuses are treated as "in flight" and preventing indefinite waiting on unrecognized states.

Media Library and Admin Integration

  • Updated media row actions and transcoded URL field logic to use attachment-based checks (not just MIME type), so only truly supported documents offer previews or transcoding actions, excluding files like .srt or .c that share text/plain. [1] [2]

These changes together provide seamless, accurate support for a wide variety of document formats, improving both the backend processing and the user experience in the editor and media library.

Demo

Gutenberg Blocks

Screen.Recording.2026-08-19.at.11.53.25.AM.mov

Elementor Widget

Screen.Recording.2026-08-19.at.1.18.12.PM.mov

WPBakery Element
Screenshot 2026-08-19 at 1 20 03 PM

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.
Copilot AI balanced review requested due to automatic review settings August 14, 2026 10:55

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Extends the Document block to support Office, OpenDocument, TXT, and CSV files through PDF previews generated by GoDAM Central.

Changes:

  • Adds document classification, transcoding, preview, and download URL handling.
  • Introduces a lazy react-pdf viewer for editor and frontend rendering.
  • Expands document selection across Gutenberg, Elementor, WPBakery, and GoDAM Media.

Reviewed changes

Copilot reviewed 27 out of 28 changed files in this pull request and generated 8 comments.

Show a summary per file
File Description
tests/php/DocumentSupportTest.php Expands document format and URL tests.
package.json Adds PDF viewer dependencies.
package-lock.json Locks new dependencies.
inc/helpers/custom-functions.php Adds document classifiers and URL resolvers.
inc/classes/wpbakery-elements/class-wpb-godam-document.php Updates WPBakery document options.
inc/classes/shortcodes/class-godam-document.php Updates unsupported-format messaging.
inc/classes/rest-api/class-meta-rest-fields.php Exposes preview and transcoding metadata.
inc/classes/rest-api/class-media-library.php Imports document jobs and preview URLs.
inc/classes/elementor-widgets/class-godam-document.php Expands Elementor document selection.
inc/classes/class-video-metadata.php Adds document thumbnails.
inc/classes/class-media-library-ajax.php Handles document media and MIME mapping.
assets/src/js/wpbakery/wpbakery-document-selector-param.js Expands WPBakery MIME filters.
assets/src/js/media-library/views/godam-media-frame-shared.js Normalizes document tab requests.
assets/src/js/elementor/controls/godam-media.js Supports multiple Elementor MIME types.
assets/src/blocks/godam-pdf/viewer/worker.js Configures the pdf.js worker.
assets/src/blocks/godam-pdf/viewer/viewer.scss Styles the PDF viewer.
assets/src/blocks/godam-pdf/viewer/index.js Implements page rendering.
assets/src/blocks/godam-pdf/view.js Lazily mounts frontend viewers.
assets/src/blocks/godam-pdf/style.scss Adds shared viewer and fallback styles.
assets/src/blocks/godam-pdf/render.php Separates preview and download rendering.
assets/src/blocks/godam-pdf/editor.scss Adds editor processing states.
assets/src/blocks/godam-pdf/edit.js Integrates document previews in the editor.
assets/src/blocks/godam-pdf/constants.js Defines supported document formats.
assets/src/blocks/godam-pdf/block.json Updates block discovery metadata.
admin/godam-transcoder-actions.php Includes documents in media actions.
admin/class-rtgodam-transcoder-rest-routes.php Stores document callback results.
admin/class-rtgodam-transcoder-handler.php Dispatches document conversion jobs.
admin/class-rtgodam-retranscodemedia.php Enables document retranscoding.

💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

Comment thread inc/helpers/custom-functions.php Resolved
Comment thread assets/src/blocks/godam-pdf/edit.js Resolved
Comment thread assets/src/blocks/godam-pdf/edit.js Resolved
Comment on lines +360 to +363
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 {

@subodhr258 subodhr258 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed the full diff (excluding the lockfile). This is a careful, well documented change and the core design holds together:

  • the preview-vs-download URL split is consistent across render.php, the editor, and the rtgodam_get_document_preview_url() / rtgodam_get_document_download_url() resolvers;
  • legacy PDF blocks keep rendering with no migration (test_preview_url_falls_back_for_legacy_pdfs);
  • pdfjs-dist (4.8.69) matches what react-pdf 9.2.1 depends on, so there is no worker/API version mismatch;
  • the preview_pdf_url path is wired end to end (Central to ajax to JS import, plus the transcoder callback), and download always serves the original upload;
  • the PHP-to-JS constant-sync test is a solid guard against the two lists drifting.

A few non-blocking things left inline:

  • Document pickers request text/plain, which also surfaces .srt/.c/.h/.asc as selectable (medium).
  • @since 2.2.0 is hardcoded while the branch still uses @since n.e.x.t elsewhere.
  • view.js error fallback is not idempotent.
  • The editor viewer has no onError/download fallback, unlike the front end.
  • document_extensions leading-comma explode footgun.

One more that could not be anchored inline (the line is outside the diff): assets/src/blocks/godam-pdf/edit.js:278 still reads // Reset so useEffect re-counts pages for the new file., but the useEffect was removed in this PR (counting now happens in onPreviewLoaded), so that comment is now stale.

/**
* MIME types, for MediaUpload's `allowedTypes`.
*/
export const ALLOWED_MEDIA_TYPES = Object.keys( SUPPORTED_DOCUMENT_TYPES );

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ALLOWED_MEDIA_TYPES includes text/plain, and it is used as allowedTypes / library.type for every document picker (block, Elementor, WPBakery). WordPress maps .srt, .asc, .c, .cc, .h to text/plain too, so those files appear as selectable in the library picker even though they have no conversion path.

The upload dialog is limited by extension via DOCUMENT_ACCEPT, and the transcoder guards by extension (rtgodam_is_supported_document_attachment), but library selection filters by MIME. So a user can pick an existing .srt/.c/.h, isSupportedDocument() accepts it on MIME, and the block then only ever shows the 'no preview available' panel.

Worth deciding whether that is acceptable, or whether the picker / isSupportedDocument() should also apply the extension gate so these text/plain lookalikes are not offered as documents.

Comment thread inc/helpers/custom-functions.php Resolved
Comment thread assets/src/blocks/godam-pdf/view.js Resolved
Comment thread assets/src/blocks/godam-pdf/edit.js Resolved
KMchaudhary added 3 commits August 18, 2026 17:22
- require the extension to agree with the MIME type, so text/plain lookalikes (.srt/.c/.h) are not offered as documents
- hand pdf.js an explicit PDFWorker, so one document unmounting no longer destroys the shared worker and breaks the block
- editor: try each preview URL candidate before the download-only panel, and wait for the attachment record before judging state
- show transcoding status and page-0 previews for every document type in the media library, not just PDF
- clear a stale preview when a document job is re-queued, and infer a missing MIME from the file name
- use @SInCE n.e.x.t instead of hardcoding 2.2.0
…sible

- mount only the pages near the viewport, backed by placeholders of each page's real height, and release off-screen canvases: a 160-page PDF drops from 160 canvases / ~3.1 GB of canvas memory to 2-3 / ~40-60 MB, with the scroll height unchanged
- keep a two-page floor and fall back to rendering everything without IntersectionObserver, since it reports nothing while a document is hidden
- discard a previous document's page geometry when the file changes
- label the scroll container as a focusable region, so keyboard and screen-reader users can reach and scroll it
- guard view.js's native fallback against being run twice by a single failure
pdf.js 4.8 calls Promise.withResolvers() unguarded in 31 places, including every document load, but the method only arrived in Safari 17.4 — so Safari 16.4-17.3 threw out of react-pdf's load effect, unmounting the viewer and leaving an empty box. Polyfill it on the main thread, and via a new worker entry on the worker thread, which shares no globals with the page.
@KMchaudhary KMchaudhary changed the title 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. Aug 19, 2026
return () => observer.disconnect();
// Re-observes when the page count changes, which is when the slots themselves are
// replaced. Page width is deliberately not a dependency: a resize moves the same slots.
}, [ numPages ] );

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The on-demand rendering can leave a document showing only the first 2 pages if the viewer loads while its container is zero-width.

This effect is keyed on [numPages] and observes whatever slots exist when it runs (slotRefs.current.forEach( ... observe )), but the slots below only render once pageWidth > 0. If numPages is set while the container is zero-width (a Document block inside a collapsed tab/accordion, which is exactly the "hidden viewer" case the INITIAL_PAGES comment describes), there are no slots to observe, and this effect never re-runs when the panel is later expanded and the slots appear. pagesInView then stays at the INITIAL_PAGES seed, so only the first 2 pages mount and the rest stay blank placeholders.

A background tab is fine (non-zero width, so slots exist and get observed), but a zero-width-at-load container is not. Re-running the observer once slots first appear fixes it, e.g. add a pageWidth > 0 boolean to this effect's deps, or call observer.observe() from the slot ref callback.

@subodhr258

Copy link
Copy Markdown
Collaborator

Re-reviewed (commits through dd0d907). Every point from the first review round is addressed, and the classifier changes now have test coverage in tests/php/DocumentSupportTest.php. Verified each:

Copilot's points

  1. Classifier no longer MIME-only: godam_is_supported_document() now requires the MIME type and the extension to agree, falling back to MIME alone only when the file cannot be resolved. Tested (.srt/.asc/.c/.cc/.h rejected, .txt kept). ✓
  2. isSupportedDocument() mirrors that on the client via hasUnsupportedDocumentExtension(). ✓
  3. Editor uses sourceUrl before src, through an ordered previewCandidates list with per-URL failure fallback. ✓
  4. get_mime_type_for_job_type() infers the MIME from orignal_file_name instead of labelling converted docs application/pdf; PDF is the last resort. ✓
  5. Page count is held in state and committed from an effect when the block becomes selected. ✓
  6. Viewer renders pages on demand via IntersectionObserver, with correct-height placeholders. ✓
  7. Scroll container is now a focusable role="region". ✓
  8. Stale preview is cleared at queue time in the handler, so failed or pending replacements no longer serve the old document. ✓

My earlier points
9. text/plain lookalikes: still selectable from the library picker (WordPress filters that picker by MIME), but they now surface the unsupported panel instead of a broken block. Reasonable resolution. ✓
10. @since 2.2.0 reverted to @since n.e.x.t. ✓
11. handledError guard prevents the double unmount and double <object>. ✓
12. Editor canvas now has an error path (error boundary plus candidate fallback into the download-only panel). ✓
13. Leading empty extension fixed (dropped the comma and added a '' !== $extension guard). ✓

The per-document pdf.js worker handover in viewer/worker.js is also the right fix for the shared-worker teardown, and the JS/PHP parity test guards the two lists from drifting.

Two things before merge:

1. On-demand viewer can miss pages when it loads at zero width (viewer/index.js, inline comment added). The IntersectionObserver effect is keyed on [numPages] and observes only the slots that exist when it runs, but slots render only once pageWidth > 0. If numPages arrives while the container is zero-width (a Document block inside a collapsed tab or accordion, the "hidden viewer" case the INITIAL_PAGES comment calls out), the observer attaches to nothing; when the panel is expanded later the slots render but the effect does not re-run, so only the 2 seed pages ever mount and the rest stay blank placeholders. Re-running the observer once slots first appear fixes it (add a pageWidth > 0 signal to the effect deps, or call observer.observe() from the slot ref callback).

2. Merge conflict. The PR currently conflicts with develop in assets/src/js/media-library/views/attachment-detail-two-column.js (develop's media-library work touched the same file). It needs a rebase or merge before it can go in.

Otherwise this looks good.

// Any convertible document, not just PDF: Central rasterises page 0 of the preview for
// all of them, and set_media_library_thumbnail() puts it on `image`, so an .xlsx has a
// real preview to show here instead of the generic document icon.
if ( isDocumentModel( this.model ) ) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Blocking: isDocumentModel is used here but is not imported in this file, so this throws ReferenceError: isDocumentModel is not defined.

The develop merge (222e273) resolved the import-line conflict to import { canManageAttachment } from '../utility'; (line 16), dropping the isDocumentModel the pre-merge PR tip imported. The symbol is still exported by utility.js and imported correctly in attachment.js, just not here. Because this sits inside render() (line 991) and the call evaluates the condition unconditionally, opening the two-column attachment details for any attachment throws at the end of render.

Fix: add it back to the import on line 16, import { canManageAttachment, isDocumentModel } from '../utility';.

@subodhr258

Copy link
Copy Markdown
Collaborator

Verified both items from the last round are fixed:

  • Zero-width viewer (f015e021): the IntersectionObserver is now stashed in a ref and each slot observes itself from its ref callback, so slots that first appear when a collapsed / zero-width viewer is revealed get picked up. Correct, and the unobserve-on-replace and unmount handling is right.
  • Merge conflict resolved (222e273b). The new WPBakery inline-editor asset loading (0414c618) also looks sound (double-mount guard before the first await, Elementor element_ready plus a WPBakery preview observer, all idempotent).

One blocking regression the develop merge introduced, so I can't approve yet:

assets/src/js/media-library/views/attachment-detail-two-column.js uses isDocumentModel( this.model ) in render() (line 1181), but the merge dropped isDocumentModel from this file's import (line 16 now imports only canManageAttachment). The symbol is still exported by utility.js and imported fine in attachment.js, so it is just this one file. As written it throws ReferenceError: isDocumentModel is not defined every time the two-column attachment details render, for any attachment. One-line fix (inline comment).

Once that import is restored I'll approve.

…details

The develop merge dropped isDocumentModel from this file's import while
render() still called it, throwing a ReferenceError on every two-column
attachment details render, for any attachment.
@KMchaudhary

Copy link
Copy Markdown
Collaborator Author

Thanks for catching that — you're right, and it wasn't document-specific: render() calls isDocumentModel unconditionally, so the missing import threw for every attachment in the two-column details view.

Fixed in b451498 by restoring the symbol to this file's import:

import { canManageAttachment, isDocumentModel } from '../utility';

I also linted the whole media-library and godam-pdf trees to check the merge hadn't dropped anything else — no no-undef anywhere, so this was indeed the only affected file. The remaining lint errors there are pre-existing and untouched by this PR (import/no-unresolved on @wordpress/block-editor in caption.js/edit.js, and no-unsafe-wp-apis on the __experimentalToggleGroupControl imports).

Ready for another look.

@subodhr258

Copy link
Copy Markdown
Collaborator

The code is good now — isDocumentModel is restored to the import in attachment-detail-two-column.js (b451498f), the zero-width viewer fix is correct, and every point from the earlier rounds is addressed. So this is approvable on the code.

Holding the approval on one CI thing: Run JS unit tests is failing at npm ci with Missing: … from lock file (dompurify@3.2.7, @babel/core@7.25.7, markdown-it, @opentelemetry/*, date-fns, yaml, and more), which means package-lock.json is out of sync with package.json on this branch. This is specific to this PR, not the old base-wide drift: #2085 passes the same check on the same develop base. Most likely the develop merge left the lockfile inconsistent.

Fix: run npm install on the branch and commit the regenerated package-lock.json, then confirm the JS unit tests job goes green. Once it does I'll approve.

(The red POT and Plugin Check are the usual pre-existing/expected ones.)

The lock regenerated when react-pdf and pdfjs-dist were added had its
nested duplicate entries pruned, so npm 10.9.2 (the version behind the
.nvmrc Node) recomputed 44 entries the lock never recorded and npm ci
failed before the unit tests could run. Rebase the lock onto develop's
and re-resolve, so the only difference is the react-pdf subtree.
@github-actions

Copy link
Copy Markdown

🔍 WordPress Plugin Check Report

❌ Status: Failed

📊 Report

🎯 Total Issues ❌ Errors ⚠️ Warnings
17 1 16

❌ Errors (1)

📁 readme.txt (1 error)
📍 Line 🔖 Check 💬 Message
0 outdated_tested_upto_header Tested up to: 7.0 < 7.1. The "Tested up to" value in your plugin is not set to the current version of WordPress. This means your plugin will not show up in searches, as we require plugins to be compatible and documented as tested up to the most recent version of WordPress.

⚠️ Warnings (16)

📁 readme.txt (2 warnings)
📍 Line 🔖 Check 💬 Message
0 mismatched_plugin_name Plugin name "GoDAM - Organize WordPress Media Library & File Manager with Unlimited Folders for Images, Videos & more" is different from the name declared in plugin header "GoDAM".
0 trademarked_term The plugin name includes a restricted term. Your chosen plugin name - "GoDAM - Organize WordPress Media Library & File Manager with Unlimited Folders for Images, Videos & more" - contains the restricted term "wordpress" which cannot be used at all in your plugin name.
📁 composer.json (1 warning)
📍 Line 🔖 Check 💬 Message
0 missing_composer_json_file The "/vendor" directory using composer exists, but "composer.json" file is missing.
📁 assets/build/blocks/godam-gallery-v2/render.php (2 warnings)
📍 Line 🔖 Check 💬 Message
15 WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound Global variables defined by a theme/plugin should start with the theme/plugin prefix. Found: "$inner_block_video_ids".
23 WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound Global variables defined by a theme/plugin should start with the theme/plugin prefix. Found: "$inner_block_video_ids".
📁 assets/build/css/main.css (1 warning)
📍 Line 🔖 Check 💬 Message
0 EnqueuedStylesScope This style is being loaded in all contexts.
📁 assets/src/libs/analytics.min.js (5 warnings)
📍 Line 🔖 Check 💬 Message
0 EnqueuedScriptsScope This script is being loaded in all frontend contexts.
0 NonBlockingScripts.NoStrategy This script on http://localhost:8880 (with handle analytics-library) is loaded in the footer. Consider a defer or async script loading strategy instead.
0 NonBlockingScripts.NoStrategy This script on http://localhost:8880/2026/08/20/hello-world/ (with handle analytics-library) is loaded in the footer. Consider a defer or async script loading strategy instead.
0 NonBlockingScripts.NoStrategy This script on http://localhost:8880/sample-page/ (with handle analytics-library) is loaded in the footer. Consider a defer or async script loading strategy instead.
0 NonBlockingScripts.NoStrategy This script on http://localhost:8880/demo-attachment-post/ (with handle analytics-library) is loaded in the footer. Consider a defer or async script loading strategy instead.
📁 assets/build/js/main.min.js (5 warnings)
📍 Line 🔖 Check 💬 Message
0 EnqueuedScriptsScope This script is being loaded in all frontend contexts.
0 NonBlockingScripts.NoStrategy This script on http://localhost:8880 (with handle rtgodam-script) is loaded in the footer. Consider a defer or async script loading strategy instead.
0 NonBlockingScripts.NoStrategy This script on http://localhost:8880/2026/08/20/hello-world/ (with handle rtgodam-script) is loaded in the footer. Consider a defer or async script loading strategy instead.
0 NonBlockingScripts.NoStrategy This script on http://localhost:8880/sample-page/ (with handle rtgodam-script) is loaded in the footer. Consider a defer or async script loading strategy instead.
0 NonBlockingScripts.NoStrategy This script on http://localhost:8880/demo-attachment-post/ (with handle rtgodam-script) is loaded in the footer. Consider a defer or async script loading strategy instead.

🤖 Generated by WordPress Plugin Check Action • Learn more about Plugin Check

@subodhr258
subodhr258 merged commit 7d2b6ed into develop Aug 20, 2026
4 of 6 checks passed
@subodhr258
subodhr258 deleted the feat/document-block-support-all-docs branch August 20, 2026 07:57
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants