Skip to content
Closed
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
2 changes: 2 additions & 0 deletions .ackrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
--ignore-dir=packages/superdoc/dist
--ignore-dir=packages/super-editor/dist/
30 changes: 27 additions & 3 deletions packages/super-editor/src/components/toolbar/super-toolbar.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,12 @@ import { makeDefaultItems } from './defaultItems';
import { getActiveFormatting } from '@core/helpers/getActiveFormatting.js';
import { vClickOutside } from '@harbour-enterprises/common';
import Toolbar from './Toolbar.vue';
import { startImageUpload, getFileOpener } from '../../extensions/image/imageHelpers/index.js';
import {
checkAndProcessImage,
replaceSelectionWithImagePlaceholder,
uploadAndInsertImage,
getFileOpener,
} from '../../extensions/image/imageHelpers/index.js';
import { findParentNode } from '@helpers/index.js';
import { toolbarIcons } from './toolbarIcons.js';
import { toolbarTexts } from './toolbarTexts.js';
Expand Down Expand Up @@ -366,10 +371,29 @@ export class SuperToolbar extends EventEmitter {
return;
}

startImageUpload({
const { size, file } = await checkAndProcessImage({
file: result.file,
getMaxContentSize: () => this.activeEditor.getMaxContentSize(),
});

if (!file) {
return;
}

const id = {};

replaceSelectionWithImagePlaceholder({
view: this.activeEditor.view,
editorOptions: this.activeEditor.options,
id,
});

await uploadAndInsertImage({
editor: this.activeEditor,
view: this.activeEditor.view,
file: result.file,
file,
size,
id,
});
},

Expand Down
4 changes: 2 additions & 2 deletions packages/super-editor/src/extensions/image/image.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { Attribute, Node } from '@core/index.js';
import { ImagePlaceholderPlugin } from './imageHelpers/imagePlaceholderPlugin.js';
import { ImageRegistrationPlugin } from './imageHelpers/imageRegistrationPlugin.js';
import { ImagePositionPlugin } from './imageHelpers/imagePositionPlugin.js';

export const Image = Node.create({
Expand Down Expand Up @@ -147,6 +147,6 @@ export const Image = Node.create({
},

addPmPlugins() {
return [ImagePlaceholderPlugin(), ImagePositionPlugin({ editor: this.editor })];
return [ImageRegistrationPlugin({ editor: this.editor }), ImagePositionPlugin({ editor: this.editor })];
},
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
const simpleHash = (str) => {
let hash = 0;
for (let i = 0; i < str.length; i++) {
const char = str.charCodeAt(i);
hash = (hash << 5) - hash + char;
hash = hash & hash; // Convert to 32-bit integer
}
return Math.abs(hash).toString();
};

export const base64ToFile = (base64String) => {
const arr = base64String.split(',');
const mimeMatch = arr[0].match(/:(.*?);/);
const mimeType = mimeMatch ? mimeMatch[1] : '';
const data = arr[1];

// Decode the base64 string
const binaryString = atob(data);

// Generate filename using a hash of the binary data
const hash = simpleHash(binaryString);
const extension = mimeType.split('/')[1] || 'bin'; // Simple way to get extension
const filename = `image-${hash}.${extension}`;

// Create a typed array from the binary string
const bytes = new Uint8Array(binaryString.length);
for (let i = 0; i < binaryString.length; i++) {
bytes[i] = binaryString.charCodeAt(i);
}

// Create a Blob and then a File
const blob = new Blob([bytes], { type: mimeType });
return new File([blob], filename, { type: mimeType });
};
106 changes: 106 additions & 0 deletions packages/super-editor/src/extensions/image/imageHelpers/handleUrl.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
/**
* Handles URL to File conversion with comprehensive CORS error handling
*/

/**
* Converts a URL to a File object with proper CORS error handling
* @param {string} url - The image URL to fetch
* @param {string} [filename] - Optional filename for the resulting file
* @param {string} [mimeType] - Optional MIME type for the resulting file
* @returns {Promise<File|null>} File object or null if CORS prevents access
*/
export const urlToFile = async (url, filename, mimeType) => {
try {
// Try to fetch the image with credentials mode set to 'omit' to avoid CORS preflight
const response = await fetch(url, {
mode: 'cors',
credentials: 'omit',
headers: {
// Add common headers that might help with CORS
Accept: 'image/*,*/*;q=0.8',
},
});

if (!response.ok) {
console.warn(`Failed to fetch image from ${url}: ${response.status} ${response.statusText}`);
return null;
}

const blob = await response.blob();

// Extract filename from URL if not provided
const finalFilename = filename || extractFilenameFromUrl(url);

// Determine MIME type from response if not provided
const finalMimeType = mimeType || response.headers.get('content-type') || blob.type || 'image/jpeg';

return new File([blob], finalFilename, { type: finalMimeType });
} catch (error) {
if (isCorsError(error)) {
console.warn(`CORS policy prevents accessing image from ${url}:`, error.message);
return null;
}

console.error(`Error fetching image from ${url}:`, error);
return null;
}
};

/**
* Checks if an error is likely a CORS-related error
* @param {Error} error - The error to check
* @returns {boolean} True if the error appears to be CORS-related
*/
const isCorsError = (error) => {
const errorMessage = error.message.toLowerCase();
const errorName = error.name.toLowerCase();

return (
errorName.includes('cors') ||
errorMessage.includes('cors') ||
errorMessage.includes('cross-origin') ||
errorMessage.includes('access-control') ||
errorMessage.includes('network error') || // Often indicates CORS in browsers
errorMessage.includes('failed to fetch') // Common CORS error message
);
};

/**
* Extracts a filename from a URL
* @param {string} url - The URL to extract filename from
* @returns {string} The extracted filename
*/
const extractFilenameFromUrl = (url) => {
try {
const urlObj = new URL(url);
const pathname = urlObj.pathname;
const filename = pathname.split('/').pop();

// If no extension, add a default one
if (filename && !filename.includes('.')) {
return `${filename}.jpg`;
}

return filename || 'image.jpg';
} catch {
return 'image.jpg';
}
};

/**
* Validates if a URL can be accessed without CORS issues
* @param {string} url - The URL to validate
* @returns {Promise<boolean>} True if the URL is accessible without CORS issues
*/
export const validateUrlAccessibility = async (url) => {
try {
const response = await fetch(url, {
method: 'HEAD',
mode: 'cors',
credentials: 'omit',
});
return response.ok;
} catch (_error) {

Check warning on line 103 in packages/super-editor/src/extensions/image/imageHelpers/handleUrl.js

View workflow job for this annotation

GitHub Actions / validate

'_error' is defined but never used
return false;
}
};

This file was deleted.

Loading
Loading