54 lines
2.0 KiB
Python
54 lines
2.0 KiB
Python
"""Custom WTForms fields/widgets for the admin image picker."""
|
|
from markupsafe import Markup
|
|
from wtforms import StringField
|
|
from wtforms.widgets import TextInput
|
|
|
|
|
|
class ImagePickerWidget(TextInput):
|
|
def __call__(self, field, **kwargs):
|
|
kwargs.setdefault("class", "form-control image-picker-input")
|
|
kwargs["style"] = kwargs.get("style", "") + ";display:none"
|
|
kwargs["id"] = field.id
|
|
field_id = field.id
|
|
val = field._value() if hasattr(field, "_value") else (field.data or "")
|
|
|
|
hidden = (
|
|
f'<input type="text" name="{field.name}" id="{field_id}" '
|
|
f'value="{val}" class="form-control image-picker-input" style="display:none">'
|
|
)
|
|
|
|
preview_src = val or ""
|
|
preview_display = "block" if preview_src else "none"
|
|
|
|
html = f"""
|
|
<div class="image-picker-wrapper" data-field="{field_id}">
|
|
{hidden}
|
|
<div class="image-picker-preview" id="preview-{field_id}" style="display:{preview_display}">
|
|
<img src="{preview_src}" id="preview-img-{field_id}" alt="预览">
|
|
<button type="button" class="image-picker-remove" onclick="imagePickerClear('{field_id}')"
|
|
title="移除图片">×</button>
|
|
</div>
|
|
<div class="image-picker-actions">
|
|
<button type="button" class="btn btn-sm btn-outline-primary"
|
|
onclick="imagePickerOpen('{field_id}')">
|
|
<i class="fa-solid fa-images"></i> 从素材库选择
|
|
</button>
|
|
<button type="button" class="btn btn-sm btn-outline-success"
|
|
onclick="imagePickerUpload('{field_id}')">
|
|
<i class="fa-solid fa-upload"></i> 上传新图片
|
|
</button>
|
|
<input type="file" id="file-{field_id}" accept="image/*"
|
|
style="display:none" onchange="imagePickerFileSelected('{field_id}', this)">
|
|
</div>
|
|
<div class="image-picker-url-display" id="url-display-{field_id}"
|
|
style="margin-top:6px;font-size:12px;color:#94a3b8;word-break:break-all">
|
|
{val}
|
|
</div>
|
|
</div>
|
|
"""
|
|
return Markup(html)
|
|
|
|
|
|
class ImagePickerField(StringField):
|
|
widget = ImagePickerWidget()
|