Commit f754ac73 by Яков

fix image

parent e21301e8
{
"name": "react-ag-qeditor",
"version": "1.1.26",
"version": "1.1.27",
"description": "WYSIWYG html editor",
"author": "atma",
"license": "MIT",
......
......@@ -23,26 +23,35 @@ const ResizableImageTemplate = ({ node, updateAttributes, editor, getPos, select
// Добавляем прозрачный нулевой пробел после изображения
useEffect(() => {
if (!editor || !getPos) return;
if (!editor || !getPos || editor.isDestroyed) return
let pos;
let pos
try {
pos = getPos();
if (typeof pos !== 'number') return;
} catch (e) {
console.warn('getPos() failed:', e);
return;
pos = getPos()
} catch {
return
}
if (typeof pos !== 'number') return
const doc = editor.state.doc;
const { doc } = editor.state
const node = doc.nodeAt(pos)
if (!node || node.type.name !== 'image') return
if (doc.nodeSize > pos && doc.nodeAt(pos)?.textContent !== '\u200B') {
editor.commands.insertContentAt(pos + 1, {
type: 'text',
text: '\u200B'
});
}
}, [editor, getPos]);
const next = doc.nodeAt(pos + node.nodeSize)
if (next?.isText && next.text === '\u200B') return
requestAnimationFrame(() => {
if (editor.isDestroyed) return
try {
const p = getPos()
const n = editor.state.doc.nodeAt(p)
if (!n || n.type.name !== 'image') return
editor.commands.insertContentAt(p + n.nodeSize, '\u200B')
} catch {}
})
}, [])
// Получаем текущую ширину редактора и доступное пространство
......@@ -79,38 +88,84 @@ const ResizableImageTemplate = ({ node, updateAttributes, editor, getPos, select
// Безопасное обновление атрибутов с учетом выравнивания и границ
const safeUpdateAttributes = (newAttrs) => {
const { width: editorWidth, availableSpace } = getEditorDimensions();
let { width, height, align } = { ...node.attrs, ...newAttrs };
const newAlign = newAttrs.align || align;
// При изменении выравнивания проверяем доступное пространство
if (newAlign && newAlign !== align) {
const maxWidth = availableSpace;
if (width > maxWidth) {
const ratio = maxWidth / width;
width = maxWidth;
height = Math.round(height * ratio);
}
} else {
// Для обычного обновления размеров
const maxWidth = availableSpace;
if (width > maxWidth) {
const ratio = maxWidth / width;
width = maxWidth;
height = Math.round(height * ratio);
}
}
const clamp = (v, min, max) => Math.min(max, Math.max(min, v))
// Проверяем минимальный размер
if (width < MIN_WIDTH) {
const ratio = MIN_WIDTH / width;
width = MIN_WIDTH;
height = Math.round(height * ratio);
}
const safeUpdateAttributes = (patch) => {
if (!editor || editor.isDestroyed) return
updateAttributes({ width, height, ...newAttrs });
};
let pos
try {
pos = getPos()
} catch {
return
}
if (typeof pos !== 'number') return
const currentNode = editor.state.doc.nodeAt(pos)
if (!currentNode || currentNode.type.name !== 'image') return
const base = currentNode.attrs || {}
// 1) сохраняем то, что не хотим потерять
const keep = {
align: base.align,
border: base.border,
borderColor: base.borderColor,
borderWidth: base.borderWidth,
borderRadius: base.borderRadius,
}
// 2) кандидат на апдейт
let next = { ...keep, ...base, ...patch }
// 3) нормализуем размеры (границы)
const minW = 80
const maxW = 1600
const minH = 40
const maxH = 2000
if (next.width != null) next.width = clamp(Number(next.width) || 0, minW, maxW)
if (next.height != null) next.height = clamp(Number(next.height) || 0, minH, maxH)
// 4) нормализуем align (чтобы не улетало в мусор)
const allowedAlign = new Set(['left', 'center', 'right', 'full'])
if (next.align && !allowedAlign.has(next.align)) next.align = base.align || 'center'
updateAttributes(next)
}
//
// const safeUpdateAttributes = (newAttrs) => {
// const { width: editorWidth, availableSpace } = getEditorDimensions();
// let { width, height, align } = { ...node.attrs, ...newAttrs };
// const newAlign = newAttrs.align || align;
//
// // При изменении выравнивания проверяем доступное пространство
// if (newAlign && newAlign !== align) {
// const maxWidth = availableSpace;
// if (width > maxWidth) {
// const ratio = maxWidth / width;
// width = maxWidth;
// height = Math.round(height * ratio);
// }
// } else {
// // Для обычного обновления размеров
// const maxWidth = availableSpace;
// if (width > maxWidth) {
// const ratio = maxWidth / width;
// width = maxWidth;
// height = Math.round(height * ratio);
// }
// }
//
// // Проверяем минимальный размер
// if (width < MIN_WIDTH) {
// const ratio = MIN_WIDTH / width;
// width = MIN_WIDTH;
// height = Math.round(height * ratio);
// }
//
// updateAttributes({ width, height, ...newAttrs });
// };
// Инициализация изображения
useEffect(() => {
......@@ -388,20 +443,20 @@ const ResizableImageTemplate = ({ node, updateAttributes, editor, getPos, select
ref={imgRef}
draggable={true}
style={getImageStyle()}
onLoad={() => {
if (imgRef.current && !isInitialized.current && !node.attrs.width && !node.attrs.height) {
const { width: editorWidth } = getEditorDimensions();
const naturalWidth = imgRef.current.naturalWidth;
const naturalHeight = imgRef.current.naturalHeight;
safeUpdateAttributes({
width: naturalWidth,
height: naturalHeight,
'data-node-id': node.attrs['data-node-id'] || Math.random().toString(36).substr(2, 9)
});
isInitialized.current = true;
}
}}
// onLoad={() => {
// if (imgRef.current && !isInitialized.current && !node.attrs.width && !node.attrs.height) {
// const { width: editorWidth } = getEditorDimensions();
// const naturalWidth = imgRef.current.naturalWidth;
// const naturalHeight = imgRef.current.naturalHeight;
//
// safeUpdateAttributes({
// width: naturalWidth,
// height: naturalHeight,
// 'data-node-id': node.attrs['data-node-id'] || Math.random().toString(36).substr(2, 9)
// });
// isInitialized.current = true;
// }
// }}
/>
{
node.attrs.frontAlt?.length > 0 &&
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment