diff --git a/lang/fr/back.php b/lang/fr/back.php index 7df0bdf3..21d280ef 100644 --- a/lang/fr/back.php +++ b/lang/fr/back.php @@ -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", diff --git a/lang/fr/validation.php b/lang/fr/validation.php index e339c77b..c01c2d52 100644 --- a/lang/fr/validation.php +++ b/lang/fr/validation.php @@ -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", diff --git a/resources/ts/back/Components/Inputs/CompleteInputFile.tsx b/resources/ts/back/Components/Inputs/CompleteInputFile.tsx index d275e9e6..736e5eee 100644 --- a/resources/ts/back/Components/Inputs/CompleteInputFile.tsx +++ b/resources/ts/back/Components/Inputs/CompleteInputFile.tsx @@ -33,6 +33,7 @@ type CompleteInputFileProps = FileValidation & { required?: boolean; fileName?: string; hasRefreshBtn?: boolean; + parentErrors?: Record | 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>>({ @@ -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) { /> )} - + ); } diff --git a/resources/ts/back/Components/Inputs/Wysiwyg/Plugins/Image/Image.ts b/resources/ts/back/Components/Inputs/Wysiwyg/Plugins/Image/Image.ts new file mode 100644 index 00000000..5b83fa77 --- /dev/null +++ b/resources/ts/back/Components/Inputs/Wysiwyg/Plugins/Image/Image.ts @@ -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({ + addOptions() { + return { + ...this.parent?.(), + openOnClick: false, + button: ({ editor }: { editor: Editor }) => ({ + component: ImageButton, + componentProps: { + editor, + tooltip: useTrans('back.wysiwyg_plugins.image.tooltip'), + }, + }), + }; + }, +}); \ No newline at end of file diff --git a/resources/ts/back/Components/Inputs/Wysiwyg/Plugins/Image/ImageButton.tsx b/resources/ts/back/Components/Inputs/Wysiwyg/Plugins/Image/ImageButton.tsx new file mode 100644 index 00000000..363e7790 --- /dev/null +++ b/resources/ts/back/Components/Inputs/Wysiwyg/Plugins/Image/ImageButton.tsx @@ -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(null); + // Value of the input alt image. + const [inputAlt, setInputAlt] = useState(""); + + // State of the loader. + const [loading, setLoading] = useState(false); + // Value of errors. + const [errors, setErrors] = useState>({}); + + // 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 + */ + const uploadImage = async (file: File, alt: string): Promise => { + // 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 = {}; + const keyMap: Record = { + 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 ( + { + setOpen(v); + if (!v) setTimeout(() => resetComponent(), animationTime); + }} + > + {/* Button trigger in wysiwyg navigation. */} + + } + tooltipContent={tooltip} + className="cursor-grab richtext-px-2 richtext-w-[32px] richtext-h-[32px]" + type="button" + variant="ghost" + size="icon" + /> + + + + + {useTrans("back.wysiwyg_plugins.image.title")} + + + {useTrans("back.wysiwyg_plugins.image.subtitle")} + + + console.log("reset", name)} + value={null} + required={true} + maxFileSize="5120" + allowedFormats="jpg,jpeg,png,webp" + validationRules={{ + width: "1920", + height: "1080", + }} + parentErrors={errors} + /> + +
+
+ {/* Save button. */} + + {/* Cancel button. */} + +
+
+
+
+ ); +} diff --git a/resources/ts/back/Components/Inputs/Wysiwyg/Plugins/Image/image.d.ts b/resources/ts/back/Components/Inputs/Wysiwyg/Plugins/Image/image.d.ts new file mode 100644 index 00000000..52d862d0 --- /dev/null +++ b/resources/ts/back/Components/Inputs/Wysiwyg/Plugins/Image/image.d.ts @@ -0,0 +1,13 @@ +import '@tiptap/core'; + +declare module '@tiptap/core' { + interface Commands { + Image: { + setImage: (attrs: { + src: string, + alt: string; + }) => ReturnType; + unsetImage: () => ReturnType; + }; + } +} diff --git a/resources/ts/back/Components/Inputs/Wysiwyg/Plugins/Link/Link.ts b/resources/ts/back/Components/Inputs/Wysiwyg/Plugins/Link/Link.ts index 578c4c05..9b09a86b 100644 --- a/resources/ts/back/Components/Inputs/Wysiwyg/Plugins/Link/Link.ts +++ b/resources/ts/back/Components/Inputs/Wysiwyg/Plugins/Link/Link.ts @@ -30,7 +30,7 @@ export const Link = TiptapLink.extend({ 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({ 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({ 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({ 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({ 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({ const link = target.closest("a"); if (!link) return false; - // Trouver la position exacte du node + // Find the exact position of the gat . 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({ ); } - // Ouvrir ta modale + // Open the modale. this.editor.emit("open-link-editor", { href: link.getAttribute("href") ?? "", blank: link.getAttribute("target") === "_blank", diff --git a/resources/ts/back/Components/Inputs/Wysiwyg/SimpleWysiwyg.tsx b/resources/ts/back/Components/Inputs/Wysiwyg/SimpleWysiwyg.tsx index 38a061eb..0f6e41b3 100644 --- a/resources/ts/back/Components/Inputs/Wysiwyg/SimpleWysiwyg.tsx +++ b/resources/ts/back/Components/Inputs/Wysiwyg/SimpleWysiwyg.tsx @@ -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 => { - // 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, }, }, };