Compare commits

10 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
30 changed files with 7495 additions and 4372 deletions

View File

@@ -1,7 +1,7 @@
**/build
**/public
**/package.json
**/.eslintrc.cjs
**/eslint.config.mjs
**/tsconfig.json
.husky

View File

@@ -23,11 +23,11 @@ The RTE plugin has the following configuration available. The values should be s
## Getting started
Run `npm install` in the root and the [rte](rte), [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.
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.
- 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.

10281
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -18,28 +18,33 @@
"prepare": "husky"
},
"dependencies": {
"@contentstack/app-sdk": "^2.0.1",
"@contentstack/venus-components": "2.2.3",
"react": "^18.2.0",
"react-dom": "^18.2.0"
"@contentstack/app-sdk": "^2.3.1",
"@contentstack/venus-components": "^3.0.0",
"react": "^19.1.0",
"react-dom": "^19.1.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",
"husky": "^9.0.11",
"lint-staged": "^15.2.2",
"prettier": "^3.2.5",
"typescript": "^5.1.6",
"vite": "^5.1.0",
"vite-tsconfig-paths": "^4.2.1"
"@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"
}
}

View File

@@ -1,90 +0,0 @@
/**
* 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,
},
},
],
}

View File

@@ -27,23 +27,20 @@ export default function ConfigForm({
<FieldLabel version="v2" htmlFor="baseUrl">
Base url for contentstack
</FieldLabel>
<Help text="Including the region. Used as publishing source on ImageVault" />
<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,
}))
setFinalValues((prev) => ({ ...prev, baseUrl: evt.target.value }))
setInstallationData({
configuration: {
...finalValues,
baseUrl: evt.target.value,
},
configuration: { ...finalValues, baseUrl: evt.target.value },
serverConfiguration: {},
})
}}
@@ -61,7 +58,10 @@ export default function ConfigForm({
<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" />
<Help
type="basic"
text="Images are fetched with a certain format. This should be an id from ImageVault"
/>
<TextInput
id="formatId"
name="formatId"
@@ -73,16 +73,10 @@ export default function ConfigForm({
version="v2"
width="large"
onChange={(evt: ChangeEvent<HTMLInputElement>) => {
setFinalValues((prev) => ({
...prev,
formatId: evt.target.value,
}))
setFinalValues((prev) => ({ ...prev, formatId: evt.target.value }))
setInstallationData({
configuration: {
...finalValues,
formatId: evt.target.value,
},
configuration: { ...finalValues, formatId: evt.target.value },
serverConfiguration: {},
})
}}

View File

@@ -1,20 +1,21 @@
import { useState, useEffect, ChangeEvent } from "react"
import {
ModalFooter,
ModalBody,
ModalHeader,
ButtonGroup,
Button,
ButtonGroup,
Field as FieldComponent,
FieldLabel,
ModalBody,
ModalFooter,
ModalHeader,
TextInput,
} from "@contentstack/venus-components"
import { ChangeEvent, useEffect, useState } from "react"
import type { InsertResponse } from "~/types/imagevault"
import FocalPointPicker from "~/shared-components/FocalPointPicker"
import type { FocalPoint, ImageVaultAsset } from "~/types/imagevault"
type ImageEditModalProps = {
fieldData: InsertResponse
setData: (data: InsertResponse) => void
fieldData: ImageVaultAsset
setData: (data: ImageVaultAsset) => void
closeModal: () => void
}
@@ -25,65 +26,63 @@ export default function ImageEditModal({
}: ImageEditModalProps) {
const [altText, setAltText] = useState("")
const [caption, setCaption] = useState("")
const [focalPoint, setFocalPoint] = useState<FocalPoint>({ x: 50, y: 50 })
const assetUrl = fieldData.MediaConversions[0].Url
const assetUrl = fieldData.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 ?? "")
if (fieldData.meta.alt) {
setAltText(fieldData.meta.alt)
}
}, [fieldData.Metadata])
if (fieldData.meta.caption) {
setCaption(fieldData.meta.caption)
}
}, [fieldData.meta])
useEffect(() => {
if (fieldData.focalPoint) {
setFocalPoint(fieldData.focalPoint)
}
}, [fieldData.focalPoint])
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({
const newData = {
...fieldData,
Metadata: newMetadata,
})
meta: {
alt: altText,
caption,
},
focalPoint,
}
setData(newData)
closeModal()
}
function changeFocalPoint(focalPoint: FocalPoint) {
setFocalPoint(focalPoint)
}
return (
<>
<ModalHeader title="Update image" closeModal={closeModal} />
<ModalBody
style={{
display: "flex",
display: "grid",
gridTemplateColumns: "1fr minmax(max-content, 250px)",
gap: "1rem",
justifyContent: "space-between",
alignItems: "center",
width: "100%",
width: "auto",
maxHeight: "calc(90dvh - 124px)", // 124px is the height of the header and footer
maxWidth: "90dvw",
overflow: "auto",
}}
>
<div style={{ flex: 1, overflowY: "auto" }}>
<img
src={assetUrl}
alt={altText}
height="100%"
style={{ maxHeight: "345px" }}
/>
</div>
<div style={{ flex: 1 }}>
<FocalPointPicker
imageSrc={assetUrl}
focalPoint={focalPoint}
onChange={changeFocalPoint}
/>
<div>
<FieldComponent>
<FieldLabel htmlFor="alt">Alt text</FieldLabel>
<TextInput
@@ -107,6 +106,24 @@ export default function ImageEditModal({
}
/>
</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>

View File

@@ -7,28 +7,26 @@ import {
FieldLabel,
cbModal,
} from "@contentstack/venus-components"
import ImageEditModal from "./ImageEditModal"
import FullSizeImage from "./FullSizeImage"
import { isInsertResponse, openImageVault } from "~/utils/imagevault"
import ImageEditModal from "./ImageEditModal"
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 { 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 type { Lang } from "~/types/lang"
import FullSizeImage from "./FullSizeImage"
export type ImageVaultDAMProps = {
sdk: UiLocation
config: ImageVaultDAMConfig
initialData: InsertResponse | null
initialData: ImageVaultAsset | null
}
type DAMButtonProps = {
onClick: () => void
}
type DAMButtonProps = { onClick: () => void }
function DAMButton({ onClick }: DAMButtonProps) {
return (
@@ -49,30 +47,26 @@ function DAMButton({ onClick }: DAMButtonProps) {
}
type MediaProps = {
media: InsertResponse
media: ImageVaultAsset
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 { url, meta, dimensions } = media
const { width, height, aspectRatio } = dimensions
const assetUrl = media.url
const assetTitle = `Id: ${media.imageVaultId} - ${media.fileName}`
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
const alt = meta.alt || meta.caption || ""
const title = meta.caption || meta.alt || ""
return (
<div key={Url} style={{ fontFamily: "Inter" }}>
<div key={url} style={{ fontFamily: "Inter" }}>
<AssetCardVertical
assetType="image"
assetUrl={assetUrl}
title={title}
title={assetTitle}
version="v2"
width={width}
height={height}
@@ -86,10 +80,10 @@ function Media({ media, onDelete, onEdit }: MediaProps) {
<FullSizeImage
// eslint-disable-next-line react/prop-types
onClose={props.closeModal}
imageUrl={Url}
imageUrl={url}
alt={alt}
title={Name}
aspectRatio={AspectRatio}
title={title}
aspectRatio={aspectRatio}
/>
)
},
@@ -119,7 +113,7 @@ export default function ImageVaultDAM({
config,
initialData,
}: ImageVaultDAMProps) {
const [media, setMedia] = useState<InsertResponse | null>(initialData)
const [media, setMedia] = useState(initialData)
const field = sdk.location.CustomField?.field
const frame = sdk.location.CustomField?.frame
@@ -130,17 +124,17 @@ export default function ImageVaultDAM({
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)
setTimeout(() => frame.updateHeight(), 0)
}
}, [frame])
const handleMedia = useCallback(
(result?: InsertResponse) => {
(asset?: ImageVaultAsset) => {
if (field) {
flushSync(() => {
setMedia(result || null)
// Data inside the field is supposed to be an empty object if nothing is selected
field.setData(result || {})
const data = asset || null
setMedia(data)
field.setData(data)
document.body.style.overflow = "hidden"
})
}
@@ -150,13 +144,9 @@ export default function ImageVaultDAM({
[field, updateFrameHeight]
)
useEffect(() => {
updateFrameHeight()
}, [updateFrameHeight])
const handleEdit = useCallback(() => {
const fieldData = field?.getData() as InsertResponse
if (isInsertResponse(fieldData)) {
const fieldData = field?.getData()
if (fieldData) {
cbModal({
// @ts-expect-error: Component is badly typed
component: (compProps) => (
@@ -168,15 +158,30 @@ export default function ImageVaultDAM({
),
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",
@@ -191,22 +196,16 @@ export default function ImageVaultDAM({
return (
<div>
<div>
<FieldLabel htmlFor="imagevaultpicker" version="v2">
ImageVault Asset
</FieldLabel>
</div>
<FieldLabel htmlFor="imagevaultpicker" version="v2">
ImageVault Asset
</FieldLabel>
{media ? (
<Media media={media} onDelete={handleMedia} onEdit={handleEdit} />
) : (
<DAMButton
onClick={() => {
openImageVault({
config,
entryData,
onSuccess: handleMedia,
})
openImageVault({ config, entryData, onSuccess: handleMedia })
}}
/>
)}

View File

@@ -1,10 +1,10 @@
import UiLocation from "@contentstack/app-sdk/dist/src/uiLocation"
import { useEffect, useState } from "react"
import { useEffect, useRef, useState } from "react"
export class SDKLoadingError extends Error {}
export default function useApp() {
const modalElementId = "field"
const ref = useRef<HTMLDivElement>(null)
const [, setError] = useState()
const [sdk, setSdk] = useState<UiLocation>()
const [config, setConfig] = useState<Record<string, string>>()
@@ -20,8 +20,7 @@ export default function useApp() {
const config = await initSdk.getConfig()
setConfig(config)
const iframeWrapperRef = document.getElementById(modalElementId)
window.iframeRef = iframeWrapperRef
window.iframeRef = ref.current
window.postRobot = initSdk.postRobot
} catch (e) {
let err: Error
@@ -43,6 +42,6 @@ export default function useApp() {
return {
sdk,
config,
modalElementId,
ref,
}
}

View File

@@ -6,7 +6,7 @@ import {
ScrollRestoration,
useRouteError,
} from "@remix-run/react"
import { SDKLoadingError } from "./hooks/useApp"
import { SDKLoadingError } from "~/hooks/useApp"
export function Layout({ children }: { children: React.ReactNode }) {
return (

View File

@@ -1,3 +1,5 @@
import "@contentstack/venus-components/build/main.css"
import { Suspense, lazy, useEffect, useState } from "react"
import { useScript } from "usehooks-ts"
import useApp from "~/hooks/useApp"
@@ -5,19 +7,31 @@ 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"
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"))
export default function Field() {
const { sdk, config: appConfig, modalElementId } = useApp()
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>()
const [fieldData, setFieldData] = useState<
InsertResponse | ImageVaultAsset | null
>()
const [dataIsLoaded, setDataIsLoaded] = useState(false)
const entry = sdk?.location.CustomField?.entry
const field = sdk?.location.CustomField?.field
@@ -31,14 +45,19 @@ export default function Field() {
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")
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])
@@ -46,13 +65,13 @@ export default function Field() {
return <Disclaimer />
}
const loaded = !!(fieldData && ivStatus === "ready" && sdk && appConfig)
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 dependecies...</p>
return <p style={{ fontFamily: "Inter" }}> Loading dependencies...</p>
}
if (!isImageVaultDAMConfig(appConfig)) {
@@ -60,16 +79,25 @@ export default function Field() {
}
const fieldConfig = sdk.location.CustomField?.fieldConfig
const config = {
...appConfig,
...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 (
<div id={modalElementId}>
<Suspense fallback={<p>Loading field...</p>}>
<ImageVaultDAM config={config} sdk={sdk} initialData={initialData} />
</Suspense>
<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
View File

@@ -1,2 +1 @@
/// <reference types="@remix-run/node" />
/// <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,
},
},
},
])

View File

@@ -12,14 +12,14 @@
"typecheck": "tsc"
},
"dependencies": {
"@remix-run/node": "^2.8.1",
"@remix-run/react": "^2.8.1",
"usehooks-ts": "^3.0.2"
"@remix-run/node": "^2.16.8",
"@remix-run/react": "^2.16.8",
"usehooks-ts": "^3.1.1"
},
"devDependencies": {
"@remix-run/dev": "^2.8.1"
"@remix-run/dev": "^2.16.8"
},
"engines": {
"node": ">=18.0.0"
"node": ">=22.0.0"
}
}

View File

@@ -4,10 +4,14 @@
"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": {
@@ -15,7 +19,8 @@
"~/types/*": ["../types/*"],
"~/utils/*": ["../utils/*"],
"~/components/*": ["./app/components/*"],
"~/hooks/*": ["./app/hooks/*"]
"~/hooks/*": ["./app/hooks/*"],
"~/shared-components/*": ["../shared-components/*"],
}
}
}

View File

@@ -1,15 +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,
}),
remix({ ssr: false }),
tsconfigPaths(),
libInjectCss(),
devtoolsJson(),
],
build: {
emptyOutDir: true,
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

@@ -1,90 +0,0 @@
/**
* 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,
},
},
],
}

View File

@@ -1,179 +1,94 @@
import React, { useState, useEffect, ChangeEvent } from "react"
import {
ModalFooter,
ModalBody,
ModalHeader,
ButtonGroup,
Button,
Field,
ButtonGroup,
Field as FieldComponent,
FieldLabel,
ModalBody,
ModalFooter,
ModalHeader,
TextInput,
Select,
} from "@contentstack/venus-components"
import { Path } from "slate"
import React, { ChangeEvent, useEffect, useState } from "react"
import type {
IRteParam,
IRteElementType,
} from "@contentstack/app-sdk/dist/src/RTE/types"
import type { InsertResponse } from "~/types/imagevault"
import type { IRteElementType } from "@contentstack/app-sdk/dist/src/RTE/types"
import FocalPointPicker from "~/shared-components/FocalPointPicker"
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",
},
]
import type { FocalPoint, ImageVaultAsset } from "~/types/imagevault"
type ImageEditModalProps = {
element: IRteElementType & {
attrs: InsertResponse
attrs: ImageVaultAsset
}
rte: IRteParam
setData: (data: ImageVaultAsset) => void
closeModal: () => void
path: Path
}
export default function ImageEditModal({
element,
setData,
closeModal,
path,
rte,
}: ImageEditModalProps) {
const [alignment, setAlignment] = useState<DropDownItem>({
label: "None",
value: DropdownValues.none,
type: "select",
})
const imageVaultAsset: ImageVaultAsset = element.attrs
const [altText, setAltText] = useState("")
const [caption, setCaption] = useState("")
const [focalPoint, setFocalPoint] = useState<FocalPoint>({ x: 50, y: 50 })
const assetUrl = element.attrs.MediaConversions[0].Url
const assetUrl = imageVaultAsset.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 ?? "")
if (imageVaultAsset.meta.alt) {
setAltText(imageVaultAsset.meta.alt)
}
}, [element.attrs.Metadata])
if (imageVaultAsset.meta.caption) {
setCaption(imageVaultAsset.meta.caption)
}
}, [imageVaultAsset.meta])
useEffect(() => {
if (imageVaultAsset.focalPoint) {
setFocalPoint(imageVaultAsset.focalPoint)
}
}, [imageVaultAsset.focalPoint])
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 },
},
const newData = {
...imageVaultAsset,
meta: {
alt: altText,
caption,
},
{ at: path }
)
focalPoint,
}
setData(newData)
closeModal()
}
function changeFocalPoint(focalPoint: FocalPoint) {
setFocalPoint(focalPoint)
}
return (
<>
<ModalHeader title="Update image" closeModal={closeModal} />
<ModalBody
style={{
display: "flex",
display: "grid",
gridTemplateColumns: "1fr minmax(max-content, 250px)",
gap: "1rem",
justifyContent: "space-between",
alignItems: "center",
width: "100%",
width: "auto",
maxHeight: "calc(90dvh - 124px)", // 124px is the height of the header and footer
maxWidth: "90dvw",
overflow: "auto",
}}
>
<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>
<FocalPointPicker
imageSrc={assetUrl}
focalPoint={focalPoint}
onChange={changeFocalPoint}
/>
<div>
<FieldComponent>
<FieldLabel htmlFor="alt">Alt text</FieldLabel>
<TextInput
value={altText}
@@ -183,9 +98,9 @@ export default function ImageEditModal({
setAltText(e.target.value)
}
/>
</Field>
</FieldComponent>
<Field>
<FieldComponent>
<FieldLabel htmlFor="caption">Caption</FieldLabel>
<TextInput
value={caption}
@@ -195,7 +110,25 @@ export default function ImageEditModal({
setCaption(e.target.value)
}
/>
</Field>
</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>

View File

@@ -1,43 +1,67 @@
import React, { useRef, useCallback, PropsWithChildren } from "react"
import { Tooltip, Icon, cbModal } from "@contentstack/venus-components"
import { Icon, Tooltip, cbModal } from "@contentstack/venus-components"
import React, { PropsWithChildren, useCallback } from "react"
import { Resizable } from "re-resizable"
import EmbedBtn from "./EmbedBtn"
import ImageEditModal from "./ImageEditModal"
import type {
IRteParam,
IRteElementType,
IRteParam,
} from "@contentstack/app-sdk/dist/src/RTE/types"
import type { InsertResponse } from "~/types/imagevault"
import type { ImageVaultAsset, InsertResponse } from "~/types/imagevault"
import {
getImageVaultAssetFromData,
isInsertResponse,
} from "~/utils/imagevault"
type ImageElementProps = PropsWithChildren & {
element: IRteElementType & { attrs: InsertResponse }
element: IRteElementType & { attrs: ImageVaultAsset | 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 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 imgRef = useRef<HTMLDivElement | null>(null)
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,
rte,
path: rte.getPath(element),
...compProps,
}),
component: (compProps) => (
<ImageEditModal
element={element}
setData={handleMedia}
{...compProps}
/>
),
modalProps: {
size: "max",
style: {
content: {
maxHeight: "90dvh",
maxWidth: "90dvw",
width: "auto",
},
overlay: {},
},
},
})
}, [element, rte])
}, [element, handleMedia])
const ToolTipButtons = () => {
return (
@@ -49,7 +73,7 @@ export function ImageElement({ children, element, rte }: ImageElementProps) {
<EmbedBtn
title="remove"
content={"Remove"}
onClick={() => rte?.removeNode(element)}
onClick={() => rte.removeNode(element)}
>
<Icon icon="Trash" />
</EmbedBtn>
@@ -57,117 +81,52 @@ export function ImageElement({ children, element, rte }: ImageElementProps) {
)
}
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) }
)
if (!imageVaultAsset) {
return <>{children}</>
}
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]
// 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 (
<div
style={{
...alignmentStyles,
...element.attrs.style,
}}
<Tooltip
zIndex={909}
className="p-0"
style={{ marginBottom: "10px" }}
position="top"
variantType="light"
offset={[0, -15]}
content={<ToolTipButtons />}
>
<Tooltip
zIndex={909}
className="p-0"
style={{ marginBottom: "10px" }}
position="top"
variantType="light"
offset={[0, -15]}
content={<ToolTipButtons />}
>
<span
data-type="asset"
<span data-type="asset" contentEditable={false}>
<div
contentEditable={false}
style={element.attrs?.style}
style={{
width: "280px",
height: "auto",
...(isHighlight ? { border: "1px solid #6c5ce7" } : {}),
}}
>
<Resizable
lockAspectRatio
size={{
width: element.attrs.width ?? "180px",
height: element.attrs.heigth ?? "auto",
<img
src={imageVaultAsset.url}
onError={(event) => {
event.currentTarget.src = "https://placehold.co/600x400"
}}
onResizeStop={onResizeStop}
handleStyles={{
right: { right: 0, width: "15px" },
left: { left: 0, width: "15px" },
bottom: { bottom: "0" },
bottomRight: { width: "15px" },
style={{
width: "100%",
height: "auto",
aspectRatio: imageVaultAsset.dimensions.aspectRatio,
borderRadius: "8px",
}}
>
<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>
alt={imageVaultAsset.meta.alt}
title={`Id: ${imageVaultAsset.imageVaultId} - ${imageVaultAsset.fileName}`}
/>
</div>
{children}
</span>
</Tooltip>
)
}

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

View File

@@ -1,17 +1,16 @@
import React from "react"
import ContentstackSDK from "@contentstack/app-sdk"
import { ImageElement } from "~/components/ImageElement"
import React from "react"
import { Icon } from "@contentstack/venus-components"
import { openImageVault } from "~/utils/imagevault"
import type { Lang } from "~/types/lang"
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)
@@ -103,7 +102,7 @@ function extractContentstackEmbeddedData(
plugin,
}
} catch (e) {
console.log(`Unable to parse JWT like: ${jwtLike}`)
console.log(`Unable to parse JWT like: ${jwtLike}`, e)
}
return null
}
@@ -121,12 +120,14 @@ function loadIV(plugin: ContentstackPluginDefinition) {
}
}
async function init() {
export default ContentstackSDK.init().then((sdk) => {
try {
const sdk = await ContentstackSDK.init()
const extensionObj = sdk["location"]
const RTE = extensionObj["RTEPlugin"]
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"))
@@ -137,8 +138,6 @@ async function init() {
}
}
if (!RTE) return
const ImageVault = RTE("ImageVault", (rte) => {
if (rte) {
if (!ivloaded) {
@@ -171,16 +170,15 @@ async function init() {
)
}
},
display: ["toolbar"],
displayOn: ["toolbar"],
elementType: ["void"],
}
})
ImageVault.on("exec", async (rte) => {
if (rte) {
const savedSelection = rte?.selection?.get() ?? undefined
const savedSelection = rte.selection.get() ?? undefined
// @ts-expect-error: Added at runtime
const appConfig = await rte.getConfig()
// This is the configuration for this instance of the plugin.
@@ -213,7 +211,9 @@ async function init() {
{
// @ts-expect-error: incorrect typings
type: "ImageVault",
attrs: result,
attrs: {
...result,
},
uid: crypto.randomUUID(),
children: [{ text: "" }],
},
@@ -229,6 +229,4 @@ async function init() {
} catch (e) {
console.error({ e })
}
}
export default init()
})

View File

@@ -6,14 +6,14 @@
"scripts": {
"build": "vite build",
"dev": "IS_DEV=true vite build --watch",
"lint": "eslint --ignore-path ../.gitignore --cache --cache-location ./node_modules/.cache/eslint .",
"lint": "eslint --cache --cache-location ./node_modules/.cache/eslint .",
"prebuild": "concurrently npm:lint npm:typecheck",
"typecheck": "tsc"
},
"devDependencies": {
"@types/systemjs": "^6.13.5"
"@types/systemjs": "^6.15.3"
},
"engines": {
"node": ">=18.0.0"
"node": ">=22.0.0"
}
}

View File

@@ -4,6 +4,8 @@
"env.d.ts",
"../types/**/*.ts",
"../utils/**/*.ts",
"../shared-components/**/*.ts",
"../shared-components/**/*.tsx",
"**/*.ts",
"**/*.tsx"
],
@@ -13,7 +15,8 @@
"paths": {
"~/*": ["./*"],
"~/types/*": ["../types/*"],
"~/utils/*": ["../utils/*"]
"~/utils/*": ["../utils/*"],
"~/shared-components/*": ["../shared-components/*"],
}
}
}

View File

@@ -1,12 +1,12 @@
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()],
define: {
IS_DEV: process.env.IS_DEV === "true" ? true : false,
},
plugins: [tsconfigPaths(), libInjectCss(), devtoolsJson()],
define: { IS_DEV: process.env.IS_DEV === "true" ? true : false },
publicDir: false,
build: {
sourcemap: process.env.IS_DEV ? "inline" : "hidden",
@@ -15,14 +15,11 @@ export default defineConfig({
entry: resolve(__dirname, "main.tsx"),
name: "csiv",
fileName: () => "csiv.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",
},
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,
}
}

View File

@@ -11,6 +11,13 @@
"allowJs": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"noEmit": true
"noEmit": true,
"jsx": "react",
"baseUrl": ".",
"paths": {
"~/types/*": ["./types/*"],
"~/utils/*": ["./utils/*"],
"~/shared-components/*": ["./shared-components/*"],
}
}
}

View File

@@ -16,6 +16,11 @@ declare global {
}
}
export interface FocalPoint {
x: number
y: number
}
export declare class InsertMediaWindow {
constructor(config: Config, windowOptions: string)
openImageVault: () => void
@@ -50,15 +55,16 @@ export type MetaData = {
}
export type ImageVaultAsset = {
id: number
title: string
imageVaultId: number
fileName: string
url: string
dimensions: {
width: number
height: number
aspectRatio: number
}
meta: { alt: string | undefined; caption: string | undefined }
focalPoint: FocalPoint
meta: { alt: string; caption: string }
}
/**
@@ -91,6 +97,8 @@ export declare class InsertResponse {
AddedBy: string
Metadata?: MetaData[] | undefined
FocalPoint: FocalPoint
}
/**

View File

@@ -1,13 +1,14 @@
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,
FocalPoint,
ImageVaultAsset,
InsertResponse,
PublishDetails,
} from "../types/imagevault"
import type { Lang } from "../types/lang"
const metaIds = {
[langEnum.de]: { altText: 68, title: 77 },
@@ -49,9 +50,15 @@ export function getPublishDetails(
}
export function isInsertResponse(
res: InsertResponse | GenericObjectType
res: InsertResponse | GenericObjectType | null | undefined
): res is InsertResponse {
return (res as InsertResponse).MediaConversions !== undefined
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 = {
@@ -66,40 +73,67 @@ export function isImageVaultDAMConfig(
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
// 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
}
const caption = response.Metadata?.find((meta) =>
meta.Name.includes("Title_")
)?.Value
// 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 {
url: response.MediaConversions[0].Url,
id: response.Id,
imageVaultId: response.Id,
url: image.Url,
meta: {
alt,
caption,
},
title: response.Name,
fileName: response.Name,
dimensions: {
width: response.MediaConversions[0].Width,
height: response.MediaConversions[0].Height,
aspectRatio: response.MediaConversions[0].FormatAspectRatio,
width: image.Width,
height: image.Height,
aspectRatio: image.AspectRatio,
},
focalPoint: response.FocalPoint || focalPoint,
}
}
export type openImageVaultParams = {
config: ImageVaultDAMConfig
entryData: EntryDataPublishDetails
onSuccess: (result: InsertResponse) => void
onSuccess: (result: ImageVaultAsset) => void
onClose?: () => void
}
@@ -123,7 +157,11 @@ export function openImageVault({
publishDetails,
insertMultiple: false,
success: (result) => {
onSuccess(result.response)
const imageVaultAsset = mapInsertResponseToImageVaultAsset(
result.response,
{ x: 50, y: 50 }
)
onSuccess(imageVaultAsset)
},
close: () => {
if (typeof onClose === "function") {