Merge pull request #2507 from payloadcms/fix/preview-null

feat: supports null preview url #2472
This commit is contained in:
Jacob Fletcher
2023-04-17 16:54:41 -04:00
committed by GitHub
24 changed files with 52 additions and 12 deletions

View File

@@ -1,5 +1,6 @@
import React, { useCallback, useState } from 'react';
import React, { useCallback, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { toast } from 'react-toastify';
import { useAuth } from '../../utilities/Auth';
import Button from '../Button';
import { Props } from './types';
@@ -23,27 +24,41 @@ const PreviewButton: React.FC<Props> = (props) => {
const { token } = useAuth();
const { serverURL, routes: { api } } = useConfig();
const { t } = useTranslation('version');
const isGeneratingPreviewURL = useRef(false);
// we need to regenerate the preview URL every time the button is clicked
// to do this we need to fetch the document data fresh from the API
// this will ensure the latest data is used when generating the preview URL
const handleClick = useCallback(async () => {
setIsLoading(true);
if (!generatePreviewURL || isGeneratingPreviewURL.current) return;
isGeneratingPreviewURL.current = true;
let url = `${serverURL}${api}`;
if (collection) url = `${url}/${collection.slug}/${id}`;
if (global) url = `${url}/globals/${global.slug}`;
try {
setIsLoading(true);
const data = await fetch(`${url}?draft=true&locale=${locale}&fallback-locale=null`).then((res) => res.json());
const previewURL = await generatePreviewURL(data, { locale, token });
setIsLoading(false);
let url = `${serverURL}${api}`;
if (collection) url = `${url}/${collection.slug}/${id}`;
if (global) url = `${url}/globals/${global.slug}`;
window.open(previewURL, '_blank');
}, [serverURL, api, collection, global, id, generatePreviewURL, locale, token]);
const data = await fetch(`${url}?draft=true&locale=${locale}&fallback-locale=null`).then((res) => res.json());
const previewURL = await generatePreviewURL(data, { locale, token });
if (!previewURL) throw new Error();
setIsLoading(false);
isGeneratingPreviewURL.current = false;
window.open(previewURL, '_blank');
} catch (err) {
setIsLoading(false);
isGeneratingPreviewURL.current = false;
toast.error(t('error:previewing'));
}
}, [serverURL, api, collection, global, id, generatePreviewURL, locale, token, t]);
return (
<Button
className={baseClass}
buttonStyle="secondary"
onClick={handleClick}
disabled={isLoading}
disabled={isLoading || !generatePreviewURL}
>
{isLoading ? t('general:loading') : t('preview')}
</Button>

View File

@@ -37,7 +37,7 @@ type GeneratePreviewURLOptions = {
export type GeneratePreviewURL = (
doc: Record<string, unknown>,
options: GeneratePreviewURLOptions
) => Promise<string> | string;
) => Promise<string | null> | string | null;
export type EmailTransport = Email & {
transport: Transporter;

View File

@@ -79,6 +79,7 @@
"notAllowedToAccessPage": "Nemáte povolení přistupovat k této stránce.",
"notAllowedToPerformAction": "Nemáte povolení provádět tuto akci.",
"notFound": "Požadovaný zdroj nebyl nalezen.",
"previewing": "Při náhledu tohoto dokumentu došlo k chybě.",
"problemUploadingFile": "Při nahrávání souboru došlo k chybě.",
"tokenInvalidOrExpired": "Token je neplatný nebo vypršel.",
"unPublishingDocument": "Při zrušení publikování tohoto dokumentu došlo k chybě.",

View File

@@ -79,6 +79,7 @@
"notAllowedToAccessPage": "Du hast keine Berechtigung, auf diese Seite zuzugreifen.",
"notAllowedToPerformAction": "Du hast keine Berechtigung, diese Aktion auszuführen.",
"notFound": "Die angeforderte Ressource wurde nicht gefunden.",
"previewing": "Es gab ein Problem beim Vorschauen dieses Dokuments.",
"problemUploadingFile": "Es gab ein Problem während des Hochladens der Datei.",
"tokenInvalidOrExpired": "Token ist entweder ungültig oder abgelaufen.",
"unPublishingDocument": "Es gab ein Problem, dieses Dokument auf Entwurf zu setzen.",

View File

@@ -79,6 +79,7 @@
"notAllowedToAccessPage": "You are not allowed to access this page.",
"notAllowedToPerformAction": "You are not allowed to perform this action.",
"notFound": "The requested resource was not found.",
"previewing": "There was a problem previewing this document.",
"problemUploadingFile": "There was a problem while uploading the file.",
"tokenInvalidOrExpired": "Token is either invalid or has expired.",
"unPublishingDocument": "There was a problem while un-publishing this document.",

View File

@@ -79,6 +79,7 @@
"notAllowedToAccessPage": "No tienes permiso para acceder a esta página.",
"notAllowedToPerformAction": "No tienes permiso para realizar esta acción.",
"notFound": "No se encontró el recurso solicitado.",
"previewing": "Ocurrió un problema al previsualizar este documento.",
"problemUploadingFile": "Ocurrió un problema al subir el archivo.",
"tokenInvalidOrExpired": "El token es inválido o ya expiró.",
"unPublishingDocument": "Ocurrió un error al despublicar este documento.",

View File

@@ -79,6 +79,7 @@
"notAllowedToAccessPage": "Vous n'êtes pas autorisé à accéder à cette page.",
"notAllowedToPerformAction": "Vous n'êtes pas autorisé à effectuer cette action.",
"notFound": "La ressource demandée n'a pas été trouvée.",
"previewing": "Un problème est survenu lors de l'aperçu de ce document.",
"problemUploadingFile": "Il y a eu un problème lors du téléversement du fichier.",
"tokenInvalidOrExpired": "Le jeton n'est soit pas valide ou a expiré.",
"unPublishingDocument": "Un problème est survenu lors de l'annulation de la publication de ce document.",

View File

@@ -79,6 +79,7 @@
"notAllowedToAccessPage": "Nemate dopuštenje pristupiti ovoj stranici.",
"notAllowedToPerformAction": "Nemate dopuštenje izvršiti ovu radnju.",
"notFound": "Traženi resurs nije pronađen.",
"previewing": "Pojavio se problem pri pregledavanju ovog dokumenta.",
"problemUploadingFile": "Pojavio se problem pri učitavanju datoteke.",
"tokenInvalidOrExpired": "Token je nevaljan ili je istekao.",
"unPublishingDocument": "Pojavio se problem pri poništavanju objave ovog dokumenta.",

View File

@@ -79,6 +79,7 @@
"notAllowedToAccessPage": "Ehhez az oldalhoz nem férhet hozzá.",
"notAllowedToPerformAction": "Ezt a műveletet nem hajthatja végre.",
"notFound": "A kért erőforrás nem található.",
"previewing": "Hiba történt a dokumentum előnézetének megtekintése közben.",
"problemUploadingFile": "Hiba történt a fájl feltöltése közben.",
"tokenInvalidOrExpired": "A token érvénytelen vagy lejárt.",
"unPublishingDocument": "Hiba történt a dokumentum közzétételének visszavonása közben.",

View File

@@ -79,6 +79,7 @@
"notAllowedToAccessPage": "Non sei autorizzato ad accedere a questa pagina.",
"notAllowedToPerformAction": "Non sei autorizzato a eseguire questa azione.",
"notFound": "La risorsa richiesta non è stata trovata.",
"previewing": "Si è verificato un problema durante l'anteprima di questo documento.",
"problemUploadingFile": "Si è verificato un problema durante il caricamento del file.",
"tokenInvalidOrExpired": "Il token non è valido o è scaduto.",
"unPublishingDocument": "Si è verificato un problema durante l'annullamento della pubblicazione di questo documento.",

View File

@@ -79,6 +79,7 @@
"notAllowedToAccessPage": "この画面へのアクセスは許可されていません。",
"notAllowedToPerformAction": "このアクションは許可されていません。",
"notFound": "リクエストされたリソースは見つかりませんでした。",
"previewing": "このデータをプレビューする際に問題が発生しました。",
"problemUploadingFile": "ファイルのアップロード中に問題が発生しました。",
"tokenInvalidOrExpired": "トークンが無効、または、有効期限が切れています。",
"unPublishingDocument": "このデータを非公開する際に問題が発生しました。",

View File

@@ -79,6 +79,7 @@
"notAllowedToAccessPage": "ဤစာမျက်နှာကို ဝင်ရောက်ခွင့်မပြုပါ။",
"notAllowedToPerformAction": "ဤလုပ်ဆောင်ချက်ကို လုပ်ဆောင်ရန် ခွင့်မပြုပါ။",
"notFound": "တောင်းဆိုထားသော အရင်းအမြစ်ကို ရှာမတွေ့ပါ။",
"previewing": "ဖိုင်ကို အစမ်းကြည့်ရန် ပြဿနာရှိနေသည်။",
"problemUploadingFile": "ဖိုင်ကို အပ်လုဒ်တင်ရာတွင် ပြဿနာရှိနေသည်။",
"tokenInvalidOrExpired": "တိုကင်သည် မမှန်ကန်ပါ သို့မဟုတ် သက်တမ်းကုန်သွားပါပြီ။",
"unPublishingDocument": "ဖိုင်ကို ပြန်လည့် သိမ်းဆည်းခြင်းမှာ ပြဿနာရှိနေသည်။",

View File

@@ -79,6 +79,7 @@
"notAllowedToAccessPage": "Du har ikke tilgang til denne siden.",
"notAllowedToPerformAction": "Du har ikke tillatelse til å utføre denne handlingen.",
"notFound": "Den forespurte ressursen ble ikke funnet.",
"previewing": "Det oppstod et problem under forhåndsvisning av dokumentet.",
"problemUploadingFile": "Det oppstod et problem under opplasting av filen.",
"tokenInvalidOrExpired": "Token er enten ugyldig eller har utløpt.",
"unPublishingDocument": "Det oppstod et problem under avpublisering av dokumentet.",

View File

@@ -79,6 +79,7 @@
"notAllowedToAccessPage": "U hebt geen toegang tot deze pagina.",
"notAllowedToPerformAction": "U mag deze actie niet uitvoeren.",
"notFound": "De gevraagde resource werd niet gevonden.",
"previewing": "Er was een probleem met het voorvertonen van dit document.",
"problemUploadingFile": "Er was een probleem bij het uploaden van het bestand.",
"tokenInvalidOrExpired": "Token is ongeldig of verlopen.",
"unPublishingDocument": "Er was een probleem met het depubliceren van dit document.",

View File

@@ -79,6 +79,7 @@
"notAllowedToAccessPage": "Nie masz dostępu do tej strony.",
"notAllowedToPerformAction": "Nie możesz wykonać tej akcji.",
"notFound": "Żądany zasób nie został znaleziony.",
"previewing": "Wystąpił problem podczas podglądu tego dokumentu.",
"problemUploadingFile": "Wystąpił problem podczas przesyłania pliku.",
"tokenInvalidOrExpired": "Token jest nieprawidłowy lub wygasł.",
"unPublishingDocument": "Wystąpił problem podczas cofania publikacji tego dokumentu.",

View File

@@ -79,6 +79,7 @@
"notAllowedToAccessPage": "Você não tem permissão para acessar essa página.",
"notAllowedToPerformAction": "Você não tem permissão para realizar essa ação.",
"notFound": "O recurso requisitado não foi encontrado.",
"previewing": "Ocorreu um problema ao visualizar esse documento.",
"problemUploadingFile": "Ocorreu um problema ao carregar o arquivo.",
"tokenInvalidOrExpired": "Token expirado ou inválido.",
"unPublishingDocument": "Ocorreu um problema ao despublicar esse documento",

View File

@@ -79,6 +79,7 @@
"notAllowedToAccessPage": "Вы не имеете права доступа к этой странице.",
"notAllowedToPerformAction": "У вас нет права на выполнение этого действия.",
"notFound": "Запрашиваемый ресурс не найден.",
"previewing": "При предварительном просмотре этого документа возникла проблема.",
"problemUploadingFile": "Возникла проблема при загрузке файла.",
"tokenInvalidOrExpired": "Токен либо недействителен, либо срок его действия истек.",
"unPublishingDocument": "При отмене публикации этого документа возникла проблема.",

View File

@@ -79,6 +79,7 @@
"notAllowedToAccessPage": "Du får inte komma åt den här sidan.",
"notAllowedToPerformAction": "Du får inte utföra denna åtgärd.",
"notFound": "Den begärda resursen hittades inte.",
"previewing": "Det uppstod ett problem när det här dokumentet skulle förhandsgranskas.",
"problemUploadingFile": "Det uppstod ett problem när filen laddades upp.",
"tokenInvalidOrExpired": "Token är antingen ogiltig eller har löpt ut.",
"unPublishingDocument": "Det uppstod ett problem när det här dokumentet skulle avpubliceras.",

View File

@@ -79,6 +79,7 @@
"notAllowedToAccessPage": "คุณไม่ได้รับอนุญาตให้เข้าถึงหน้านี้",
"notAllowedToPerformAction": "คุณไม่ได้รับอนุญาตให้ดำเนินการสิ่งนี้",
"notFound": "ไม่พบหน้าที่คุณต้องการ",
"previewing": "เกิดปัญหาระหว่างการแสดงตัวอย่างเอกสาร",
"problemUploadingFile": "เกิดปัญหาระหว่างการอัปโหลดไฟล์",
"tokenInvalidOrExpired": "Token ไม่ถูกต้องหรือหมดอายุ",
"unPublishingDocument": "เกิดปัญหาระหว่างการยกเลิกการเผยแพร่เอกสารนี้",

View File

@@ -79,6 +79,7 @@
"notAllowedToAccessPage": "Bu sayfaya erişim izniniz yok.",
"notAllowedToPerformAction": "Bu işlemi gerçekleştirmek için izniniz yok.",
"notFound": "Sayfa bulunamadı.",
"previewing": "Önizleme başarısız oldu",
"problemUploadingFile": "Dosya yüklenirken bir sorun oluştu.",
"tokenInvalidOrExpired": "Geçersiz veya süresi dolmuş token.",
"unPublishingDocument": "Geçerli döküman yayından kaldırılırken bir sorun oluştu.",

View File

@@ -300,6 +300,9 @@
"notFound": {
"type": "string"
},
"previewing": {
"type": "string"
},
"problemUploadingFile": {
"type": "string"
},
@@ -357,6 +360,7 @@
"notAllowedToAccessPage",
"notAllowedToPerformAction",
"notFound",
"previewing",
"problemUploadingFile",
"tokenInvalidOrExpired",
"unPublishingDocument",

View File

@@ -79,6 +79,7 @@
"notAllowedToAccessPage": "Ви не маєте доступу до цієї сторінки.",
"notAllowedToPerformAction": "Вам не дозволено виконувати цю дію.",
"notFound": "Запитуваний ресурс не знайдено.",
"previewing": "Виникла помилка під час попереднього перегляду цього документа.",
"problemUploadingFile": "Виникла помилка під час завантаження файлу.",
"tokenInvalidOrExpired": "Токен або не дійсний, або його строк дії закінчився.",
"unPublishingDocument": "Підчас відміни публікації даного документа, виникла помилка.",

View File

@@ -79,6 +79,7 @@
"notAllowedToAccessPage": "Lỗi - Bạn không có quyền truy cập trang này.",
"notAllowedToPerformAction": "Lỗi - Bạn không có quyền thực hiện lệnh này.",
"notFound": "Lỗi - Không thể tìm thấy.",
"previewing": "Lỗi - Đã xảy ra vấn đề khi xem trước bản tài liệu này.",
"problemUploadingFile": "Lỗi - Đã xảy ra vấn để khi tải lên file sau.",
"tokenInvalidOrExpired": "Lỗi - Token không hợp lệ hoặc đã hết hạn.",
"unPublishingDocument": "Lỗi - Đã xảy ra vấn để khi ẩn bản tài liệu.",

View File

@@ -79,6 +79,7 @@
"notAllowedToAccessPage": "您无权访问此页面。",
"notAllowedToPerformAction": "您不被允许执行此操作。",
"notFound": "没有找到请求的资源。",
"previewing": "预览文件时出现了问题。",
"problemUploadingFile": "上传文件时出现了问题。",
"tokenInvalidOrExpired": "令牌无效或已过期。",
"unPublishingDocument": "取消发布此文件时出现了问题。",