feat: Contentstack <-> ImageVault integration
This commit is contained in:
2
.gitignore
vendored
Normal file
2
.gitignore
vendored
Normal file
@@ -0,0 +1,2 @@
|
||||
node_modules
|
||||
build
|
||||
1
.prettierignore
Normal file
1
.prettierignore
Normal file
@@ -0,0 +1 @@
|
||||
**/public/**/*
|
||||
14
README.md
Normal file
14
README.md
Normal file
@@ -0,0 +1,14 @@
|
||||
# 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.
|
||||
14354
package-lock.json
generated
Normal file
14354
package-lock.json
generated
Normal file
File diff suppressed because it is too large
Load Diff
38
package.json
Normal file
38
package.json
Normal file
@@ -0,0 +1,38 @@
|
||||
{
|
||||
"name": "@scandichotels/contentstack-imagevault",
|
||||
"version": "1.0.0",
|
||||
"private": true,
|
||||
"description": "Integration between Contentstack and ImageVault",
|
||||
"workspaces": [
|
||||
"remix",
|
||||
"rte"
|
||||
],
|
||||
"scripts": {
|
||||
"build": "npm run build --workspaces",
|
||||
"dev": "concurrently npm:dev:*",
|
||||
"dev:remix": "cd remix && npm run dev",
|
||||
"dev:rte": "cd rte && npm run dev"
|
||||
},
|
||||
"dependencies": {
|
||||
"@contentstack/app-sdk": "^2.0.1",
|
||||
"@contentstack/venus-components": "2.2.3",
|
||||
"react": "^18.2.0",
|
||||
"react-dom": "^18.2.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/react": "^18.2.20",
|
||||
"@types/react-dom": "^18.2.7",
|
||||
"@typescript-eslint/eslint-plugin": "^6.7.4",
|
||||
"@typescript-eslint/parser": "^6.7.4",
|
||||
"concurrently": "^8.2.2",
|
||||
"eslint": "^8.38.0",
|
||||
"eslint-import-resolver-typescript": "^3.6.1",
|
||||
"eslint-plugin-import": "^2.28.1",
|
||||
"eslint-plugin-jsx-a11y": "^6.7.1",
|
||||
"eslint-plugin-react": "^7.33.2",
|
||||
"eslint-plugin-react-hooks": "^4.6.0",
|
||||
"typescript": "^5.1.6",
|
||||
"vite": "^5.1.0",
|
||||
"vite-tsconfig-paths": "^4.2.1"
|
||||
}
|
||||
}
|
||||
90
remix/.eslintrc.cjs
Normal file
90
remix/.eslintrc.cjs
Normal file
@@ -0,0 +1,90 @@
|
||||
/**
|
||||
* This is intended to be a basic starting point for linting in your app.
|
||||
* It relies on recommended configs out of the box for simplicity, but you can
|
||||
* and should modify this configuration to best suit your team's needs.
|
||||
*/
|
||||
|
||||
/** @type {import('eslint').Linter.Config} */
|
||||
module.exports = {
|
||||
root: true,
|
||||
parserOptions: {
|
||||
ecmaVersion: 'latest',
|
||||
sourceType: 'module',
|
||||
ecmaFeatures: {
|
||||
jsx: true,
|
||||
},
|
||||
},
|
||||
env: {
|
||||
browser: true,
|
||||
commonjs: true,
|
||||
es6: true,
|
||||
},
|
||||
ignorePatterns: ['build/**/*', 'node_modules/**/*', 'public/**/*'],
|
||||
|
||||
// Base config
|
||||
extends: ['eslint:recommended'],
|
||||
|
||||
overrides: [
|
||||
// React
|
||||
{
|
||||
files: ['**/*.{js,jsx,ts,tsx}'],
|
||||
plugins: ['react', 'jsx-a11y'],
|
||||
rules: {
|
||||
'react/jsx-uses-vars': 'error',
|
||||
'react/jsx-uses-react': 'error',
|
||||
},
|
||||
extends: [
|
||||
'plugin:react/recommended',
|
||||
'plugin:react/jsx-runtime',
|
||||
'plugin:react-hooks/recommended',
|
||||
'plugin:jsx-a11y/recommended',
|
||||
],
|
||||
settings: {
|
||||
react: {
|
||||
version: 'detect',
|
||||
},
|
||||
formComponents: ['Form'],
|
||||
linkComponents: [
|
||||
{ name: 'Link', linkAttribute: 'to' },
|
||||
{ name: 'NavLink', linkAttribute: 'to' },
|
||||
],
|
||||
'import/resolver': {
|
||||
typescript: {
|
||||
project: './remix/tsconfig.json',
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
|
||||
// Typescript
|
||||
{
|
||||
files: ['**/*.{ts,tsx}'],
|
||||
plugins: ['@typescript-eslint', 'import'],
|
||||
parser: '@typescript-eslint/parser',
|
||||
settings: {
|
||||
'import/internal-regex': '^~/',
|
||||
'import/resolver': {
|
||||
node: {
|
||||
extensions: ['.ts', '.tsx'],
|
||||
},
|
||||
typescript: {
|
||||
alwaysTryTypes: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
extends: [
|
||||
'plugin:@typescript-eslint/recommended',
|
||||
'plugin:import/recommended',
|
||||
'plugin:import/typescript',
|
||||
],
|
||||
},
|
||||
|
||||
// Node
|
||||
{
|
||||
files: ['.eslintrc.cjs'],
|
||||
env: {
|
||||
node: true,
|
||||
},
|
||||
},
|
||||
],
|
||||
};
|
||||
126
remix/app/components/ConfigForm.tsx
Normal file
126
remix/app/components/ConfigForm.tsx
Normal 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>
|
||||
);
|
||||
}
|
||||
12
remix/app/components/Disclaimer.tsx
Normal file
12
remix/app/components/Disclaimer.tsx
Normal 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>
|
||||
);
|
||||
}
|
||||
41
remix/app/components/FullSizeImage.tsx
Normal file
41
remix/app/components/FullSizeImage.tsx
Normal 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>
|
||||
</>
|
||||
);
|
||||
}
|
||||
124
remix/app/components/ImageEditModal.tsx
Normal file
124
remix/app/components/ImageEditModal.tsx
Normal 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>
|
||||
</>
|
||||
);
|
||||
}
|
||||
221
remix/app/components/ImageVaultDAM.tsx
Normal file
221
remix/app/components/ImageVaultDAM.tsx
Normal 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>
|
||||
);
|
||||
}
|
||||
11
remix/app/components/InvalidConfig.tsx
Normal file
11
remix/app/components/InvalidConfig.tsx
Normal 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>
|
||||
);
|
||||
}
|
||||
12
remix/app/entry.client.tsx
Normal file
12
remix/app/entry.client.tsx
Normal 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>
|
||||
);
|
||||
});
|
||||
19
remix/app/entry.server.tsx
Normal file
19
remix/app/entry.server.tsx
Normal 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
46
remix/app/hooks/useApp.ts
Normal 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
72
remix/app/root.tsx
Normal 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>
|
||||
);
|
||||
}
|
||||
15
remix/app/routes/_index.tsx
Normal file
15
remix/app/routes/_index.tsx
Normal 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;
|
||||
}
|
||||
38
remix/app/routes/config.tsx
Normal file
38
remix/app/routes/config.tsx
Normal 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>
|
||||
);
|
||||
}
|
||||
69
remix/app/routes/field.tsx
Normal file
69
remix/app/routes/field.tsx
Normal 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>
|
||||
);
|
||||
}
|
||||
2
remix/env.d.ts
vendored
Normal file
2
remix/env.d.ts
vendored
Normal file
@@ -0,0 +1,2 @@
|
||||
/// <reference types="@remix-run/node" />
|
||||
/// <reference types="vite/client" />
|
||||
25
remix/package.json
Normal file
25
remix/package.json
Normal 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.8.1",
|
||||
"@remix-run/react": "^2.8.1",
|
||||
"usehooks-ts": "^3.0.2"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@remix-run/dev": "^2.8.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=18.0.0"
|
||||
}
|
||||
}
|
||||
BIN
remix/public/favicon.ico
Normal file
BIN
remix/public/favicon.ico
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 3.5 KiB |
3
remix/public/scripts/imagevault-insert-media/insertmediawindow.min.js
vendored
Normal file
3
remix/public/scripts/imagevault-insert-media/insertmediawindow.min.js
vendored
Normal 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)})();
|
||||
21
remix/tsconfig.json
Normal file
21
remix/tsconfig.json
Normal file
@@ -0,0 +1,21 @@
|
||||
{
|
||||
"extends": "../tsconfig.json",
|
||||
"include": [
|
||||
"env.d.ts",
|
||||
"../types/**/*.ts",
|
||||
"../utils/**/*.ts",
|
||||
"**/*.ts",
|
||||
"**/*.tsx"
|
||||
],
|
||||
"compilerOptions": {
|
||||
"jsx": "react-jsx",
|
||||
"baseUrl": ".",
|
||||
"paths": {
|
||||
"~/*": ["./remix/*"],
|
||||
"~/types/*": ["../types/*"],
|
||||
"~/utils/*": ["../utils/*"],
|
||||
"~/components/*": ["./app/components/*"],
|
||||
"~/hooks/*": ["./app/hooks/*"]
|
||||
}
|
||||
}
|
||||
}
|
||||
15
remix/vite.config.ts
Normal file
15
remix/vite.config.ts
Normal file
@@ -0,0 +1,15 @@
|
||||
import { vitePlugin as remix } from '@remix-run/dev';
|
||||
import { defineConfig } from 'vite';
|
||||
import tsconfigPaths from 'vite-tsconfig-paths';
|
||||
|
||||
export default defineConfig({
|
||||
plugins: [
|
||||
remix({
|
||||
ssr: false,
|
||||
}),
|
||||
tsconfigPaths(),
|
||||
],
|
||||
build: {
|
||||
emptyOutDir: true,
|
||||
},
|
||||
});
|
||||
90
rte/.eslintrc.cjs
Normal file
90
rte/.eslintrc.cjs
Normal file
@@ -0,0 +1,90 @@
|
||||
/**
|
||||
* This is intended to be a basic starting point for linting in your app.
|
||||
* It relies on recommended configs out of the box for simplicity, but you can
|
||||
* and should modify this configuration to best suit your team's needs.
|
||||
*/
|
||||
|
||||
/** @type {import('eslint').Linter.Config} */
|
||||
module.exports = {
|
||||
root: true,
|
||||
parserOptions: {
|
||||
ecmaVersion: 'latest',
|
||||
sourceType: 'module',
|
||||
ecmaFeatures: {
|
||||
jsx: true,
|
||||
},
|
||||
},
|
||||
env: {
|
||||
browser: true,
|
||||
commonjs: true,
|
||||
es6: true,
|
||||
},
|
||||
ignorePatterns: ['node_modules/**/*'],
|
||||
|
||||
// Base config
|
||||
extends: ['eslint:recommended'],
|
||||
|
||||
overrides: [
|
||||
// React
|
||||
{
|
||||
files: ['**/*.{js,jsx,ts,tsx}'],
|
||||
plugins: ['react', 'jsx-a11y'],
|
||||
rules: {
|
||||
'react/jsx-uses-vars': 'error',
|
||||
'react/jsx-uses-react': 'error',
|
||||
},
|
||||
extends: [
|
||||
'plugin:react/recommended',
|
||||
'plugin:react/jsx-runtime',
|
||||
'plugin:react-hooks/recommended',
|
||||
'plugin:jsx-a11y/recommended',
|
||||
],
|
||||
settings: {
|
||||
react: {
|
||||
version: 'detect',
|
||||
},
|
||||
formComponents: ['Form'],
|
||||
linkComponents: [
|
||||
{ name: 'Link', linkAttribute: 'to' },
|
||||
{ name: 'NavLink', linkAttribute: 'to' },
|
||||
],
|
||||
'import/resolver': {
|
||||
typescript: {
|
||||
project: './rte/tsconfig.json',
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
|
||||
// Typescript
|
||||
{
|
||||
files: ['**/*.{ts,tsx}'],
|
||||
plugins: ['@typescript-eslint', 'import'],
|
||||
parser: '@typescript-eslint/parser',
|
||||
settings: {
|
||||
'import/internal-regex': '^~/',
|
||||
'import/resolver': {
|
||||
node: {
|
||||
extensions: ['.ts', '.tsx'],
|
||||
},
|
||||
typescript: {
|
||||
alwaysTryTypes: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
extends: [
|
||||
'plugin:@typescript-eslint/recommended',
|
||||
'plugin:import/recommended',
|
||||
'plugin:import/typescript',
|
||||
],
|
||||
},
|
||||
|
||||
// Node
|
||||
{
|
||||
files: ['.eslintrc.cjs'],
|
||||
env: {
|
||||
node: true,
|
||||
},
|
||||
},
|
||||
],
|
||||
};
|
||||
31
rte/components/EmbedBtn.tsx
Normal file
31
rte/components/EmbedBtn.tsx
Normal 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>
|
||||
);
|
||||
}
|
||||
213
rte/components/ImageEditModal.tsx
Normal file
213
rte/components/ImageEditModal.tsx
Normal file
@@ -0,0 +1,213 @@
|
||||
import React, { useState, useEffect, ChangeEvent } from 'react';
|
||||
import {
|
||||
ModalFooter,
|
||||
ModalBody,
|
||||
ModalHeader,
|
||||
ButtonGroup,
|
||||
Button,
|
||||
Field,
|
||||
FieldLabel,
|
||||
TextInput,
|
||||
Select,
|
||||
} from '@contentstack/venus-components';
|
||||
import { Path } from 'slate';
|
||||
|
||||
import type {
|
||||
IRteParam,
|
||||
IRteElementType,
|
||||
} from '@contentstack/app-sdk/dist/src/RTE/types';
|
||||
import type { InsertResponse } from "~/types/imagevault";
|
||||
|
||||
enum DropdownValues {
|
||||
center = "center",
|
||||
left = "left",
|
||||
right = "right",
|
||||
none = "none",
|
||||
}
|
||||
|
||||
type DropDownItem = {
|
||||
label: string;
|
||||
value: DropdownValues;
|
||||
type: string;
|
||||
};
|
||||
|
||||
const dropdownList: DropDownItem[] = [
|
||||
{
|
||||
label: "None",
|
||||
value: DropdownValues.none,
|
||||
type: "select",
|
||||
},
|
||||
{
|
||||
label: "Center",
|
||||
value: DropdownValues.center,
|
||||
type: "select",
|
||||
},
|
||||
{
|
||||
label: "Left",
|
||||
value: DropdownValues.left,
|
||||
type: "select",
|
||||
},
|
||||
{
|
||||
label: "Right",
|
||||
value: DropdownValues.right,
|
||||
type: "select",
|
||||
},
|
||||
];
|
||||
|
||||
type ImageEditModalProps = {
|
||||
element: IRteElementType & {
|
||||
attrs: InsertResponse;
|
||||
};
|
||||
rte: IRteParam;
|
||||
closeModal: () => void;
|
||||
path: Path;
|
||||
};
|
||||
|
||||
export default function ImageEditModal({
|
||||
element,
|
||||
closeModal,
|
||||
path,
|
||||
rte,
|
||||
}: ImageEditModalProps) {
|
||||
const [alignment, setAlignment] = useState<DropDownItem>({
|
||||
label: "None",
|
||||
value: DropdownValues.none,
|
||||
type: "select",
|
||||
});
|
||||
const [altText, setAltText] = useState("");
|
||||
const [caption, setCaption] = useState("");
|
||||
|
||||
const assetUrl = element.attrs.MediaConversions[0].Url;
|
||||
|
||||
useEffect(() => {
|
||||
if (element.attrs.Metadata && element.attrs.Metadata.length) {
|
||||
const altText = element.attrs.Metadata.find((meta) =>
|
||||
meta.Name.includes("AltText_")
|
||||
)?.Value;
|
||||
|
||||
const caption = element.attrs.Metadata.find((meta) =>
|
||||
meta.Name.includes("Title_")
|
||||
)?.Value;
|
||||
|
||||
setAltText(altText ?? "");
|
||||
setCaption(caption ?? "");
|
||||
}
|
||||
}, [element.attrs.Metadata]);
|
||||
|
||||
function handleSave() {
|
||||
let newStyle;
|
||||
|
||||
switch (alignment.value) {
|
||||
case DropdownValues.center:
|
||||
case DropdownValues.left:
|
||||
case DropdownValues.right:
|
||||
newStyle = {
|
||||
textAlign: alignment.value,
|
||||
maxWidth: element.attrs.width
|
||||
? `${element.attrs.width}px`
|
||||
: undefined,
|
||||
};
|
||||
break;
|
||||
case DropdownValues.none:
|
||||
default:
|
||||
newStyle = {};
|
||||
break;
|
||||
}
|
||||
|
||||
const metaData = element.attrs.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;
|
||||
});
|
||||
|
||||
rte._adv.Transforms?.setNodes<IRteElementType>(
|
||||
rte._adv.editor,
|
||||
{
|
||||
attrs: {
|
||||
...element.attrs,
|
||||
Metadata: newMetadata,
|
||||
position: alignment.value,
|
||||
style: { ...element.attrs.style, ...newStyle },
|
||||
},
|
||||
},
|
||||
{ at: path }
|
||||
);
|
||||
|
||||
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 }}>
|
||||
<Field>
|
||||
<Select
|
||||
selectLabel="Alignment"
|
||||
value={alignment}
|
||||
onChange={(e: DropDownItem) => {
|
||||
setAlignment(e);
|
||||
}}
|
||||
options={dropdownList}
|
||||
/>
|
||||
</Field>
|
||||
<Field>
|
||||
<FieldLabel htmlFor="alt">Alt text</FieldLabel>
|
||||
<TextInput
|
||||
value={altText}
|
||||
placeholder="Alt text for image"
|
||||
name="alt"
|
||||
onChange={(e: ChangeEvent<HTMLInputElement>) =>
|
||||
setAltText(e.target.value)
|
||||
}
|
||||
/>
|
||||
</Field>
|
||||
|
||||
<Field>
|
||||
<FieldLabel htmlFor="caption">Caption</FieldLabel>
|
||||
<TextInput
|
||||
value={caption}
|
||||
placeholder="Caption for image..."
|
||||
name="caption"
|
||||
onChange={(e: ChangeEvent<HTMLInputElement>) =>
|
||||
setCaption(e.target.value)
|
||||
}
|
||||
/>
|
||||
</Field>
|
||||
</div>
|
||||
</ModalBody>
|
||||
<ModalFooter>
|
||||
<ButtonGroup>
|
||||
<Button onClick={closeModal} buttonType="light">
|
||||
Cancel
|
||||
</Button>
|
||||
<Button onClick={handleSave} icon="SaveWhite">
|
||||
Save
|
||||
</Button>
|
||||
</ButtonGroup>
|
||||
</ModalFooter>
|
||||
</>
|
||||
);
|
||||
}
|
||||
173
rte/components/ImageElement.tsx
Normal file
173
rte/components/ImageElement.tsx
Normal file
@@ -0,0 +1,173 @@
|
||||
import React, { useRef, useCallback, PropsWithChildren } from 'react';
|
||||
import { Tooltip, Icon, cbModal } from '@contentstack/venus-components';
|
||||
|
||||
import { Resizable } from 're-resizable';
|
||||
import EmbedBtn from './EmbedBtn';
|
||||
import ImageEditModal from './ImageEditModal';
|
||||
|
||||
import type {
|
||||
IRteParam,
|
||||
IRteElementType,
|
||||
} from '@contentstack/app-sdk/dist/src/RTE/types';
|
||||
import type { InsertResponse } from '~/types/imagevault';
|
||||
|
||||
type ImageElementProps = PropsWithChildren & {
|
||||
element: IRteElementType & { attrs: InsertResponse };
|
||||
rte: IRteParam;
|
||||
};
|
||||
export function ImageElement({ children, element, rte }: ImageElementProps) {
|
||||
const assetUrl = element.attrs.MediaConversions[0].Url;
|
||||
const isSelected = rte?.selection?.isSelected();
|
||||
const isFocused = rte?.selection?.isFocused();
|
||||
const isHighlight = isFocused && isSelected;
|
||||
|
||||
const imgRef = useRef<HTMLDivElement | null>(null);
|
||||
|
||||
const handleEdit = useCallback(() => {
|
||||
cbModal({
|
||||
// @ts-expect-error: Component is badly typed
|
||||
component: (compProps) =>
|
||||
ImageEditModal({
|
||||
element,
|
||||
rte,
|
||||
path: rte.getPath(element),
|
||||
...compProps,
|
||||
}),
|
||||
modalProps: {
|
||||
size: "max",
|
||||
},
|
||||
});
|
||||
}, [element, rte]);
|
||||
|
||||
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>
|
||||
);
|
||||
};
|
||||
|
||||
const onResizeStop = () => {
|
||||
const { attrs: elementAttrs } = element;
|
||||
const { offsetWidth: width, offsetHeight: height } = imgRef?.current ?? {};
|
||||
|
||||
const newAttrs: { [key: string]: unknown } = {
|
||||
...elementAttrs,
|
||||
style: {
|
||||
...(elementAttrs?.style ?? {}),
|
||||
"max-width": `${width}px`,
|
||||
},
|
||||
...(width && height
|
||||
? { width: `${width.toString()}px`, height: `${height.toString()}px` }
|
||||
: {}),
|
||||
};
|
||||
|
||||
rte?._adv?.Transforms?.setNodes<IRteElementType>(
|
||||
rte._adv.editor,
|
||||
{ attrs: newAttrs },
|
||||
{ at: rte.getPath(element) }
|
||||
);
|
||||
};
|
||||
|
||||
let alignmentStyles = {};
|
||||
const marginAlignment: Record<string, { [key: string]: string }> = {
|
||||
center: { margin: "auto" },
|
||||
left: { marginRight: "auto" },
|
||||
right: { marginLeft: "auto" },
|
||||
};
|
||||
|
||||
if (typeof element.attrs.position === "string") {
|
||||
alignmentStyles = marginAlignment[element.attrs.position];
|
||||
}
|
||||
|
||||
return (
|
||||
<div
|
||||
style={{
|
||||
...alignmentStyles,
|
||||
...element.attrs.style,
|
||||
}}
|
||||
>
|
||||
<Tooltip
|
||||
zIndex={909}
|
||||
className="p-0"
|
||||
style={{ marginBottom: "10px" }}
|
||||
position="top"
|
||||
variantType="light"
|
||||
offset={[0, -15]}
|
||||
content={<ToolTipButtons />}
|
||||
>
|
||||
<span
|
||||
data-type="asset"
|
||||
contentEditable={false}
|
||||
style={element.attrs?.style}
|
||||
>
|
||||
<Resizable
|
||||
lockAspectRatio
|
||||
size={{
|
||||
width: element.attrs.width ?? "180px",
|
||||
height: element.attrs.heigth ?? "auto",
|
||||
}}
|
||||
onResizeStop={onResizeStop}
|
||||
handleStyles={{
|
||||
right: { right: 0, width: "15px" },
|
||||
left: { left: 0, width: "15px" },
|
||||
bottom: { bottom: "0" },
|
||||
bottomRight: { width: "15px" },
|
||||
}}
|
||||
>
|
||||
<div
|
||||
ref={imgRef}
|
||||
contentEditable={false}
|
||||
style={{
|
||||
width: "100%",
|
||||
height: "100%",
|
||||
...(isHighlight ? { border: "1px solid #6c5ce7" } : {}),
|
||||
}}
|
||||
>
|
||||
<img
|
||||
src={assetUrl}
|
||||
onError={(event) => {
|
||||
event.currentTarget.src = "https://placehold.co/600x400";
|
||||
}}
|
||||
style={{
|
||||
width: "100%",
|
||||
height: "auto",
|
||||
aspectRatio: element.attrs.MediaConversions[0].AspectRatio,
|
||||
borderRadius: "8px",
|
||||
}}
|
||||
alt={element.attrs.altText}
|
||||
title={element.attrs?.Name}
|
||||
/>
|
||||
<div
|
||||
style={{
|
||||
position: "absolute",
|
||||
bottom: 0,
|
||||
right: 0,
|
||||
background: "#fff",
|
||||
color: "#000",
|
||||
height: "25px",
|
||||
padding: "3px",
|
||||
borderRadius: "4px",
|
||||
}}
|
||||
>
|
||||
<Icon icon="Embed" />
|
||||
</div>
|
||||
</div>
|
||||
</Resizable>
|
||||
|
||||
{children}
|
||||
</span>
|
||||
</Tooltip>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
1
rte/env.d.ts
vendored
Normal file
1
rte/env.d.ts
vendored
Normal file
@@ -0,0 +1 @@
|
||||
declare const IS_DEV: boolean;
|
||||
224
rte/main.tsx
Normal file
224
rte/main.tsx
Normal file
@@ -0,0 +1,224 @@
|
||||
import React from 'react';
|
||||
import ContentstackSDK from '@contentstack/app-sdk';
|
||||
|
||||
import { ImageElement } from '~/components/ImageElement';
|
||||
|
||||
import { Icon } from '@contentstack/venus-components';
|
||||
import { openImageVault } from '~/utils/imagevault';
|
||||
|
||||
import type { Lang } from '~/types/lang';
|
||||
import type {
|
||||
ContentstackEmbeddedData,
|
||||
ContentstackPluginDefinition,
|
||||
ExtractedContentstackEmbeddedData,
|
||||
} from '~/types/contentstack';
|
||||
|
||||
function findThisPlugin(ext: ContentstackPluginDefinition) {
|
||||
return ext.type === 'rte_plugin' && ext.title === 'ImageVault';
|
||||
}
|
||||
|
||||
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}`);
|
||||
}
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
async function init() {
|
||||
try {
|
||||
const sdk = await ContentstackSDK.init();
|
||||
|
||||
const extensionObj = sdk?.location;
|
||||
const RTE = extensionObj?.RTEPlugin;
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
if (!RTE) return;
|
||||
|
||||
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>
|
||||
);
|
||||
}
|
||||
},
|
||||
display: ["toolbar"],
|
||||
elementType: ["void"],
|
||||
};
|
||||
});
|
||||
|
||||
ImageVault.on("exec", async (rte) => {
|
||||
if (rte) {
|
||||
const savedSelection = rte?.selection?.get() ?? undefined;
|
||||
|
||||
// @ts-expect-error: Added at runtime
|
||||
const config = await rte.getConfig();
|
||||
|
||||
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 });
|
||||
}
|
||||
}
|
||||
|
||||
export default init();
|
||||
19
rte/package.json
Normal file
19
rte/package.json
Normal 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 --ignore-path ../.gitignore --cache --cache-location ./node_modules/.cache/eslint .",
|
||||
"prebuild": "concurrently npm:lint npm:typecheck",
|
||||
"typecheck": "tsc"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/systemjs": "^6.13.5"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=18.0.0"
|
||||
}
|
||||
}
|
||||
19
rte/tsconfig.json
Normal file
19
rte/tsconfig.json
Normal file
@@ -0,0 +1,19 @@
|
||||
{
|
||||
"extends": "../tsconfig.json",
|
||||
"include": [
|
||||
"env.d.ts",
|
||||
"../types/**/*.ts",
|
||||
"../utils/**/*.ts",
|
||||
"**/*.ts",
|
||||
"**/*.tsx"
|
||||
],
|
||||
"compilerOptions": {
|
||||
"jsx": "react",
|
||||
"baseUrl": ".",
|
||||
"paths": {
|
||||
"~/*": ["./*"],
|
||||
"~/types/*": ["../types/*"],
|
||||
"~/utils/*": ["../utils/*"]
|
||||
}
|
||||
}
|
||||
}
|
||||
28
rte/vite.config.ts
Normal file
28
rte/vite.config.ts
Normal file
@@ -0,0 +1,28 @@
|
||||
import { resolve } from 'path';
|
||||
import { defineConfig } from 'vite';
|
||||
import tsconfigPaths from 'vite-tsconfig-paths';
|
||||
|
||||
export default defineConfig({
|
||||
plugins: [tsconfigPaths()],
|
||||
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: () => (process.env.IS_DEV ? 'csiv.js' : 'csiv-[hash].js'),
|
||||
// @ts-expect-error: 'system' not valid by typings, but works with Rollup
|
||||
formats: ['system'],
|
||||
},
|
||||
rollupOptions: {
|
||||
external: ['react', 'react-dom', '@contentstack/venus-components'],
|
||||
output: {
|
||||
dir: '../remix/public/build/rte',
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
16
tsconfig.json
Normal file
16
tsconfig.json
Normal file
@@ -0,0 +1,16 @@
|
||||
{
|
||||
"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
|
||||
}
|
||||
}
|
||||
60
types/contentstack.ts
Normal file
60
types/contentstack.ts
Normal 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;
|
||||
};
|
||||
243
types/imagevault.ts
Normal file
243
types/imagevault.ts
Normal file
@@ -0,0 +1,243 @@
|
||||
/**
|
||||
* @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 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 = {
|
||||
id: number;
|
||||
title: string;
|
||||
url: string;
|
||||
dimensions: {
|
||||
width: number;
|
||||
height: number;
|
||||
aspectRatio: number;
|
||||
};
|
||||
meta: { alt: string | undefined; caption: string | undefined };
|
||||
};
|
||||
|
||||
/**
|
||||
* 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;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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
10
types/lang.ts
Normal 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;
|
||||
149
utils/imagevault.ts
Normal file
149
utils/imagevault.ts
Normal file
@@ -0,0 +1,149 @@
|
||||
import { langEnum } from '../types/lang';
|
||||
|
||||
import type { GenericObjectType } from '@contentstack/app-sdk/dist/src/types/common.types';
|
||||
import type { Lang } from '../types/lang';
|
||||
import type {
|
||||
Config,
|
||||
ImageVaultAsset,
|
||||
InsertResponse,
|
||||
PublishDetails,
|
||||
} from "../types/imagevault";
|
||||
|
||||
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
|
||||
): res is InsertResponse {
|
||||
return (res as InsertResponse).MediaConversions !== 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 convert InsertResponse to ImageVaultAsset, used mainly for custom field images
|
||||
// For RTE this function is not enough since rte:s also need attrs, like position and the size thats
|
||||
// chosen in the editor
|
||||
export function insertResponseToImageVaultAsset(
|
||||
response: InsertResponse
|
||||
): ImageVaultAsset {
|
||||
const alt = response.Metadata?.find((meta) =>
|
||||
meta.Name.includes("AltText_")
|
||||
)?.Value;
|
||||
|
||||
const caption = response.Metadata?.find((meta) =>
|
||||
meta.Name.includes("Title_")
|
||||
)?.Value;
|
||||
|
||||
return {
|
||||
url: response.MediaConversions[0].Url,
|
||||
id: response.Id,
|
||||
meta: {
|
||||
alt,
|
||||
caption,
|
||||
},
|
||||
title: response.Name,
|
||||
dimensions: {
|
||||
width: response.MediaConversions[0].Width,
|
||||
height: response.MediaConversions[0].Height,
|
||||
aspectRatio: response.MediaConversions[0].FormatAspectRatio,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export type openImageVaultParams = {
|
||||
config: ImageVaultDAMConfig;
|
||||
entryData: EntryDataPublishDetails;
|
||||
onSuccess: (result: InsertResponse) => 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) => {
|
||||
onSuccess(result.response);
|
||||
},
|
||||
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?");
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user