feat: add drop image product mgmt

This commit is contained in:
Methapon2001 2024-12-23 17:17:39 +07:00
parent bd3a7bc9a4
commit 3eda26bbf7
3 changed files with 126 additions and 21 deletions

View file

@ -1,6 +1,8 @@
import { ModelRef, Ref } from 'vue';
import { Dark } from 'quasar';
import { setLocale as setDateTimeLocale } from './datetime';
import { i18n } from 'src/boot/i18n';
import { fileToBase64 } from './file';
export enum Theme {
Light = 'light',
@ -75,3 +77,58 @@ export function setLang(lang: Lang): Lang {
return lang;
}
/**
* This is for use with ContentEditable element and with q-editor
*/
export function createEditorImageDrop(ref: Ref<string> | ModelRef<string>) {
return async (e: DragEvent) => {
e.preventDefault();
e.stopPropagation();
const target = e.target;
if (!target || !(target instanceof HTMLElement)) return;
const items = e.dataTransfer?.items;
const promises: Promise<string>[] = [];
if (!items) return;
for (let i = 0; i < items.length; i++) {
const file = items[i].getAsFile();
if (!file || file.type.indexOf('image') === -1) continue;
promises.push(fileToBase64(file));
}
const getCaret = () => {
if (target.isContentEditable || document.designMode === 'on') {
target.focus();
const range = document.getSelection()?.getRangeAt(0);
if (!range?.collapsed) return null;
const tmp = document.createTextNode('\0');
range.insertNode(tmp);
const pos = target.innerHTML.indexOf('\0');
tmp.parentNode?.removeChild(tmp);
return pos;
}
return null;
};
for (const base64 of await Promise.all(promises)) {
const image = document.createElement('img') as HTMLImageElement;
const caret = getCaret();
image.src = base64;
if (caret) {
ref.value =
ref.value.substring(0, caret) +
image.outerHTML +
ref.value.substring(caret, ref.value.length);
} else {
ref.value += image.outerHTML;
}
}
};
}