22 Commits

Author SHA1 Message Date
Erik Tiekstra
4b066706a5 fix(BOOK-478): Fixed issue with running handleMedia inside a useEffect which is causing an infinite loop 2025-11-25 11:30:29 +01:00
Erik Tiekstra
1337e8293f feat(SW-2541): Changed asset types to only add the data needed 2025-09-05 11:30:40 +02:00
Erik Tiekstra
64556d4b9c fix: Removed Resizable componenet as that breaks Imagevault implementation inside RTE
Approved-by: Michael Zetterberg
2025-06-23 09:29:26 +00:00
Erik Tiekstra
7e64becb40 Feat/SW-3031 imagevault updates
* chore(SW-3031): Updated dependencies
* feat(SW-3031): Added Imagevault Id to title and updated delete functionality

Approved-by: Michael Zetterberg
2025-06-18 13:14:02 +00:00
Erik Tiekstra
b1aaa6fd56 fix: removed @ts-expect-error 2024-10-25 07:53:58 +02:00
Erik Tiekstra
0c813d1eaf feat: updated packages to latest 2024-10-25 07:50:01 +02:00
Erik Tiekstra
babb66d989 fix: added fix for the height of the model content to not overflow on smaller devices 2024-10-25 07:45:53 +02:00
Erik Tiekstra
4c1ee66542 feat: moved to shared-components and implemented focal point picker in RTE 2024-10-15 11:33:51 +02:00
Erik Tiekstra
b1493bcd3d feat: implemented focal point picker inside ImageVault 2024-10-15 08:27:05 +02:00
Erik Tiekstra
5f9bd57a7c chore: updated readme with short 'setting started' and 'possible issues' texts. 2024-10-14 12:06:37 +02:00
Erik Tiekstra
a780698e83 chore: updated readme with getting started and possible issues 2024-10-14 12:06:37 +02:00
Erik Tiekstra
814a459866 fix: added solution to delete asset from image vault fields 2024-10-14 10:00:09 +02:00
Michael Zetterberg
7c6dda1781 fix: improve handling of config and rte plugin 2024-03-26 14:40:24 +01:00
Michael Zetterberg
8cad5ea290 fix: change CORS settings to apply only to RTE and specific domain 2024-03-26 14:03:50 +01:00
Michael Zetterberg
b35a32ab82 fix: allow CORS for Contentstack and its subdomains 2024-03-26 13:58:25 +01:00
Michael Zetterberg
d3fe77291d fix: rte build output named csiv.js always 2024-03-26 13:43:02 +01:00
Michael Zetterberg
44f277230f fix: spa mode redirects on Netlify 2024-03-26 13:28:39 +01:00
Michael Zetterberg
e65df3eb97 chore(tooling): add husky and lint-staged 2024-03-26 13:12:21 +01:00
Michael Zetterberg
083c57d0ca chore: add and run prettier 2024-03-26 13:03:24 +01:00
Michael Zetterberg
e9349992f8 feat: improve handling of config to allow overrides 2024-03-26 12:57:28 +01:00
Michael Zetterberg
c683f85bd8 chore(build): build rte before remix 2024-03-26 12:17:08 +01:00
Michael Zetterberg
a706b9cf8a feat: Contentstack <-> ImageVault integration 2024-03-26 11:53:20 +01:00
46 changed files with 20489 additions and 0 deletions

2
.gitignore vendored Normal file
View File

@@ -0,0 +1,2 @@
node_modules
build

1
.husky/pre-commit Normal file
View File

@@ -0,0 +1 @@
npx lint-staged

14
.prettierignore Normal file
View File

@@ -0,0 +1,14 @@
**/build
**/public
**/package.json
**/eslint.config.mjs
**/tsconfig.json
.husky
.prettierignore
lint-staged.config.js
netlify.toml
package.json
package-lock.json
prettier.config.cjs
tsconfig.json

33
README.md Normal file
View File

@@ -0,0 +1,33 @@
# Integration between Contentstack and ImageVault
Provides the following:
- A Custom field for Contentstack to select images in an ImageVault instance.
- A Custom RTE field for Contentstack to insert images from an ImageVault instance into an JSON RTE field.
## Custom field
The code is in `remix` folder.
## Custom RTE field
The code is in `rte` folder.
### Configuration
The RTE plugin has the following configuration available. The values should be set on App Config level and overriden when needed on Plugin Config level.
- `baseUrl`: The base url for Contentstack, most likely `https://eu-app.contentstack.com/`
- `formatId`: The id for the format in ImageVault to use when selecting an asset in ImageVault
- `imageVaultUrl`: The URL to the ImageVault instance to use when selecting an asset.
## Getting started
Run `npm install` in the root, the [rte](rte) and [remix](remix) folders to install all dependencies. After that you can start the project by running `npm run dev` in the root of the repository.
To use the local version of ImageVault inside contentstack, you need to add the `Dev ImageVault Custom field` as custom extension instead of the default `ImageVault` extension.
### Possible issues
- Browsers/Browser extensions
- ContentStack is using the extension from your locally served extension through `localhost:3000`. This means that some browsers or browser extensions block ContentStack from talking with `localhost`. **Solution:** Disable this functionality in your browser.

7
lint-staged.config.js Normal file
View File

@@ -0,0 +1,7 @@
const config = {
"remix/*.{ts,tsx}": () => "tsc -p remix/tsconfig.json --noEmit",
"rte/*.{ts,tsx}": () => "tsc -p rte/tsconfig.json --noEmit",
"*": "prettier --write",
}
export default config

12
netlify.toml Normal file
View File

@@ -0,0 +1,12 @@
[[headers]]
for = "/build/rte/csiv.js"
[headers.values]
Access-Control-Allow-Origin = "https://eu-rte-extension.contentstack.com"
Access-Control-Allow-Methods = "GET, HEAD"
Access-Control-Allow-Headers = "*"
[[redirects]]
from = "/*"
to = "/index.html"
status = 200

17875
package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

50
package.json Normal file
View File

@@ -0,0 +1,50 @@
{
"name": "@scandichotels/contentstack-imagevault",
"version": "1.0.0",
"private": true,
"type": "module",
"description": "Integration between Contentstack and ImageVault",
"workspaces": [
"remix",
"rte"
],
"scripts": {
"build": "npm run build:rte && npm run build:remix",
"build:remix": "cd remix && npm run build",
"build:rte": "cd rte && npm run build",
"dev": "concurrently npm:dev:*",
"dev:remix": "cd remix && npm run dev",
"dev:rte": "cd rte && npm run dev",
"prepare": "husky"
},
"dependencies": {
"@contentstack/app-sdk": "^2.3.1",
"@contentstack/venus-components": "^3.0.0",
"react": "^19.1.0",
"react-dom": "^19.1.0"
},
"devDependencies": {
"@eslint/compat": "^1.3.0",
"@eslint/eslintrc": "^3.3.1",
"@eslint/js": "^9.29.0",
"@types/react-dom": "^19.1.6",
"@typescript-eslint/eslint-plugin": "^8.34.0",
"@typescript-eslint/parser": "^8.34.0",
"concurrently": "^9.1.2",
"eslint": "^9.29.0",
"eslint-import-resolver-typescript": "^4.4.3",
"eslint-plugin-import": "^2.31.0",
"eslint-plugin-jsx-a11y": "^6.10.2",
"eslint-plugin-react": "^7.37.5",
"eslint-plugin-react-hooks": "^5.2.0",
"globals": "^16.2.0",
"husky": "^9.1.7",
"lint-staged": "^16.1.2",
"prettier": "^3.5.3",
"typescript": "^5.8.3",
"vite": "^6.3.5",
"vite-plugin-devtools-json": "^0.2.0",
"vite-plugin-lib-inject-css": "^2.2.2",
"vite-tsconfig-paths": "^5.1.4"
}
}

8
prettier.config.cjs Normal file
View File

@@ -0,0 +1,8 @@
module.exports = {
semi: false,
trailingComma: "es5",
singleQuote: false,
printWidth: 80,
tabWidth: 2,
endOfLine: "lf",
}

View File

@@ -0,0 +1,120 @@
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
type="basic"
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
type="basic"
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,141 @@
import {
Button,
ButtonGroup,
Field as FieldComponent,
FieldLabel,
ModalBody,
ModalFooter,
ModalHeader,
TextInput,
} from "@contentstack/venus-components"
import { ChangeEvent, useEffect, useState } from "react"
import FocalPointPicker from "~/shared-components/FocalPointPicker"
import type { FocalPoint, ImageVaultAsset } from "~/types/imagevault"
type ImageEditModalProps = {
fieldData: ImageVaultAsset
setData: (data: ImageVaultAsset) => void
closeModal: () => void
}
export default function ImageEditModal({
fieldData,
closeModal,
setData,
}: ImageEditModalProps) {
const [altText, setAltText] = useState("")
const [caption, setCaption] = useState("")
const [focalPoint, setFocalPoint] = useState<FocalPoint>({ x: 50, y: 50 })
const assetUrl = fieldData.url
useEffect(() => {
if (fieldData.meta.alt) {
setAltText(fieldData.meta.alt)
}
if (fieldData.meta.caption) {
setCaption(fieldData.meta.caption)
}
}, [fieldData.meta])
useEffect(() => {
if (fieldData.focalPoint) {
setFocalPoint(fieldData.focalPoint)
}
}, [fieldData.focalPoint])
function handleSave() {
const newData = {
...fieldData,
meta: {
alt: altText,
caption,
},
focalPoint,
}
setData(newData)
closeModal()
}
function changeFocalPoint(focalPoint: FocalPoint) {
setFocalPoint(focalPoint)
}
return (
<>
<ModalHeader title="Update image" closeModal={closeModal} />
<ModalBody
style={{
display: "grid",
gridTemplateColumns: "1fr minmax(max-content, 250px)",
gap: "1rem",
alignItems: "center",
width: "auto",
maxHeight: "calc(90dvh - 124px)", // 124px is the height of the header and footer
maxWidth: "90dvw",
overflow: "auto",
}}
>
<FocalPointPicker
imageSrc={assetUrl}
focalPoint={focalPoint}
onChange={changeFocalPoint}
/>
<div>
<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>
<FieldComponent>
<FieldLabel htmlFor="focalPoint">Focal Point</FieldLabel>
<TextInput
value={`X: ${focalPoint.x}, Y: ${focalPoint.y}`}
name="focalPoint"
disabled
/>
</FieldComponent>
<FieldComponent>
<FieldLabel htmlFor="imageVaultId">Imagevault Id</FieldLabel>
<TextInput
value={fieldData.imageVaultId}
name="imageVaultId"
disabled
/>
</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,214 @@
import { useCallback, useEffect, useState } from "react"
import { flushSync } from "react-dom"
import {
AssetCardVertical,
Button,
FieldLabel,
cbModal,
} from "@contentstack/venus-components"
import { isInsertResponse, openImageVault } from "~/utils/imagevault"
import ImageEditModal from "./ImageEditModal"
import type UiLocation from "@contentstack/app-sdk/dist/src/uiLocation"
import type { CbModalProps } from "@contentstack/venus-components/build/components/Modal/Modal"
import type { ImageVaultAsset } from "~/types/imagevault"
import type { Lang } from "~/types/lang"
import type {
EntryDataPublishDetails,
ImageVaultDAMConfig,
} from "~/utils/imagevault"
import FullSizeImage from "./FullSizeImage"
export type ImageVaultDAMProps = {
sdk: UiLocation
config: ImageVaultDAMConfig
initialData: ImageVaultAsset | 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: ImageVaultAsset
onDelete: () => void
onEdit: () => void
}
function Media({ media, onDelete, onEdit }: MediaProps) {
const { url, meta, dimensions } = media
const { width, height, aspectRatio } = dimensions
const assetUrl = media.url
const assetTitle = `Id: ${media.imageVaultId} - ${media.fileName}`
const alt = meta.alt || meta.caption || ""
const title = meta.caption || meta.alt || ""
return (
<div key={url} style={{ fontFamily: "Inter" }}>
<AssetCardVertical
assetType="image"
assetUrl={assetUrl}
title={assetTitle}
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={title}
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(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(), 0)
}
}, [frame])
const handleMedia = useCallback(
(asset?: ImageVaultAsset) => {
if (field) {
flushSync(() => {
const data = asset || null
setMedia(data)
field.setData(data)
document.body.style.overflow = "hidden"
})
}
updateFrameHeight()
},
[field, updateFrameHeight]
)
const handleEdit = useCallback(() => {
const fieldData = field?.getData()
if (fieldData) {
cbModal({
// @ts-expect-error: Component is badly typed
component: (compProps) => (
<ImageEditModal
fieldData={fieldData}
setData={handleMedia}
{...compProps}
/>
),
modalProps: {
size: "max",
style: {
content: { maxHeight: "90dvh", maxWidth: "90dvw", width: "auto" },
overlay: {},
},
},
})
}
}, [field, handleMedia])
useEffect(() => {
updateFrameHeight()
}, [updateFrameHeight])
if (!field || !frame || !entry || !stack) {
return <p>Initializing custom field...</p>
}
// The existing data might still be in InsertResponse format if the user has not edited it yet.
// We'll convert it to ImageVaultAsset when the component mounts.
const fieldData = field.getData()
if (isInsertResponse(fieldData)) {
field.setData(initialData)
}
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>
<FieldLabel htmlFor="imagevaultpicker" version="v2">
ImageVault Asset
</FieldLabel>
{media ? (
<Media media={media} onDelete={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,
})
}

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

@@ -0,0 +1,47 @@
import UiLocation from "@contentstack/app-sdk/dist/src/uiLocation"
import { useEffect, useRef, useState } from "react"
export class SDKLoadingError extends Error {}
export default function useApp() {
const ref = useRef<HTMLDivElement>(null)
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)
window.iframeRef = ref.current
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,
ref,
}
}

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>
)
}

103
remix/app/routes/field.tsx Normal file
View File

@@ -0,0 +1,103 @@
import "@contentstack/venus-components/build/main.css"
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 { GenericObjectType } from "@contentstack/app-sdk/dist/src/types/common.types"
import UiLocation from "@contentstack/app-sdk/dist/src/uiLocation"
import type { ImageVaultAsset, InsertResponse } from "~/types/imagevault"
import {
getImageVaultAssetFromData,
isImageVaultDAMConfig,
} from "~/utils/imagevault"
const ImageVaultDAM = lazy(() => import("~/components/ImageVaultDAM"))
interface FieldContentProps {
sdk?: UiLocation
appConfig?: GenericObjectType
}
function FieldContent({ sdk, appConfig }: FieldContentProps) {
const ivStatus = useScript(
"/scripts/imagevault-insert-media/insertmediawindow.min.js"
)
const [showDisclaimer, setShowDisclaimer] = useState(false)
const [fieldData, setFieldData] = useState<
InsertResponse | ImageVaultAsset | null
>()
const [dataIsLoaded, setDataIsLoaded] = useState(false)
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 (!title) {
throw new Error("Missing title for entry")
}
if (data) {
setFieldData(data as InsertResponse)
}
setDataIsLoaded(true)
}
} catch (e) {
setShowDisclaimer(true)
console.log("Unable to get field data from SDK: ", e)
}
}, [entry, field])
if (showDisclaimer) {
return <Disclaimer />
}
const loaded = !!(dataIsLoaded && ivStatus === "ready" && sdk && appConfig)
const initialData =
fieldData && Object.keys(fieldData).length > 0 ? fieldData : null
if (!loaded) {
return <p style={{ fontFamily: "Inter" }}> Loading dependencies...</p>
}
if (!isImageVaultDAMConfig(appConfig)) {
return <InvalidConfig />
}
const fieldConfig = sdk.location.CustomField?.fieldConfig
const config = { ...appConfig, ...fieldConfig }
// The existing data might still be in InsertResponse format if the user has not edited it yet.
// We'll convert it to ImageVaultAsset when the component mounts.
const imageVaultAsset = getImageVaultAssetFromData(initialData)
return (
<Suspense fallback={<p>Loading field...</p>}>
<ImageVaultDAM config={config} sdk={sdk} initialData={imageVaultAsset} />
</Suspense>
)
}
export default function Field() {
const { sdk, config, ref } = useApp()
return (
<div ref={ref}>
<FieldContent sdk={sdk} appConfig={config} />
</div>
)
}

1
remix/env.d.ts vendored Normal file
View File

@@ -0,0 +1 @@
/// <reference types="vite/client" />

133
remix/eslint.config.mjs Normal file
View File

@@ -0,0 +1,133 @@
import { fixupConfigRules, fixupPluginRules } from "@eslint/compat"
import { FlatCompat } from "@eslint/eslintrc"
import js from "@eslint/js"
import typescriptEslint from "@typescript-eslint/eslint-plugin"
import tsParser from "@typescript-eslint/parser"
import _import from "eslint-plugin-import"
import jsxA11Y from "eslint-plugin-jsx-a11y"
import react from "eslint-plugin-react"
import { defineConfig, globalIgnores } from "eslint/config"
import globals from "globals"
import path from "node:path"
import { fileURLToPath } from "node:url"
const __filename = fileURLToPath(import.meta.url)
const __dirname = path.dirname(__filename)
const compat = new FlatCompat({
baseDirectory: __dirname,
recommendedConfig: js.configs.recommended,
allConfig: js.configs.all,
})
export default defineConfig([
globalIgnores(["build/**/*", "node_modules/**/*", "public/**/*"]),
{
extends: compat.extends("eslint:recommended"),
languageOptions: {
globals: {
...globals.browser,
...globals.commonjs,
},
ecmaVersion: "latest",
sourceType: "module",
parserOptions: {
ecmaFeatures: {
jsx: true,
},
},
},
},
{
files: ["**/*.{js,jsx,ts,tsx}"],
extends: fixupConfigRules(
compat.extends(
"plugin:react/recommended",
"plugin:react/jsx-runtime",
"plugin:react-hooks/recommended",
"plugin:jsx-a11y/recommended"
)
),
plugins: {
react: fixupPluginRules(react),
"jsx-a11y": fixupPluginRules(jsxA11Y),
},
settings: {
react: {
version: "detect",
},
formComponents: ["Form"],
linkComponents: [
{
name: "Link",
linkAttribute: "to",
},
{
name: "NavLink",
linkAttribute: "to",
},
],
"import/resolver": {
typescript: {
project: "./remix/tsconfig.json",
},
},
},
rules: {
"react/jsx-uses-vars": "error",
"react/jsx-uses-react": "error",
},
},
{
files: ["**/*.{ts,tsx}"],
extends: fixupConfigRules(
compat.extends(
"plugin:@typescript-eslint/recommended",
"plugin:import/recommended",
"plugin:import/typescript"
)
),
plugins: {
"@typescript-eslint": fixupPluginRules(typescriptEslint),
import: fixupPluginRules(_import),
},
languageOptions: {
parser: tsParser,
},
settings: {
"import/internal-regex": "^~/",
"import/resolver": {
node: {
extensions: [".ts", ".tsx"],
},
typescript: {
alwaysTryTypes: true,
},
},
},
},
{
files: ["**/.eslintrc.cjs"],
languageOptions: {
globals: {
...globals.node,
},
},
},
])

25
remix/package.json Normal file
View File

@@ -0,0 +1,25 @@
{
"name": "@scandichotels/contentstack-imagevault-remix",
"private": true,
"sideEffects": false,
"type": "module",
"scripts": {
"build": "remix vite:build",
"dev": "remix vite:dev --port 3000",
"lint": "eslint --cache --cache-location ./node_modules/.cache/eslint .",
"prebuild": "concurrently npm:lint npm:typecheck",
"preview": "vite preview",
"typecheck": "tsc"
},
"dependencies": {
"@remix-run/node": "^2.16.8",
"@remix-run/react": "^2.16.8",
"usehooks-ts": "^3.1.1"
},
"devDependencies": {
"@remix-run/dev": "^2.16.8"
},
"engines": {
"node": ">=22.0.0"
}
}

BIN
remix/public/favicon.ico Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.5 KiB

View File

@@ -0,0 +1,3 @@
// This file is sourced from https://clientscript.imagevault.se/scripts/imagevault-insert-media/scripts/insertmediawindow.min.js
// Removed sourceMap line.
(()=>{"use strict";var e={26:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.InsertMediaBase=void 0;var n=function(){function e(e){this.postMessageCallbackReceived=!1,this.pingOn=!1,this.readConfig(e)}return e.prototype.messageEvent=function(e){this.messageReceiver(e)},e.prototype.readConfig=function(e){var t=null;if(null==e.origin){var n=document.createElement("a");n.href=e.imageVaultUiUrl,e.origin=n.protocol+"//"+n.hostname,n.port&&(/http:/i.test(n.protocol)&&"80"!==n.port||/https:/i.test(n.protocol)&&"443"!==n.port)&&(e.origin+=":".concat(n.port))}if(e.publishingSource||(t="Publish source must be configured"),null!=t&&e.error)e.error(null,t);else if(null!=t)throw t;this.config=e},e.prototype.setupCallback=function(){var e=this;if(this.postMessageCallbackReceived)return!0;if(this.containerWindow.postMessage){try{this.containerWindow.postMessage("init",this.config.origin)}catch(e){}setTimeout((function(){e.setupCallback()}),1e3)}return!1},e.prototype.ping=function(){var e=this;if(this.pingOn){if(this.containerWindow.postMessage)try{this.containerWindow.postMessage("ping",this.config.origin)}catch(e){}setTimeout((function(){e.ping()}),1e3)}},e.prototype.messageReceiver=function(e){var t=this;if(e.origin===this.config.origin){if("initReceived"===e.data)return this.postMessageCallbackReceived=!0,this.pingOn=!0,setTimeout((function(){t.ping()}),1e3),void(this.config.debug&&this.config.debug(e));if("pong"!==e.data)return"close"===e.data?(this.pingOn=!1,this.beforeClose&&this.beforeClose(e),void(this.config.close&&this.config.close(e))):void(this.config.success&&(e.response=JSON.parse(e.data),this.config.success(e)));this.config.debug&&this.config.debug(e)}else this.config.error&&this.config.error(e,"origin does not match")},e}();t.InsertMediaBase=n},655:function(e,t,n){var o,i=this&&this.__extends||(o=function(e,t){return o=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n])},o(e,t)},function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");function n(){this.constructor=e}o(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)});Object.defineProperty(t,"__esModule",{value:!0}),t.InsertMediaWindow=void 0;var s=function(e){function t(t,n){var o=e.call(this,t)||this;return o.setupComplete=!0,o.windowOptions=n,o}return i(t,e),t.prototype.openImageVault=function(){var e=this.config;e.formatId||(e.formatId="0");var t="mediaurlbase=".concat(encodeURIComponent(e.mediaUrlBase),"&ensurepublishingsource=").concat(encodeURIComponent(e.publishingSource))+(e.uiLang?"&uiLang=".concat(encodeURIComponent(e.uiLang)):"")+(e.pageLang?"&pagelang=".concat(encodeURIComponent(e.pageLang)):"")+(e.mediaUrl?"&mediaUrl=".concat(encodeURIComponent(e.mediaUrl)):"")+(e.insertMode?"&insertMode=".concat(encodeURIComponent(e.insertMode.toString())):"")+(e.insertMultiple?"&insertmultiple=".concat(encodeURIComponent(e.insertMultiple.toString())):"")+"&formatId=".concat(e.formatId.toString())+(e.additionalMetadataIds?"&additionalMetadataIds=".concat(encodeURIComponent(e.additionalMetadataIds.toString())):""),n=e.publishDetails;n&&(t+=(n.text?"&publishdetails.Text=".concat(encodeURIComponent(n.text)):"")+(n.url?"&publishdetails.Url=".concat(encodeURIComponent(n.url)):"")+(n.groupId?"&publishdetails.GroupId=".concat(encodeURIComponent(n.groupId)):"")),t+=e.mediaId?"#search=".concat(e.mediaId)+"&items="+e.mediaId:"#",this.containerWindow=window.open("".concat(this.config.imageVaultUiUrl,"?").concat(t),"ImageVault",this.windowOptions);var o=this,i=function(e){return o.messageEvent(e)};window.addEventListener("message",i,!1),this.beforeClose=function(){o.containerWindow.close()};var s=window.setInterval((function(){(null==o.containerWindow||o.containerWindow.closed)&&(window.clearInterval(s),window.removeEventListener("message",i,!1),window.removeEventListener("message",i,!0))}),200);this.setupComplete&&(this.postMessageCallbackReceived=!1,this.setupCallback())},t}(n(26).InsertMediaBase);t.InsertMediaWindow=s,(window.ImageVault=window.ImageVault||{}).InsertMediaWindow=s}},t={};!function n(o){var i=t[o];if(void 0!==i)return i.exports;var s=t[o]={exports:{}};return e[o].call(s.exports,s,s.exports,n),s.exports}(655)})();

26
remix/tsconfig.json Normal file
View File

@@ -0,0 +1,26 @@
{
"extends": "../tsconfig.json",
"include": [
"env.d.ts",
"../types/**/*.ts",
"../utils/**/*.ts",
"../shared-components/**/*.ts",
"../shared-components/**/*.tsx",
"**/*.ts",
"**/*.tsx"
],
"compilerOptions": {
"types": ["@remix-run/node", "vite/client"],
"skipLibCheck": true,
"jsx": "react-jsx",
"baseUrl": ".",
"paths": {
"~/*": ["./remix/*"],
"~/types/*": ["../types/*"],
"~/utils/*": ["../utils/*"],
"~/components/*": ["./app/components/*"],
"~/hooks/*": ["./app/hooks/*"],
"~/shared-components/*": ["../shared-components/*"],
}
}
}

23
remix/vite.config.ts Normal file
View File

@@ -0,0 +1,23 @@
import { vitePlugin as remix } from "@remix-run/dev"
import { defineConfig } from "vite"
import devtoolsJson from "vite-plugin-devtools-json"
import { libInjectCss } from "vite-plugin-lib-inject-css"
import tsconfigPaths from "vite-tsconfig-paths"
export default defineConfig({
plugins: [
remix({ ssr: false }),
tsconfigPaths(),
libInjectCss(),
devtoolsJson(),
],
server: {
headers: {
"Access-Control-Allow-Origin":
"https://eu-rte-extension.contentstack.com",
"Access-Control-Allow-Methods": "GET, HEAD",
"Access-Control-Allow-Headers": "*",
},
},
build: { emptyOutDir: true },
})

View File

@@ -0,0 +1,31 @@
import React, { PropsWithChildren } from "react"
import { Tooltip } from "@contentstack/venus-components"
type EmbedBtnProps = PropsWithChildren & {
content: string
onClick: (e: unknown) => void
title: string
}
export default function EmbedBtn({
content,
title,
onClick,
children,
}: EmbedBtnProps) {
return (
<Tooltip position="bottom" content={content}>
<button
id={title}
type="button"
onClick={(e) => {
e?.preventDefault()
e?.stopPropagation()
onClick(e)
}}
>
{children}
</button>
</Tooltip>
)
}

View File

@@ -0,0 +1,146 @@
import {
Button,
ButtonGroup,
Field as FieldComponent,
FieldLabel,
ModalBody,
ModalFooter,
ModalHeader,
TextInput,
} from "@contentstack/venus-components"
import React, { ChangeEvent, useEffect, useState } from "react"
import type { IRteElementType } from "@contentstack/app-sdk/dist/src/RTE/types"
import FocalPointPicker from "~/shared-components/FocalPointPicker"
import type { FocalPoint, ImageVaultAsset } from "~/types/imagevault"
type ImageEditModalProps = {
element: IRteElementType & {
attrs: ImageVaultAsset
}
setData: (data: ImageVaultAsset) => void
closeModal: () => void
}
export default function ImageEditModal({
element,
setData,
closeModal,
}: ImageEditModalProps) {
const imageVaultAsset: ImageVaultAsset = element.attrs
const [altText, setAltText] = useState("")
const [caption, setCaption] = useState("")
const [focalPoint, setFocalPoint] = useState<FocalPoint>({ x: 50, y: 50 })
const assetUrl = imageVaultAsset.url
useEffect(() => {
if (imageVaultAsset.meta.alt) {
setAltText(imageVaultAsset.meta.alt)
}
if (imageVaultAsset.meta.caption) {
setCaption(imageVaultAsset.meta.caption)
}
}, [imageVaultAsset.meta])
useEffect(() => {
if (imageVaultAsset.focalPoint) {
setFocalPoint(imageVaultAsset.focalPoint)
}
}, [imageVaultAsset.focalPoint])
function handleSave() {
const newData = {
...imageVaultAsset,
meta: {
alt: altText,
caption,
},
focalPoint,
}
setData(newData)
closeModal()
}
function changeFocalPoint(focalPoint: FocalPoint) {
setFocalPoint(focalPoint)
}
return (
<>
<ModalHeader title="Update image" closeModal={closeModal} />
<ModalBody
style={{
display: "grid",
gridTemplateColumns: "1fr minmax(max-content, 250px)",
gap: "1rem",
alignItems: "center",
width: "auto",
maxHeight: "calc(90dvh - 124px)", // 124px is the height of the header and footer
maxWidth: "90dvw",
overflow: "auto",
}}
>
<FocalPointPicker
imageSrc={assetUrl}
focalPoint={focalPoint}
onChange={changeFocalPoint}
/>
<div>
<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>
<FieldComponent>
<FieldLabel htmlFor="focalPoint">Focal Point</FieldLabel>
<TextInput
value={`X: ${focalPoint.x}, Y: ${focalPoint.y}`}
name="focalPoint"
disabled
/>
</FieldComponent>
<FieldComponent>
<FieldLabel htmlFor="imageVaultId">Imagevault Id</FieldLabel>
<TextInput
value={imageVaultAsset.imageVaultId}
name="imageVaultId"
disabled
/>
</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,132 @@
import { Icon, Tooltip, cbModal } from "@contentstack/venus-components"
import React, { PropsWithChildren, useCallback } from "react"
import EmbedBtn from "./EmbedBtn"
import ImageEditModal from "./ImageEditModal"
import type {
IRteElementType,
IRteParam,
} from "@contentstack/app-sdk/dist/src/RTE/types"
import type { ImageVaultAsset, InsertResponse } from "~/types/imagevault"
import {
getImageVaultAssetFromData,
isInsertResponse,
} from "~/utils/imagevault"
type ImageElementProps = PropsWithChildren & {
element: IRteElementType & { attrs: ImageVaultAsset | InsertResponse }
rte: IRteParam
}
export function ImageElement({ children, element, rte }: ImageElementProps) {
const assetIsInsertResponse = isInsertResponse(element.attrs)
const imageVaultAsset = getImageVaultAssetFromData(element.attrs)
const isSelected = rte.selection.isSelected()
const isFocused = rte.selection.isFocused()
const path = rte.getPath(element)
const isHighlight = isFocused && isSelected
const handleMedia = useCallback(
(asset: ImageVaultAsset) => {
rte._adv.Transforms.setNodes<IRteElementType>(
rte._adv.editor,
{
attrs: { ...asset },
},
{ at: path }
)
},
[rte, path]
)
const handleEdit = useCallback(() => {
cbModal({
// @ts-expect-error: Component is badly typed
component: (compProps) => (
<ImageEditModal
element={element}
setData={handleMedia}
{...compProps}
/>
),
modalProps: {
size: "max",
style: {
content: {
maxHeight: "90dvh",
maxWidth: "90dvw",
width: "auto",
},
overlay: {},
},
},
})
}, [element, handleMedia])
const ToolTipButtons = () => {
return (
<div contentEditable={false} className="embed--btn-group">
<EmbedBtn title="edit" content="Edit" onClick={handleEdit}>
<Icon icon="Rename" />
</EmbedBtn>
<EmbedBtn
title="remove"
content={"Remove"}
onClick={() => rte.removeNode(element)}
>
<Icon icon="Trash" />
</EmbedBtn>
</div>
)
}
if (!imageVaultAsset) {
return <>{children}</>
}
// The existing data might still be in InsertResponse format if the user has not edited it yet.
// We'll convert it to ImageVaultAsset when the user edits the RTE.
if (assetIsInsertResponse) {
handleMedia(imageVaultAsset)
}
return (
<Tooltip
zIndex={909}
className="p-0"
style={{ marginBottom: "10px" }}
position="top"
variantType="light"
offset={[0, -15]}
content={<ToolTipButtons />}
>
<span data-type="asset" contentEditable={false}>
<div
contentEditable={false}
style={{
width: "280px",
height: "auto",
...(isHighlight ? { border: "1px solid #6c5ce7" } : {}),
}}
>
<img
src={imageVaultAsset.url}
onError={(event) => {
event.currentTarget.src = "https://placehold.co/600x400"
}}
style={{
width: "100%",
height: "auto",
aspectRatio: imageVaultAsset.dimensions.aspectRatio,
borderRadius: "8px",
}}
alt={imageVaultAsset.meta.alt}
title={`Id: ${imageVaultAsset.imageVaultId} - ${imageVaultAsset.fileName}`}
/>
</div>
{children}
</span>
</Tooltip>
)
}

1
rte/env.d.ts vendored Normal file
View File

@@ -0,0 +1 @@
declare const IS_DEV: boolean

133
rte/eslint.config.mjs Normal file
View File

@@ -0,0 +1,133 @@
import { fixupConfigRules, fixupPluginRules } from "@eslint/compat"
import { FlatCompat } from "@eslint/eslintrc"
import js from "@eslint/js"
import typescriptEslint from "@typescript-eslint/eslint-plugin"
import tsParser from "@typescript-eslint/parser"
import _import from "eslint-plugin-import"
import jsxA11Y from "eslint-plugin-jsx-a11y"
import react from "eslint-plugin-react"
import { defineConfig, globalIgnores } from "eslint/config"
import globals from "globals"
import path from "node:path"
import { fileURLToPath } from "node:url"
const __filename = fileURLToPath(import.meta.url)
const __dirname = path.dirname(__filename)
const compat = new FlatCompat({
baseDirectory: __dirname,
recommendedConfig: js.configs.recommended,
allConfig: js.configs.all,
})
export default defineConfig([
globalIgnores(["node_modules/**/*"]),
{
extends: compat.extends("eslint:recommended"),
languageOptions: {
globals: {
...globals.browser,
...globals.commonjs,
},
ecmaVersion: "latest",
sourceType: "module",
parserOptions: {
ecmaFeatures: {
jsx: true,
},
},
},
},
{
files: ["**/*.{js,jsx,ts,tsx}"],
extends: fixupConfigRules(
compat.extends(
"plugin:react/recommended",
"plugin:react/jsx-runtime",
"plugin:react-hooks/recommended",
"plugin:jsx-a11y/recommended"
)
),
plugins: {
react: fixupPluginRules(react),
"jsx-a11y": fixupPluginRules(jsxA11Y),
},
settings: {
react: {
version: "detect",
},
formComponents: ["Form"],
linkComponents: [
{
name: "Link",
linkAttribute: "to",
},
{
name: "NavLink",
linkAttribute: "to",
},
],
"import/resolver": {
typescript: {
project: "./rte/tsconfig.json",
},
},
},
rules: {
"react/jsx-uses-vars": "error",
"react/jsx-uses-react": "error",
},
},
{
files: ["**/*.{ts,tsx}"],
extends: fixupConfigRules(
compat.extends(
"plugin:@typescript-eslint/recommended",
"plugin:import/recommended",
"plugin:import/typescript"
)
),
plugins: {
"@typescript-eslint": fixupPluginRules(typescriptEslint),
import: fixupPluginRules(_import),
},
languageOptions: {
parser: tsParser,
},
settings: {
"import/internal-regex": "^~/",
"import/resolver": {
node: {
extensions: [".ts", ".tsx"],
},
typescript: {
alwaysTryTypes: true,
},
},
},
},
{
files: ["**/.eslintrc.cjs"],
languageOptions: {
globals: {
...globals.node,
},
},
},
])

232
rte/main.tsx Normal file
View File

@@ -0,0 +1,232 @@
import ContentstackSDK from "@contentstack/app-sdk"
import React from "react"
import { Icon } from "@contentstack/venus-components"
import { openImageVault } from "~/utils/imagevault"
import { ImageElement } from "~/components/ImageElement"
import type {
ContentstackEmbeddedData,
ContentstackPluginDefinition,
ExtractedContentstackEmbeddedData,
} from "~/types/contentstack"
import type { Lang } from "~/types/lang"
function findThisPlugin(ext: ContentstackPluginDefinition) {
return ext.type === "rte_plugin" && /imagevault/i.test(ext.title)
}
async function loadScript(url: string) {
return new Promise((resolve, reject) => {
if (!document) {
throw new Error("Run in browser only")
}
const head = document.head || document.getElementsByTagName("head")[0]
const script = document.createElement("script")
script.type = "text/javascript"
script.async = true
script.src = url
script.onload = function () {
this.onerror = this.onload = null
resolve(window.ImageVault)
}
script.onerror = function () {
this.onerror = this.onload = null
reject(`Failed to load ${this.src}`)
}
head.appendChild(script)
})
}
function extractContentstackEmbeddedData(
jwtLike: string
): ExtractedContentstackEmbeddedData | null {
try {
const base64str = jwtLike.replace(/-/g, "+").replace(/_/g, "/")
const jsonStr = decodeURIComponent(
window
.atob(base64str)
.split("")
.map(function (c) {
return "%" + ("00" + c.charCodeAt(0).toString(16)).slice(-2)
})
.join("")
)
const json = JSON.parse(jsonStr)
json.exports = JSON.parse(json.exports)
json.props.value = JSON.parse(json.props.value)
if (IS_DEV) {
console.log(`Contentstack Embedded Data`, json)
}
const {
entryMetadata,
utilis: {
content_type: { schema },
extensions,
},
requestProps: {
stack: { api_key },
branch,
},
}: ContentstackEmbeddedData = json.props.value
const titleField = schema.find((f) => f.uid === "title")
// We force this value with ! because we know it exists.
// Otherwise this code would not run.
const plugin = extensions.find(findThisPlugin)!
return {
stack: {
apiKey: api_key,
},
branch,
contentType: {
uid: entryMetadata.contentTypeUid,
},
entry: {
locale: entryMetadata.locale,
title:
titleField && titleField.data_type === "text"
? titleField.value
: "Untitled",
uid: entryMetadata.entryUid,
},
plugin,
}
} catch (e) {
console.log(`Unable to parse JWT like: ${jwtLike}`, e)
}
return null
}
let ivloaded = false
function loadIV(plugin: ContentstackPluginDefinition) {
if (plugin.src) {
const url = new URL(plugin.src)
url.pathname = "/scripts/imagevault-insert-media/insertmediawindow.min.js"
if (IS_DEV) {
console.log(`Loading script: ${url.toString()}`)
}
loadScript(url.toString())
ivloaded = true
}
}
export default ContentstackSDK.init().then((sdk) => {
try {
const extensionObj = sdk["location"]
const RTE = extensionObj["RTEPlugin"]
if (!RTE) {
return
}
let embeddedData: ExtractedContentstackEmbeddedData | null = null
const jwtLike = window.name.split("__").find((str) => str.startsWith("ey"))
if (jwtLike) {
embeddedData = extractContentstackEmbeddedData(jwtLike)
if (embeddedData?.plugin) {
loadIV(embeddedData.plugin)
}
}
const ImageVault = RTE("ImageVault", (rte) => {
if (rte) {
if (!ivloaded) {
// Loading failed via embedded data above, try again with data inside RTE
// @ts-expect-error: incorrect typings, requestProps is available at runtime
const extensions = rte._adv.editor.requestProps
.extensions as ContentstackPluginDefinition[]
const plugin = extensions.find(findThisPlugin)
if (plugin) {
loadIV(plugin)
}
}
}
return {
title: "Choose assets from ImageVault",
icon: <Icon icon="Image" version="v2" height={24} width={24} />,
render: (props) => {
if (rte) {
return (
<ImageElement element={props.element} rte={rte}>
{props.children}
</ImageElement>
)
} else {
console.error("No instance of RTE found")
return (
<p>An unexpected error occured, see console for more info.</p>
)
}
},
displayOn: ["toolbar"],
elementType: ["void"],
}
})
ImageVault.on("exec", async (rte) => {
if (rte) {
const savedSelection = rte.selection.get() ?? undefined
const appConfig = await rte.getConfig()
// This is the configuration for this instance of the plugin.
// You edit this in the content types settings RTE plugin section.
// @ts-expect-error: Added at runtime
const pluginConfig = await rte.getFieldConfig()
const config = {
...appConfig,
...pluginConfig,
}
openImageVault({
config,
entryData: {
//TODO: Add support for branches
branch: embeddedData ? embeddedData.contentType.uid : "main",
contentTypeUid: embeddedData
? embeddedData.contentType.uid
: "Unknown",
locale: embeddedData
? embeddedData.entry.locale
: ("unknown" as Lang),
stackApiKey: embeddedData ? embeddedData.stack.apiKey : "unknown",
title: embeddedData ? embeddedData.entry.title : "Untitled",
uid: embeddedData ? embeddedData.entry.uid : "unknown",
},
onSuccess(result) {
rte.insertNode(
{
// @ts-expect-error: incorrect typings
type: "ImageVault",
attrs: {
...result,
},
uid: crypto.randomUUID(),
children: [{ text: "" }],
},
{ at: savedSelection }
)
},
})
}
})
return {
ImageVault,
}
} catch (e) {
console.error({ e })
}
})

19
rte/package.json Normal file
View File

@@ -0,0 +1,19 @@
{
"name": "@scandichotels/contentstack-imagevault-rte",
"private": true,
"sideEffects": false,
"type": "module",
"scripts": {
"build": "vite build",
"dev": "IS_DEV=true vite build --watch",
"lint": "eslint --cache --cache-location ./node_modules/.cache/eslint .",
"prebuild": "concurrently npm:lint npm:typecheck",
"typecheck": "tsc"
},
"devDependencies": {
"@types/systemjs": "^6.15.3"
},
"engines": {
"node": ">=22.0.0"
}
}

22
rte/tsconfig.json Normal file
View File

@@ -0,0 +1,22 @@
{
"extends": "../tsconfig.json",
"include": [
"env.d.ts",
"../types/**/*.ts",
"../utils/**/*.ts",
"../shared-components/**/*.ts",
"../shared-components/**/*.tsx",
"**/*.ts",
"**/*.tsx"
],
"compilerOptions": {
"jsx": "react",
"baseUrl": ".",
"paths": {
"~/*": ["./*"],
"~/types/*": ["../types/*"],
"~/utils/*": ["../utils/*"],
"~/shared-components/*": ["../shared-components/*"],
}
}
}

25
rte/vite.config.ts Normal file
View File

@@ -0,0 +1,25 @@
import { resolve } from "path"
import { defineConfig } from "vite"
import devtoolsJson from "vite-plugin-devtools-json"
import { libInjectCss } from "vite-plugin-lib-inject-css"
import tsconfigPaths from "vite-tsconfig-paths"
export default defineConfig({
plugins: [tsconfigPaths(), libInjectCss(), devtoolsJson()],
define: { IS_DEV: process.env.IS_DEV === "true" ? true : false },
publicDir: false,
build: {
sourcemap: process.env.IS_DEV ? "inline" : "hidden",
emptyOutDir: true,
lib: {
entry: resolve(__dirname, "main.tsx"),
name: "csiv",
fileName: () => "csiv.js",
formats: ["system"],
},
rollupOptions: {
external: ["react", "react-dom", "@contentstack/venus-components"],
output: { dir: "../remix/public/build/rte" },
},
},
})

View File

@@ -0,0 +1,47 @@
.container {
display: grid;
gap: 1rem;
border-right: 1px solid #eee;
padding-right: 1rem;
}
.focalPointWrapper {
position: relative;
user-select: none;
justify-self: center;
}
.focalPointButton {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
background-color: rgba(255, 0, 0, 0.4);
border: 3px solid red;
display: block;
width: 25px;
height: 25px;
border-radius: 50%;
}
.focalPointImage {
height: 100%;
max-height: 350px;
}
.examples {
width: 100%;
max-width: 600px;
max-height: 400px;
display: grid;
grid-template-columns: 3fr 1fr;
grid-template-rows: 2fr 1fr;
gap: 0.25rem;
}
.examples img {
width: 100%;
height: 100%;
object-fit: cover;
overflow: hidden;
}

View File

@@ -0,0 +1,53 @@
import React from "react"
import useFocalPoint from "./useFocalPoint"
import type { FocalPoint } from "~/types/imagevault"
import "./focalPointPicker.css"
export interface FocalPointPickerProps {
focalPoint?: FocalPoint
imageSrc: string
onChange: (focalPoint: FocalPoint) => void
}
export default function FocalPointPicker({
focalPoint,
imageSrc,
onChange,
}: FocalPointPickerProps) {
const { ref, x, y, onMove, canMove, setCanMove } = useFocalPoint({
focalPoint,
onChange,
})
const imagesArray = Array.from({ length: 4 })
return (
<div className="container">
<div className="focalPointWrapper" ref={ref} onMouseMove={onMove}>
<button
className="focalPointButton"
style={{
left: `${x}%`,
top: `${y}%`,
cursor: canMove ? "grabbing" : "grab",
}}
onMouseDown={() => setCanMove(true)}
onMouseUp={() => setCanMove(false)}
></button>
<img className="focalPointImage" src={imageSrc} alt="" />
</div>
<div className="examples">
{imagesArray.map((_, idx) => (
<img
key={idx}
src={imageSrc}
alt=""
style={{ objectPosition: `${x}% ${y}%` }}
/>
))}
</div>
</div>
)
}

View File

@@ -0,0 +1,59 @@
import { useCallback, useRef, useState, MouseEvent, useEffect } from "react"
import { FocalPoint } from "~/types/imagevault"
interface UseFocalPointProps {
focalPoint?: FocalPoint
onChange: (focalPoint: FocalPoint) => void
}
const DEFAULT_PERCENTAGE = 50
export default function useFocalPoint({
focalPoint,
onChange,
}: UseFocalPointProps) {
const ref = useRef<HTMLDivElement>(null)
const [x, setX] = useState<number>(DEFAULT_PERCENTAGE)
const [y, setY] = useState<number>(DEFAULT_PERCENTAGE)
const [canMove, setCanMove] = useState(false)
useEffect(() => {
if (focalPoint) {
setX(focalPoint.x)
setY(focalPoint.y)
}
}, [focalPoint])
const onMove = useCallback(
(e: MouseEvent) => {
if (canMove) {
const containerBoundingRectangle = ref.current!.getBoundingClientRect()
const xPixels = e.clientX - containerBoundingRectangle.left
const yPixels = e.clientY - containerBoundingRectangle.top
let x = Math.min(
Math.max((xPixels * 100) / ref.current!.clientWidth, 0),
100
)
let y = Math.min(
Math.max((yPixels * 100) / ref.current!.clientHeight, 0),
100
)
x = parseFloat(x.toFixed(2))
y = parseFloat(y.toFixed(2))
setX(x)
setY(y)
onChange({ x, y })
}
},
[canMove, onChange]
)
return {
ref,
x,
y,
onMove,
canMove,
setCanMove,
}
}

23
tsconfig.json Normal file
View File

@@ -0,0 +1,23 @@
{
"compilerOptions": {
"lib": ["DOM", "DOM.Iterable", "ES2022"],
"isolatedModules": true,
"esModuleInterop": true,
"module": "ESNext",
"moduleResolution": "Bundler",
"resolveJsonModule": true,
"target": "ES2022",
"strict": true,
"allowJs": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"noEmit": true,
"jsx": "react",
"baseUrl": ".",
"paths": {
"~/types/*": ["./types/*"],
"~/utils/*": ["./utils/*"],
"~/shared-components/*": ["./shared-components/*"],
}
}
}

60
types/contentstack.ts Normal file
View File

@@ -0,0 +1,60 @@
import { Lang } from "./lang"
// This type is only a partial of the data available.
export type ContentstackPluginDefinition = {
type: "field" | "rte_plugin"
title: string
src: string
}
// This type is only a partial of the data available.
// Check console when editing an entry for all the data available.
// The data comes from Contentstack, we have no control.
// Extend this if needed.
export type ContentstackEmbeddedData = {
entryMetadata: {
contentTypeUid: string
entryUid: string
locale: Lang
}
utilis: {
content_type: {
schema: Array<
| {
uid: string
data_type: "text"
value: string
}
| {
uid: string
data_type: "json"
value: unknown
}
>
}
extensions: ContentstackPluginDefinition[]
}
requestProps: {
stack: {
api_key: string
}
branch: string
}
}
// This is our version of the required fields we need that are available in ContentstackEmbeddedData
export type ExtractedContentstackEmbeddedData = {
contentType: {
uid: string
}
entry: {
locale: Lang
title: string
uid: string
}
plugin: ContentstackPluginDefinition
stack: {
apiKey: string
}
branch: string
}

251
types/imagevault.ts Normal file
View File

@@ -0,0 +1,251 @@
/**
* @file TypeScript typings for ImageVault
*
* The types in this file are based on the source maps of the downloaded
* distribution at https://clientscript.imagevault.se/Installation/ImageVaultInsertMedia
*
* They have been clean up and amended to.
*/
declare global {
interface Window {
ImageVault: {
InsertMediaWindow: typeof InsertMediaWindow
}
iframeRef: HTMLElement | null
}
}
export interface FocalPoint {
x: number
y: number
}
export declare class InsertMediaWindow {
constructor(config: Config, windowOptions: string)
openImageVault: () => void
containerWindow: Window | null
}
export interface IInsertSuccessCallback {
(message: InsertSuccessMessageEvent): void
}
/**
* Message returned from the Success Callback method
*/
export interface InsertSuccessMessageEvent extends MessageEvent {
/**
* The response from the ImageVault insert operation
*/
data: string
/**
* The response from the ImageVault insert operation
*/
response: InsertResponse
}
export type MetaData = {
DefinitionType?: number
Description: string | null
LanguageId: null
MetadataDefinitionId: number
Name: string
Value: string
}
export type ImageVaultAsset = {
imageVaultId: number
fileName: string
url: string
dimensions: {
width: number
height: number
aspectRatio: number
}
focalPoint: FocalPoint
meta: { alt: string; caption: string }
}
/**
* The response from ImageVault when inserting an asset
*/
export declare class InsertResponse {
/**
* The media item id of the asset
*/
Id: number
/**
* The id of the vault where the asset resides
*/
VaultId: number
/**
* The name of the asset
*/
Name: string
/**
* The conversion selected by the user. Is an array but will only contain one object
*/
MediaConversions: MediaConversion[]
/**
* Date when the asset was added to ImageVault
*/
DateAdded: string
/**
* Name of the user that added the asset to ImageVault
*/
AddedBy: string
Metadata?: MetaData[] | undefined
FocalPoint: FocalPoint
}
/**
* Defines a media asset, original or conversion
*/
export declare class MediaConversion {
/**
* The url to the conversion
*/
Url: string
/**
* Name of the conversion
*/
Name: string
/**
* Html representing the conversion
*/
Html: string
/**
* Content type of the conversion
*/
ContentType: string
/**
* Width, in pixels, of the conversion
*/
Width: number
/**
* Height, in pixels, of the conversion
*/
Height: number
/**
* Aspect ratio of the conversion
*/
AspectRatio: number
/**
* Width of the selected/requested format
*/
FormatWidth: number
/**
* Height of the selected/requested format
*/
FormatHeight: number
/**
* Aspect ratio of the selected/requested format
*/
FormatAspectRatio: number
/**
* Name of the media format
*/
MediaFormatName: string
/**
* Id of the selected media format
*/
MediaFormatId: number
}
/**
* Defines where an ImageVault asset is used when requesting it
*/
export declare class PublishDetails {
/**
* The textual description on where an asset is used
*/
text: string
/**
* The url to where the asset is used
*/
url: string
/**
* An optional id for grouping usage
*/
groupId?: string
}
/**
* Defines the configuration needed to invoke the insert function
*/
export declare class Config {
/**
* The url to the ImageVault ui that should be used
*/
imageVaultUiUrl: string
/**
* [Optional] Origin where the insert function is launched from. Is normally calculated and does not need to be supplied.
*/
origin?: string
/**
* The language that the ImageVault ui should be displayed in
*/
uiLang: string
/**
* [Optional] The language for the default content in ImageVault
*/
pageLang?: string
/**
* The publishingSource where the image should be used. Normally the url for the site.
*/
publishingSource: string
/**
* If it should be possible to select multiple assets from ImageVault. Default is false.
*/
insertMultiple: boolean
/**
* The url base that the media assets should use. Supply the url to a cdn.
*/
mediaUrlBase: string
/**
* The ids of the formats that the selection should result in.
*/
formatId: string
/**
* [Optional] The comma-separated id-list of additional metadata definitions that the selection should result in.
*/
additionalMetadataIds?: string
/**
* The publishDetails to use. If supplied, published urls are returned.
*/
publishDetails?: PublishDetails
/**
* Function that is invoked when the user insert items from ImageVault
*/
success: IInsertSuccessCallback
/**
* This function is called when the Insert window should be closed
*/
close: (result: unknown) => void
/**
* [Optional] This function is called whenever an error is encountered
*/
error?: (result: unknown, errorMessage: string) => void
/**
* [Optional] Listen on this method for debug messages
*/
debug?: (result: unknown) => void
/**
* [Optional] Set media url to edit existing media
*/
mediaUrl?: string
/**
* [Optional] Set media id to show specific media
*/
mediaId?: number
/**
* [Optional]
* @0 (Default) Insert with format or choose format from dropdown in ImageVault UI
* @1 Same as 0 (default) except that you can edit media in editor before insert
*/
insertMode?: number
}

10
types/lang.ts Normal file
View File

@@ -0,0 +1,10 @@
export const langEnum = {
en: "en",
sv: "sv",
no: "no",
fi: "fi",
da: "da",
de: "de",
} as const
export type Lang = keyof typeof langEnum

187
utils/imagevault.ts Normal file
View File

@@ -0,0 +1,187 @@
import { langEnum } from "../types/lang"
import type { GenericObjectType } from "@contentstack/app-sdk/dist/src/types/common.types"
import type {
Config,
FocalPoint,
ImageVaultAsset,
InsertResponse,
PublishDetails,
} from "../types/imagevault"
import type { Lang } from "../types/lang"
const metaIds = {
[langEnum.de]: { altText: 68, title: 77 },
[langEnum.da]: { altText: 67, title: 76 },
[langEnum.fi]: { altText: 70, title: 78 },
[langEnum.no]: { altText: 71, title: 79 },
[langEnum.sv]: { altText: 74, title: 82 },
[langEnum.en]: { altText: 69, title: 65 },
}
export function getMetaIds(lang: Lang) {
return metaIds[lang]
}
export type EntryDataPublishDetails = {
branch: string
contentTypeUid: string
locale: Lang
stackApiKey: string
title: string
uid: string
}
export function getPublishDetails(
baseUrl: string,
{
branch,
contentTypeUid,
locale,
stackApiKey,
title,
uid,
}: EntryDataPublishDetails
): PublishDetails {
const text = `${title} (${uid})`
const url = `${baseUrl}#!/stack/${stackApiKey}/content-type/${contentTypeUid}/${locale}/entry/${uid}/edit?branch=${branch}`
return { text, url }
}
export function isInsertResponse(
res: InsertResponse | GenericObjectType | null | undefined
): res is InsertResponse {
return (res as InsertResponse)?.MediaConversions !== undefined
}
export function isImageVaultAsset(
res: ImageVaultAsset | InsertResponse | GenericObjectType | null | undefined
): res is ImageVaultAsset {
return (res as ImageVaultAsset)?.url !== undefined
}
export type ImageVaultDAMConfig = {
imageVaultUrl: string
baseUrl: string
formatId: string
}
export function isImageVaultDAMConfig(
config: Record<string, string>
): config is ImageVaultDAMConfig {
return !!(config.baseUrl && config.formatId && config.imageVaultUrl)
}
// Utility function to get ImageVaultAsset from either InsertResponse or ImageVaultAsset
// Because we currently have both types saved in Contentstack, we need to account for both when retrieving the data of the asset.
export function getImageVaultAssetFromData(
data: InsertResponse | ImageVaultAsset | GenericObjectType | null | undefined
): ImageVaultAsset | null {
if (isImageVaultAsset(data)) {
return data
}
if (isInsertResponse(data)) {
return mapInsertResponseToImageVaultAsset(data, { x: 50, y: 50 })
}
return null
}
// Utility function to convert InsertResponse to ImageVaultAsset
function mapInsertResponseToImageVaultAsset(
response: InsertResponse,
focalPoint: FocalPoint
): ImageVaultAsset {
let image = response.MediaConversions.find(
(conversion) =>
conversion.MediaFormatName === "Original" &&
conversion.ContentType === "image/jpeg"
)
// We only receive one alt and title is in the response, depending on the language of the entry
// This is why we're getting the first one found
const alt =
response.Metadata?.find((meta) => meta.Name.includes("AltText_"))?.Value ||
""
const caption =
response.Metadata?.find((meta) => meta.Name.includes("Title_"))?.Value || ""
if (!image) {
const imageAsJpeg = response.MediaConversions.find(
(conversion) => conversion.ContentType === "image/jpeg"
)
image = imageAsJpeg || response.MediaConversions[0]
}
return {
imageVaultId: response.Id,
url: image.Url,
meta: {
alt,
caption,
},
fileName: response.Name,
dimensions: {
width: image.Width,
height: image.Height,
aspectRatio: image.AspectRatio,
},
focalPoint: response.FocalPoint || focalPoint,
}
}
export type openImageVaultParams = {
config: ImageVaultDAMConfig
entryData: EntryDataPublishDetails
onSuccess: (result: ImageVaultAsset) => void
onClose?: () => void
}
export function openImageVault({
config,
entryData,
onSuccess,
onClose,
}: openImageVaultParams) {
if (window.ImageVault) {
const publishDetails = getPublishDetails(config.baseUrl, entryData)
const metaIdsForLocale = getMetaIds(entryData.locale)
const insertMediaWindowOptions: Config = {
imageVaultUiUrl: config.imageVaultUrl,
uiLang: "en",
pageLang: "en",
publishingSource: config.baseUrl,
mediaUrlBase: config.imageVaultUrl,
formatId: config.formatId,
publishDetails,
insertMultiple: false,
success: (result) => {
const imageVaultAsset = mapInsertResponseToImageVaultAsset(
result.response,
{ x: 50, y: 50 }
)
onSuccess(imageVaultAsset)
},
close: () => {
if (typeof onClose === "function") {
onClose()
}
windowInserter.containerWindow?.close()
},
}
if (metaIdsForLocale) {
const additionalMetadataIds = Object.values(metaIdsForLocale).join(",")
insertMediaWindowOptions.additionalMetadataIds = additionalMetadataIds
}
const windowInserter = new window.ImageVault.InsertMediaWindow(
insertMediaWindowOptions,
`left=0,top=0,width=${window.screen.width},height=${window.screen.height}`
)
windowInserter.openImageVault()
} else {
console.error("Missing ImageVault global. ImageVault script not loaded?")
}
}