Карточки записей, таблицы, настройки сайта в Larena и формы в других
продуктах рисуют свойства одним набором —
полями по типу свойства.
Здесь каждый тип и каждый его вариант показан рядом в двух видах: как
значение читается и как оно правится. Список строится из реестра набора
SF.fieldRenderers.registry, поэтому тип, добавленный в выпуск, появляется
здесь сам.
Все типы
Переключатель «Только чтение» показывает, как поле выглядит, когда менять
его нельзя. Изменения уходят странице-хосту через setFieldValue; строка
под таблицей показывает, что хост получил.
Все типы
HTML
<div class="flex flex-col gap-3" data-type-gallery data-gallery-picture="assets/place-03-4x3.svg">
<sf-switch label="Только чтение" size="1/2" data-gallery-readonly></sf-switch>
<div class="grid grid-col-1 sm:grid-col-3 gap-2 color-on-surface-variant">
<span>Тип</span><span>Просмотр</span><span>Правка</span>
</div>
<div class="flex flex-col gap-3" data-gallery-rows></div>
<p class="m-0 color-on-surface-variant" role="status" data-gallery-log>Измените любое поле: здесь появится то, что получил хост.</p>
</div>
JavaScript
// Every property type of the renderer set, and every template, drawn by the set
// itself in the view and in the edit. The list comes from the set's own
// registry (SF.fieldRenderers.registry), so a type added to the release shows
// up here without touching the page. The page is the host: it keeps the values,
// serves the record pickers a short list and takes every write.
const gallery = document.querySelector('[data-type-gallery]');
const list = gallery.querySelector('[data-gallery-rows]');
const log = gallery.querySelector('[data-gallery-log]');
const readonlyBox = gallery.querySelector('[data-gallery-readonly]');
function whenLoader() {
if (window.SF?.whenFieldRenderers) return Promise.resolve();
return new Promise((resolve) => window.addEventListener('sf-loader-init', resolve, {once: true}));
}
const people = [
{value: 'u-1', label: 'Анна Ковалёва', avatarText: 'АК'},
{value: 'u-2', label: 'Илья Сорокин', avatarText: 'ИС'},
];
const records = [
{value: 'r-178', label: 'SIMAI: Платежи №178'},
{value: 'r-201', label: 'SIMAI: Доставка №201'},
];
const regions = [
{value: 'ru-tat', label: 'Татарстан'},
{value: 'ru-mow', label: 'Москва'},
{value: 'ru-spe', label: 'Санкт-Петербург'},
];
const statuses = [
{value: 'live', label: 'Опубликовано', color: 'success'},
{value: 'draft', label: 'Черновик', color: 'warning'},
{value: 'archived', label: 'В архиве'},
];
// A sample field and value for a type and template (null: the type's default).
function sample(type, template) {
const field = {key: template ? `${type}-${template}` : type, propertyType: type, ...(template ? {template} : {})};
switch (type) {
case 'string': return [{...field, placeholder: 'Название'}, 'SIMAI: Платежи'];
case 'phone': return [field, '+79001234567'];
case 'password': return [field, {set: true}];
case 'url': return [field, 'https://simai.io'];
case 'link': return [field, {href: 'https://simai.io', text: 'SIMAI'}];
case 'text': return [field, 'Приём платежей, возвраты и сверка с банком.'];
case 'number':
if (template === 'scale' || template === 'meter') return [field, '64'];
return [{...field, unit: 'кг', decimals: 1}, '2.5'];
case 'percent': return [field, '64'];
case 'date': return [field, '2026-10-25'];
case 'datetime': return [field, '2026-10-25T10:30:00+03:00'];
case 'time': return [field, '10:30'];
case 'boolean': return [field, true];
case 'choice': return [{...field, options: statuses}, 'live'];
case 'choices': return [{...field, options: statuses}, ['live', 'draft']];
case 'user': return [field, people[0]];
case 'record':
case 'relation': return [field, records[0]];
case 'lookup': return [{...field, options: regions}, regions[0]];
case 'file':
if (template && template.startsWith('image')) {
// A picture of the documentation set (D22), kept beside the example.
const href = gallery.dataset.galleryPicture;
const image = {label: 'Обложка.svg', mime: 'image/svg+xml', href};
return [{...field, multiple: template === 'image_list'}, template === 'image_list' ? [image, image] : image];
}
return [field, {label: 'Договор.pdf', mime: 'application/pdf', size: 184320}];
case 'color': return [field, '#005bbe'];
case 'include': return [{...field, templateParams: {language: 'html'}}, '<sf-button>Сохранить</sf-button>'];
default: return [field, null];
}
}
async function start() {
await whenLoader();
const set = await SF.whenFieldRenderers();
const {html, render} = SF;
const lang = document.documentElement.lang === 'en' ? 'en' : 'ru';
const rows = [];
for (const entry of set.registry) {
for (const template of entry.templates) {
const variant = template.default ? null : template;
const [field, value] = sample(entry.type, variant?.id);
field.label = variant ? `${entry.label[lang]}: ${variant.label[lang]}` : entry.label[lang];
rows.push({entry, variant, field, value});
}
}
const values = Object.fromEntries(rows.map((row) => [row.field.key, row.value]));
const pages = {user: people, record: records, relation: records};
const host = {
setFieldValue(field, value) {
values[field.key] = value;
log.textContent = `setFieldValue: ${field.key} = ${JSON.stringify(value)}`;
draw();
},
getFieldOptionsPage(field) {
return {items: pages[field.propertyType] || [], status: 'ready', nextCursor: null};
},
loadFieldOptions() {},
getFieldOptionSearch() { return ''; },
setFieldOptionSearch() {},
};
const nothing = (content) => (content === null || content === undefined || content === SF.nothing ? '—' : content);
function draw() {
const readonly = readonlyBox.hasAttribute('checked');
render(rows.map(({entry, variant, field}) => {
const shown = readonly ? {...field, readonly: true} : field;
return html`
<div class="grid grid-col-1 sm:grid-col-3 gap-2 items-cross-start">
<div class="flex flex-col">
<span>${field.label}</span>
<code class="sf-body-small color-on-surface-variant">${entry.type}${variant ? ` · ${variant.id}` : ''}</code>
</div>
<div>${nothing(set.renderViewField(field, values[field.key], host))}</div>
<div>${nothing(set.renderEditField(shown, values[field.key], host, {size: '1/2'}))}</div>
</div>`;
}), list);
}
readonlyBox.addEventListener('change', draw);
draw();
}
start().catch((error) => { log.textContent = error.message; });
Все типы
Как читать галерею
Тип — название и код propertyType; после точки — variant.
Просмотр — renderViewField: значение в карточке записи. Пустое
значение показано прочерком страницы.
Правка — renderEditField со ступенью 1/2: элемент управления
поля. Поля выбора записи (user, record, relation) получают короткий
список от хоста; lookup берёт варианты из options.
Файлы в галерее только показываются: загрузку хост включает методами
startFieldUpload и getFieldUploads.