can edit text + fix font weight - remove character space

This commit is contained in:
hamid zarghami
2025-11-26 15:45:00 +03:30
parent aacf209894
commit 735355822a
19 changed files with 342 additions and 160 deletions
Binary file not shown.

After

Width:  |  Height:  |  Size: 24 KiB

+102
View File
@@ -0,0 +1,102 @@
import { type FC, type InputHTMLAttributes, useState, useRef, useEffect } from 'react'
import { clx } from '../helpers/utils'
import Error from './Error'
import ColorfilterIcon from '@/assets/icons/color.png'
type Props = {
label?: string
className?: string
error_text?: string
isNotRequired?: boolean
value?: string
onChange?: (value: string) => void
} & Omit<InputHTMLAttributes<HTMLInputElement>, 'onChange' | 'value'>
const ColorPicker: FC<Props> = (props: Props) => {
const [color, setColor] = useState<string>(props.value || '#000000')
const colorInputRef = useRef<HTMLInputElement>(null)
const inputClass = clx(
'w-full bg-white h-10 text-black block pl-10 pr-10 text-xs rounded-xl border border-border',
props.readOnly && 'bg-gray-100 border-0 text-description',
props.className
)
const handleColorChange = (event: React.ChangeEvent<HTMLInputElement>) => {
const newColor = event.target.value
setColor(newColor)
props.onChange?.(newColor)
}
const handleTextChange = (event: React.ChangeEvent<HTMLInputElement>) => {
const value = event.target.value
if (/^#[0-9A-Fa-f]{0,6}$/.test(value) || value === '') {
const finalColor = value || '#000000'
setColor(finalColor)
props.onChange?.(finalColor)
}
}
const handleColorIconClick = () => {
if (!props.readOnly) {
colorInputRef.current?.click()
}
}
useEffect(() => {
if (props.value !== undefined) {
setColor(props.value)
}
}, [props.value])
return (
<div className='w-full'>
<label className='text-sm'>
{props.label}
</label>
<div className='w-full relative mt-1'>
<input
type='text'
value={color}
onChange={handleTextChange}
placeholder='#000000'
readOnly={props.readOnly}
className={inputClass}
/>
<button
type='button'
onClick={handleColorIconClick}
disabled={props.readOnly}
className={clx(
'absolute top-0 bottom-0 my-auto left-3 cursor-pointer',
props.readOnly && 'cursor-not-allowed opacity-50'
)}
>
<img src={ColorfilterIcon} alt='color-filter' className='size-7' />
</button>
<div
className='absolute top-0 bottom-0 my-auto right-3 w-5 h-5 rounded-full'
style={{ backgroundColor: color }}
/>
<input
ref={colorInputRef}
type='color'
value={color}
onChange={handleColorChange}
className='absolute opacity-0 pointer-events-none w-0 h-0'
/>
{props.error_text && (
<Error errorText={props.error_text} />
)}
</div>
</div>
)
}
export default ColorPicker
+8 -1
View File
@@ -78,6 +78,13 @@ const Input: FC<Props> = (props: Props) => {
}, [search, props])
const resolvedType =
props.type === 'password'
? showPassword
? 'text'
: 'password'
: props.type;
return (
<div className='w-full'>
<label className='text-sm'>
@@ -88,7 +95,7 @@ const Input: FC<Props> = (props: Props) => {
<input {...props} onChange={(e) => {
setSearch(e.target.value)
handleInputChange(e)
}} value={props.seprator ? formattedValue : props.value} type={props.type === 'password' && showPassword ? 'text' : props.type === 'password' ? 'password' : undefined} className={inputClass} />
}} value={props.seprator ? formattedValue : props.value} type={resolvedType} className={inputClass} />
{
props.type === 'password' &&
+9 -2
View File
@@ -65,7 +65,11 @@ const EditorCanvas = () => {
draggable={tool === "select"}
/>
))}
{selectedObjectId && (
{selectedObjectId && (() => {
const selectedObject = objects.find(obj => obj.id === selectedObjectId);
const isText = selectedObject?.type === "text";
return (
<Transformer
ref={transformerRef}
boundBoxFunc={(oldBox, newBox) => {
@@ -74,6 +78,8 @@ const EditorCanvas = () => {
}
return newBox;
}}
ignoreStroke={isText}
perfectDrawEnabled={false}
anchorFill="#3b82f6"
anchorStroke="#ffffff"
borderStroke="#3b82f6"
@@ -91,7 +97,8 @@ const EditorCanvas = () => {
"middle-right",
]}
/>
)}
);
})()}
</Layer>
</Stage>
</div>
@@ -28,7 +28,7 @@ export const createDrawingObject = ({
height: Math.abs(height),
fill: "#3b82f6",
stroke: "#1e40af",
strokeWidth: 2,
strokeWidth: 0,
shapeType: activeShape,
};
}
@@ -44,7 +44,7 @@ export const createDrawingObject = ({
height: radius * 2,
fill: "#10b981",
stroke: "#059669",
strokeWidth: 2,
strokeWidth: 0,
};
}
@@ -1,6 +1,8 @@
import { type FC, useRef, useState, useEffect } from "react";
import { type FC, useState, useEffect, useMemo } from "react";
import Input from "@/components/Input";
import Select from "@/components/Select";
import ColorPicker from "@/components/ColorPicker";
import Button from "@/components/Button";
import { useEditorStore } from "@/pages/editor/store/editorStore";
import { useTextDefaultsStore } from "@/pages/editor/store/textDefaultsStore";
@@ -15,6 +17,17 @@ const fontWeightOptions = [
{ label: "Light", value: "300" },
];
type TextFormState = {
text: string;
fontFamily: string;
fontWeight: string;
fontSize: number;
fill: string;
opacity: number;
letterSpacing: number;
wordSpacing: number;
};
const TextInstruction: FC = () => {
const { selectedObjectId, objects, updateObject } = useEditorStore();
const { defaults, updateDefaults } = useTextDefaultsStore();
@@ -24,8 +37,10 @@ const TextInstruction: FC = () => {
: null;
const isEditing = !!selectedObject;
const currentValues = isEditing
? {
const baseValues = useMemo(() => {
if (isEditing && selectedObject) {
return {
text: selectedObject.text || "",
fontFamily: selectedObject.fontFamily || defaults.fontFamily,
fontWeight: selectedObject.fontWeight || defaults.fontWeight,
fontSize: selectedObject.fontSize || defaults.fontSize,
@@ -33,30 +48,52 @@ const TextInstruction: FC = () => {
opacity: selectedObject.opacity ?? defaults.opacity,
letterSpacing: selectedObject.letterSpacing ?? defaults.letterSpacing,
wordSpacing: selectedObject.wordSpacing ?? defaults.wordSpacing,
};
}
: defaults;
return { text: "", ...defaults };
}, [isEditing, selectedObject, defaults]);
const handleChange = (field: string, value: string | number) => {
const [formState, setFormState] = useState<TextFormState>(baseValues);
useEffect(() => {
setFormState(baseValues);
}, [baseValues]);
const handleChange = (field: keyof TextFormState, value: string | number) => {
if (isEditing && selectedObject) {
updateObject(selectedObject.id, { [field]: value });
setFormState((prev) => ({ ...prev, [field]: value }));
} else {
// text فقط برای حالت ویرایش است و نباید در defaults ذخیره شود
if (field !== "text") {
updateDefaults({ [field]: value });
}
}
};
const hexColor = (currentValues.fill || "#000000").replace("#", "").toUpperCase();
const opacityValue = currentValues.opacity;
const colorInputRef = useRef<HTMLInputElement>(null);
const handleSave = () => {
if (isEditing && selectedObject) {
updateObject(selectedObject.id, formState);
}
};
const isDirty = isEditing && selectedObject
? formState.text !== baseValues.text ||
formState.fontFamily !== baseValues.fontFamily ||
formState.fontWeight !== baseValues.fontWeight ||
formState.fontSize !== baseValues.fontSize ||
formState.fill !== baseValues.fill ||
formState.opacity !== baseValues.opacity ||
formState.letterSpacing !== baseValues.letterSpacing ||
formState.wordSpacing !== baseValues.wordSpacing
: false;
const opacityValue = formState.opacity;
const [opacityInput, setOpacityInput] = useState<string>(`${opacityValue}`);
useEffect(() => {
setOpacityInput(`${opacityValue}`);
}, [opacityValue]);
const handleColorClick = () => {
colorInputRef.current?.click();
};
const handleOpacityChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const value = e.target.value.replace("%", "").trim();
setOpacityInput(value);
@@ -66,20 +103,31 @@ const TextInstruction: FC = () => {
const numValue = parseInt(opacityInput) || 0;
const clampedValue = Math.min(100, Math.max(0, numValue));
setOpacityInput(`${clampedValue}`);
if (clampedValue !== opacityValue) {
handleChange("opacity", clampedValue);
}
};
return (
<div>
<h2 className="font-bold">متن</h2>
<div className="mt-8">
{isEditing && (
<div className="mt-4">
<label className="text-sm mb-1 block">متن</label>
<textarea
className="w-full min-h-[80px] rounded-xl border border-border px-3 py-2 text-sm outline-none focus:border-primary resize-y"
value={formState.text}
onChange={(e) => handleChange("text", e.target.value)}
placeholder="متن خود را وارد کنید..."
/>
</div>
)}
<div className="mt-4">
<Select
items={fontOptions}
placeholder="انتخاب فونت"
label="فونت"
value={currentValues.fontFamily}
value={formState.fontFamily}
onChange={(e) => handleChange("fontFamily", e.target.value)}
/>
</div>
@@ -88,12 +136,12 @@ const TextInstruction: FC = () => {
<Select
label="وزن"
items={fontWeightOptions}
value={currentValues.fontWeight}
value={formState.fontWeight}
onChange={(e) => handleChange("fontWeight", e.target.value)}
/>
<Input
value={`${currentValues.fontSize}px`}
value={`${formState.fontSize}px`}
label="سایز"
onChange={(e) => {
const value = e.target.value.replace("px", "").trim();
@@ -103,31 +151,20 @@ const TextInstruction: FC = () => {
/>
</div>
<div className="mt-4">
<div className="text-sm">رنگ</div>
<div className="mt-2 border border-border rounded-xl p-2 flex items-center">
<button
type="button"
onClick={handleColorClick}
className="flex-1 flex items-center gap-1.5 cursor-pointer hover:opacity-80 transition-opacity"
>
<div
className="size-6 rounded"
style={{ backgroundColor: currentValues.fill }}
<div className="mt-4 flex flex-col gap-2">
<div className="flex gap-3">
<ColorPicker
label="رنگ"
className="flex-1"
value={formState.fill}
onChange={(value) => handleChange("fill", value)}
/>
<div className="text-sm">{hexColor}</div>
</button>
<input
ref={colorInputRef}
type="color"
value={currentValues.fill}
onChange={(e) => handleChange("fill", e.target.value)}
className="hidden"
/>
<div className="text-sm flex px-2 mr-3 border-r border-border">
<div className="w-28">
<label className="text-sm">شفافیت</label>
<div className="mt-1 flex h-10 items-center rounded-xl border border-border px-2 text-sm">
<input
type="text"
className="text-center w-14 border-none outline-none bg-transparent text-sm"
className="w-full border-none bg-transparent text-center text-sm outline-none"
value={`${opacityInput}%`}
onChange={handleOpacityChange}
onBlur={handleOpacityBlur}
@@ -140,11 +177,12 @@ const TextInstruction: FC = () => {
</div>
</div>
</div>
</div>
<div className="mt-4 flex gap-2">
{/* <div className="mt-4 flex gap-2">
<Input
label="فاصله کلمات"
value={`${currentValues.wordSpacing}px`}
value={`${formState.wordSpacing}px`}
onChange={(e) => {
const value = e.target.value.replace("px", "").trim();
const numValue = parseInt(value) || 0;
@@ -154,14 +192,22 @@ const TextInstruction: FC = () => {
<Input
label="فاصله حروف"
value={`${currentValues.letterSpacing}px`}
value={`${formState.letterSpacing}px`}
onChange={(e) => {
const value = e.target.value.replace("px", "").trim();
const numValue = parseInt(value) || 0;
handleChange("letterSpacing", numValue);
}}
/>
</div> */}
{isEditing && (
<div className="mt-4">
<Button type="button" onClick={handleSave} disabled={!isDirty} className="w-full">
ذخیره تغییرات
</Button>
</div>
)}
</div>
);
};
@@ -1,5 +1,6 @@
import type { EditorObject } from "../../../store/editorStore";
import Input from "@/components/Input";
import ColorPicker from "@/components/ColorPicker";
type LineSettingsProps = {
selectedObject: EditorObject;
@@ -9,19 +10,19 @@ type LineSettingsProps = {
const LineSettings = ({ selectedObject, onUpdate }: LineSettingsProps) => {
return (
<>
<Input
<ColorPicker
label="رنگ خط"
type="color"
value={selectedObject.stroke || "#000000"}
onChange={(e) => onUpdate(selectedObject.id, { stroke: e.target.value })}
onChange={(value) => onUpdate(selectedObject.id, { stroke: value })}
/>
<Input
label="ضخامت خط"
type="number"
value={selectedObject.strokeWidth || 2}
min={0}
value={selectedObject.strokeWidth ?? 0}
onChange={(e) =>
onUpdate(selectedObject.id, {
strokeWidth: parseInt(e.target.value) || 2,
strokeWidth: parseInt(e.target.value) || 0,
})
}
/>
@@ -1,5 +1,6 @@
import type { EditorObject } from "../../../store/editorStore";
import Input from "@/components/Input";
import ColorPicker from "@/components/ColorPicker";
type LinkSettingsProps = {
selectedObject: EditorObject;
@@ -30,11 +31,10 @@ const LinkSettings = ({ selectedObject, onUpdate }: LinkSettingsProps) => {
})
}
/>
<Input
<ColorPicker
label="رنگ متن"
type="color"
value={selectedObject.fill || "#0000ff"}
onChange={(e) => onUpdate(selectedObject.id, { fill: e.target.value })}
onChange={(value) => onUpdate(selectedObject.id, { fill: value })}
/>
</>
);
@@ -1,6 +1,7 @@
import { useEffect, useState } from "react";
import Button from "@/components/Button";
import Input from "@/components/Input";
import ColorPicker from "@/components/ColorPicker";
import type { EditorObject } from "@/pages/editor/store/editorStore";
type ShapeSettingsProps = {
@@ -21,7 +22,7 @@ const ShapeSettings = ({ selectedObject, onUpdate }: ShapeSettingsProps) => {
const baseHeight = selectedObject.height ?? 100;
const baseFill = selectedObject.fill ?? "#3b82f6";
const baseStroke = selectedObject.stroke ?? "#1e40af";
const baseStrokeWidth = selectedObject.strokeWidth ?? 2;
const baseStrokeWidth = selectedObject.strokeWidth ?? 0;
const [formState, setFormState] = useState<ShapeFormState>({
width: String(baseWidth),
@@ -87,25 +88,23 @@ const ShapeSettings = ({ selectedObject, onUpdate }: ShapeSettingsProps) => {
}))
}
/>
<Input
<ColorPicker
label="رنگ پس‌زمینه"
type="color"
value={formState.fill}
onChange={(e) =>
onChange={(value) =>
setFormState((prev) => ({
...prev,
fill: e.target.value,
fill: value,
}))
}
/>
<Input
<ColorPicker
label="رنگ خط"
type="color"
value={formState.stroke}
onChange={(e) =>
onChange={(value) =>
setFormState((prev) => ({
...prev,
stroke: e.target.value,
stroke: value,
}))
}
/>
@@ -119,7 +118,7 @@ const ShapeSettings = ({ selectedObject, onUpdate }: ShapeSettingsProps) => {
strokeWidth: e.target.value,
}))
}
min={1}
min={0}
/>
<Button type="button" onClick={handleSave} disabled={!isDirty} className="w-full">
ذخیره تغییرات
@@ -1,5 +1,6 @@
import type { EditorObject } from "../../../store/editorStore";
import Input from "@/components/Input";
import ColorPicker from "@/components/ColorPicker";
type TextSettingsProps = {
selectedObject: EditorObject;
@@ -24,11 +25,10 @@ const TextSettings = ({ selectedObject, onUpdate }: TextSettingsProps) => {
})
}
/>
<Input
<ColorPicker
label="رنگ متن"
type="color"
value={selectedObject.fill || "#000000"}
onChange={(e) => onUpdate(selectedObject.id, { fill: e.target.value })}
onChange={(value) => onUpdate(selectedObject.id, { fill: value })}
/>
</>
);
@@ -28,7 +28,7 @@ const AbstractShape = ({ obj, isSelected, transformerRef, onSelect, onUpdate, dr
outerRadius={radius}
fill={obj.fill}
stroke={isSelected ? "#3b82f6" : obj.stroke}
strokeWidth={isSelected ? 3 : obj.strokeWidth || 2}
strokeWidth={isSelected ? 3 : (obj.strokeWidth ?? 0)}
rotation={obj.rotation || 0}
draggable={draggable}
onClick={() => {
@@ -20,7 +20,7 @@ const ArrowShape = ({ obj, isSelected, transformerRef, onSelect, onUpdate, dragg
y={obj.y}
points={[0, 0, (obj.width || 0) - obj.x, (obj.height || 0) - obj.y]}
stroke={isSelected ? "#3b82f6" : obj.stroke || "#000000"}
strokeWidth={isSelected ? 3 : obj.strokeWidth || 2}
strokeWidth={isSelected ? 3 : (obj.strokeWidth ?? 0)}
fill={isSelected ? "#3b82f6" : obj.stroke || "#000000"}
rotation={obj.rotation || 0}
draggable={draggable}
@@ -21,7 +21,7 @@ const CircleShape = ({ obj, isSelected, transformerRef, onSelect, onUpdate, drag
radius={(obj.width || 50) / 2}
fill={obj.fill}
stroke={isSelected ? "#3b82f6" : obj.stroke}
strokeWidth={isSelected ? 3 : obj.strokeWidth || 2}
strokeWidth={isSelected ? 3 : (obj.strokeWidth ?? 0)}
rotation={obj.rotation || 0}
draggable={draggable}
onClick={() => {
@@ -20,7 +20,7 @@ const LineShape = ({ obj, isSelected, transformerRef, onSelect, onUpdate, dragga
y={obj.y}
points={[0, 0, (obj.width || 0) - obj.x, (obj.height || 0) - obj.y]}
stroke={isSelected ? "#3b82f6" : obj.stroke || "#000000"}
strokeWidth={isSelected ? 3 : obj.strokeWidth || 2}
strokeWidth={isSelected ? 3 : (obj.strokeWidth ?? 0)}
rotation={obj.rotation || 0}
draggable={draggable}
onClick={() => {
@@ -22,7 +22,7 @@ const RectangleShape = ({ obj, isSelected, transformerRef, onSelect, onUpdate, d
height={obj.height || 100}
fill={obj.fill}
stroke={isSelected ? "#3b82f6" : obj.stroke}
strokeWidth={isSelected ? 3 : obj.strokeWidth || 2}
strokeWidth={isSelected ? 3 : (obj.strokeWidth ?? 0)}
rotation={obj.rotation || 0}
draggable={draggable}
onClick={() => {
+37 -16
View File
@@ -11,13 +11,13 @@ const getFontFamily = (fontFamily?: string): string => {
return fontMap[fontFamily || "1"] || "irancell";
};
const getFontWeight = (fontWeight?: string): string | number => {
const weightMap: Record<string, string | number> = {
bold: "600",
normal: "300",
const getFontWeight = (fontWeight?: string): string => {
const weightMap: Record<string, string> = {
bold: "bold",
normal: "normal",
"300": "300",
};
return weightMap[fontWeight || "normal"] || "300";
return weightMap[fontWeight || "normal"] || "normal";
};
const getColorWithOpacity = (fill?: string, opacity?: number): string => {
@@ -46,10 +46,23 @@ const TextShape = ({
useEffect(() => {
if (isSelected && shapeRef.current && transformerRef.current) {
transformerRef.current.nodes([shapeRef.current]);
const textNode = shapeRef.current;
// تنظیم offset برای حذف فضای خالی
textNode.offsetX(0);
textNode.offsetY(0);
transformerRef.current.nodes([textNode]);
// به‌روزرسانی transformer بعد از یک تیک برای محاسبه دقیق bounds
setTimeout(() => {
if (transformerRef.current && shapeRef.current) {
transformerRef.current.forceUpdate();
transformerRef.current.getLayer()?.batchDraw();
}
}, [isSelected, transformerRef]);
}, 0);
}
}, [isSelected, transformerRef, obj.text, obj.width, obj.height, obj.fontSize, obj.fontFamily, obj.fontWeight]);
const fontFamily = useMemo(() => getFontFamily(obj.fontFamily), [obj.fontFamily]);
const fontWeight = useMemo(() => getFontWeight(obj.fontWeight), [obj.fontWeight]);
@@ -64,10 +77,11 @@ const TextShape = ({
fontSize={obj.fontSize || 24}
fill={fillColor}
fontFamily={fontFamily}
fontWeight={fontWeight}
letterSpacing={obj.letterSpacing}
fontStyle={fontWeight}
letterSpacing={obj.letterSpacing ?? 0}
width={obj.width}
height={obj.height}
align="right"
rotation={obj.rotation || 0}
draggable={draggable}
onClick={() => {
@@ -105,35 +119,42 @@ const TextShape = ({
const stage = textNode.getStage();
if (!stage) return;
const stageBox = stage.container().getBoundingClientRect();
const textPosition = textNode.absolutePosition();
const scaleX = stage.scaleX() || 1;
const scaleY = stage.scaleY() || 1;
const areaPosition = {
x: stage.container().offsetLeft + textPosition.x,
y: stage.container().offsetTop + textPosition.y,
x: stageBox.left + textPosition.x * scaleX,
y: stageBox.top + textPosition.y * scaleY,
};
const textarea = document.createElement("textarea");
document.body.appendChild(textarea);
textNode.hide();
layerRef.current?.draw();
textarea.value = textNode.text();
textarea.style.position = "absolute";
textarea.style.top = `${areaPosition.y}px`;
textarea.style.left = `${areaPosition.x}px`;
textarea.style.width = `${textNode.width()}px`;
textarea.style.fontSize = `${textNode.fontSize()}px`;
textarea.style.width = `${textNode.width() * scaleX}px`;
textarea.style.fontSize = `${textNode.fontSize() * scaleY}px`;
textarea.style.border = "none";
textarea.style.padding = "0px";
textarea.style.padding = "50px";
textarea.style.margin = "0px";
textarea.style.overflow = "hidden";
textarea.style.background = "transparent";
textarea.style.outline = "none";
textarea.style.resize = "none";
textarea.style.fontFamily = fontFamily;
textarea.style.fontWeight = String(fontWeight);
textarea.style.letterSpacing = `${obj.letterSpacing || 0}px`;
textarea.style.fontWeight = fontWeight === "bold" ? "bold" : "normal";
textarea.style.letterSpacing = `${obj.letterSpacing ?? 0}px`;
textarea.style.textAlign = textNode.align() || "right";
textarea.style.direction = "rtl";
textarea.focus();
const removeTextarea = () => {
document.body.removeChild(textarea);
textNode.show();
textNode.text(textarea.value);
onUpdate(obj.id, { text: textarea.value });
layerRef.current?.draw();
@@ -24,7 +24,7 @@ const TriangleShape = ({ obj, isSelected, transformerRef, onSelect, onUpdate, dr
radius={radius}
fill={obj.fill}
stroke={isSelected ? "#3b82f6" : obj.stroke}
strokeWidth={isSelected ? 3 : obj.strokeWidth || 2}
strokeWidth={isSelected ? 3 : (obj.strokeWidth ?? 0)}
rotation={obj.rotation || 0}
draggable={draggable}
onClick={() => {
@@ -30,7 +30,7 @@ const VideoShape = ({
height={obj.height || 300}
fill="#000000"
stroke={isSelected ? "#3b82f6" : "#666666"}
strokeWidth={isSelected ? 3 : 2}
strokeWidth={isSelected ? 3 : (obj.strokeWidth ?? 0)}
rotation={obj.rotation || 0}
draggable={draggable}
onClick={() => {
+2 -3
View File
@@ -20,9 +20,9 @@ export const useTextDefaultsStore = create<TextDefaultsStoreType>((set) => ({
fontFamily: "1",
fontWeight: "bold",
fontSize: 16,
fill: "#A27BC1",
fill: "#000000",
opacity: 100,
letterSpacing: 10,
letterSpacing: 0,
wordSpacing: 10,
},
updateDefaults: (updates) =>
@@ -30,4 +30,3 @@ export const useTextDefaultsStore = create<TextDefaultsStoreType>((set) => ({
defaults: { ...state.defaults, ...updates },
})),
}));