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 **/build
**/public **/public
**/package.json **/package.json
**/.eslintrc.cjs **/eslint.config.mjs
**/tsconfig.json **/tsconfig.json
.husky .husky

View File

@@ -23,11 +23,11 @@ The RTE plugin has the following configuration available. The values should be s
## Getting started ## 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. 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 ### Possible issues
- Browsers/Browser extensions - 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.

10283
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -18,28 +18,33 @@
"prepare": "husky" "prepare": "husky"
}, },
"dependencies": { "dependencies": {
"@contentstack/app-sdk": "^2.0.1", "@contentstack/app-sdk": "^2.3.1",
"@contentstack/venus-components": "2.2.3", "@contentstack/venus-components": "^3.0.0",
"react": "^18.2.0", "react": "^19.1.0",
"react-dom": "^18.2.0" "react-dom": "^19.1.0"
}, },
"devDependencies": { "devDependencies": {
"@types/react": "^18.2.20", "@eslint/compat": "^1.3.0",
"@types/react-dom": "^18.2.7", "@eslint/eslintrc": "^3.3.1",
"@typescript-eslint/eslint-plugin": "^6.7.4", "@eslint/js": "^9.29.0",
"@typescript-eslint/parser": "^6.7.4", "@types/react-dom": "^19.1.6",
"concurrently": "^8.2.2", "@typescript-eslint/eslint-plugin": "^8.34.0",
"eslint": "^8.38.0", "@typescript-eslint/parser": "^8.34.0",
"eslint-import-resolver-typescript": "^3.6.1", "concurrently": "^9.1.2",
"eslint-plugin-import": "^2.28.1", "eslint": "^9.29.0",
"eslint-plugin-jsx-a11y": "^6.7.1", "eslint-import-resolver-typescript": "^4.4.3",
"eslint-plugin-react": "^7.33.2", "eslint-plugin-import": "^2.31.0",
"eslint-plugin-react-hooks": "^4.6.0", "eslint-plugin-jsx-a11y": "^6.10.2",
"husky": "^9.0.11", "eslint-plugin-react": "^7.37.5",
"lint-staged": "^15.2.2", "eslint-plugin-react-hooks": "^5.2.0",
"prettier": "^3.2.5", "globals": "^16.2.0",
"typescript": "^5.1.6", "husky": "^9.1.7",
"vite": "^5.1.0", "lint-staged": "^16.1.2",
"vite-tsconfig-paths": "^4.2.1" "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"> <FieldLabel version="v2" htmlFor="baseUrl">
Base url for contentstack Base url for contentstack
</FieldLabel> </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 <TextInput
id="baseUrl" id="baseUrl"
name="baseUrl" name="baseUrl"
type="url" type="url"
value={finalValues.baseUrl} value={finalValues.baseUrl}
onChange={(evt: ChangeEvent<HTMLInputElement>) => { onChange={(evt: ChangeEvent<HTMLInputElement>) => {
setFinalValues((prev) => ({ setFinalValues((prev) => ({ ...prev, baseUrl: evt.target.value }))
...prev,
baseUrl: evt.target.value,
}))
setInstallationData({ setInstallationData({
configuration: { configuration: { ...finalValues, baseUrl: evt.target.value },
...finalValues,
baseUrl: evt.target.value,
},
serverConfiguration: {}, serverConfiguration: {},
}) })
}} }}
@@ -61,7 +58,10 @@ export default function ConfigForm({
<FieldLabel version="v2" htmlFor="formatId"> <FieldLabel version="v2" htmlFor="formatId">
Format Id for images Format Id for images
</FieldLabel> </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 <TextInput
id="formatId" id="formatId"
name="formatId" name="formatId"
@@ -73,16 +73,10 @@ export default function ConfigForm({
version="v2" version="v2"
width="large" width="large"
onChange={(evt: ChangeEvent<HTMLInputElement>) => { onChange={(evt: ChangeEvent<HTMLInputElement>) => {
setFinalValues((prev) => ({ setFinalValues((prev) => ({ ...prev, formatId: evt.target.value }))
...prev,
formatId: evt.target.value,
}))
setInstallationData({ setInstallationData({
configuration: { configuration: { ...finalValues, formatId: evt.target.value },
...finalValues,
formatId: evt.target.value,
},
serverConfiguration: {}, serverConfiguration: {},
}) })
}} }}

View File

@@ -1,20 +1,21 @@
import { useState, useEffect, ChangeEvent } from "react"
import { import {
ModalFooter,
ModalBody,
ModalHeader,
ButtonGroup,
Button, Button,
ButtonGroup,
Field as FieldComponent, Field as FieldComponent,
FieldLabel, FieldLabel,
ModalBody,
ModalFooter,
ModalHeader,
TextInput, TextInput,
} from "@contentstack/venus-components" } 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 = { type ImageEditModalProps = {
fieldData: InsertResponse fieldData: ImageVaultAsset
setData: (data: InsertResponse) => void setData: (data: ImageVaultAsset) => void
closeModal: () => void closeModal: () => void
} }
@@ -25,65 +26,63 @@ export default function ImageEditModal({
}: ImageEditModalProps) { }: ImageEditModalProps) {
const [altText, setAltText] = useState("") const [altText, setAltText] = useState("")
const [caption, setCaption] = 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(() => { useEffect(() => {
if (fieldData.Metadata && fieldData.Metadata.length) { if (fieldData.meta.alt) {
const altText = fieldData.Metadata.find((meta) => setAltText(fieldData.meta.alt)
meta.Name.includes("AltText_")
)?.Value
const caption = fieldData.Metadata.find((meta) =>
meta.Name.includes("Title_")
)?.Value
setAltText(altText ?? "")
setCaption(caption ?? "")
} }
}, [fieldData.Metadata]) if (fieldData.meta.caption) {
setCaption(fieldData.meta.caption)
}
}, [fieldData.meta])
useEffect(() => {
if (fieldData.focalPoint) {
setFocalPoint(fieldData.focalPoint)
}
}, [fieldData.focalPoint])
function handleSave() { function handleSave() {
const metaData = fieldData.Metadata ?? [] const newData = {
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, ...fieldData,
Metadata: newMetadata, meta: {
}) alt: altText,
caption,
},
focalPoint,
}
setData(newData)
closeModal() closeModal()
} }
function changeFocalPoint(focalPoint: FocalPoint) {
setFocalPoint(focalPoint)
}
return ( return (
<> <>
<ModalHeader title="Update image" closeModal={closeModal} /> <ModalHeader title="Update image" closeModal={closeModal} />
<ModalBody <ModalBody
style={{ style={{
display: "flex", display: "grid",
gridTemplateColumns: "1fr minmax(max-content, 250px)",
gap: "1rem", gap: "1rem",
justifyContent: "space-between",
alignItems: "center", 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" }}> <FocalPointPicker
<img imageSrc={assetUrl}
src={assetUrl} focalPoint={focalPoint}
alt={altText} onChange={changeFocalPoint}
height="100%"
style={{ maxHeight: "345px" }}
/> />
</div> <div>
<div style={{ flex: 1 }}>
<FieldComponent> <FieldComponent>
<FieldLabel htmlFor="alt">Alt text</FieldLabel> <FieldLabel htmlFor="alt">Alt text</FieldLabel>
<TextInput <TextInput
@@ -107,6 +106,24 @@ export default function ImageEditModal({
} }
/> />
</FieldComponent> </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> </div>
</ModalBody> </ModalBody>
<ModalFooter> <ModalFooter>

View File

@@ -7,28 +7,26 @@ import {
FieldLabel, FieldLabel,
cbModal, cbModal,
} from "@contentstack/venus-components" } from "@contentstack/venus-components"
import ImageEditModal from "./ImageEditModal"
import FullSizeImage from "./FullSizeImage"
import { isInsertResponse, openImageVault } from "~/utils/imagevault" 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 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 { import type {
EntryDataPublishDetails, EntryDataPublishDetails,
ImageVaultDAMConfig, ImageVaultDAMConfig,
} from "~/utils/imagevault" } from "~/utils/imagevault"
import type { Lang } from "~/types/lang" import FullSizeImage from "./FullSizeImage"
export type ImageVaultDAMProps = { export type ImageVaultDAMProps = {
sdk: UiLocation sdk: UiLocation
config: ImageVaultDAMConfig config: ImageVaultDAMConfig
initialData: InsertResponse | null initialData: ImageVaultAsset | null
} }
type DAMButtonProps = { type DAMButtonProps = { onClick: () => void }
onClick: () => void
}
function DAMButton({ onClick }: DAMButtonProps) { function DAMButton({ onClick }: DAMButtonProps) {
return ( return (
@@ -49,30 +47,26 @@ function DAMButton({ onClick }: DAMButtonProps) {
} }
type MediaProps = { type MediaProps = {
media: InsertResponse media: ImageVaultAsset
onDelete: () => void onDelete: () => void
onEdit: () => void onEdit: () => void
} }
function Media({ media, onDelete, onEdit }: MediaProps) { function Media({ media, onDelete, onEdit }: MediaProps) {
// MediaConversions is an array but will only contain one object const { url, meta, dimensions } = media
const { Url, Height, FormatHeight, Width, FormatWidth, Name, AspectRatio } = const { width, height, aspectRatio } = dimensions
media.MediaConversions[0] const assetUrl = media.url
const assetTitle = `Id: ${media.imageVaultId} - ${media.fileName}`
const assetUrl = Url const alt = meta.alt || meta.caption || ""
const title = media.Name const title = meta.caption || meta.alt || ""
const width = FormatWidth || Width
const height = FormatHeight || Height
const alt =
media.Metadata?.find((meta) => meta.Name.includes("AltText_"))?.Value ||
Name
return ( return (
<div key={Url} style={{ fontFamily: "Inter" }}> <div key={url} style={{ fontFamily: "Inter" }}>
<AssetCardVertical <AssetCardVertical
assetType="image" assetType="image"
assetUrl={assetUrl} assetUrl={assetUrl}
title={title} title={assetTitle}
version="v2" version="v2"
width={width} width={width}
height={height} height={height}
@@ -86,10 +80,10 @@ function Media({ media, onDelete, onEdit }: MediaProps) {
<FullSizeImage <FullSizeImage
// eslint-disable-next-line react/prop-types // eslint-disable-next-line react/prop-types
onClose={props.closeModal} onClose={props.closeModal}
imageUrl={Url} imageUrl={url}
alt={alt} alt={alt}
title={Name} title={title}
aspectRatio={AspectRatio} aspectRatio={aspectRatio}
/> />
) )
}, },
@@ -119,7 +113,7 @@ export default function ImageVaultDAM({
config, config,
initialData, initialData,
}: ImageVaultDAMProps) { }: ImageVaultDAMProps) {
const [media, setMedia] = useState<InsertResponse | null>(initialData) const [media, setMedia] = useState(initialData)
const field = sdk.location.CustomField?.field const field = sdk.location.CustomField?.field
const frame = sdk.location.CustomField?.frame const frame = sdk.location.CustomField?.frame
@@ -130,17 +124,17 @@ export default function ImageVaultDAM({
if (frame?.updateHeight) { if (frame?.updateHeight) {
// We need to recalculate the height of the iframe when an image is added. // We need to recalculate the height of the iframe when an image is added.
// Cannot use flushSync inside useEffect. // Cannot use flushSync inside useEffect.
setTimeout(() => frame.updateHeight(document.body.scrollHeight), 0) setTimeout(() => frame.updateHeight(), 0)
} }
}, [frame]) }, [frame])
const handleMedia = useCallback( const handleMedia = useCallback(
(result?: InsertResponse) => { (asset?: ImageVaultAsset) => {
if (field) { if (field) {
flushSync(() => { flushSync(() => {
setMedia(result || null) const data = asset || null
// Data inside the field is supposed to be an empty object if nothing is selected setMedia(data)
field.setData(result || {}) field.setData(data)
document.body.style.overflow = "hidden" document.body.style.overflow = "hidden"
}) })
} }
@@ -150,13 +144,9 @@ export default function ImageVaultDAM({
[field, updateFrameHeight] [field, updateFrameHeight]
) )
useEffect(() => {
updateFrameHeight()
}, [updateFrameHeight])
const handleEdit = useCallback(() => { const handleEdit = useCallback(() => {
const fieldData = field?.getData() as InsertResponse const fieldData = field?.getData()
if (isInsertResponse(fieldData)) { if (fieldData) {
cbModal({ cbModal({
// @ts-expect-error: Component is badly typed // @ts-expect-error: Component is badly typed
component: (compProps) => ( component: (compProps) => (
@@ -168,15 +158,30 @@ export default function ImageVaultDAM({
), ),
modalProps: { modalProps: {
size: "max", size: "max",
style: {
content: { maxHeight: "90dvh", maxWidth: "90dvw", width: "auto" },
overlay: {},
},
}, },
}) })
} }
}, [field, handleMedia]) }, [field, handleMedia])
useEffect(() => {
updateFrameHeight()
}, [updateFrameHeight])
if (!field || !frame || !entry || !stack) { if (!field || !frame || !entry || !stack) {
return <p>Initializing custom field...</p> 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 = { const entryData: EntryDataPublishDetails = {
//TODO: Add support for branches //TODO: Add support for branches
branch: "main", branch: "main",
@@ -190,23 +195,17 @@ export default function ImageVaultDAM({
} }
return ( return (
<div>
<div> <div>
<FieldLabel htmlFor="imagevaultpicker" version="v2"> <FieldLabel htmlFor="imagevaultpicker" version="v2">
ImageVault Asset ImageVault Asset
</FieldLabel> </FieldLabel>
</div>
{media ? ( {media ? (
<Media media={media} onDelete={handleMedia} onEdit={handleEdit} /> <Media media={media} onDelete={handleMedia} onEdit={handleEdit} />
) : ( ) : (
<DAMButton <DAMButton
onClick={() => { onClick={() => {
openImageVault({ openImageVault({ config, entryData, onSuccess: handleMedia })
config,
entryData,
onSuccess: handleMedia,
})
}} }}
/> />
)} )}

View File

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

View File

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

View File

@@ -1,3 +1,5 @@
import "@contentstack/venus-components/build/main.css"
import { Suspense, lazy, useEffect, useState } from "react" import { Suspense, lazy, useEffect, useState } from "react"
import { useScript } from "usehooks-ts" import { useScript } from "usehooks-ts"
import useApp from "~/hooks/useApp" import useApp from "~/hooks/useApp"
@@ -5,19 +7,31 @@ import useApp from "~/hooks/useApp"
import Disclaimer from "~/components/Disclaimer" import Disclaimer from "~/components/Disclaimer"
import InvalidConfig from "~/components/InvalidConfig" import InvalidConfig from "~/components/InvalidConfig"
import { isImageVaultDAMConfig } from "~/utils/imagevault" import { GenericObjectType } from "@contentstack/app-sdk/dist/src/types/common.types"
import type { InsertResponse } from "~/types/imagevault" 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")) const ImageVaultDAM = lazy(() => import("~/components/ImageVaultDAM"))
export default function Field() { interface FieldContentProps {
const { sdk, config: appConfig, modalElementId } = useApp() sdk?: UiLocation
appConfig?: GenericObjectType
}
function FieldContent({ sdk, appConfig }: FieldContentProps) {
const ivStatus = useScript( const ivStatus = useScript(
"/scripts/imagevault-insert-media/insertmediawindow.min.js" "/scripts/imagevault-insert-media/insertmediawindow.min.js"
) )
const [showDisclaimer, setShowDisclaimer] = useState(false) 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 entry = sdk?.location.CustomField?.entry
const field = sdk?.location.CustomField?.field const field = sdk?.location.CustomField?.field
@@ -31,14 +45,19 @@ export default function Field() {
if (field && entry) { if (field && entry) {
const data = field.getData() const data = field.getData()
const title = entry.getField("title").getData().toString() const title = entry.getField("title").getData().toString()
if (data && title) { if (!title) {
setFieldData(data as InsertResponse) throw new Error("Missing title for entry")
} else {
throw new Error("Missing data or title for entry")
} }
if (data) {
setFieldData(data as InsertResponse)
}
setDataIsLoaded(true)
} }
} catch (e) { } catch (e) {
setShowDisclaimer(true) setShowDisclaimer(true)
console.log("Unable to get field data from SDK: ", e)
} }
}, [entry, field]) }, [entry, field])
@@ -46,13 +65,13 @@ export default function Field() {
return <Disclaimer /> return <Disclaimer />
} }
const loaded = !!(fieldData && ivStatus === "ready" && sdk && appConfig) const loaded = !!(dataIsLoaded && ivStatus === "ready" && sdk && appConfig)
const initialData = const initialData =
fieldData && Object.keys(fieldData).length > 0 ? fieldData : null fieldData && Object.keys(fieldData).length > 0 ? fieldData : null
if (!loaded) { if (!loaded) {
return <p style={{ fontFamily: "Inter" }}> Loading dependecies...</p> return <p style={{ fontFamily: "Inter" }}> Loading dependencies...</p>
} }
if (!isImageVaultDAMConfig(appConfig)) { if (!isImageVaultDAMConfig(appConfig)) {
@@ -60,16 +79,25 @@ export default function Field() {
} }
const fieldConfig = sdk.location.CustomField?.fieldConfig const fieldConfig = sdk.location.CustomField?.fieldConfig
const config = { const config = { ...appConfig, ...fieldConfig }
...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 ( return (
<div id={modalElementId}>
<Suspense fallback={<p>Loading field...</p>}> <Suspense fallback={<p>Loading field...</p>}>
<ImageVaultDAM config={config} sdk={sdk} initialData={initialData} /> <ImageVaultDAM config={config} sdk={sdk} initialData={imageVaultAsset} />
</Suspense> </Suspense>
)
}
export default function Field() {
const { sdk, config, ref } = useApp()
return (
<div ref={ref}>
<FieldContent sdk={sdk} appConfig={config} />
</div> </div>
) )
} }

1
remix/env.d.ts vendored
View File

@@ -1,2 +1 @@
/// <reference types="@remix-run/node" />
/// <reference types="vite/client" /> /// <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" "typecheck": "tsc"
}, },
"dependencies": { "dependencies": {
"@remix-run/node": "^2.8.1", "@remix-run/node": "^2.16.8",
"@remix-run/react": "^2.8.1", "@remix-run/react": "^2.16.8",
"usehooks-ts": "^3.0.2" "usehooks-ts": "^3.1.1"
}, },
"devDependencies": { "devDependencies": {
"@remix-run/dev": "^2.8.1" "@remix-run/dev": "^2.16.8"
}, },
"engines": { "engines": {
"node": ">=18.0.0" "node": ">=22.0.0"
} }
} }

View File

@@ -4,10 +4,14 @@
"env.d.ts", "env.d.ts",
"../types/**/*.ts", "../types/**/*.ts",
"../utils/**/*.ts", "../utils/**/*.ts",
"../shared-components/**/*.ts",
"../shared-components/**/*.tsx",
"**/*.ts", "**/*.ts",
"**/*.tsx" "**/*.tsx"
], ],
"compilerOptions": { "compilerOptions": {
"types": ["@remix-run/node", "vite/client"],
"skipLibCheck": true,
"jsx": "react-jsx", "jsx": "react-jsx",
"baseUrl": ".", "baseUrl": ".",
"paths": { "paths": {
@@ -15,7 +19,8 @@
"~/types/*": ["../types/*"], "~/types/*": ["../types/*"],
"~/utils/*": ["../utils/*"], "~/utils/*": ["../utils/*"],
"~/components/*": ["./app/components/*"], "~/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 { vitePlugin as remix } from "@remix-run/dev"
import { defineConfig } from "vite" 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" import tsconfigPaths from "vite-tsconfig-paths"
export default defineConfig({ export default defineConfig({
plugins: [ plugins: [
remix({ remix({ ssr: false }),
ssr: false,
}),
tsconfigPaths(), tsconfigPaths(),
libInjectCss(),
devtoolsJson(),
], ],
build: { server: {
emptyOutDir: true, 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 { import {
ModalFooter,
ModalBody,
ModalHeader,
ButtonGroup,
Button, Button,
Field, ButtonGroup,
Field as FieldComponent,
FieldLabel, FieldLabel,
ModalBody,
ModalFooter,
ModalHeader,
TextInput, TextInput,
Select,
} from "@contentstack/venus-components" } from "@contentstack/venus-components"
import { Path } from "slate" import React, { ChangeEvent, useEffect, useState } from "react"
import type { import type { IRteElementType } from "@contentstack/app-sdk/dist/src/RTE/types"
IRteParam, import FocalPointPicker from "~/shared-components/FocalPointPicker"
IRteElementType,
} from "@contentstack/app-sdk/dist/src/RTE/types"
import type { InsertResponse } from "~/types/imagevault"
enum DropdownValues { import type { FocalPoint, ImageVaultAsset } from "~/types/imagevault"
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 = { type ImageEditModalProps = {
element: IRteElementType & { element: IRteElementType & {
attrs: InsertResponse attrs: ImageVaultAsset
} }
rte: IRteParam setData: (data: ImageVaultAsset) => void
closeModal: () => void closeModal: () => void
path: Path
} }
export default function ImageEditModal({ export default function ImageEditModal({
element, element,
setData,
closeModal, closeModal,
path,
rte,
}: ImageEditModalProps) { }: ImageEditModalProps) {
const [alignment, setAlignment] = useState<DropDownItem>({ const imageVaultAsset: ImageVaultAsset = element.attrs
label: "None",
value: DropdownValues.none,
type: "select",
})
const [altText, setAltText] = useState("") const [altText, setAltText] = useState("")
const [caption, setCaption] = 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(() => { useEffect(() => {
if (element.attrs.Metadata && element.attrs.Metadata.length) { if (imageVaultAsset.meta.alt) {
const altText = element.attrs.Metadata.find((meta) => setAltText(imageVaultAsset.meta.alt)
meta.Name.includes("AltText_")
)?.Value
const caption = element.attrs.Metadata.find((meta) =>
meta.Name.includes("Title_")
)?.Value
setAltText(altText ?? "")
setCaption(caption ?? "")
} }
}, [element.attrs.Metadata]) if (imageVaultAsset.meta.caption) {
setCaption(imageVaultAsset.meta.caption)
}
}, [imageVaultAsset.meta])
useEffect(() => {
if (imageVaultAsset.focalPoint) {
setFocalPoint(imageVaultAsset.focalPoint)
}
}, [imageVaultAsset.focalPoint])
function handleSave() { function handleSave() {
let newStyle const newData = {
...imageVaultAsset,
switch (alignment.value) { meta: {
case DropdownValues.center: alt: altText,
case DropdownValues.left: caption,
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 },
}, },
}, focalPoint,
{ at: path } }
) setData(newData)
closeModal() closeModal()
} }
function changeFocalPoint(focalPoint: FocalPoint) {
setFocalPoint(focalPoint)
}
return ( return (
<> <>
<ModalHeader title="Update image" closeModal={closeModal} /> <ModalHeader title="Update image" closeModal={closeModal} />
<ModalBody <ModalBody
style={{ style={{
display: "flex", display: "grid",
gridTemplateColumns: "1fr minmax(max-content, 250px)",
gap: "1rem", gap: "1rem",
justifyContent: "space-between",
alignItems: "center", 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" }}> <FocalPointPicker
<img imageSrc={assetUrl}
src={assetUrl} focalPoint={focalPoint}
alt={altText} onChange={changeFocalPoint}
height="100%"
style={{ maxHeight: "345px" }}
/> />
</div> <div>
<div style={{ flex: 1 }}> <FieldComponent>
<Field>
<Select
selectLabel="Alignment"
value={alignment}
onChange={(e: DropDownItem) => {
setAlignment(e)
}}
options={dropdownList}
/>
</Field>
<Field>
<FieldLabel htmlFor="alt">Alt text</FieldLabel> <FieldLabel htmlFor="alt">Alt text</FieldLabel>
<TextInput <TextInput
value={altText} value={altText}
@@ -183,9 +98,9 @@ export default function ImageEditModal({
setAltText(e.target.value) setAltText(e.target.value)
} }
/> />
</Field> </FieldComponent>
<Field> <FieldComponent>
<FieldLabel htmlFor="caption">Caption</FieldLabel> <FieldLabel htmlFor="caption">Caption</FieldLabel>
<TextInput <TextInput
value={caption} value={caption}
@@ -195,7 +110,25 @@ export default function ImageEditModal({
setCaption(e.target.value) 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> </div>
</ModalBody> </ModalBody>
<ModalFooter> <ModalFooter>

View File

@@ -1,43 +1,67 @@
import React, { useRef, useCallback, PropsWithChildren } from "react" import { Icon, Tooltip, cbModal } from "@contentstack/venus-components"
import { Tooltip, Icon, cbModal } from "@contentstack/venus-components" import React, { PropsWithChildren, useCallback } from "react"
import { Resizable } from "re-resizable"
import EmbedBtn from "./EmbedBtn" import EmbedBtn from "./EmbedBtn"
import ImageEditModal from "./ImageEditModal" import ImageEditModal from "./ImageEditModal"
import type { import type {
IRteParam,
IRteElementType, IRteElementType,
IRteParam,
} from "@contentstack/app-sdk/dist/src/RTE/types" } 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 & { type ImageElementProps = PropsWithChildren & {
element: IRteElementType & { attrs: InsertResponse } element: IRteElementType & { attrs: ImageVaultAsset | InsertResponse }
rte: IRteParam rte: IRteParam
} }
export function ImageElement({ children, element, rte }: ImageElementProps) { export function ImageElement({ children, element, rte }: ImageElementProps) {
const assetUrl = element.attrs.MediaConversions[0].Url const assetIsInsertResponse = isInsertResponse(element.attrs)
const isSelected = rte?.selection?.isSelected() const imageVaultAsset = getImageVaultAssetFromData(element.attrs)
const isFocused = rte?.selection?.isFocused() const isSelected = rte.selection.isSelected()
const isFocused = rte.selection.isFocused()
const path = rte.getPath(element)
const isHighlight = isFocused && isSelected 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(() => { const handleEdit = useCallback(() => {
cbModal({ cbModal({
// @ts-expect-error: Component is badly typed // @ts-expect-error: Component is badly typed
component: (compProps) => component: (compProps) => (
ImageEditModal({ <ImageEditModal
element, element={element}
rte, setData={handleMedia}
path: rte.getPath(element), {...compProps}
...compProps, />
}), ),
modalProps: { modalProps: {
size: "max", size: "max",
style: {
content: {
maxHeight: "90dvh",
maxWidth: "90dvw",
width: "auto",
},
overlay: {},
},
}, },
}) })
}, [element, rte]) }, [element, handleMedia])
const ToolTipButtons = () => { const ToolTipButtons = () => {
return ( return (
@@ -49,7 +73,7 @@ export function ImageElement({ children, element, rte }: ImageElementProps) {
<EmbedBtn <EmbedBtn
title="remove" title="remove"
content={"Remove"} content={"Remove"}
onClick={() => rte?.removeNode(element)} onClick={() => rte.removeNode(element)}
> >
<Icon icon="Trash" /> <Icon icon="Trash" />
</EmbedBtn> </EmbedBtn>
@@ -57,46 +81,17 @@ export function ImageElement({ children, element, rte }: ImageElementProps) {
) )
} }
const onResizeStop = () => { if (!imageVaultAsset) {
const { attrs: elementAttrs } = element return <>{children}</>
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>( // The existing data might still be in InsertResponse format if the user has not edited it yet.
rte._adv.editor, // We'll convert it to ImageVaultAsset when the user edits the RTE.
{ attrs: newAttrs }, if (assetIsInsertResponse) {
{ at: rte.getPath(element) } handleMedia(imageVaultAsset)
)
}
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 ( return (
<div
style={{
...alignmentStyles,
...element.attrs.style,
}}
>
<Tooltip <Tooltip
zIndex={909} zIndex={909}
className="p-0" className="p-0"
@@ -106,68 +101,32 @@ export function ImageElement({ children, element, rte }: ImageElementProps) {
offset={[0, -15]} offset={[0, -15]}
content={<ToolTipButtons />} content={<ToolTipButtons />}
> >
<span <span data-type="asset" contentEditable={false}>
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 <div
ref={imgRef}
contentEditable={false} contentEditable={false}
style={{ style={{
width: "100%", width: "280px",
height: "100%", height: "auto",
...(isHighlight ? { border: "1px solid #6c5ce7" } : {}), ...(isHighlight ? { border: "1px solid #6c5ce7" } : {}),
}} }}
> >
<img <img
src={assetUrl} src={imageVaultAsset.url}
onError={(event) => { onError={(event) => {
event.currentTarget.src = "https://placehold.co/600x400" event.currentTarget.src = "https://placehold.co/600x400"
}} }}
style={{ style={{
width: "100%", width: "100%",
height: "auto", height: "auto",
aspectRatio: element.attrs.MediaConversions[0].AspectRatio, aspectRatio: imageVaultAsset.dimensions.aspectRatio,
borderRadius: "8px", borderRadius: "8px",
}} }}
alt={element.attrs.altText} alt={imageVaultAsset.meta.alt}
title={element.attrs?.Name} title={`Id: ${imageVaultAsset.imageVaultId} - ${imageVaultAsset.fileName}`}
/> />
<div
style={{
position: "absolute",
bottom: 0,
right: 0,
background: "#fff",
color: "#000",
height: "25px",
padding: "3px",
borderRadius: "4px",
}}
>
<Icon icon="Embed" />
</div> </div>
</div>
</Resizable>
{children} {children}
</span> </span>
</Tooltip> </Tooltip>
</div>
) )
} }

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

View File

@@ -6,14 +6,14 @@
"scripts": { "scripts": {
"build": "vite build", "build": "vite build",
"dev": "IS_DEV=true vite build --watch", "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", "prebuild": "concurrently npm:lint npm:typecheck",
"typecheck": "tsc" "typecheck": "tsc"
}, },
"devDependencies": { "devDependencies": {
"@types/systemjs": "^6.13.5" "@types/systemjs": "^6.15.3"
}, },
"engines": { "engines": {
"node": ">=18.0.0" "node": ">=22.0.0"
} }
} }

View File

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

View File

@@ -1,12 +1,12 @@
import { resolve } from "path" import { resolve } from "path"
import { defineConfig } from "vite" 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" import tsconfigPaths from "vite-tsconfig-paths"
export default defineConfig({ export default defineConfig({
plugins: [tsconfigPaths()], plugins: [tsconfigPaths(), libInjectCss(), devtoolsJson()],
define: { define: { IS_DEV: process.env.IS_DEV === "true" ? true : false },
IS_DEV: process.env.IS_DEV === "true" ? true : false,
},
publicDir: false, publicDir: false,
build: { build: {
sourcemap: process.env.IS_DEV ? "inline" : "hidden", sourcemap: process.env.IS_DEV ? "inline" : "hidden",
@@ -15,14 +15,11 @@ export default defineConfig({
entry: resolve(__dirname, "main.tsx"), entry: resolve(__dirname, "main.tsx"),
name: "csiv", name: "csiv",
fileName: () => "csiv.js", fileName: () => "csiv.js",
// @ts-expect-error: 'system' not valid by typings, but works with Rollup
formats: ["system"], formats: ["system"],
}, },
rollupOptions: { rollupOptions: {
external: ["react", "react-dom", "@contentstack/venus-components"], external: ["react", "react-dom", "@contentstack/venus-components"],
output: { output: { dir: "../remix/public/build/rte" },
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, "allowJs": true,
"skipLibCheck": true, "skipLibCheck": true,
"forceConsistentCasingInFileNames": 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 { export declare class InsertMediaWindow {
constructor(config: Config, windowOptions: string) constructor(config: Config, windowOptions: string)
openImageVault: () => void openImageVault: () => void
@@ -50,15 +55,16 @@ export type MetaData = {
} }
export type ImageVaultAsset = { export type ImageVaultAsset = {
id: number imageVaultId: number
title: string fileName: string
url: string url: string
dimensions: { dimensions: {
width: number width: number
height: number height: number
aspectRatio: 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 AddedBy: string
Metadata?: MetaData[] | undefined Metadata?: MetaData[] | undefined
FocalPoint: FocalPoint
} }
/** /**

View File

@@ -1,13 +1,14 @@
import { langEnum } from "../types/lang" import { langEnum } from "../types/lang"
import type { GenericObjectType } from "@contentstack/app-sdk/dist/src/types/common.types" import type { GenericObjectType } from "@contentstack/app-sdk/dist/src/types/common.types"
import type { Lang } from "../types/lang"
import type { import type {
Config, Config,
FocalPoint,
ImageVaultAsset, ImageVaultAsset,
InsertResponse, InsertResponse,
PublishDetails, PublishDetails,
} from "../types/imagevault" } from "../types/imagevault"
import type { Lang } from "../types/lang"
const metaIds = { const metaIds = {
[langEnum.de]: { altText: 68, title: 77 }, [langEnum.de]: { altText: 68, title: 77 },
@@ -49,9 +50,15 @@ export function getPublishDetails(
} }
export function isInsertResponse( export function isInsertResponse(
res: InsertResponse | GenericObjectType res: InsertResponse | GenericObjectType | null | undefined
): res is InsertResponse { ): 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 = { export type ImageVaultDAMConfig = {
@@ -66,40 +73,67 @@ export function isImageVaultDAMConfig(
return !!(config.baseUrl && config.formatId && config.imageVaultUrl) return !!(config.baseUrl && config.formatId && config.imageVaultUrl)
} }
// Utility function to convert InsertResponse to ImageVaultAsset, used mainly for custom field images // Utility function to get ImageVaultAsset from either InsertResponse or ImageVaultAsset
// For RTE this function is not enough since rte:s also need attrs, like position and the size thats // Because we currently have both types saved in Contentstack, we need to account for both when retrieving the data of the asset.
// chosen in the editor export function getImageVaultAssetFromData(
export function insertResponseToImageVaultAsset( data: InsertResponse | ImageVaultAsset | GenericObjectType | null | undefined
response: InsertResponse ): ImageVaultAsset | null {
): ImageVaultAsset { if (isImageVaultAsset(data)) {
const alt = response.Metadata?.find((meta) => return data
meta.Name.includes("AltText_") }
)?.Value if (isInsertResponse(data)) {
return mapInsertResponseToImageVaultAsset(data, { x: 50, y: 50 })
}
return null
}
const caption = response.Metadata?.find((meta) => // Utility function to convert InsertResponse to ImageVaultAsset
meta.Name.includes("Title_") function mapInsertResponseToImageVaultAsset(
)?.Value 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 { return {
url: response.MediaConversions[0].Url, imageVaultId: response.Id,
id: response.Id, url: image.Url,
meta: { meta: {
alt, alt,
caption, caption,
}, },
title: response.Name, fileName: response.Name,
dimensions: { dimensions: {
width: response.MediaConversions[0].Width, width: image.Width,
height: response.MediaConversions[0].Height, height: image.Height,
aspectRatio: response.MediaConversions[0].FormatAspectRatio, aspectRatio: image.AspectRatio,
}, },
focalPoint: response.FocalPoint || focalPoint,
} }
} }
export type openImageVaultParams = { export type openImageVaultParams = {
config: ImageVaultDAMConfig config: ImageVaultDAMConfig
entryData: EntryDataPublishDetails entryData: EntryDataPublishDetails
onSuccess: (result: InsertResponse) => void onSuccess: (result: ImageVaultAsset) => void
onClose?: () => void onClose?: () => void
} }
@@ -123,7 +157,11 @@ export function openImageVault({
publishDetails, publishDetails,
insertMultiple: false, insertMultiple: false,
success: (result) => { success: (result) => {
onSuccess(result.response) const imageVaultAsset = mapInsertResponseToImageVaultAsset(
result.response,
{ x: 50, y: 50 }
)
onSuccess(imageVaultAsset)
}, },
close: () => { close: () => {
if (typeof onClose === "function") { if (typeof onClose === "function") {