feat: Contentstack <-> ImageVault integration

This commit is contained in:
Michael Zetterberg
2024-03-25 11:38:14 +01:00
parent 920cbf241a
commit a706b9cf8a
39 changed files with 16647 additions and 0 deletions

View File

@@ -0,0 +1,126 @@
import {
Field,
FieldLabel,
Help,
Line,
TextInput,
} from "@contentstack/venus-components";
import { ChangeEvent, useState } from "react";
import { ImageVaultDAMConfig } from "~/utils/imagevault";
import type { IInstallationData } from "@contentstack/app-sdk/dist/src/types";
export type ConfigFormProps = {
values: Partial<ImageVaultDAMConfig>;
setInstallationData: (data: IInstallationData) => void;
};
export default function ConfigForm({
values,
setInstallationData,
}: ConfigFormProps) {
const [finalValues, setFinalValues] = useState(values);
return (
<div style={{ display: "grid", gap: "18px", margin: "18px" }}>
<Field style={{}}>
<FieldLabel version="v2" htmlFor="baseUrl">
Base url for contentstack
</FieldLabel>
<Help text="Including the region. Used as publishing source on ImageVault" />
<TextInput
id="baseUrl"
name="baseUrl"
type="url"
value={finalValues.baseUrl}
onChange={(evt: ChangeEvent<HTMLInputElement>) => {
setFinalValues((prev) => ({
...prev,
baseUrl: evt.target.value,
}));
setInstallationData({
configuration: {
...finalValues,
baseUrl: evt.target.value,
},
serverConfiguration: {},
});
}}
required={true}
willBlurOnEsc={true}
placeholder="Base url for Contentstack....."
version="v2"
width="large"
/>
</Field>
<Line type="dashed" />
<Field>
<FieldLabel version="v2" htmlFor="formatId">
Format Id for images
</FieldLabel>
<Help text="Images are fetched with a certain format. This should be an id from ImageVault" />
<TextInput
id="formatId"
name="formatId"
type="number"
value={finalValues?.formatId}
required={true}
willBlurOnEsc={true}
placeholder="Id for selected format..."
version="v2"
width="large"
onChange={(evt: ChangeEvent<HTMLInputElement>) => {
setFinalValues((prev) => ({
...prev,
formatId: evt.target.value,
}));
setInstallationData({
configuration: {
...finalValues,
formatId: evt.target.value,
},
serverConfiguration: {},
});
}}
/>
</Field>
<Line type="dashed" />
<Field>
<FieldLabel version="v2" htmlFor="v">
Url to ImageVault
</FieldLabel>
<TextInput
id="imageVaultUrl"
name="imageVaultUrl"
type="url"
value={finalValues.imageVaultUrl}
required={true}
willBlurOnEsc={true}
placeholder="www..."
version="v2"
width="large"
onChange={(evt: ChangeEvent<HTMLInputElement>) => {
setFinalValues((prev) => ({
...prev,
imageVaultUrl: evt.target.value,
}));
setInstallationData({
configuration: {
...finalValues,
imageVaultUrl: evt.target.value,
},
serverConfiguration: {},
});
}}
/>
</Field>
</div>
);
}

View File

@@ -0,0 +1,12 @@
export default function Disclaimer() {
return (
<div>
<p>Entry has not been saved or is missing value for title!</p>
<p>
ImageVault provides better publication tracking if the entry has been
saved and has a title before picking an asset. Therefore you need to
save the entry at least once with a title before choosing an image.
</p>
</div>
);
}

View File

@@ -0,0 +1,41 @@
import { ModalBody, ModalHeader } from "@contentstack/venus-components";
export default function FullSizeImage({
title,
onClose,
imageUrl,
alt,
aspectRatio,
}: {
title: string;
onClose: () => void;
imageUrl: string;
alt: string;
aspectRatio: number;
}) {
return (
<>
<ModalHeader title={title} closeModal={onClose} />
<ModalBody
id="fullsize-image"
style={{
maxHeight: "inherit",
borderRadius: "50px",
display: "flex",
justifyContent: "center",
}}
>
<img
src={imageUrl}
style={{
aspectRatio,
maxWidth: "100%",
maxHeight: "100%",
objectFit: "contain",
}}
alt={alt}
/>
</ModalBody>
</>
);
}

View File

@@ -0,0 +1,124 @@
import { useState, useEffect, ChangeEvent } from "react";
import {
ModalFooter,
ModalBody,
ModalHeader,
ButtonGroup,
Button,
Field as FieldComponent,
FieldLabel,
TextInput,
} from "@contentstack/venus-components";
import type { InsertResponse } from "~/types/imagevault";
type ImageEditModalProps = {
fieldData: InsertResponse;
setData: (data: InsertResponse) => void;
closeModal: () => void;
};
export default function ImageEditModal({
fieldData,
closeModal,
setData,
}: ImageEditModalProps) {
const [altText, setAltText] = useState("");
const [caption, setCaption] = useState("");
const assetUrl = fieldData.MediaConversions[0].Url;
useEffect(() => {
if (fieldData.Metadata && fieldData.Metadata.length) {
const altText = fieldData.Metadata.find((meta) =>
meta.Name.includes("AltText_")
)?.Value;
const caption = fieldData.Metadata.find((meta) =>
meta.Name.includes("Title_")
)?.Value;
setAltText(altText ?? "");
setCaption(caption ?? "");
}
}, [fieldData.Metadata]);
function handleSave() {
const metaData = fieldData.Metadata ?? [];
const newMetadata = metaData.map((meta) => {
if (meta.Name.includes("AltText_")) {
return { ...meta, Value: altText };
}
if (meta.Name.includes("Title_")) {
return { ...meta, Value: caption };
}
return meta;
});
setData({
...fieldData,
Metadata: newMetadata,
});
closeModal();
}
return (
<>
<ModalHeader title="Update image" closeModal={closeModal} />
<ModalBody
style={{
display: "flex",
gap: "1rem",
justifyContent: "space-between",
alignItems: "center",
width: "100%",
}}
>
<div style={{ flex: 1, overflowY: "auto" }}>
<img
src={assetUrl}
alt={altText}
height="100%"
style={{ maxHeight: "345px" }}
/>
</div>
<div style={{ flex: 1 }}>
<FieldComponent>
<FieldLabel htmlFor="alt">Alt text</FieldLabel>
<TextInput
value={altText}
placeholder="Alt text for image"
name="alt"
onChange={(e: ChangeEvent<HTMLInputElement>) =>
setAltText(e.target.value)
}
/>
</FieldComponent>
<FieldComponent>
<FieldLabel htmlFor="caption">Caption</FieldLabel>
<TextInput
value={caption}
placeholder="Caption for image..."
name="caption"
onChange={(e: ChangeEvent<HTMLInputElement>) =>
setCaption(e.target.value)
}
/>
</FieldComponent>
</div>
</ModalBody>
<ModalFooter>
<ButtonGroup>
<Button onClick={closeModal} buttonType="light">
Cancel
</Button>
<Button onClick={handleSave} icon="SaveWhite">
Save
</Button>
</ButtonGroup>
</ModalFooter>
</>
);
}

View File

@@ -0,0 +1,221 @@
import { useCallback, useEffect, useState } from "react";
import { flushSync } from "react-dom";
import {
AssetCardVertical,
Button,
FieldLabel,
cbModal,
} from "@contentstack/venus-components";
import ImageEditModal from "./ImageEditModal";
import FullSizeImage from "./FullSizeImage";
import { isInsertResponse, openImageVault } from "~/utils/imagevault";
import type { CbModalProps } from "@contentstack/venus-components/build/components/Modal/Modal";
import type UiLocation from "@contentstack/app-sdk/dist/src/uiLocation";
import type { InsertResponse } from "~/types/imagevault";
import type {
EntryDataPublishDetails,
ImageVaultDAMConfig,
} from "~/utils/imagevault";
import type { Lang } from "~/types/lang";
export type ImageVaultDAMProps = {
sdk: UiLocation;
config: ImageVaultDAMConfig;
initialData: InsertResponse | null;
};
type DAMButtonProps = {
onClick: () => void;
};
function DAMButton({ onClick }: DAMButtonProps) {
return (
<div style={{ padding: 2 }}>
<Button
onClick={onClick}
buttonType="link"
version="v2"
icon="v2-Assets"
iconAlignment="left"
size="small"
id="imagevaultpicker"
>
Choose a file
</Button>
</div>
);
}
type MediaProps = {
media: InsertResponse;
onDelete: () => void;
onEdit: () => void;
};
function Media({ media, onDelete, onEdit }: MediaProps) {
// MediaConversions is an array but will only contain one object
const { Url, Height, FormatHeight, Width, FormatWidth, Name, AspectRatio } =
media.MediaConversions[0];
const assetUrl = Url;
const title = media.Name;
const width = FormatWidth || Width;
const height = FormatHeight || Height;
const alt =
media.Metadata?.find((meta) => meta.Name.includes("AltText_"))?.Value ||
Name;
return (
<div key={Url} style={{ fontFamily: "Inter" }}>
<AssetCardVertical
assetType="image"
assetUrl={assetUrl}
title={title}
version="v2"
width={width}
height={height}
onDeleteClick={onDelete}
onEditClick={onEdit}
onFullScreenClick={() => {
const cbModalProps: CbModalProps = {
// @ts-expect-error: Component is badly typed
component: (props) => {
return (
<FullSizeImage
// eslint-disable-next-line react/prop-types
onClose={props.closeModal}
imageUrl={Url}
alt={alt}
title={Name}
aspectRatio={AspectRatio}
/>
);
},
modalProps: {
size: "max",
style: {
content: {
display: "grid",
width: "90dvw",
height: "90dvh",
maxHeight: "100%",
gridTemplateRows: "auto 1fr",
},
overlay: {},
},
},
};
cbModal(cbModalProps);
}}
/>
</div>
);
}
export default function ImageVaultDAM({
sdk,
config,
initialData,
}: ImageVaultDAMProps) {
const [media, setMedia] = useState<InsertResponse | null>(initialData);
const field = sdk.location.CustomField?.field;
const frame = sdk.location.CustomField?.frame;
const entry = sdk.location.CustomField?.entry;
const stack = sdk.location.CustomField?.stack;
const updateFrameHeight = useCallback(() => {
if (frame?.updateHeight) {
// We need to recalculate the height of the iframe when an image is added.
// Cannot use flushSync inside useEffect.
setTimeout(() => frame.updateHeight(document.body.scrollHeight), 0);
}
}, [frame]);
const handleMedia = useCallback(
(result?: InsertResponse) => {
if (field && result) {
flushSync(() => {
setMedia(result);
field.setData(result);
document.body.style.overflow = "hidden";
});
}
updateFrameHeight();
},
[field, updateFrameHeight]
);
useEffect(() => {
updateFrameHeight();
}, [updateFrameHeight]);
const handleEdit = useCallback(() => {
const fieldData = field?.getData() as InsertResponse;
if (isInsertResponse(fieldData)) {
cbModal({
// @ts-expect-error: Component is badly typed
component: (compProps) => (
<ImageEditModal
fieldData={fieldData}
setData={handleMedia}
{...compProps}
/>
),
modalProps: {
size: "max",
},
});
}
}, [field, handleMedia]);
if (!field || !frame || !entry || !stack) {
return <p>Initializing custom field...</p>;
}
const entryData: EntryDataPublishDetails = {
//TODO: Add support for branches
branch: "main",
contentTypeUid: entry.content_type.uid,
locale: entry.locale as Lang,
stackApiKey: stack._data.api_key,
title:
entry.getField("title").getData().toString() ||
`Untitled (${entry.content_type.uid})`,
uid: entry._data.uid,
};
return (
<div>
<div>
<FieldLabel htmlFor="imagevaultpicker" version="v2">
ImageVault Asset
</FieldLabel>
</div>
{media ? (
<Media
media={media}
onDelete={() => {
setMedia(null);
handleMedia();
}}
onEdit={handleEdit}
/>
) : (
<DAMButton
onClick={() => {
openImageVault({
config,
entryData,
onSuccess: handleMedia,
});
}}
/>
)}
</div>
);
}

View File

@@ -0,0 +1,11 @@
export default function InvalidConfig() {
return (
<div>
<p>The configuration for this app is not correct!</p>
<p>
Go to the app configuration to fill in all fields in order for this app
to run correctly.
</p>
</div>
);
}

View File

@@ -0,0 +1,12 @@
import { RemixBrowser } from "@remix-run/react";
import { startTransition, StrictMode } from "react";
import { hydrateRoot } from "react-dom/client";
startTransition(() => {
hydrateRoot(
document,
<StrictMode>
<RemixBrowser />
</StrictMode>
);
});

View File

@@ -0,0 +1,19 @@
import type { EntryContext } from "@remix-run/node";
import { RemixServer } from "@remix-run/react";
import { renderToString } from "react-dom/server";
export default function handleRequest(
request: Request,
responseStatusCode: number,
responseHeaders: Headers,
remixContext: EntryContext
) {
let html = renderToString(
<RemixServer context={remixContext} url={request.url} />
);
html = "<!DOCTYPE html>\n" + html;
return new Response(html, {
headers: { "Content-Type": "text/html" },
status: responseStatusCode,
});
}

46
remix/app/hooks/useApp.ts Normal file
View File

@@ -0,0 +1,46 @@
import UiLocation from "@contentstack/app-sdk/dist/src/uiLocation";
import { useEffect, useState } from "react";
export class SDKLoadingError extends Error {}
export default function useApp() {
const [, setError] = useState();
const [sdk, setSdk] = useState<UiLocation>();
const [config, setConfig] = useState<Record<string, string>>();
useEffect(() => {
async function init() {
try {
const ContentstackAppSDK = (await import("@contentstack/app-sdk"))
.default;
const initSdk = await ContentstackAppSDK.init();
setSdk(initSdk);
const config = await initSdk.getConfig();
setConfig(config);
const iframeWrapperRef = document.getElementById("field");
window.iframeRef = iframeWrapperRef;
window.postRobot = initSdk.postRobot;
} catch (e) {
let err: Error;
if (e instanceof Error) {
err = new SDKLoadingError(e.message);
}
// Error boundaries do not support async functions. Workaround:
// https://github.com/vercel/next.js/discussions/50564#discussioncomment-6063866
setError(() => {
throw err;
});
}
}
init();
}, [setSdk, setConfig]);
return {
sdk,
config,
};
}

72
remix/app/root.tsx Normal file
View File

@@ -0,0 +1,72 @@
import {
Links,
Meta,
Outlet,
Scripts,
ScrollRestoration,
useRouteError,
} from '@remix-run/react';
import { SDKLoadingError } from './hooks/useApp';
export function Layout({ children }: { children: React.ReactNode }) {
return (
<html lang="en">
<head>
<meta charSet="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<Meta />
<link
rel="stylesheet"
href="https://fonts.googleapis.com/css2?family=Inter:wght@100;200;300;400;500;600;700;800;900&display=swap"
/>
<link
rel="stylesheet"
href="https://www.unpkg.com/@contentstack/venus-components@2.2.3/build/main.css"
/>
<Links />
</head>
<body>
{children}
<ScrollRestoration />
<Scripts />
</body>
</html>
);
}
export default function App() {
return <Outlet />;
}
export function HydrateFallback() {
return <p>Loading...</p>;
}
export function ErrorBoundary() {
const error = useRouteError();
console.error(error);
return (
<html lang="en">
<head>
<title>Oh no!</title>
<Meta />
<Links />
</head>
<body>
{error instanceof SDKLoadingError ? (
<div>
<h2>Unable to load Contentstack SDK</h2>
<p>Make sure you have proper configuration in Contentstack.</p>
</div>
) : (
<div>
<h2>Something went wrong</h2>
<p>Check the console for the error.</p>
</div>
)}
<Scripts />
</body>
</html>
);
}

View File

@@ -0,0 +1,15 @@
import type { MetaFunction } from '@remix-run/node';
export const meta: MetaFunction = () => {
return [
{ title: 'DAM: ImageVault integration' },
{
name: 'description',
content: 'Integration of ImageVault as a DAM for Contentstack',
},
];
};
export default function Index() {
return null;
}

View File

@@ -0,0 +1,38 @@
import { Suspense, lazy } from "react";
import useApp from "~/hooks/useApp";
const ConfigForm = lazy(() => import("~/components/ConfigForm"));
export default function ConfigPage() {
const { sdk, config } = useApp();
const appConfigWidget = sdk?.location.AppConfigWidget;
const setInstallationData = appConfigWidget?.installation.setInstallationData;
if (!config) {
return (
<div>
<p>
Could not fetch the current configuration, please try again later!
</p>
</div>
);
}
if (!setInstallationData) {
return (
<div>
<p>
THe configuration cannot be updated right now, please try again later!
</p>
</div>
);
}
return (
<Suspense fallback={<p>Loading config form...</p>}>
<ConfigForm values={config} setInstallationData={setInstallationData} />
</Suspense>
);
}

View File

@@ -0,0 +1,69 @@
import { Suspense, lazy, useEffect, useState } from "react";
import { useScript } from "usehooks-ts";
import useApp from "~/hooks/useApp";
import Disclaimer from "~/components/Disclaimer";
import InvalidConfig from "~/components/InvalidConfig";
import { isImageVaultDAMConfig } from "~/utils/imagevault";
import type { InsertResponse } from "~/types/imagevault";
const ImageVaultDAM = lazy(() => import("~/components/ImageVaultDAM"));
export default function Field() {
const { sdk, config } = useApp();
const ivStatus = useScript(
"/scripts/imagevault-insert-media/insertmediawindow.min.js"
);
const [showDisclaimer, setShowDisclaimer] = useState(false);
const [fieldData, setFieldData] = useState<InsertResponse>();
const entry = sdk?.location.CustomField?.entry;
const field = sdk?.location.CustomField?.field;
useEffect(() => {
// If we can get field data from the SDK that means the entry has been
// saved at least once. If this is true, we are guaranteed entry UID.
// Entry that has not been saved does not have a entry UID and therefore
// cannot be referred to by ImageVault. Entry title is also required by us.
try {
if (field && entry) {
const data = field.getData();
const title = entry.getField("title").getData().toString();
if (data && title) {
setFieldData(data as InsertResponse);
} else {
throw new Error("Missing data or title for entry");
}
}
} catch (e) {
setShowDisclaimer(true);
}
}, [entry, field]);
if (showDisclaimer) {
return <Disclaimer />;
}
const loaded = !!(fieldData && ivStatus === "ready" && sdk && config);
const initialData =
fieldData && Object.keys(fieldData).length > 0 ? fieldData : null;
if (!loaded) {
return <p style={{ fontFamily: "Inter" }}> Loading dependecies...</p>;
}
return (
<div id="field">
{isImageVaultDAMConfig(config) ? (
<Suspense fallback={<p>Loading field...</p>}>
<ImageVaultDAM config={config} sdk={sdk} initialData={initialData} />
</Suspense>
) : (
<InvalidConfig />
)}
</div>
);
}