Skip to content
Merged
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
Original file line number Diff line number Diff line change
Expand Up @@ -138,6 +138,10 @@ export const insertNewRelationship = (target, type, editor) => {
},
};

if (type === 'hyperlink') {
newRel.attributes.TargetMode = 'External';
}

// Insert the new relationship
relationshipsTag.elements.push(newRel);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -308,6 +308,7 @@ describe('insertNewRelationship', () => {
Id: 'rId43',
Type: RELATIONSHIP_TYPES.hyperlink,
Target: 'bar',
TargetMode: 'External',
},
});
});
Expand Down
Original file line number Diff line number Diff line change
@@ -1,15 +1,15 @@
import { ImagePlaceholderPluginKey, findPlaceholder } from './imagePlaceholderPlugin.js';
import { handleImageUpload as handleImageUploadDefault } from './handleImageUpload.js';
import { processUploadedImage } from './processUploadedImage.js';
import { insertNewRelationship } from '@core/super-converter/docx-helpers/document-rels.js';

export const startImageUpload = async ({ editor, view, file }) => {
// Handler from config or default
let imageUploadHandler =
const imageUploadHandler =
typeof editor.options.handleImageUpload === 'function'
? editor.options.handleImageUpload
: handleImageUploadDefault;

let fileSizeMb = (file.size / (1024 * 1024)).toFixed(4);
let fileSizeMb = Number((file.size / (1024 * 1024)).toFixed(4));
Comment thread
harbournick marked this conversation as resolved.

if (fileSizeMb > 5) {
window.alert('Image size must be less than 5MB');
Expand All @@ -29,6 +29,16 @@ export const startImageUpload = async ({ editor, view, file }) => {
return;
}

await uploadImage({
editor,
view,
file,
size: { width, height },
uploadHandler: imageUploadHandler,
});
};

export async function uploadImage({ editor, view, file, size, uploadHandler }) {
// A fresh object to act as the ID for this upload
let id = {};

Expand All @@ -52,45 +62,63 @@ export const startImageUpload = async ({ editor, view, file }) => {
tr.setMeta(ImagePlaceholderPluginKey, imageMeta);
view.dispatch(tr);

imageUploadHandler(file).then(
(url) => {
let fileName = file.name.replace(' ', '_');
let placeholderPos = findPlaceholder(view.state, id);

// If the content around the placeholder has been deleted,
// drop the image
if (placeholderPos == null) {
return;
}

// Otherwise, insert it at the placeholder's position, and remove
// the placeholder
let removeMeta = { type: 'remove', id };

let mediaPath = `word/media/${fileName}`;
let imageNode = schema.nodes.image.create({
src: mediaPath,
size: { width, height },
});

editor.storage.image.media = Object.assign(editor.storage.image.media, { [mediaPath]: url });

// If we are in collaboration, we need to share the image with other clients
if (editor.options.ydoc) {
editor.commands.addImageToCollaboration({ mediaPath, fileData: url });
}

view.dispatch(
view.state.tr
.replaceWith(placeholderPos, placeholderPos, imageNode) // or .insert(placeholderPos, imageNode)
.setMeta(ImagePlaceholderPluginKey, removeMeta),
);
},
() => {
let removeMeta = { type: 'remove', id };

// On failure, just clean up the placeholder
view.dispatch(tr.setMeta(ImagePlaceholderPluginKey, removeMeta));
},
);
};
try {
let url = await uploadHandler(file);

let fileName = file.name.replace(' ', '_');
let placeholderPos = findPlaceholder(view.state, id);

// If the content around the placeholder has been deleted,
// drop the image
if (placeholderPos == null) {
return;
}

// Otherwise, insert it at the placeholder's position, and remove
// the placeholder
let removeMeta = { type: 'remove', id };

let mediaPath = `word/media/${fileName}`;

let rId = null;
if (editor.options.mode === 'docx') {
const [, path] = mediaPath.split('word/'); // Path without 'word/' part.
const id = addImageRelationship({ editor, path });
if (id) rId = id;
}

let imageNode = schema.nodes.image.create({
src: mediaPath,
size,
rId,
});

editor.storage.image.media = Object.assign(editor.storage.image.media, { [mediaPath]: url });

// If we are in collaboration, we need to share the image with other clients
if (editor.options.ydoc) {
editor.commands.addImageToCollaboration({ mediaPath, fileData: url });
}

view.dispatch(
view.state.tr
.replaceWith(placeholderPos, placeholderPos, imageNode) // or .insert(placeholderPos, imageNode)
.setMeta(ImagePlaceholderPluginKey, removeMeta),
);
} catch {
let removeMeta = { type: 'remove', id };
// On failure, just clean up the placeholder
view.dispatch(tr.setMeta(ImagePlaceholderPluginKey, removeMeta));
}
}

function addImageRelationship({ editor, path }) {
const target = path;
const type = 'image';
try {
const id = insertNewRelationship(target, type, editor);
return id;
} catch {
return null;
}
}
22 changes: 21 additions & 1 deletion packages/super-editor/src/extensions/link/link.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@

import { Mark, Attribute } from '@core/index.js';
import { getMarkRange } from '@core/helpers/getMarkRange.js';
import { insertNewRelationship } from '@core/super-converter/docx-helpers/document-rels.js';

/**
* @module Link
Expand Down Expand Up @@ -134,7 +135,15 @@ export const Link = Mark.create({
if (underlineMarkType) tr = tr.removeMark(from, to, underlineMarkType);

if (underlineMarkType) tr = tr.addMark(from, to, underlineMarkType.create());
tr = tr.addMark(from, to, linkMarkType.create({ href, text: finalText }));

let rId = null;
if (editor.options.mode === 'docx') {
const id = addLinkRelationship({ editor, href });
if (id) rId = id;
}

const newLinkMarkType = linkMarkType.create({ href, text: finalText, rId });
tr = tr.addMark(from, to, newLinkMarkType);

dispatch(tr.scrollIntoView());
return true;
Expand Down Expand Up @@ -239,3 +248,14 @@ const trimRange = (doc, from, to) => {
// starting and ending without doc specific whitespace
return { from, to };
};

function addLinkRelationship({ editor, href }) {
const target = href;
const type = 'hyperlink';
try {
const id = insertNewRelationship(target, type, editor);
return id;
} catch {
return null;
}
}
1 change: 1 addition & 0 deletions packages/super-editor/src/tests/editor/data/imageBase64.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

61 changes: 61 additions & 0 deletions packages/super-editor/src/tests/editor/relationships.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
import { loadTestDataForEditorTests, initTestEditor } from '@tests/helpers/helpers.js';
import { TextSelection } from 'prosemirror-state';
import { expect } from 'vitest';
import { getDocumentRelationshipElements } from '@core/super-converter/docx-helpers/document-rels.js';
import { uploadImage } from '@extensions/image/imageHelpers/startImageUpload.js';
import { handleImageUpload as handleImageUploadDefault } from '@extensions/image/imageHelpers/handleImageUpload.js';
import { imageBase64 } from './data/imageBase64.js';

describe('Relationships tests', () => {
window.URL.createObjectURL = vi.fn().mockImplementation((file) => {
return file.name;
});

const filename = 'blank-doc.docx';
let docx, media, mediaFiles, fonts, editor;

beforeAll(async () => ({ docx, media, mediaFiles, fonts } = await loadTestDataForEditorTests(filename)));
beforeEach(() => ({ editor } = initTestEditor({ content: docx, media, mediaFiles, fonts })));

it('tests that the inserted link has a rId and a relationship', () => {
editor.commands.insertContentAt(0, 'link');

editor.view.dispatch(editor.state.tr.setSelection(TextSelection.create(editor.state.doc, 0, 5)));
editor.commands.setLink({ href: 'https://www.superdoc.dev' });

const linkMark = editor.state.doc.firstChild.firstChild.marks[0];

expect(linkMark.type.name).toBe('link');
expect(linkMark.attrs.rId).toBeTruthy();

const relationships = getDocumentRelationshipElements(editor);
const found = relationships.find((i) => i.attributes.Id === linkMark.attrs.rId);

expect(found).toBeTruthy();
expect(found.attributes.Target).toBe('https://www.superdoc.dev');
});

it('tests that the uploaded image has a rId and a relationship', async () => {
const blob = await fetch(imageBase64).then((res) => res.blob());
const file = new File([blob], 'image.png', { type: 'image/png' });

await uploadImage({
editor,
view: editor.view,
file,
size: { width: 100, height: 100 },
uploadHandler: handleImageUploadDefault,
});

const imageNode = editor.state.doc.firstChild.firstChild;

expect(imageNode.type.name).toBe('image');
expect(imageNode.attrs.rId).toBeTruthy();

const relationships = getDocumentRelationshipElements(editor);
const found = relationships.find((i) => i.attributes.Id === imageNode.attrs.rId);

expect(found).toBeTruthy();
expect(found.attributes.Target).toBe('media/image.png');
});
});
Loading