Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix medias popup + improved assets to markdown serialization #42

Open
wants to merge 7 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
209 changes: 209 additions & 0 deletions admin/src/components/CustomField.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,209 @@
import { FC as FunctionComponent, useState, useEffect, useMemo } from "react";
import { Flex, Field } from "@strapi/design-system";
import type { Schema } from "@strapi/types";
import { commands, ICommand } from "@uiw/react-md-editor";
import { useIntl } from "react-intl";
import { styled } from "styled-components";
import "@uiw/react-markdown-preview/markdown.css";
import { PLUGIN_ID } from '../utils/pluginId';
import MediaLib from "./MediaLib";
import { useField } from "@strapi/strapi/admin";
import assetsToMarkdown from "../utils/assetsToMarkdown";
import CustomMDEditor from "./CustomMDEditor";

const Wrapper = styled.div`
flex-basis: 100%;
> div:nth-child(2) {
display: none;
}
.w-md-editor-bar {
display: none;
}
.w-md-editor {
border: 1px solid #dcdce4;
border-radius: 4px;
box-shadow: none;
&:focus-within {
border: 1px solid #4945ff;
box-shadow: #4945ff 0px 0px 0px 2px;
}
min-height: 400px;
display: flex;
flex-direction: column;
img {
max-width: 100%;
}
ul,ol{
list-style:inherit;
}
.w-md-editor-preview {
display: block;
strong {
font-weight: bold;
}
em {
font-style: italic;
}
}
}
.w-md-editor-content {
flex: 1 1 auto;
}
.w-md-editor-fullscreen {
z-index: 11;
}
.w-md-editor-text {
margin: 0;
}
.w-md-editor-preview ol {
list-style: auto;
}
`;

interface FieldProps {
name: string;
onChange: (e: { target: { name: string; value: string } }) => void;
value: string;
intlLabel: {
id: string;
defaultMessage: string;
};
disabled?: boolean;
error?: string;
description?: {
id: string;
defaultMessage: string;
};
required?: boolean;
attribute?: any; // TO FIX
labelAction?: React.ReactNode; //TO FIX TO CHECK
}

interface CursorPosition {
start: number;
end: number;
}

const CustomField: FunctionComponent<FieldProps> = ({
attribute,
name,
disabled,
labelAction,
required,
description,
error,
intlLabel,
}) => {
// const { formatMessage } = useIntl();
const field: any = useField(name);

const formatMessage = (message: { id: string; defaultMessage: string }) =>
message?.defaultMessage ?? "";
const [mediaLibVisible, setMediaLibVisible] = useState(false);
const [cursorPosition, setCursorPosition] = useState<CursorPosition | null>(null);

const handleToggleMediaLib = () => setMediaLibVisible((prev) => !prev);

const updateFieldValue = (value:any) => {
field.onChange({ target: { name, value: value } });
}

const handleChangeAssets = (assets: Schema.Attribute.MediaValue<true>) => {

let output;
const assetsString = assetsToMarkdown(assets);

if (cursorPosition) {
output = field.value.slice(0, cursorPosition.start) + assetsString + field.value.slice(cursorPosition.end);
}else{
output = field.value + assetsString;
}

updateFieldValue(output);
handleToggleMediaLib();
};

const [config, setConfig] = useState<{ toolbarCommands?: string[] }>({});

const toolbarCommands = useMemo(() => {
const mediaLibraryButton: ICommand = {
name: "media",
keyCommand: "media",
buttonProps: { "aria-label": "Insert media" },
icon: (
<svg width="12" height="12" viewBox="0 0 20 20">
<path
fill="currentColor"
d="M15 9c1.1 0 2-.9 2-2s-.9-2-2-2-2 .9-2 2 .9 2 2 2zm4-7H1c-.55 0-1 .45-1 1v14c0 .55.45 1 1 1h18c.55 0 1-.45 1-1V3c0-.55-.45-1-1-1zm-1 13l-6-5-2 2-4-5-4 8V4h16v11z"
></path>
</svg>
),
execute: (state, _api) => {
setCursorPosition(state.selection);
handleToggleMediaLib();
},
};
if (!config?.toolbarCommands) {
return [...commands.getCommands(),
commands.divider,
mediaLibraryButton
] as ICommand[];
}
const customCommands = config?.toolbarCommands
?.map((config) => {
if (config === "mediaLibraryButton") return mediaLibraryButton;
if (
config in commands &&
commands[config as unknown as keyof typeof commands]
) {
return commands[
config as unknown as keyof typeof commands
] as ICommand;
}
})
.filter((command): command is ICommand => command !== undefined);

return customCommands;
}, [JSON.stringify(config)]);

useEffect(() => {
fetch(`/${PLUGIN_ID}`)
.then((response) => response.json())
.then((data) => {
setConfig(data);
});
}, []);

return (
<Field.Root
name={name}
id={name}
error={error}
hint={description && formatMessage(description)}
>
<Flex spacing={1} alignItems="normal" style={{ flexDirection: "column" }}>
<Field.Label action={labelAction} required={required}>
{intlLabel ? formatMessage(intlLabel) : name}
</Field.Label>
<Wrapper>
<CustomMDEditor
hidden={disabled}
value={field.value}
onChange={updateFieldValue}
commands={toolbarCommands}
/>
</Wrapper>
<Field.Hint />
<Field.Error />
</Flex>
<MediaLib
/*allowedTypes={['images']}*/
isOpen={mediaLibVisible}
onChange={handleChangeAssets}
onToggle={handleToggleMediaLib}
/>
</Field.Root>
);
};

export { CustomField };
26 changes: 26 additions & 0 deletions admin/src/components/CustomMDEditor.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import React, { useState,useEffect } from "react";
import MDEditor from "@uiw/react-md-editor";

const CustomMDEditor = (props:any) => {

const [value, setValue] = useState<string | undefined>(props.value);

useEffect(() => {
setValue(props.value)
}, [props.value]);

useEffect(() => {
props.onChange(value);
}, [value]);

return (
<MDEditor
value={value}
onChange={setValue}
hidden={props.hidden}
commands={props.commands}
/>
);
};

export default CustomMDEditor;
4 changes: 2 additions & 2 deletions admin/src/components/Initializer.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
*/

import { useEffect, useRef } from 'react';
import pluginId from '../pluginId';
import {PLUGIN_ID} from '../utils/pluginId';

type InitializerProps = {
setPlugin: (id: string) => void;
Expand All @@ -15,7 +15,7 @@ const Initializer = ({ setPlugin }: InitializerProps) => {
const ref = useRef(setPlugin);

useEffect(() => {
ref.current(pluginId);
ref.current(PLUGIN_ID);
}, []);

return null;
Expand Down
63 changes: 26 additions & 37 deletions admin/src/components/MediaLib.tsx
Original file line number Diff line number Diff line change
@@ -1,60 +1,49 @@
import { FC as FunctionComponent } from "react";

import { useStrapiApp } from "@strapi/admin/strapi-admin";
import type { Schema } from "@strapi/types";

const prefixFileUrlWithBackendUrl = (fileURL: string) => {
return !!fileURL &&
fileURL.startsWith("/") &&
"strapi" in window &&
window.strapi instanceof Object &&
"backendURL" in window.strapi &&
window.strapi.backendURL
? `${window.strapi.backendURL}${fileURL}`
: fileURL;
};

interface MediaLibComponentProps {
isOpen: boolean;
onChange: (files: Schema.Attribute.MediaValue<true>) => void;
onToggle: () => void;
}
import React from 'react';
import prefixFileUrlWithBackendUrl from '../utils/prefixFileUrlWithBackendUrl';
import { useStrapiApp } from '@strapi/strapi/admin';
import type { Schema } from '@strapi/types';

const MediaLib: FunctionComponent<MediaLibComponentProps> = ({
isOpen,
const MediaLibComponent: React.FC<any> = ({
isOpen = false,
onChange,
onToggle,
allowedTypes
}) => {
const components = useStrapiApp("ImageDialog", (state) => state.components);

const components = useStrapiApp('ImageDialog', (state) => state.components);
if (!components || !isOpen) return null;

const MediaLibraryDialog = components["media-library"] as FunctionComponent<{
const MediaLibraryDialog = components['media-library'] as React.ComponentType<{
allowedTypes?: Schema.Attribute.MediaKind[]; // 'images' | 'videos' | 'files' | 'audios'
onClose: () => void;
onSelectAssets: (_images: Schema.Attribute.MediaValue<true>) => void;
}>;

const handleSelectAssets = (files: Schema.Attribute.MediaValue<true>) => {
const formattedFiles = files.map((f) => ({

const handleSelectAssets = (assets: Schema.Attribute.MediaValue<true>) => {
const formattedFiles = assets.map((f) => ({
alt: f.alternativeText || f.name,
url: prefixFileUrlWithBackendUrl(f.url),
mime: f.mime,
//width: f.width,
//height: f.height,
//size: f.size,
//formats:f.formats,
}));

onChange(formattedFiles);
};

if (!isOpen) {
return null;
}

return (
<MediaLibraryDialog
Copy link
Owner

@kwinyyyc kwinyyyc Oct 19, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There is a typing issue on MediaLibraryDialog causing strapi build failed

'MediaLibraryDialog' cannot be used as a JSX component.

onClose={onToggle}
onSelectAssets={handleSelectAssets}
allowedTypes={allowedTypes}
onClose={onToggle}
onSelectAssets={handleSelectAssets}
/>
);
};

MediaLib.defaultProps = {
isOpen: false,
onChange: (_files: Schema.Attribute.MediaValue<true>) => {},
onToggle: () => {},
};

export { MediaLib };
export default MediaLibComponent;
Loading