chore: add and run prettier

This commit is contained in:
Michael Zetterberg
2024-03-26 13:02:26 +01:00
parent e9349992f8
commit 083c57d0ca
27 changed files with 430 additions and 379 deletions

7
rte/.prettierignore Normal file
View File

@@ -0,0 +1,7 @@
# Files
.eslintrc.cjs
.prettierignore
package.json
package-lock.json
prettier.config.cjs
tsconfig.json

View File

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

View File

@@ -1,4 +1,4 @@
import React, { useState, useEffect, ChangeEvent } from 'react';
import React, { useState, useEffect, ChangeEvent } from "react"
import {
ModalFooter,
ModalBody,
@@ -9,14 +9,14 @@ import {
FieldLabel,
TextInput,
Select,
} from '@contentstack/venus-components';
import { Path } from 'slate';
} from "@contentstack/venus-components"
import { Path } from "slate"
import type {
IRteParam,
IRteElementType,
} from '@contentstack/app-sdk/dist/src/RTE/types';
import type { InsertResponse } from "~/types/imagevault";
} from "@contentstack/app-sdk/dist/src/RTE/types"
import type { InsertResponse } from "~/types/imagevault"
enum DropdownValues {
center = "center",
@@ -26,10 +26,10 @@ enum DropdownValues {
}
type DropDownItem = {
label: string;
value: DropdownValues;
type: string;
};
label: string
value: DropdownValues
type: string
}
const dropdownList: DropDownItem[] = [
{
@@ -52,16 +52,16 @@ const dropdownList: DropDownItem[] = [
value: DropdownValues.right,
type: "select",
},
];
]
type ImageEditModalProps = {
element: IRteElementType & {
attrs: InsertResponse;
};
rte: IRteParam;
closeModal: () => void;
path: Path;
};
attrs: InsertResponse
}
rte: IRteParam
closeModal: () => void
path: Path
}
export default function ImageEditModal({
element,
@@ -73,29 +73,29 @@ export default function ImageEditModal({
label: "None",
value: DropdownValues.none,
type: "select",
});
const [altText, setAltText] = useState("");
const [caption, setCaption] = useState("");
})
const [altText, setAltText] = useState("")
const [caption, setCaption] = useState("")
const assetUrl = element.attrs.MediaConversions[0].Url;
const assetUrl = element.attrs.MediaConversions[0].Url
useEffect(() => {
if (element.attrs.Metadata && element.attrs.Metadata.length) {
const altText = element.attrs.Metadata.find((meta) =>
meta.Name.includes("AltText_")
)?.Value;
)?.Value
const caption = element.attrs.Metadata.find((meta) =>
meta.Name.includes("Title_")
)?.Value;
)?.Value
setAltText(altText ?? "");
setCaption(caption ?? "");
setAltText(altText ?? "")
setCaption(caption ?? "")
}
}, [element.attrs.Metadata]);
}, [element.attrs.Metadata])
function handleSave() {
let newStyle;
let newStyle
switch (alignment.value) {
case DropdownValues.center:
@@ -106,25 +106,25 @@ export default function ImageEditModal({
maxWidth: element.attrs.width
? `${element.attrs.width}px`
: undefined,
};
break;
}
break
case DropdownValues.none:
default:
newStyle = {};
break;
newStyle = {}
break
}
const metaData = element.attrs.Metadata ?? [];
const metaData = element.attrs.Metadata ?? []
const newMetadata = metaData.map((meta) => {
if (meta.Name.includes("AltText_")) {
return { ...meta, Value: altText };
return { ...meta, Value: altText }
}
if (meta.Name.includes("Title_")) {
return { ...meta, Value: caption };
return { ...meta, Value: caption }
}
return meta;
});
return meta
})
rte._adv.Transforms?.setNodes<IRteElementType>(
rte._adv.editor,
@@ -137,9 +137,9 @@ export default function ImageEditModal({
},
},
{ at: path }
);
)
closeModal();
closeModal()
}
return (
@@ -168,7 +168,7 @@ export default function ImageEditModal({
selectLabel="Alignment"
value={alignment}
onChange={(e: DropDownItem) => {
setAlignment(e);
setAlignment(e)
}}
options={dropdownList}
/>
@@ -209,5 +209,5 @@ export default function ImageEditModal({
</ButtonGroup>
</ModalFooter>
</>
);
)
}

View File

@@ -1,27 +1,27 @@
import React, { useRef, useCallback, PropsWithChildren } from 'react';
import { Tooltip, Icon, cbModal } from '@contentstack/venus-components';
import React, { useRef, useCallback, PropsWithChildren } from "react"
import { Tooltip, Icon, cbModal } from "@contentstack/venus-components"
import { Resizable } from 're-resizable';
import EmbedBtn from './EmbedBtn';
import ImageEditModal from './ImageEditModal';
import { Resizable } from "re-resizable"
import EmbedBtn from "./EmbedBtn"
import ImageEditModal from "./ImageEditModal"
import type {
IRteParam,
IRteElementType,
} from '@contentstack/app-sdk/dist/src/RTE/types';
import type { InsertResponse } from '~/types/imagevault';
} from "@contentstack/app-sdk/dist/src/RTE/types"
import type { InsertResponse } from "~/types/imagevault"
type ImageElementProps = PropsWithChildren & {
element: IRteElementType & { attrs: InsertResponse };
rte: IRteParam;
};
element: IRteElementType & { attrs: InsertResponse }
rte: IRteParam
}
export function ImageElement({ children, element, rte }: ImageElementProps) {
const assetUrl = element.attrs.MediaConversions[0].Url;
const isSelected = rte?.selection?.isSelected();
const isFocused = rte?.selection?.isFocused();
const isHighlight = isFocused && isSelected;
const assetUrl = element.attrs.MediaConversions[0].Url
const isSelected = rte?.selection?.isSelected()
const isFocused = rte?.selection?.isFocused()
const isHighlight = isFocused && isSelected
const imgRef = useRef<HTMLDivElement | null>(null);
const imgRef = useRef<HTMLDivElement | null>(null)
const handleEdit = useCallback(() => {
cbModal({
@@ -36,8 +36,8 @@ export function ImageElement({ children, element, rte }: ImageElementProps) {
modalProps: {
size: "max",
},
});
}, [element, rte]);
})
}, [element, rte])
const ToolTipButtons = () => {
return (
@@ -54,12 +54,12 @@ export function ImageElement({ children, element, rte }: ImageElementProps) {
<Icon icon="Trash" />
</EmbedBtn>
</div>
);
};
)
}
const onResizeStop = () => {
const { attrs: elementAttrs } = element;
const { offsetWidth: width, offsetHeight: height } = imgRef?.current ?? {};
const { attrs: elementAttrs } = element
const { offsetWidth: width, offsetHeight: height } = imgRef?.current ?? {}
const newAttrs: { [key: string]: unknown } = {
...elementAttrs,
@@ -70,24 +70,24 @@ export function ImageElement({ children, element, rte }: ImageElementProps) {
...(width && height
? { width: `${width.toString()}px`, height: `${height.toString()}px` }
: {}),
};
}
rte?._adv?.Transforms?.setNodes<IRteElementType>(
rte._adv.editor,
{ attrs: newAttrs },
{ at: rte.getPath(element) }
);
};
)
}
let alignmentStyles = {};
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];
alignmentStyles = marginAlignment[element.attrs.position]
}
return (
@@ -137,7 +137,7 @@ export function ImageElement({ children, element, rte }: ImageElementProps) {
<img
src={assetUrl}
onError={(event) => {
event.currentTarget.src = "https://placehold.co/600x400";
event.currentTarget.src = "https://placehold.co/600x400"
}}
style={{
width: "100%",
@@ -169,5 +169,5 @@ export function ImageElement({ children, element, rte }: ImageElementProps) {
</span>
</Tooltip>
</div>
);
)
}

2
rte/env.d.ts vendored
View File

@@ -1 +1 @@
declare const IS_DEV: boolean;
declare const IS_DEV: boolean

View File

@@ -1,70 +1,70 @@
import React from 'react';
import ContentstackSDK from '@contentstack/app-sdk';
import React from "react"
import ContentstackSDK from "@contentstack/app-sdk"
import { ImageElement } from '~/components/ImageElement';
import { ImageElement } from "~/components/ImageElement"
import { Icon } from '@contentstack/venus-components';
import { openImageVault } from '~/utils/imagevault';
import { Icon } from "@contentstack/venus-components"
import { openImageVault } from "~/utils/imagevault"
import type { Lang } from '~/types/lang';
import type { Lang } from "~/types/lang"
import type {
ContentstackEmbeddedData,
ContentstackPluginDefinition,
ExtractedContentstackEmbeddedData,
} from '~/types/contentstack';
} from "~/types/contentstack"
function findThisPlugin(ext: ContentstackPluginDefinition) {
return ext.type === 'rte_plugin' && ext.title === 'ImageVault';
return ext.type === "rte_plugin" && ext.title === "ImageVault"
}
async function loadScript(url: string) {
return new Promise((resolve, reject) => {
if (!document) {
throw new Error('Run in browser only');
throw new Error("Run in browser only")
}
const head = document.head || document.getElementsByTagName('head')[0];
const head = document.head || document.getElementsByTagName("head")[0]
const script = document.createElement('script');
script.type = 'text/javascript';
script.async = true;
script.src = url;
const script = document.createElement("script")
script.type = "text/javascript"
script.async = true
script.src = url
script.onload = function () {
this.onerror = this.onload = null;
resolve(window.ImageVault);
};
this.onerror = this.onload = null
resolve(window.ImageVault)
}
script.onerror = function () {
this.onerror = this.onload = null;
reject(`Failed to load ${this.src}`);
};
this.onerror = this.onload = null
reject(`Failed to load ${this.src}`)
}
head.appendChild(script);
});
head.appendChild(script)
})
}
function extractContentstackEmbeddedData(
jwtLike: string
): ExtractedContentstackEmbeddedData | null {
try {
const base64str = jwtLike.replace(/-/g, "+").replace(/_/g, "/");
const base64str = jwtLike.replace(/-/g, "+").replace(/_/g, "/")
const jsonStr = decodeURIComponent(
window
.atob(base64str)
.split("")
.map(function (c) {
return "%" + ("00" + c.charCodeAt(0).toString(16)).slice(-2);
return "%" + ("00" + c.charCodeAt(0).toString(16)).slice(-2)
})
.join("")
);
)
const json = JSON.parse(jsonStr);
json.exports = JSON.parse(json.exports);
json.props.value = JSON.parse(json.props.value);
const json = JSON.parse(jsonStr)
json.exports = JSON.parse(json.exports)
json.props.value = JSON.parse(json.props.value)
if (IS_DEV) {
console.log(`Contentstack Embedded Data`, json);
console.log(`Contentstack Embedded Data`, json)
}
const {
@@ -77,12 +77,12 @@ function extractContentstackEmbeddedData(
stack: { api_key },
branch,
},
}: ContentstackEmbeddedData = json.props.value;
}: ContentstackEmbeddedData = json.props.value
const titleField = schema.find((f) => f.uid === "title");
const titleField = schema.find((f) => f.uid === "title")
// We force this value with ! because we know it exists.
// Otherwise this code would not run.
const plugin = extensions.find(findThisPlugin)!;
const plugin = extensions.find(findThisPlugin)!
return {
stack: {
@@ -101,43 +101,43 @@ function extractContentstackEmbeddedData(
uid: entryMetadata.entryUid,
},
plugin,
};
}
} catch (e) {
console.log(`Unable to parse JWT like: ${jwtLike}`);
console.log(`Unable to parse JWT like: ${jwtLike}`)
}
return null;
return null
}
let ivloaded = false;
let ivloaded = false
function loadIV(plugin: ContentstackPluginDefinition) {
if (plugin.src) {
const url = new URL(plugin.src);
url.pathname = "/scripts/imagevault-insert-media/insertmediawindow.min.js";
const url = new URL(plugin.src)
url.pathname = "/scripts/imagevault-insert-media/insertmediawindow.min.js"
if (IS_DEV) {
console.log(`Loading script: ${url.toString()}`);
console.log(`Loading script: ${url.toString()}`)
}
loadScript(url.toString());
ivloaded = true;
loadScript(url.toString())
ivloaded = true
}
}
async function init() {
try {
const sdk = await ContentstackSDK.init();
const sdk = await ContentstackSDK.init()
const extensionObj = sdk?.location;
const RTE = extensionObj?.RTEPlugin;
const extensionObj = sdk?.location
const RTE = extensionObj?.RTEPlugin
let embeddedData: ExtractedContentstackEmbeddedData | null = null;
const jwtLike = window.name.split("__").find((str) => str.startsWith("ey"));
let embeddedData: ExtractedContentstackEmbeddedData | null = null
const jwtLike = window.name.split("__").find((str) => str.startsWith("ey"))
if (jwtLike) {
embeddedData = extractContentstackEmbeddedData(jwtLike);
embeddedData = extractContentstackEmbeddedData(jwtLike)
if (embeddedData?.plugin) {
loadIV(embeddedData.plugin);
loadIV(embeddedData.plugin)
}
}
if (!RTE) return;
if (!RTE) return
const ImageVault = RTE("ImageVault", (rte) => {
if (rte) {
@@ -145,11 +145,11 @@ async function init() {
// Loading failed via embedded data above, try again with data inside RTE
// @ts-expect-error: incorrect typings, requestProps is available at runtime
const extensions = rte._adv.editor.requestProps
.extensions as ContentstackPluginDefinition[];
const plugin = extensions.find(findThisPlugin);
.extensions as ContentstackPluginDefinition[]
const plugin = extensions.find(findThisPlugin)
if (plugin) {
loadIV(plugin);
loadIV(plugin)
}
}
}
@@ -163,35 +163,35 @@ async function init() {
<ImageElement element={props.element} rte={rte}>
{props.children}
</ImageElement>
);
)
} else {
console.error("No instance of RTE found");
console.error("No instance of RTE found")
return (
<p>An unexpected error occured, see console for more info.</p>
);
)
}
},
display: ["toolbar"],
elementType: ["void"],
};
});
}
})
ImageVault.on("exec", async (rte) => {
if (rte) {
const savedSelection = rte?.selection?.get() ?? undefined;
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.
// You edit this in the content types settings RTE plugin section.
// @ts-expect-error: Added at runtime
const pluginConfig = await rte.getFieldConfig();
const pluginConfig = await rte.getFieldConfig()
const config = {
...appConfig,
...pluginConfig,
};
}
openImageVault({
config,
@@ -218,17 +218,17 @@ async function init() {
children: [{ text: "" }],
},
{ at: savedSelection }
);
)
},
});
})
}
});
})
return {
ImageVault,
};
}
} catch (e) {
console.error({ e });
console.error({ e })
}
}
export default init();
export default init()

8
rte/prettier.config.cjs Normal file
View File

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

View File

@@ -1,28 +1,28 @@
import { resolve } from 'path';
import { defineConfig } from 'vite';
import tsconfigPaths from 'vite-tsconfig-paths';
import { resolve } from "path"
import { defineConfig } from "vite"
import tsconfigPaths from "vite-tsconfig-paths"
export default defineConfig({
plugins: [tsconfigPaths()],
define: {
IS_DEV: process.env.IS_DEV === 'true' ? true : false,
IS_DEV: process.env.IS_DEV === "true" ? true : false,
},
publicDir: false,
build: {
sourcemap: process.env.IS_DEV ? 'inline' : 'hidden',
sourcemap: process.env.IS_DEV ? "inline" : "hidden",
emptyOutDir: true,
lib: {
entry: resolve(__dirname, 'main.tsx'),
name: 'csiv',
fileName: () => (process.env.IS_DEV ? 'csiv.js' : 'csiv-[hash].js'),
entry: resolve(__dirname, "main.tsx"),
name: "csiv",
fileName: () => (process.env.IS_DEV ? "csiv.js" : "csiv-[hash].js"),
// @ts-expect-error: 'system' not valid by typings, but works with Rollup
formats: ['system'],
formats: ["system"],
},
rollupOptions: {
external: ['react', 'react-dom', '@contentstack/venus-components'],
external: ["react", "react-dom", "@contentstack/venus-components"],
output: {
dir: '../remix/public/build/rte',
dir: "../remix/public/build/rte",
},
},
},
});
})