fix(lead-forms): multiline options, editable title, color palette, builder validation and unique new form names

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
2026-10-07 13:49:27 +03:30
co-authored by Cursor
parent d683932d1b
commit 678cb87de7
2 changed files with 244 additions and 31 deletions
+235 -28
View File
@@ -1,6 +1,6 @@
<script setup lang="ts">
import { computed, onMounted, ref } from 'vue';
import { useRoute } from 'vue-router';
import { computed, nextTick, onMounted, ref, watch } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import axios from 'axios';
import { api } from '@/lib/api';
import UiIcon from '@/components/UiIcon.vue';
@@ -25,6 +25,7 @@ type IconName =
| 'check' | 'chart' | 'document' | 'star' | 'megaphone' | 'building';
const route = useRoute();
const router = useRouter();
const id = computed(() => String(route.params.id || ''));
const loading = ref(true);
@@ -135,6 +136,71 @@ const coverSrc = computed(() =>
form.value?.hasCover ? `/api/public/forms/${form.value.publicToken}/cover` : '',
);
const editingField = computed(() => fields.value.find((f) => f.key === editFieldKey.value) ?? null);
/** متن خام گزینه‌ها — جدا از options تا خط خالی هنگام تایپ حذف نشود */
const optionsDraft = ref('');
const sheetError = ref('');
function parseOptions(raw: string): string[] {
return [...new Set(raw.split('\n').map((s) => s.trim()).filter(Boolean))];
}
function syncOptions() {
if (editingField.value) editingField.value.options = parseOptions(optionsDraft.value);
}
watch(editFieldKey, () => {
optionsDraft.value = editingField.value?.options.join('\n') ?? '';
sheetError.value = '';
});
function needsOptions(type: string) {
return type === 'select' || type === 'radio' || type === 'checkbox';
}
function closeFieldSheet() {
const f = editingField.value;
if (f) {
if (!f.label.trim()) {
sheetError.value = 'عنوان فیلد را بنویسید.';
return;
}
if (needsOptions(f.fieldType) && !f.options.length) {
sheetError.value = 'حداقل یک گزینه بنویسید.';
return;
}
f.label = f.label.trim();
optionsDraft.value = f.options.join('\n');
}
editFieldKey.value = null;
}
/* ---------- رنگ دکمه ---------- */
const COLOR_PRESETS = [
'#14b8a6', '#0d9488', '#10b981', '#22c55e', '#3b82f6', '#2563eb',
'#6366f1', '#8b5cf6', '#a855f7', '#ec4899', '#f43f5e', '#ef4444',
'#f97316', '#f59e0b', '#eab308', '#64748b', '#334155', '#0f172a',
];
const colorOpen = ref(false);
const hexDraft = ref('');
function toggleColor() {
colorOpen.value = !colorOpen.value;
hexDraft.value = submitColor.value;
}
function pickColor(c: string) {
submitColor.value = c;
hexDraft.value = c;
}
function applyHex() {
const v = hexDraft.value.trim();
const hex = v.startsWith('#') ? v : `#${v}`;
if (/^#([0-9a-f]{3}|[0-9a-f]{6})$/i.test(hex)) submitColor.value = hex.toLowerCase();
else hexDraft.value = submitColor.value;
}
const titleInput = ref<HTMLInputElement | null>(null);
const conversionRate = computed(() => {
const submits = form.value?.submitCount ?? 0;
const leads = form.value?.leadCreateCount ?? 0;
@@ -160,11 +226,26 @@ function newKey(label: string) {
}
function defaultMap(type: LeadFormFieldType): LeadFormMapTo {
if (type === 'email') return 'custom';
if (type === 'phone') return 'lead.mobile';
if (type === 'text') return 'lead.contactName';
if (type === 'textarea') return 'lead.notes';
return 'custom';
let target: LeadFormMapTo = 'custom';
if (type === 'phone') target = 'lead.mobile';
else if (type === 'text') target = 'lead.contactName';
else if (type === 'textarea') target = 'lead.notes';
return fields.value.some((f) => f.mapTo === target) ? 'custom' : target;
}
const mapConflict = computed(() => {
const f = editingField.value;
if (!f || f.mapTo === 'custom' || f.mapTo === 'notes') return null;
return fields.value.find((o) => o.key !== f.key && o.mapTo === f.mapTo) ?? null;
});
const fieldLabels = computed(() => Object.fromEntries(fields.value.map((f) => [f.key, f.label])));
function formatValue(val: unknown): string {
if (Array.isArray(val)) return val.join('، ');
if (val === true) return 'بله';
if (val === false) return 'خیر';
return val == null ? '' : String(val);
}
function readyIcon(type: LeadFormFieldType | string): IconName {
@@ -174,18 +255,23 @@ function readyIcon(type: LeadFormFieldType | string): IconName {
function addField(type: LeadFormFieldType, preset?: Partial<LeadFormFieldInput>) {
const meta = toolbox.find((t) => t.type === type);
const label = preset?.label || meta?.label || 'فیلد جدید';
const needsOptions = type === 'select' || type === 'radio' || type === 'checkbox';
const key = newKey(label);
fields.value.push({
id: newKey(label),
key: newKey(label),
id: key,
key,
label,
fieldType: type,
required: preset?.required ?? type !== 'heading',
mapTo: (preset?.mapTo as LeadFormMapTo) || defaultMap(type),
position: fields.value.length,
placeholder: preset?.placeholder ?? '',
options: preset?.options ?? (needsOptions ? ['گزینه ۱', 'گزینه ۲'] : []),
options: preset?.options ?? (needsOptions(type) ? ['گزینه ۱', 'گزینه ۲'] : []),
});
return key;
}
function addAndEdit(type: LeadFormFieldType) {
editFieldKey.value = addField(type);
}
function duplicateField(field: LeadFormFieldDto) {
@@ -194,6 +280,7 @@ function duplicateField(field: LeadFormFieldDto) {
mapTo: field.mapTo as LeadFormMapTo,
options: [...field.options],
placeholder: field.placeholder,
required: field.required,
});
}
@@ -254,9 +341,36 @@ async function load() {
} finally {
loading.value = false;
}
if (route.query.new && !error.value) {
tab.value = 'edit';
await nextTick();
titleInput.value?.focus();
titleInput.value?.select();
void router.replace({ query: {} });
}
}
function validate(): string {
if (!name.value.trim()) return 'عنوان فرم را بنویسید.';
const noLabel = fields.value.find((f) => !f.label.trim());
if (noLabel) return 'یکی از فیلدها عنوان ندارد.';
const noOptions = fields.value.find((f) => needsOptions(f.fieldType) && !f.options.length);
if (noOptions) return `فیلد «${noOptions.label}» هیچ گزینه‌ای ندارد.`;
return '';
}
async function save() {
const invalid = validate();
if (invalid) {
error.value = invalid;
ok.value = '';
if (!name.value.trim()) {
tab.value = 'edit';
await nextTick();
titleInput.value?.focus();
}
return;
}
saving.value = true;
error.value = '';
ok.value = '';
@@ -431,8 +545,20 @@ onMounted(load);
<button v-if="coverSrc" class="link" type="button" @click="clearCover">حذف کاور</button>
<div class="title-card">
<input v-model="name" class="title" />
<textarea v-model="description" rows="2" placeholder="توضیح فرم را بنویسید" />
<label class="title-label" for="form-title">
عنوان فرم
<UiIcon name="pencil" :size="13" />
</label>
<input
id="form-title"
ref="titleInput"
v-model="name"
class="title"
maxlength="120"
placeholder="مثلاً: فرم ثبت‌نام وبینار"
/>
<label class="title-label" for="form-desc">توضیح فرم</label>
<textarea id="form-desc" v-model="description" rows="2" placeholder="توضیح کوتاه برای بازدیدکننده (اختیاری)" />
</div>
<article
@@ -445,9 +571,12 @@ onMounted(load);
@drop="onDrop(f.key)"
>
<span class="grip"><UiIcon name="grip" :size="16" /></span>
<div>
<strong>{{ f.label }}</strong>
<small>{{ typeLabel[f.fieldType] || f.fieldType }}</small>
<div class="fbody" @click="editFieldKey = f.key">
<strong>{{ f.label }}<span v-if="f.required" class="req">*</span></strong>
<small>
{{ typeLabel[f.fieldType] || f.fieldType }}
<template v-if="needsOptions(f.fieldType)"> · {{ toFaDigits(f.options.length) }} گزینه</template>
</small>
</div>
<div class="fops">
<button type="button" title="کپی" @click="duplicateField(f)"><UiIcon name="layers" :size="14" /></button>
@@ -456,15 +585,61 @@ onMounted(load);
</div>
</article>
<button class="add-field" type="button" @click="addField('text')">+ افزودن فیلد جدید</button>
<button class="add-field" type="button" @click="addAndEdit('text')">+ افزودن فیلد جدید</button>
<div class="submit-card">
<label>متن دکمه ارسال
<input v-model="submitLabel" />
</label>
<label>رنگ دکمه
<input v-model="submitColor" type="color" />
</label>
<div class="color-row">
<span class="color-label">رنگ دکمه</span>
<div class="color-pick">
<button
type="button"
class="swatch-btn"
:aria-expanded="colorOpen"
aria-label="انتخاب رنگ دکمه"
@click="toggleColor"
>
<span class="swatch" :style="{ background: submitColor }" />
<span class="hex" dir="ltr">{{ submitColor }}</span>
<UiIcon name="chevron" :size="14" />
</button>
<div v-if="colorOpen" class="palette-backdrop" @click="colorOpen = false" />
<div v-if="colorOpen" class="palette" @click.stop>
<div class="presets">
<button
v-for="c in COLOR_PRESETS"
:key="c"
type="button"
class="preset"
:class="{ on: submitColor.toLowerCase() === c }"
:style="{ background: c }"
:aria-label="c"
@click="pickColor(c)"
>
<UiIcon v-if="submitColor.toLowerCase() === c" name="check-plain" :size="12" />
</button>
</div>
<div class="custom">
<label class="native">
<input v-model="submitColor" type="color" @input="hexDraft = submitColor" />
رنگ دلخواه
</label>
<input
v-model="hexDraft"
class="hex-input"
dir="ltr"
maxlength="7"
placeholder="#14b8a6"
@keydown.enter.prevent="applyHex"
@blur="applyHex"
/>
</div>
<button type="button" class="palette-done" @click="colorOpen = false">تأیید</button>
</div>
</div>
</div>
</div>
<button class="adv" type="button" @click="advancedOpen = !advancedOpen">تنظیمات پیشرفته</button>
@@ -648,7 +823,7 @@ onMounted(load);
<span v-if="s.status"> · {{ s.status }}</span>
<span v-if="s.leadId"> · لید</span>
</small>
<p v-for="(val, key) in s.values" :key="key"><b>{{ key }}:</b> {{ val }}</p>
<p v-for="(val, key) in s.values" :key="key"><b>{{ fieldLabels[key] || key }}:</b> {{ formatValue(val) }}</p>
</article>
</section>
@@ -693,10 +868,10 @@ onMounted(load);
</div>
</div>
<div v-if="editingField" class="overlay" @click.self="editFieldKey = null">
<div v-if="editingField" class="overlay" @click.self="closeFieldSheet">
<div class="sheet">
<h3>ویرایش فیلد</h3>
<label>عنوان <input v-model="editingField.label" /></label>
<label>عنوان <input v-model="editingField.label" maxlength="120" /></label>
<label>متن راهنما <input v-model="editingField.placeholder" /></label>
<label class="chk"><input v-model="editingField.required" type="checkbox" /> الزامی</label>
<label>اتصال به
@@ -728,16 +903,24 @@ onMounted(load);
<option value="notes">یادداشت</option>
<option value="custom">فقط در پاسخ فرم</option>
</select>
<small v-if="mapConflict" class="sheet-warn">
فیلد «{{ mapConflict.label }}» هم به همین مقصد وصل است؛ مقدار یکی روی دیگری نوشته می‌شود.
</small>
</label>
<label v-if="['select','radio','checkbox'].includes(editingField.fieldType)">
گزینه‌ها (هر خط یکی)
<textarea
:value="editingField.options.join('\n')"
rows="4"
@input="editingField.options = ($event.target as HTMLTextAreaElement).value.split('\n').map(s => s.trim()).filter(Boolean)"
v-model="optionsDraft"
rows="5"
placeholder="گزینه ۱&#10;گزینه ۲"
@input="syncOptions"
/>
<small class="sheet-hint">
{{ toFaDigits(editingField.options.length) }} گزینه — با Enter به خط بعد بروید؛ خطوط خالی و تکراری نادیده گرفته می‌شوند.
</small>
</label>
<button class="btn primary" type="button" @click="editFieldKey = null">تمام</button>
<p v-if="sheetError" class="sheet-error">{{ sheetError }}</p>
<button class="btn primary" type="button" @click="closeFieldSheet">تمام</button>
</div>
</div>
@@ -828,7 +1011,31 @@ onMounted(load);
.cover-box { width: 100%; min-height: 88px; border: 1.5px dashed #99f6e4; border-radius: var(--radius); background: #f0fdfa; color: #0f766e; font: inherit; font-weight: 700; cursor: pointer; overflow: hidden; }
.cover-box img { width: 100%; height: 88px; object-fit: cover; display: block; }
.title-card, .field-card, .submit-card, .adv-box { border: 1px solid #eef2f7; border-radius: var(--radius); padding: 0.8rem; display: grid; gap: 0.45rem; }
.title { font-size: 1.15rem; font-weight: 600; border: 0; background: transparent; font: inherit; }
.title { font: inherit; font-size: 1.1rem; font-weight: 700; color: #0f172a; border: 1px solid #e2e8f0; border-radius: var(--radius); padding: 0.55rem 0.7rem; background: #fff; width: 100%; box-sizing: border-box; }
.title:hover { border-color: #99f6e4; }
.title:focus { outline: none; border-color: var(--teal); box-shadow: 0 0 0 3px rgba(20,184,166,.15); }
.title-label { display: inline-flex; align-items: center; gap: 0.3rem; font-size: 0.78rem; font-weight: 700; color: #64748b; }
.color-row { display: flex; align-items: center; justify-content: space-between; gap: 0.6rem; font-size: 0.88rem; font-weight: 700; color: #334155; }
.color-pick { position: relative; }
.swatch-btn { display: inline-flex; align-items: center; gap: 0.45rem; border: 1px solid #e2e8f0; background: #fff; border-radius: var(--radius); padding: 0.3rem 0.5rem; font: inherit; cursor: pointer; }
.swatch-btn:hover { border-color: #99f6e4; }
.swatch { width: 26px; height: 26px; border-radius: 8px; box-shadow: inset 0 0 0 1px rgba(15,23,42,.12); }
.hex { font-size: 0.8rem; color: #475569; font-family: ui-monospace, monospace; }
.palette { position: absolute; inset-inline-end: 0; top: calc(100% + 6px); z-index: 30; width: 236px; background: #fff; border: 1px solid #e2e8f0; border-radius: var(--radius); box-shadow: 0 16px 40px rgba(15,23,42,.16); padding: 0.65rem; display: grid; gap: 0.6rem; }
.presets { display: grid; grid-template-columns: repeat(6, 1fr); gap: 0.35rem; }
.preset { width: 100%; aspect-ratio: 1; border: 0; border-radius: 8px; cursor: pointer; display: grid; place-items: center; color: #fff; box-shadow: inset 0 0 0 1px rgba(15,23,42,.1); }
.preset.on { outline: 2px solid #0f172a; outline-offset: 2px; }
.custom { display: flex; align-items: center; gap: 0.4rem; }
.native { display: inline-flex; align-items: center; gap: 0.3rem; font-size: 0.78rem; font-weight: 600; color: #475569; cursor: pointer; white-space: nowrap; }
.palette-backdrop { position: fixed; inset: 0; z-index: 29; }
.sheet-warn { font-size: 0.76rem; font-weight: 600; color: #b45309; }
.fbody { cursor: pointer; min-width: 0; }
.req { color: #ef4444; margin-inline-start: 0.15rem; }
.submit-card .native input { width: 28px; height: 28px; padding: 0; border: 0; background: none; cursor: pointer; }
.submit-card .hex-input { flex: 1; min-width: 0; padding: 0.35rem 0.5rem; font-family: ui-monospace, monospace; font-size: 0.82rem; }
.palette-done { border: 0; background: var(--teal); color: #fff; border-radius: var(--radius); min-height: 32px; font: inherit; font-weight: 700; cursor: pointer; }
.sheet-hint { font-size: 0.74rem; font-weight: 500; color: #94a3b8; }
.sheet-error { margin: 0; color: #b91c1c; font-size: 0.84rem; }
.title-card textarea, .submit-card input, .panel input, .panel select, .sheet input, .sheet select, .sheet textarea {
border: 1px solid #e2e8f0; border-radius: var(--radius); padding: 0.55rem 0.7rem; font: inherit; width: 100%;
}
+9 -3
View File
@@ -35,20 +35,26 @@ async function load() {
}
}
function nextFormName() {
const taken = new Set(forms.value.map((f) => f.name.trim()));
let n = forms.value.length + 1;
while (taken.has(`فرم جدید ${toFaDigits(n)}`)) n += 1;
return `فرم جدید ${toFaDigits(n)}`;
}
async function createForm() {
saving.value = true;
error.value = '';
try {
const { data } = await api.post<LeadFormDto>('/lead-forms', {
name: 'درخواست مشاوره',
description: 'فرم دریافت درخواست مشاوره مشتریان',
name: nextFormName(),
source: 'وب‌سایت',
createLead: true,
createPerson: false,
createDeal: false,
duplicateMode: 'update',
});
await router.push({ name: 'lead-form-builder', params: { id: data.id } });
await router.push({ name: 'lead-form-builder', params: { id: data.id }, query: { new: '1' } });
} catch {
error.value = 'ساخت فرم ناموفق بود.';
} finally {