Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 | <script setup lang="ts">
import { getCsrfToken } from '@/lib/csrf';
import { computed, defineAsyncComponent, onMounted, ref, watch } from 'vue';
type UnlayerDesign = Record<string, unknown>;
interface UnlayerExportData {
design: UnlayerDesign;
html: string;
}
interface UnlayerEditorInstance {
loadDesign: (design: UnlayerDesign) => void;
exportHtml: (callback: (data: UnlayerExportData) => void) => void;
addEventListener: (event: string, callback: () => void) => void;
registerCallback?: (event: string, callback: (file: unknown, done: (result: unknown) => void) => void) => void;
}
interface UnlayerEditorRef {
editor: UnlayerEditorInstance;
}
const EmailEditor = defineAsyncComponent({
loader: async () => {
const module = await import('vue-email-editor');
return (module as { default?: unknown; EmailEditor?: unknown }).default
?? (module as { default?: unknown; EmailEditor?: unknown }).EmailEditor
?? module;
},
suspensible: false,
});
const DESIGN_MARKER_PREFIX = '<!-- unlayer-design:';
const DESIGN_MARKER_SUFFIX = ' -->';
const props = defineProps<{
modelValue: string;
imageUploadUrl?: string;
}>();
const emit = defineEmits<{
(event: 'update:modelValue', value: string): void;
}>();
const isClient = ref(false);
const activeTab = ref<'designer' | 'html'>('designer');
const emailEditorRef = ref<UnlayerEditorRef | null>(null);
const isReady = ref(false);
const editorLoadError = ref(false);
const manualHtml = ref('');
const pendingDesign = ref<UnlayerDesign | null>(null);
const uploadUrl = computed(() => props.imageUploadUrl || '/administration/email-templates/upload-image');
const wrapWithDesignMarker = (design: UnlayerDesign, html: string) => {
const encoded = encodeURIComponent(JSON.stringify(design));
return `${DESIGN_MARKER_PREFIX}${encoded}${DESIGN_MARKER_SUFFIX}\n${html}`;
};
const unwrapDesignMarker = (input: string) => {
if (!input?.startsWith(DESIGN_MARKER_PREFIX)) {
return { design: null as UnlayerDesign | null, html: input || '' };
}
const endIndex = input.indexOf(DESIGN_MARKER_SUFFIX);
if (endIndex === -1) {
return { design: null as UnlayerDesign | null, html: input || '' };
}
const encoded = input.slice(DESIGN_MARKER_PREFIX.length, endIndex).trim();
const html = input.slice(endIndex + DESIGN_MARKER_SUFFIX.length).replace(/^\n/, '');
try {
const decoded = decodeURIComponent(encoded);
return {
design: JSON.parse(decoded) as UnlayerDesign,
html,
};
} catch {
return { design: null as UnlayerDesign | null, html: input || '' };
}
};
const syncFromEditor = () => {
const editor = emailEditorRef.value?.editor;
if (!editor || !isReady.value) {
return;
}
editor.exportHtml((data) => {
manualHtml.value = data.html || '';
emit('update:modelValue', wrapWithDesignMarker(data.design || {}, data.html || ''));
});
};
const findFile = (payload: unknown): File | null => {
if (!payload || typeof payload !== 'object') {
return null;
}
const direct = (payload as { file?: File }).file;
if (direct instanceof File) {
return direct;
}
const attachments = (payload as { attachments?: unknown[] }).attachments;
if (Array.isArray(attachments)) {
const first = attachments.find((item) => item instanceof File);
if (first instanceof File) {
return first;
}
}
return null;
};
const registerImageUpload = () => {
const editor = emailEditorRef.value?.editor;
if (!editor?.registerCallback) {
return;
}
editor.registerCallback('image', async (payload: unknown, done: (result: unknown) => void) => {
const imageFile = findFile(payload);
if (!imageFile) {
done({ progress: 100, url: '' });
return;
}
try {
const formData = new FormData();
formData.append('image', imageFile);
const response = await fetch(uploadUrl.value, {
method: 'POST',
headers: {
'X-CSRF-TOKEN': getCsrfToken(),
'X-Requested-With': 'XMLHttpRequest',
},
body: formData,
});
const data = await response.json();
const src = data?.data?.[0]?.src || '';
done({ progress: 100, url: src });
} catch {
done({ progress: 100, url: '' });
}
});
};
const onEditorReady = () => {
isReady.value = true;
editorLoadError.value = false;
registerImageUpload();
const editor = emailEditorRef.value?.editor;
if (!editor) {
return;
}
if (pendingDesign.value) {
editor.loadDesign(pendingDesign.value);
}
editor.addEventListener('design:updated', () => {
syncFromEditor();
});
};
watch(
() => props.modelValue,
(newValue) => {
const parsed = unwrapDesignMarker(newValue || '');
pendingDesign.value = parsed.design;
manualHtml.value = parsed.html;
// Keep designer in sync when modelValue changes after initial mount
const editor = emailEditorRef.value?.editor;
if (isReady.value && editor && parsed.design) {
editor.loadDesign(parsed.design);
}
},
{ immediate: true },
);
watch(
() => manualHtml.value,
(newHtml) => {
if (activeTab.value === 'html') {
emit('update:modelValue', newHtml || '');
}
},
);
onMounted(() => {
isClient.value = true;
});
</script>
<template>
<div class="space-y-3">
<div class="flex items-center gap-2">
<button
type="button"
@click="activeTab = 'designer'"
:class="[
'rounded-md px-3 py-1.5 text-xs font-medium',
activeTab === 'designer' ? 'bg-blue-600 text-white' : 'border border-gray-300 bg-white text-gray-700',
]"
>
Designer
</button>
<button
type="button"
@click="activeTab = 'html'"
:class="[
'rounded-md px-3 py-1.5 text-xs font-medium',
activeTab === 'html' ? 'bg-blue-600 text-white' : 'border border-gray-300 bg-white text-gray-700',
]"
>
Manual HTML
</button>
<button
v-if="activeTab === 'designer'"
type="button"
@click="syncFromEditor"
class="rounded-md border border-gray-300 bg-white px-3 py-1.5 text-xs font-medium text-gray-700 hover:bg-gray-50"
>
Sync Designer HTML
</button>
</div>
<div v-if="activeTab === 'designer'" class="h-[680px] overflow-hidden rounded-md border border-gray-200">
<component
:is="EmailEditor"
v-if="isClient && !editorLoadError"
ref="emailEditorRef"
:min-height="680"
class="h-full"
@load="onEditorReady"
@ready="onEditorReady"
@error="editorLoadError = true"
/>
<div v-else-if="!isClient" class="flex h-[680px] items-center justify-center text-sm text-gray-500">Loading editor...</div>
<div v-else class="flex h-[680px] flex-col items-center justify-center gap-2 p-6 text-center text-sm text-gray-600">
<p>Email designer failed to load.</p>
<p class="text-xs text-gray-500">You can continue using the Manual HTML tab while we retry.</p>
</div>
</div>
<div v-else>
<textarea
v-model="manualHtml"
rows="24"
class="w-full rounded-md border-gray-300 font-mono text-sm shadow-sm focus:border-blue-500 focus:ring-blue-500"
placeholder="<p>Write your email HTML here...</p>"
></textarea>
</div>
</div>
</template>
|