feat: ✨ use uwil image cropper as wysiwyg plugin
This commit is contained in:
parent
80af15c401
commit
43b999d5bd
8 changed files with 391 additions and 39 deletions
|
|
@ -214,6 +214,17 @@ return [
|
|||
"use_internal" => "Utilisez un lien interne pour ce domaine",
|
||||
],
|
||||
],
|
||||
"image" => [
|
||||
"tooltip" => "Image",
|
||||
"title" => "Insérer une image",
|
||||
"subtitle" => "Configurer ou modifier une image.",
|
||||
"add" => "Ajouter ce lien",
|
||||
"cancel" => "Annuler l’ajout de ce lien",
|
||||
"validation" => [
|
||||
"url" => "L’URL doit être un domaine valide avec protocole (https:// ou https://) et TLD (.com, .fr etc...)",
|
||||
"use_internal" => "Utilisez un lien interne pour ce domaine",
|
||||
],
|
||||
],
|
||||
],
|
||||
"json_editor" => [
|
||||
"item_single" => "1 élément",
|
||||
|
|
|
|||
|
|
@ -249,6 +249,7 @@ return [
|
|||
"title" => "titre SEO",
|
||||
"description" => "description SEO",
|
||||
],
|
||||
"image" => "image",
|
||||
"image_alt" => "texte alternatif de l'image",
|
||||
"image_title" => "titre de l'image",
|
||||
"content" => "contenu",
|
||||
|
|
|
|||
|
|
@ -33,6 +33,7 @@ type CompleteInputFileProps = FileValidation & {
|
|||
required?: boolean;
|
||||
fileName?: string;
|
||||
hasRefreshBtn?: boolean;
|
||||
parentErrors?: Record<string, string> | null,
|
||||
setData: (name: string, value: File | string | null) => void;
|
||||
reset: (name?: string) => void;
|
||||
};
|
||||
|
|
@ -82,7 +83,7 @@ export default function CompleteInputFile(props: CompleteInputFileProps) {
|
|||
}
|
||||
);
|
||||
|
||||
|
||||
const localErrors = props.parentErrors ?? errors;
|
||||
|
||||
const [isDialogOpen, setDialogOpen] = useState(false);
|
||||
const [accept, setAccept] = useState<Record<string, Array<string>>>({
|
||||
|
|
@ -300,7 +301,7 @@ export default function CompleteInputFile(props: CompleteInputFileProps) {
|
|||
type="button"
|
||||
className={cn(
|
||||
"flex border border-dashed overflow-hidden whitespace-normal [&_svg]:!pointer-events-auto [&_svg]:!size-auto [&_svg]:!shrink text-muted-foreground w-full h-36",
|
||||
{ "border-destructive": errors[name] }
|
||||
{ "border-destructive": localErrors[name] }
|
||||
)}
|
||||
// eslint-disable-next-line react/jsx-props-no-spreading
|
||||
{...getRootProps()}
|
||||
|
|
@ -349,7 +350,7 @@ export default function CompleteInputFile(props: CompleteInputFileProps) {
|
|||
/>
|
||||
)}
|
||||
</div>
|
||||
<InputError message={errors[name]} />
|
||||
<InputError message={localErrors[name]} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,23 @@
|
|||
// * Packages
|
||||
import type { ImageOptions as TiptapImageOptions } from '@tiptap/extension-image';
|
||||
import { Image as TiptapImage } from 'reactjs-tiptap-editor/image';
|
||||
import { Editor } from 'reactjs-tiptap-editor';
|
||||
// * Other
|
||||
import ImageButton from '@/back/Components/Inputs/Wysiwyg/Plugins/Image/ImageButton';
|
||||
import useTrans from '@/hooks/use-translations';
|
||||
|
||||
export const Image = TiptapImage.extend<TiptapImageOptions>({
|
||||
addOptions() {
|
||||
return {
|
||||
...this.parent?.(),
|
||||
openOnClick: false,
|
||||
button: ({ editor }: { editor: Editor }) => ({
|
||||
component: ImageButton,
|
||||
componentProps: {
|
||||
editor,
|
||||
tooltip: useTrans('back.wysiwyg_plugins.image.tooltip'),
|
||||
},
|
||||
}),
|
||||
};
|
||||
},
|
||||
});
|
||||
|
|
@ -0,0 +1,318 @@
|
|||
// * Packages
|
||||
import { useState } from "react";
|
||||
import axios from "axios";
|
||||
import { route } from "ziggy-js";
|
||||
import { ImageUpIcon } from "lucide-react";
|
||||
import { Editor } from "reactjs-tiptap-editor";
|
||||
import { z } from "zod";
|
||||
// * Components shadcn
|
||||
import {
|
||||
Dialog,
|
||||
DialogDescription,
|
||||
DialogContent,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
DialogTrigger,
|
||||
} from "@/components/ui/dialog";
|
||||
// * Other
|
||||
import BtnOptionnalLinkWithTooltip from "@/back/Components/BtnOptionnalLinkWithTooltip";
|
||||
import CompleteInputFile from "@/back/Components/Inputs/CompleteInputFile";
|
||||
import SimpleString from "@/back/Components/Inputs/SimpleString";
|
||||
import useTrans from "@/hooks/use-translations";
|
||||
import str from "@/hooks/use-string";
|
||||
|
||||
type ImageProps = {
|
||||
/** Wysiwyg editor instance. */
|
||||
editor: Editor;
|
||||
/** Wysiwyg menu button tooltip. */
|
||||
tooltip: string;
|
||||
};
|
||||
|
||||
export default function ImageButton({ editor, tooltip }: ImageProps) {
|
||||
// Get all editor options define with customOptions in the parent SimpleWysiwyg.
|
||||
const editorOptions = editor.options.editorProps?.attributes as { [name: string]: string };
|
||||
|
||||
// State of the plugin modal.
|
||||
const [open, setOpen] = useState(false);
|
||||
// Value of the input file image.
|
||||
const [inputFile, setFile] = useState<string | File | null>(null);
|
||||
// Value of the input alt image.
|
||||
const [inputAlt, setInputAlt] = useState<string>("");
|
||||
|
||||
// State of the loader.
|
||||
const [loading, setLoading] = useState(false);
|
||||
// Value of errors.
|
||||
const [errors, setErrors] = useState<Record<string, string>>({});
|
||||
|
||||
// Duration of modal closing animation.
|
||||
const animationTime = 200;
|
||||
|
||||
// Zod image schema.
|
||||
const inputsSchema = z.object({
|
||||
inputFile: z
|
||||
.instanceof(File, {
|
||||
message: useTrans("validation.file", {
|
||||
params: {
|
||||
attribute: useTrans("validation.custom.image"),
|
||||
},
|
||||
}),
|
||||
})
|
||||
.refine(
|
||||
(file) =>
|
||||
[
|
||||
"image/jpeg",
|
||||
"image/jpg",
|
||||
"image/png",
|
||||
"image/webp",
|
||||
].includes(file.type),
|
||||
{
|
||||
message: useTrans("validation.regex", {
|
||||
params: {
|
||||
attribute: useTrans("validation.custom.image"),
|
||||
},
|
||||
}),
|
||||
},
|
||||
)
|
||||
.refine((file) => file.size <= 5 * 1024 * 1024, {
|
||||
message: useTrans("validation.size.file", {
|
||||
params: {
|
||||
attribute: useTrans("validation.custom.image"),
|
||||
size: "5 000",
|
||||
},
|
||||
}),
|
||||
}),
|
||||
inputAlt: z
|
||||
.string({
|
||||
message: useTrans("validation.string", {
|
||||
params: {
|
||||
attribute: useTrans("validation.custom.image_alt"),
|
||||
},
|
||||
}),
|
||||
})
|
||||
.min(3, {
|
||||
message: useTrans("validation.min.string", {
|
||||
params: {
|
||||
attribute: useTrans("validation.custom.image_alt"),
|
||||
min: "3",
|
||||
},
|
||||
}),
|
||||
})
|
||||
.max(255, {
|
||||
message: useTrans("validation.max.string", {
|
||||
params: {
|
||||
attribute: useTrans("validation.custom.image_alt"),
|
||||
max: "255",
|
||||
},
|
||||
}),
|
||||
}),
|
||||
});
|
||||
|
||||
/**
|
||||
* Upload image in storage.
|
||||
*
|
||||
* @param file
|
||||
* @param alt
|
||||
* @return Promise<void>
|
||||
*/
|
||||
const uploadImage = async (file: File, alt: string): Promise<void> => {
|
||||
// Get the csrf token value.
|
||||
const csrfToken =
|
||||
document
|
||||
.querySelector('meta[name="csrf-token"]')
|
||||
?.getAttribute("content") || "";
|
||||
|
||||
// Prepare the form data.
|
||||
const data = new FormData();
|
||||
data.append("upload", file);
|
||||
data.append("folder", editorOptions.model);
|
||||
|
||||
const uploadRoute = route("back.wysiwyg.upload");
|
||||
|
||||
try {
|
||||
const response = await axios.post(uploadRoute, data, {
|
||||
headers: {
|
||||
"Content-Type": "multipart/form-data",
|
||||
Accept: "application/json",
|
||||
"X-Requested-With": "XMLHttpRequest",
|
||||
"X-Inertia": "false",
|
||||
"X-CSRF-TOKEN": csrfToken,
|
||||
},
|
||||
});
|
||||
editor.commands.setImage({
|
||||
src: response.data.url,
|
||||
alt: alt,
|
||||
});
|
||||
} catch (error: Error | unknown) {
|
||||
throw new Error(`Erreur upload: ${(error as Error).message}`);
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Add new image.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
const handleAddImage = (): void => {
|
||||
setLoading(true);
|
||||
|
||||
try {
|
||||
const parsed = inputsSchema.parse({ inputFile, inputAlt });
|
||||
uploadImage(parsed.inputFile, parsed.inputAlt);
|
||||
setOpen(false);
|
||||
setTimeout(() => resetComponent(), animationTime);
|
||||
} catch (err) {
|
||||
// Get zod error validations.
|
||||
if (err instanceof z.ZodError) {
|
||||
const fieldErrors: Record<string, string> = {};
|
||||
const keyMap: Record<string, string> = {
|
||||
inputFile: "image",
|
||||
inputAlt: "alt",
|
||||
};
|
||||
|
||||
err.issues.forEach((e) => {
|
||||
const mappedKey = keyMap[e.path[0] as string];
|
||||
if (mappedKey) fieldErrors[mappedKey] = e.message;
|
||||
});
|
||||
|
||||
setErrors(fieldErrors);
|
||||
}
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleSetAlt = (name: string, value: string) => {
|
||||
setErrors((prev) => ({ ...prev, [name]: "" }));
|
||||
setInputAlt(value);
|
||||
};
|
||||
|
||||
/**
|
||||
* Reset all states and values in the component.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
const resetComponent = () => {
|
||||
setFile(null);
|
||||
setInputAlt("");
|
||||
setErrors({});
|
||||
setLoading(false);
|
||||
};
|
||||
|
||||
/**
|
||||
* Update url value from string input.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
const handleSetImage = (
|
||||
name: string,
|
||||
value: string | File | null,
|
||||
): void => {
|
||||
setErrors((prev) => ({ ...prev, [name]: "" }));
|
||||
setFile(value);
|
||||
};
|
||||
|
||||
/**
|
||||
* Close modal and reset component.
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
const handleCancelImage = (): void => {
|
||||
setOpen(false);
|
||||
setTimeout(() => resetComponent(), animationTime);
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog
|
||||
open={open}
|
||||
onOpenChange={(v) => {
|
||||
setOpen(v);
|
||||
if (!v) setTimeout(() => resetComponent(), animationTime);
|
||||
}}
|
||||
>
|
||||
{/* Button trigger in wysiwyg navigation. */}
|
||||
<DialogTrigger asChild>
|
||||
<BtnOptionnalLinkWithTooltip
|
||||
content={<ImageUpIcon className="w-4 h-4 m-auto" />}
|
||||
tooltipContent={tooltip}
|
||||
className="cursor-grab richtext-px-2 richtext-w-[32px] richtext-h-[32px]"
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
/>
|
||||
</DialogTrigger>
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogTitle>
|
||||
{useTrans("back.wysiwyg_plugins.image.title")}
|
||||
</DialogTitle>
|
||||
<DialogDescription>
|
||||
{useTrans("back.wysiwyg_plugins.image.subtitle")}
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<CompleteInputFile
|
||||
fileName="image"
|
||||
name="image"
|
||||
label={str(useTrans("validation.custom.image"))
|
||||
.ucFirst()
|
||||
.value()}
|
||||
setData={handleSetImage}
|
||||
reset={(name) => console.log("reset", name)}
|
||||
value={null}
|
||||
required={true}
|
||||
maxFileSize="5120"
|
||||
allowedFormats="jpg,jpeg,png,webp"
|
||||
validationRules={{
|
||||
width: "1920",
|
||||
height: "1080",
|
||||
}}
|
||||
parentErrors={errors}
|
||||
/>
|
||||
<SimpleString
|
||||
name="alt"
|
||||
label={str(useTrans("validation.custom.image_alt"))
|
||||
.ucFirst()
|
||||
.value()}
|
||||
placeholder="ex: John Doe"
|
||||
required={true}
|
||||
value={inputAlt}
|
||||
setData={handleSetAlt}
|
||||
disabled={loading}
|
||||
parentErrors={errors}
|
||||
/>
|
||||
<div className="flex justify-between">
|
||||
<div className="flex justify-between gap-1.5">
|
||||
{/* Save button. */}
|
||||
<BtnOptionnalLinkWithTooltip
|
||||
content={str(useTrans("crud.actions.save"))
|
||||
.ucFirst()
|
||||
.value()}
|
||||
tooltipContent={useTrans(
|
||||
"back.wysiwyg_plugins.image.add",
|
||||
)}
|
||||
className="cursor-pointer"
|
||||
type="button"
|
||||
size="default"
|
||||
disabled={loading}
|
||||
onClick={handleAddImage}
|
||||
/>
|
||||
{/* Cancel button. */}
|
||||
<BtnOptionnalLinkWithTooltip
|
||||
content={str(useTrans("back.cancel"))
|
||||
.ucFirst()
|
||||
.value()}
|
||||
tooltipContent={useTrans(
|
||||
"back.wysiwyg_plugins.image.cancel",
|
||||
)}
|
||||
className="cursor-pointer"
|
||||
variant="secondary"
|
||||
type="button"
|
||||
size="default"
|
||||
disabled={loading}
|
||||
onClick={handleCancelImage}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
13
resources/ts/back/Components/Inputs/Wysiwyg/Plugins/Image/image.d.ts
vendored
Normal file
13
resources/ts/back/Components/Inputs/Wysiwyg/Plugins/Image/image.d.ts
vendored
Normal file
|
|
@ -0,0 +1,13 @@
|
|||
import '@tiptap/core';
|
||||
|
||||
declare module '@tiptap/core' {
|
||||
interface Commands<ReturnType> {
|
||||
Image: {
|
||||
setImage: (attrs: {
|
||||
src: string,
|
||||
alt: string;
|
||||
}) => ReturnType;
|
||||
unsetImage: () => ReturnType;
|
||||
};
|
||||
}
|
||||
}
|
||||
|
|
@ -30,7 +30,7 @@ export const Link = TiptapLink.extend<LinkOptions>({
|
|||
setLink: attrs => ({ state, commands }) => {
|
||||
const { from, to } = state.selection;
|
||||
|
||||
// Vérifier si un lien est sélectionné
|
||||
// Check if there is a selected link.
|
||||
let linkFound = false;
|
||||
state.doc.nodesBetween(from, to, node => {
|
||||
if (node.marks) {
|
||||
|
|
@ -41,7 +41,7 @@ export const Link = TiptapLink.extend<LinkOptions>({
|
|||
|
||||
if (linkFound) {
|
||||
return commands.command(({ tr, state, dispatch }) => {
|
||||
// Récupérer le mark existant
|
||||
// Get the existing mark.
|
||||
let existingMark = null;
|
||||
state.doc.nodesBetween(from, to, node => {
|
||||
if (node.marks) {
|
||||
|
|
@ -52,27 +52,27 @@ export const Link = TiptapLink.extend<LinkOptions>({
|
|||
|
||||
if (!existingMark) return false;
|
||||
|
||||
// Supprimer le texte existant
|
||||
// Remove the existing text.
|
||||
tr.delete(from, to);
|
||||
|
||||
// Insérer le nouveau texte
|
||||
// Insert the new text.
|
||||
tr.insertText(attrs.text, from);
|
||||
|
||||
// Ajouter le mark avec les nouveaux attrs
|
||||
// Set the mark with new attributes.
|
||||
tr.addMark(
|
||||
from,
|
||||
from + attrs.text.length,
|
||||
state.schema.marks[this.name].create(attrs)
|
||||
);
|
||||
|
||||
// Appliquer la transaction
|
||||
// Apply the modification.
|
||||
if (dispatch) dispatch(tr);
|
||||
|
||||
return true;
|
||||
});
|
||||
}
|
||||
|
||||
// Sinon créer un nouveau lien comme avant
|
||||
// Otherwise, create a new link like before.
|
||||
return commands.insertContent({
|
||||
type: "text",
|
||||
text: attrs.text,
|
||||
|
|
@ -82,7 +82,7 @@ export const Link = TiptapLink.extend<LinkOptions>({
|
|||
unsetLink: () => ({ state, commands }: CommandProps) => {
|
||||
const { from, to } = state.selection;
|
||||
|
||||
// Vérifier qu’il y a bien un mark Link
|
||||
// Check there is a link mark.
|
||||
let hasLink = false;
|
||||
state.doc.nodesBetween(from, to, node => {
|
||||
if (node.marks?.some(m => m.type.name === this.name)) {
|
||||
|
|
@ -92,7 +92,7 @@ export const Link = TiptapLink.extend<LinkOptions>({
|
|||
|
||||
if (!hasLink) return false;
|
||||
|
||||
// Retirer le mark de la sélection
|
||||
// Remove the mark from the selection.
|
||||
return commands.unsetMark(this.name);
|
||||
},
|
||||
};
|
||||
|
|
@ -144,11 +144,11 @@ export const Link = TiptapLink.extend<LinkOptions>({
|
|||
const link = target.closest("a");
|
||||
if (!link) return false;
|
||||
|
||||
// Trouver la position exacte du node <a>
|
||||
// Find the exact position of the gat <a>.
|
||||
const { state } = view;
|
||||
const $pos = state.doc.resolve(pos);
|
||||
|
||||
// 🔥 Étendre la sélection à l'ensemble du mark
|
||||
// Extend the selection to the entire mark.
|
||||
const markRange = getMarkRange($pos, state.schema.marks.Link);
|
||||
if (markRange) {
|
||||
view.dispatch(
|
||||
|
|
@ -158,7 +158,7 @@ export const Link = TiptapLink.extend<LinkOptions>({
|
|||
);
|
||||
}
|
||||
|
||||
// Ouvrir ta modale
|
||||
// Open the modale.
|
||||
this.editor.emit("open-link-editor", {
|
||||
href: link.getAttribute("href") ?? "",
|
||||
blank: link.getAttribute("target") === "_blank",
|
||||
|
|
|
|||
|
|
@ -10,7 +10,6 @@ import { FontSize } from "reactjs-tiptap-editor/fontsize";
|
|||
import { Heading } from "reactjs-tiptap-editor/heading";
|
||||
import { History } from "reactjs-tiptap-editor/history";
|
||||
import { HorizontalRule } from "reactjs-tiptap-editor/horizontalrule";
|
||||
import { Image } from "reactjs-tiptap-editor/image";
|
||||
import { Indent } from "reactjs-tiptap-editor/indent";
|
||||
import { Italic } from "reactjs-tiptap-editor/italic";
|
||||
import { OrderedList } from "reactjs-tiptap-editor/orderedlist";
|
||||
|
|
@ -19,14 +18,13 @@ import { Strike } from "reactjs-tiptap-editor/strike";
|
|||
import { TextAlign } from "reactjs-tiptap-editor/textalign";
|
||||
import { TextUnderline } from "reactjs-tiptap-editor/textunderline";
|
||||
import { Color } from "reactjs-tiptap-editor/color";
|
||||
import axios from "axios";
|
||||
import "react-image-crop/dist/ReactCrop.css";
|
||||
import "reactjs-tiptap-editor/lib/style.css";
|
||||
import { route } from "ziggy-js";
|
||||
// * Components shadcn
|
||||
import { Label } from "@/components/ui/label";
|
||||
// * Other
|
||||
import { Link } from "@/back/Components/Inputs/Wysiwyg/Plugins/Link/Link";
|
||||
import { Image } from "@/back/Components/Inputs/Wysiwyg/Plugins/Image/Image";
|
||||
import InputError from "@/back/Components/InputError";
|
||||
import WordCounter from "@/back/Components/WordCounter";
|
||||
import useTrans from "@/hooks/use-translations";
|
||||
|
|
@ -89,27 +87,8 @@ export default function SimpleWysiwyg({
|
|||
TextAlign,
|
||||
Blockquote,
|
||||
HorizontalRule,
|
||||
Image.configure({
|
||||
upload: async (file: File): Promise<string> => {
|
||||
// Prepare the form data.
|
||||
const data = new FormData();
|
||||
data.append("upload", file);
|
||||
data.append("folder", model);
|
||||
|
||||
const uploadRoute = route("back.wysiwyg.upload");
|
||||
|
||||
try {
|
||||
const response = await axios.post(
|
||||
uploadRoute,
|
||||
data,
|
||||
{ headers: { "Content-Type": "multipart/form-data" } }
|
||||
);
|
||||
return response.data.url;
|
||||
} catch (error: Error | unknown) {
|
||||
throw new Error(`Erreur upload: ${(error as Error).message}`);
|
||||
}
|
||||
},
|
||||
}),
|
||||
// Custom plugins.
|
||||
Image,
|
||||
Link,
|
||||
];
|
||||
|
||||
|
|
@ -129,11 +108,17 @@ export default function SimpleWysiwyg({
|
|||
setData(name, value);
|
||||
};
|
||||
|
||||
// Define some custom attributes in the editor options,
|
||||
// so that we can access them from plugins.
|
||||
const customOptions: UseEditorOptions = {
|
||||
editorProps: {
|
||||
attributes: {
|
||||
// Required status.
|
||||
required: String(required),
|
||||
// Target field name.
|
||||
id,
|
||||
// Target model name.
|
||||
model,
|
||||
},
|
||||
},
|
||||
};
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue