/** * 统一表单字段取值/赋值(单行 / 多行 / 富文本 / Markdown) * 宏:macros/entity_form_fields.html * 内容字段委托 IAREntityContent;普通 input/textarea 按 #id 读写。 */ (function (global) { 'use strict'; function _contentWrap(fieldId) { return document.querySelector('[data-iar-content-id="' + fieldId + '"]'); } function _el(fieldId) { return document.getElementById(fieldId); } function get(fieldId, opts) { opts = opts || {}; if (_contentWrap(fieldId) && global.IAREntityContent) { var packed = IAREntityContent.getValue(fieldId) || {}; if (opts.withFormat) return { format: packed.format || 'plain', value: packed.value || '' }; return packed.value || ''; } var el = _el(fieldId); if (!el) return opts.withFormat ? { format: 'plain', value: '' } : ''; var v = el.value != null ? String(el.value) : ''; return opts.withFormat ? { format: 'plain', value: v } : v; } function set(fieldId, value, format) { value = value == null ? '' : String(value); if (_contentWrap(fieldId) && global.IAREntityContent) { IAREntityContent.setValue(fieldId, value, format); return; } var el = _el(fieldId); if (el) el.value = value; } function clear(ids) { var list = Array.isArray(ids) ? ids : (ids ? [ids] : []); list.forEach(function (id) { if (_contentWrap(id) && global.IAREntityContent) { IAREntityContent.clear(id); return; } var el = _el(id); if (el) el.value = ''; }); } /** * @param {Object} map { payloadKey: fieldId, ... } 或 { fieldId: fieldId } * @returns {Object} { payloadKey: stringValue } */ function collect(map) { var out = {}; if (!map) return out; Object.keys(map).forEach(function (key) { var fieldId = map[key]; out[key] = get(fieldId) || ''; }); return out; } /** * @param {Object} map { payloadKey: fieldId } * @param {Object} data { payloadKey: value } 或 { payloadKey: { value, format } } * @param {Object} [formatMap] 可选 { payloadKey: 'markdown' } */ function populate(map, data, formatMap) { data = data || {}; formatMap = formatMap || {}; if (!map) return; Object.keys(map).forEach(function (key) { var fieldId = map[key]; var raw = data[key]; var value = ''; var format = formatMap[key]; if (raw && typeof raw === 'object' && !Array.isArray(raw)) { value = raw.value != null ? raw.value : ''; if (raw.format) format = raw.format; } else if (raw != null) { value = raw; } set(fieldId, value, format); }); } global.IAREntityField = { get: get, set: set, clear: clear, collect: collect, populate: populate, }; })(typeof window !== 'undefined' ? window : this);