/* Site Engine — stage 3 / Constructor + Expert from one Page model. Offline design prototype. */
(()=>{'use strict';
const $=(q,r=document)=>r.querySelector(q),$$=(q,r=document)=>Array.from(r.querySelectorAll(q));
const esc=s=>String(s??'').replace(/[&<>"']/g,c=>({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c]));
const clone=x=>JSON.parse(JSON.stringify(x));
const rose=document.body.dataset.theme==='rose', theme=rose?'rose':'antirion', suffix=rose?'rose-graphite':'antirion-rework';
const I={pages:'M7 3h10l4 4v14H7z M17 3v5h4 M11 13h6 M11 17h6',home:'M3 10 12 3l9 7v11H3z M9 21v-8h6v8',content:'M12 3 2 8l10 5 10-5-10-5 M2 13l10 5 10-5',publish:'M12 3v13 M7 11l5 5 5-5 M4 18v3h16v-3',image:'M3 3h18v18H3z M7 16l4-4 4 4 2-2 4 4 M8 8h.1',layers:'M3 7l9-4 9 4-9 5-9-5 M3 13l9 5 9-5',setting:'M4 7h16 M4 12h16 M4 17h16',clock:'M12 3a9 9 0 1 0 0 18a9 9 0 0 0 0-18z M12 7v5l3 2',code:'M9 7l-5 5 5 5 M15 7l5 5-5 5',blocks:'M3 3h7v7H3z M14 3h7v7h-7z M3 14h7v7H3z M14 14h7v7h-7z',plus:'M12 4v16 M4 12h16',chevron:'M9 5l7 7-7 7',up:'M12 20V4 M5 11l7-7 7 7',down:'M12 4v16 M5 13l7 7 7-7',trash:'M5 7h14 M8 7V4h8v3 M7 7l1 14h8l1-14',copy:'M8 8h12v12H8z M4 16H3V3h13v1',eye:'M2 12s3.5-6 10-6 10 6 10 6-3.5 6-10 6-10-6-10-6z M12 9a3 3 0 1 0 0 6a3 3 0 0 0 0-6z',hide:'M3 3l18 18 M2 12s3.5-6 10-6c6.5 0 10 6 10 6a17 17 0 0 1-3 3.7 M6.2 6.8C3.5 8.4 2 12 2 12s3.5 6 10 6c1.9 0 3.5-.5 4.8-1.2',check:'M4 12l5 5L20 6',alert:'M12 3 2 21h20z M12 9v5 M12 17v1',monitor:'M3 4h18v14H3z M8 21h8',tablet:'M6 2h12v20H6z',phone:'M8 2h8v20H8z',menu:'M3 7h18 M3 12h18 M3 17h18',link:'M10 13a5 5 0 0 0 7 0l3-3a5 5 0 0 0-7-7l-2 2 M14 11a5 5 0 0 0-7 0l-3 3a5 5 0 0 0 7 7l2-2',save:'M4 3h14l3 3v15H3V3z M7 3v7h10V3 M7 21v-8h10v8',filter:'M3 4h18l-7 9v7l-4 2v-9z',search:'M10 3a7 7 0 1 0 0 14a7 7 0 0 0 0-14z M15.5 15.5 21 21',arrow:'M4 12h16m-6-6 6 6-6 6',close:'M5 5l14 14 M19 5 5 19',lock:'M6 10V7a6 6 0 0 1 12 0v3 M5 10h14v11H5z',refresh:'M20 7V3h-4 M4 17v4h4 M20 11a8 8 0 0 0-14-5l-2 2 M4 13a8 8 0 0 0 14 5l2-2',more:'M4 12h2 M11 12h2 M18 12h2'};
const icon=(name)=>` `;
const sources=['literal','page.title','data.company.name','entry.title'];
const collections={services:[{title:'Telegram-боты',desc:'Автоматизируем диалоги',icon:'01'},{title:'AI-ассистенты',desc:'Интеллектуальные агенты',icon:'02'},{title:'Интеграции',desc:'Связываем процессы',icon:'03'}],scenarios:[{title:'Юридические услуги',desc:'Заявки и документы'},{title:'Недвижимость',desc:'Квалификация лидов'}],cases:[{title:'Сервисная компания',desc:'AI-квалификация обращений'}]};
const F={
hero:{name:'Hero',category:'Первый экран',desc:'Заголовок, подзаголовок и действие',fields:[['title','Заголовок','text'],['subtitle','Описание','textarea'],['button','Текст кнопки','text'],['buttonUrl','Ссылка','link']],defaults:{title:'Новая секция',subtitle:'Описание вашего предложения',button:'Обсудить проект',buttonUrl:'/request/'}},
collection_list:{name:'Список коллекции',category:'Данные',desc:'Карточки, получаемые из collection',fields:[['heading','Заголовок','text'],['collection','Коллекция','collection'],['limit','Максимум записей','number'],['sort','Сортировка','sort']],defaults:{heading:'Направления работы',collection:'services',limit:3,sort:'order'}},
section:{name:'Текстовая секция',category:'Контент',desc:'Заголовок и содержимое секции',fields:[['heading','Заголовок','text'],['text','Текст','textarea']],defaults:{heading:'Почему мы',text:'Разрабатываем решения под конкретные задачи бизнеса.'}},
steps:{name:'Этапы',category:'Контент',desc:'Три этапа реализации',fields:[['heading','Заголовок','text'],['step1','Шаг 1','text'],['step2','Шаг 2','text'],['step3','Шаг 3','text']],defaults:{heading:'Как мы работаем',step1:'Исследование',step2:'Разработка',step3:'Внедрение'}},
cta_banner:{name:'CTA-баннер',category:'Конверсия',desc:'Контрастный призыв к действию',fields:[['title','Заголовок','text'],['text','Подпись','textarea'],['button','Кнопка','text'],['buttonUrl','Ссылка','link']],defaults:{title:'Запустим ваш проект?',text:'Расскажите о задаче — подскажем решение.',button:'Оставить заявку',buttonUrl:'/request/'}},
richtext:{name:'Markdown body',category:'Контент',desc:'Выводит Markdown из файла страницы',fields:[['heading','Заголовок блока','text']],defaults:{heading:'О проекте'}},
faq:{name:'FAQ',category:'Контент',desc:'Частые вопросы',fields:[['heading','Заголовок','text'],['question','Вопрос','text'],['answer','Ответ','textarea']],defaults:{heading:'Вопросы и ответы',question:'Как начать работу?',answer:'Опишите задачу и мы подготовим план.'}},
image:{name:'Изображение',category:'Медиа',desc:'Asset из медиатеки с подписью',fields:[['asset','Медиафайл','asset'],['alt','Alt-текст','text']],defaults:{asset:'assets/team.webp',alt:'Команда разработки'}},
entry_card:{name:'Запись коллекции',category:'Данные',desc:'Карточка конкретной записи через ref',fields:[['heading','Заголовок','text'],['entry','Запись','ref']],defaults:{heading:'Рекомендуемая услуга',entry:'services/bots'}},
card_grid:{name:'Карточки',category:'Контент',desc:'Сетка преимуществ',fields:[['heading','Заголовок','text'],['card1','Карточка 1','text'],['card2','Карточка 2','text'],['card3','Карточка 3','text']],defaults:{heading:'Наши преимущества',card1:'Чёткие сроки',card2:'Прозрачность',card3:'Поддержка'}}
};
const WIDTH_MODES=['inherit','boxed','fluid','full'];
const defaultWidth=fragment=>({section_width:['hero','cta_banner'].includes(fragment)?'full':'inherit',content_width:'inherit'});
const blockLayout=b=>({...defaultWidth(b.fragment),...(b.layout||{})});
const block=(id,fragment,props={},bindings={},extra={})=>({id,fragment,props:{...F[fragment].defaults,...props},bindings,visible:true,anchor:'',note:'',layout:defaultWidth(fragment),...extra});
const seed=[
{id:'home',title:'Главная',url:'/',layout:'landing',status:'published',seo:{title:'Разработка Telegram-ботов и AI-систем',description:'Автоматизация бизнес-процессов и создание AI-решений.'},body:'Мы проектируем и внедряем Telegram-ботов, AI-ассистентов и автоматизации для бизнеса.',blocks:[
block('hero_home','hero',{title:'Автоматизируем бизнес с помощью AI',subtitle:'Telegram-боты, AI-ассистенты и интеграции, которые решают задачи, а не просто отвечают на сообщения.',button:'Обсудить проект'},{title:{kind:'literal'}}),
block('services_list','collection_list',{heading:'Наши направления',collection:'services',limit:3},{collection:{kind:'query',collection:'services'}}),
block('benefits_grid','card_grid',{heading:'Почему нам доверяют',card1:'Под задачу, а не по шаблону',card2:'Интеграции с вашим стеком',card3:'Сопровождение после запуска'}),
block('process_steps','steps'),block('cta_home','cta_banner',{title:'Обсудим вашу задачу?'})]},
{id:'services',title:'Услуги',url:'/services/',layout:'standard',status:'published',seo:{title:'Наши услуги',description:'Telegram-боты, AI и автоматизация.'},body:'Все услуги по разработке автоматизаций и AI-инструментов.',blocks:[block('services_head','hero',{title:'Сервисы и решения',subtitle:'Подберём стек и формат под процессы вашей команды.'}),block('services_query','collection_list',{collection:'services',heading:'Каталог услуг',limit:6},{collection:{kind:'query',collection:'services'}}),block('services_faq','faq')]},
{id:'about',title:'О компании',url:'/about/',layout:'standard',status:'published',seo:{title:'О студии',description:'Команда и подход.'},body:'Мы небольшая инженерная команда, ориентированная на измеримые результаты.',blocks:[block('about_intro','hero',{title:'Команда, которая делает AI полезным',subtitle:'От идеи до работающего продукта.'}),block('body_about','richtext'),block('team_asset','image',{asset:'assets/team.webp',alt:'Команда студии'})]},
{id:'contacts',title:'Контакты',url:'/contacts/',layout:'standard',status:'draft',seo:{title:'Контакты студии',description:'Свяжитесь с нами.'},body:'Оставьте заявку, чтобы обсудить проект.',blocks:[block('contacts_head','hero',{title:'Давайте знакомиться',subtitle:'Расскажите нам о вашей задаче.'}),block('contacts_cta','cta_banner',{buttonUrl:'/request/'})]},
{id:'request',title:'Заявка',url:'/request/',layout:'standard',status:'draft',seo:{title:'Обсудить проект',description:''},body:'Заполните форму на сайте.',blocks:[block('request_head','hero',{title:'Расскажите о задаче',subtitle:'Мы свяжемся с вами после уточнения деталей.'}),block('request_body','richtext')]}
];
const COLLECTION_META={services:{name:'Услуги',path:'collections/services.yaml'},scenarios:{name:'Сценарии',path:'collections/scenarios.yaml'},cases:{name:'Кейсы',path:'collections/cases.yaml'},courses:{name:'Курсы',path:'collections/courses.yaml'},posts:{name:'Публикации',path:'collections/posts.yaml'}};
const ENTRIES=[
{id:'services/bots',title:'Telegram-боты',slug:'bots',collection:'services',status:'published',order:1,desc:'Автоматизируем диалоги и заявки',asset:'assets/bots.webp',url:'/services/bots/'},
{id:'services/ai',title:'AI-ассистенты',slug:'ai',collection:'services',status:'published',order:2,desc:'Интеллектуальные агенты для бизнеса',asset:'assets/ai.webp',url:'/services/ai/'},
{id:'services/automation',title:'Интеграции',slug:'automation',collection:'services',status:'draft',order:3,desc:'Связываем процессы и системы',asset:'assets/automation.webp',url:'/services/automation/'},
{id:'scenarios/legal',title:'Юридические услуги',slug:'legal',collection:'scenarios',status:'published',order:1,desc:'Заявки и документы',asset:'assets/legal.webp',url:'/scenarios/legal/'},
{id:'scenarios/real-estate',title:'Недвижимость',slug:'real-estate',collection:'scenarios',status:'draft',order:2,desc:'Квалификация лидов',asset:'assets/houses.webp',url:'/scenarios/real-estate/'},
{id:'cases/support',title:'Поддержка клиентов',slug:'support',collection:'cases',status:'published',order:1,desc:'AI-квалификация обращений',asset:'assets/case.webp',url:'/cases/support/'}
];
const ASSETS=[{path:'assets/team.webp',name:'Команда студии',type:'image/webp',status:'ready'}, {path:'assets/hero.webp',name:'Фон главной страницы',type:'image/webp',status:'ready'}, {path:'assets/bots.webp',name:'Иконка ботов',type:'image/webp',status:'ready'}, {path:'assets/ai.webp',name:'AI-ассистенты',type:'image/webp',status:'ready'}, {path:'assets/missing.webp',name:'Удалённый файл',type:'image/webp',status:'missing'}];
const DATA={company:{name:'Flexly Studio',tagline:'AI, Telegram и автоматизация',email:'hello@studio.example'}};
const entryById=id=>ENTRIES.find(e=>e.id===id),assetByPath=path=>ASSETS.find(a=>a.path===path&&a.status==='ready');
const visibleEntries=(collection,sort='order',limit=6)=>{
let items=ENTRIES.filter(e=>e.collection===collection&&e.status!=='archived');
if(sort==='title')items.sort((a,b)=>a.title.localeCompare(b.title,'ru'));else items.sort((a,b)=>a.order-b.order);
return items.slice(0,Math.max(1,Math.min(12,Number(limit)||6)));
};
const urlKnown=value=>!value||/^(https?:\/\/|mailto:|tel:|#)/i.test(value)||s.pages.some(p=>p.url===value)||ENTRIES.some(e=>e.url===value&&e.status==='published');
const resolveValue=(b,key,p=page())=>{
const val=b?.props?.[key]??'';
const binding=b?.bindings?.[key];
if(binding?.kind==='bind'){
const path=binding.path;
if(path==='page.title')return {kind:'bind',source:path,value:p.title,valid:!!p.title};
if(path==='page.url')return {kind:'bind',source:path,value:p.url,valid:!!p.url};
if(path==='page.seo.title')return {kind:'bind',source:path,value:p.seo?.title||'',valid:!!p.seo?.title};
if(path.startsWith('data.company.')){const key=path.split('.')[2];return {kind:'bind',source:path,value:DATA.company[key]??'',valid:key in DATA.company};}
if(path==='entry.title'){const e=entryById(b.props?.entry);return {kind:'bind',source:path,value:e?.title||'⚠ запись не найдена',valid:!!e};}
return {kind:'bind',source:path,value:'⚠ источник не найден',valid:false};
}
if(key==='collection')return {kind:'query',source:val,value:`${val} · ${visibleEntries(val,b.props?.sort,b.props?.limit).length} записей`,valid:val in COLLECTION_META};
if(key==='entry')return {kind:'ref',source:val,value:entryById(val)?.title||'⚠ запись не найдена',valid:!!entryById(val)};
if(key==='asset')return {kind:'asset',source:val,value:assetByPath(val)?.name||'⚠ медиафайл не найден',valid:!!assetByPath(val)};
if(/Url$/.test(key))return {kind:'link',source:val,value:val||'Не задано',valid:urlKnown(val)};
return {kind:'literal',source:'props.'+key,value:String(val),valid:true};
};
const bindingIssue=(b,key,p=page())=>{
const v=resolveValue(b,key,p);
if(!v.valid)return {level:v.kind==='asset'?'warn':'error',text:`${b.id}.props.${key}: ${v.kind==='asset'?'медиафайл':'источник'} ${v.source||'—'} недоступен`};
if(key==='entry'){const e=entryById(b.props.entry);if(e?.status==='draft')return {level:'warn',text:`${b.id}.props.entry: ${e.id} ещё не опубликована`};}
if(/Url$/.test(key)&&b.props[key]){const target=s.pages.find(p=>p.url===b.props[key])||ENTRIES.find(e=>e.url===b.props[key]);if(target&&target.status!=='published')return {level:'warn',text:`${b.id}.props.${key}: ссылка ${b.props[key]} ведёт на неопубликованный материал`};}
if(key==='collection'&&visibleEntries(b.props.collection,b.props.sort,b.props.limit).length===0)return {level:'warn',text:`${b.id}.props.collection: коллекция ${b.props.collection} пуста`};
return null;
};
function whereUsed(type,id){const usages=[];
for(const p of s.pages)for(const b of p.blocks){
const matching=[];
for(const [key,val] of Object.entries(b.props||{})){
if(type==='collection'&&key==='collection'&&val===id)matching.push({key,mode:'query'});
if(type==='entry'&&key==='entry'&&val===id)matching.push({key,mode:'ref'});
if(type==='asset'&&key==='asset'&&val===id)matching.push({key,mode:'asset'});
if(type==='page'&&/Url$/.test(key)&&val===id)matching.push({key,mode:'link'});
}
for(const [key,bind] of Object.entries(b.bindings||{})){
if(type==='data'&&bind?.kind==='bind'&&bind.path===id)matching.push({key,mode:'bind'});
if(type==='entry'&&bind?.path==='entry.title'&&b.props.entry===id&&!matching.some(x=>x.key==='entry'))matching.push({key,mode:'bind'});
}
if(type==='entry'&&b.fragment==='collection_list'&&b.props.collection===id.split('/')[0])matching.push({key:'collection',mode:'query (динамически)'});
for(const m of matching)usages.push({page:p.id,title:p.title,block:b.id,fragment:b.fragment,...m});
}
return usages;
}
function usageButton(type,id,label='Где используется?'){return `${icon('link')} ${label} `;}
function targetKind(b,key){const f=F[b.fragment]?.fields.find(x=>x[0]===key);return f?.[2]||'text';}
function fieldSourceChoices(b,key){const typ=targetKind(b,key);
if(typ==='collection')return [{kind:'collection',title:'Коллекция',items:Object.entries(COLLECTION_META).map(([id,item])=>({id,title:item.name,detail:item.path,count:ENTRIES.filter(e=>e.collection===id).length}))},{kind:'collection',title:'Ошибочный источник (демо)',items:[{id:'missing_collection',title:'missing_collection',detail:'Нет файла collections/missing_collection.yaml',invalid:true}]}];
if(typ==='asset')return [{kind:'asset',title:'Медиатека',items:ASSETS.map(a=>({id:a.path,title:a.name,detail:a.path,invalid:a.status==='missing'}))}];
if(typ==='ref')return [{kind:'entry',title:'Записи коллекций',items:ENTRIES.map(e=>({id:e.id,title:e.title,detail:`${e.collection} · ${e.status}`,warning:e.status==='draft'})).concat([{id:'services/ghost',title:'Удалённая запись',detail:'Отсутствует content/services/ghost.md',invalid:true}])}];
if(typ==='link')return [{kind:'page',title:'Страницы сайта',items:s.pages.map(p=>({id:p.url,title:p.title,detail:`pages/${p.id}.md · ${p.status}`})).concat([{id:'/missing/',title:'Несуществующая страница',detail:'Нет подходящего route',invalid:true}])},{kind:'page',title:'Публичные записи',items:ENTRIES.map(e=>({id:e.url,title:e.title,detail:e.collection,warning:e.status!=='published'}))}];
return [{kind:'literal',title:'Значение из блока',items:[{id:'literal',title:'Literal',detail:'props.'+key+' — ручное значение'}]}, {kind:'bind',title:'Поля страницы',items:[{id:'page.title',title:'Название страницы',detail:'{bind: page.title}'},{id:'page.url',title:'URL страницы',detail:'{bind: page.url}'},{id:'page.seo.title',title:'SEO-заголовок',detail:'{bind: page.seo.title}'}]}, {kind:'bind',title:'Общие данные · data/company.yaml',items:[{id:'data.company.name',title:'Название студии',detail:'{bind: data.company.name}'},{id:'data.company.tagline',title:'Слоган',detail:'{bind: data.company.tagline}'},{id:'data.company.email',title:'Email',detail:'{bind: data.company.email}'}]}, {kind:'bind',title:'Запись (контекст)',items:[{id:'entry.title',title:'Заголовок записи',detail:'{bind: entry.title} · только при выбранной entry'}]}];
}
function pickerModal(key){const b=current();if(!b)return;s.picker={key};
const groups=fieldSourceChoices(b,key);
modal('Выбрать источник данных',`${b.id} / props.${key} · без ручного YAML`,
`
${icon('layers')} ${esc(page().id)} → ${esc(page().layout)} → main → ${esc(b.id)} → ${esc(b.fragment)} → props.${esc(key)}
${renderChoices(groups,'')}
`,button('Отмена','close'));
}
function renderChoices(groups,term){const q=term.toLowerCase().trim();return groups.map(g=>{
const items=g.items.filter(i=>(i.id+' '+i.title+' '+i.detail).toLowerCase().includes(q));
if(!items.length)return '';
return `${esc(g.title)} ${items.length}
${items.map(i=>`
${icon(g.kind==='asset'?'image':g.kind==='collection'?'content':g.kind==='page'?'link':'layers')} ${esc(i.title)} ${esc(i.detail)} ${i.invalid?'Ошибка':i.warning?'Черновик':g.kind==='literal'?'Literal':'Выбрать'} `).join('')}
`;
}).join('')||'Ничего не найдено Попробуйте другой запрос
';
}
function applyPicked(kind,value){const b=current(),key=s.picker?.key;if(!b||!key)return;
if(kind==='bind'){b.bindings[key]={kind:'bind',path:value};}
else if(kind==='literal'){delete b.bindings[key];}
else if(kind==='collection'){b.props[key]=value;b.bindings[key]={kind:'query',collection:value};}
else {b.props[key]=value;delete b.bindings[key];}
const wasLive=s.view==='live';close();s.tab='bindings';s.treeView='mapping';s.view='draft';renderHead();renderTree();renderInspector();if(wasLive)renderStage();else renderPreview();toast(`${b.id}.props.${key} · источник обновлён в workspace`);
}
function usageModal(type,id){const refs=whereUsed(type,id), relatedEntries=type==='asset'?ENTRIES.filter(e=>e.asset===id):[], human={collection:'Collection',entry:'Entry',asset:'Asset',page:'Page / URL',data:'Data'};
modal('Где используется?',`${human[type]||type}: ${id} · поиск по демо-workspace`,
`${refs.length+relatedEntries.length} использований ${esc(id)}
${refs.length?refs.map(r=>`${esc(r.title)} ${esc(r.page)} → main → ${esc(r.block)} → ${esc(r.key)} (${esc(r.mode)}) ${icon('arrow')} `).join(''):'Прямых зависимостей не найдено В демо-workspace нет блоков, использующих этот источник.
'}
${relatedEntries.length?`Использование в записях
${relatedEntries.map(e=>`${esc(e.title)} content/${esc(e.id)}.md → asset: ${esc(id)}
`).join('')}`:''}
Динамическое использование записи через collection_list показано отдельно. Реальные зависимости определит сервис индексации Site Engine.
`,button('Закрыть','close'));
}
function jumpToUsage(pageId,blockId){close();if(!s.pages.some(p=>p.id===pageId))return;s.selectedPage=pageId;s.selected=blockId;s.treeView='mapping';s.tab='bindings';s.view='draft';pendingPreviewNavigate=blockId;renderAll();toast(`Найдено использование: ${pageId} / ${blockId}`);}
function mappingDataChip(type,id){return `${esc(id)} ${usageButton(type,id,'Связи')}`;}
function libraryModal(){modal('Каталог данных','Демо-источники Site Engine · один сайт',
`Коллекции
${Object.entries(COLLECTION_META).map(([id,item])=>`
${esc(item.name)} ${esc(item.path)} · ${ENTRIES.filter(e=>e.collection===id).length} записей ${usageButton('collection',id)}
`).join('')}
Записи
${ENTRIES.map(e=>`
${esc(e.title)} content/${esc(e.id)}.md · ${e.status} ${usageButton('entry',e.id)}
`).join('')}
Ассеты
${ASSETS.map(a=>`
${esc(a.name)} ${esc(a.path)} · ${a.status} ${usageButton('asset',a.path)}
`).join('')}
Общие данные
${Object.keys(DATA.company).map(k=>`
${esc(k)} data.company.${k} ${usageButton('data','data.company.'+k)}
`).join('')}
`,button('Закрыть','close'));}
function blockIssues(b,p=page()){const fields=F[b.fragment]?.fields||[];return fields.map(([key])=>bindingIssue(b,key,p)).filter(Boolean);}
const STORAGE='site-engine-stage2-constructor-v1',savedPayload=(()=>{try{return JSON.parse(localStorage.getItem(STORAGE))}catch{return null}})();
let s={pages:seed,selectedPage:'home',selected:'hero_home',mode:'constructor',treeView:'tree',tab:'props',device:'desktop',view:'draft',layoutSidebar:false,mobileNav:false,catalog:false,catalogGroup:'Все',catalogQuery:'',modal:null,toastTimer:null,savedPages:clone(seed),livePages:clone(seed),dirty:false,savedAt:savedPayload?.savedAt||null,reviewFilter:'all',compareMode:'live',compareTab:'changes'};
if(savedPayload?.pages?.length){s.pages=savedPayload.pages;s.savedPages=clone(savedPayload.pages);s.selectedPage=s.pages[0].id;s.selected=s.pages[0].blocks[0]?.id||'header';}
const page=()=>s.pages.find(x=>x.id===s.selectedPage),livePage=()=>s.livePages.find(x=>x.id===s.selectedPage)||page();
const current=()=>page().blocks.find(b=>b.id===s.selected),isFixed=()=>s.selected==='site_header'||s.selected==='site_footer',anyDirty=()=>JSON.stringify(s.pages)!==JSON.stringify(s.savedPages);
const effective=(b,k,p=page())=>resolveValue(b,k,p).value;
let pendingPreviewNavigate=null; // target after iframe remount (add/move)
const requestedPage=new URL(location.href).searchParams.get('page');
if(requestedPage&&s.pages.some(p=>p.id===requestedPage)){s.selectedPage=requestedPage;s.selected=page().blocks[0]?.id||'site_header';}
const newID=type=>`${type}_${Math.random().toString(36).slice(2,8)}`;
function button(text,action,kind='',more=''){return `${text} `}
function toast(message){const box=$('#toast');box.textContent=message;box.style.display='block';clearTimeout(s.toastTimer);s.toastTimer=setTimeout(()=>box.style.display='none',3200)}
function changedCount(){return s.pages.reduce((sum,p)=>{const base=s.savedPages.find(x=>x.id===p.id);return sum+(JSON.stringify(p)!==JSON.stringify(base)?1:0)},0)}
function markDirty(){s.dirty=anyDirty();const l=$('[data-statusbar]');if(l)l.innerHTML=s.dirty?'● Не сохранено ':'✓ Черновик сохранён ';const title=$('[data-pagehead]');if(title)title.textContent=page().title;const hint=$('[data-savehint]');if(hint)hint.textContent=s.dirty?`${changedCount()} стр. с несохранёнными правками`:s.savedAt?`Локально сохранено · ${s.savedAt}`:'Исходный mock workspace';const counters=$('[data-checksummary]');if(counters){const report=validateDetailed(),errs=report.filter(x=>x.level==='error').length;const warns=report.length-errs;counters.innerHTML=`${errs} ошибок ${warns} предупреждений `;}}
function shell(){const active='pages';$('#app').innerHTML=``;renderAll();}
function renderHead(){const p=page();const modeLabel=$('.breadcrumbs strong');if(modeLabel)modeLabel.textContent=s.mode==='expert'?'Эксперт':'Конструктор';$('#head').innerHTML=`Page editor / Stage 3 · Конструктор ↔ Эксперт · mock ${esc(p.title)} ${esc(p.url)} · pages/${p.id==='home'?'index':p.id}.md${esc(p.status)}
${s.pages.map(x=>`${esc(x.title)} `).join('')} Конструктор Эксперт
${button(icon('check')+' Проверить','validate')}${button(icon('code')+' Сравнить','diff')}${button(icon('refresh')+' Отменить','reset','')}${button(icon('save')+' Сохранить черновик','save','primary')}
`;markDirty();}
function renderTree(){const oldScroll=$('#treepane .pane-scroll')?.scrollTop||0;let p=page();const all=p.blocks;const menu=[['tree','Дерево блоков'],['mapping','Связи данных']].map(([key,label])=>`${label} `).join('');const fixed=(id,label)=>`${icon('lock')}${label} ${id} · locked `;
const items=all.map(b=>`${icon(b.fragment==='image'?'image':b.fragment==='collection_list'?'content':'blocks')} ${esc(F[b.fragment].name)} ${esc(b.id)} ${!b.visible?icon('hide'):''}${blockIssues(b,p).length?'! ':''}${b.bindings?.collection?.kind==='query'?' ':''} `).join('');
$('#treepane').innerHTML=`Структура страницы ${p.blocks.length} блоков · ${esc(p.layout)}
${icon('plus')} ${menu}
`;const currentScroll=$('#treepane .pane-scroll');if(currentScroll)currentScroll.scrollTop=oldScroll;}
function mappingHTML(){const p=page(),issues=p.blocks.flatMap(b=>blockIssues(b,p));const total=p.blocks.reduce((sum,b)=>sum+F[b.fragment].fields.length,0);
return `Карта источников Page → Layout → Region → Block → Fragment → props → Источник → Вывод.
${total} полей ${p.blocks.length} блоков ${issues.length} проблем
${icon('layers')} Каталог данных ${p.blocks.map(b=>{const edges=F[b.fragment].fields.map(([key])=>{const res=resolveValue(b,key,p),issue=bindingIssue(b,key,p);return `${esc(key)} ${esc(res.kind)} ${esc(res.kind==='literal'?String(res.value).slice(0,38):res.source||res.value)} ↗
`}).join('');const problems=blockIssues(b,p);return `${icon('blocks')} ${esc(b.id)} Page ${esc(p.id)} → ${esc(p.layout)} → main → ${esc(b.fragment)} ${edges}${problems.map(q=>`
${icon('alert')} ${esc(q.text)}
`).join('')}
`}).join('')}`}
function stageToolbar(){return ``}
function renderStage(){let el=$('#stagepane');el.innerHTML=stageToolbar()+`
`;renderPreview();}
function sourceOf(b,key){let binding=b.bindings?.[key];return binding?.kind==='bind'?binding.path:'literal'}
function bindingControl(b,key){let source=sourceOf(b,key);return `Literal page.title data.company.name entry.title `}
function fieldHTML(b,[key,name,type]){
const res=resolveValue(b,key),bound=res.kind==='bind';const issue=bindingIssue(b,key);
const textArea=type==='textarea';let input='';
if(type==='collection')input=`${Object.keys(COLLECTION_META).concat(b.props[key]&&!COLLECTION_META[b.props[key]]?[b.props[key]]:[]).map(k=>`${esc(COLLECTION_META[k]?.name||k)} `).join('')} `;
else if(type==='sort')input=`По порядку (order) По заголовку (title) `;
else if(type==='asset'||type==='ref'||type==='link')input=`${esc(res.source||'не задано')} ${icon('search')} Выбрать
`;
else if(textArea)input=``;
else input=` `;
const isBindable=['text','textarea'].includes(type);
const sourceControl=isBindable?`${esc(bound?res.source:'literal')} ${icon('link')} `:'';
const status=issue?`${icon('alert')} ${esc(issue.text)}
`:`${res.kind==='literal'?'Хранится в props блока':res.kind==='query'?`Запрос: ${esc(res.source)} · sort: ${esc(b.props.sort||'order')} · limit: ${esc(b.props.limit)}`:`${esc(res.kind)} → ${esc(String(res.value).slice(0,80))}`} `;
return `${esc(name)} ${sourceControl} ${input}${status} `;
}
function fixedInspector(){let header=s.selected==='site_header';return `
${header?'Шапка сайта':'Подвал сайта'} ${header?'site_header':'site_footer'}${icon('lock')} Fixed Этот блок закреплён за регионом ${header?'header':'footer'} в layout. В MVP его нельзя переместить или удалить.
Откуда берутся данные
site.yaml data/company.yaml menus/main.yaml
Шаблон и его код доступны пользователю с ролью developer. Здесь показана только связь.
`}
function blockWidthControls(b){const layout=blockLayout(b);const options=[['inherit','Наследовать'],['boxed','Boxed'],['fluid','Fluid'],['full','Full Width']];return `Макет блока · ширина
Внешняя секция / фон ${options.map(([v,label])=>`${label} `).join('')} Контент внутри секции ${options.map(([v,label])=>`${label} `).join('')} Пример: фон Hero — Full Width, текст — Boxed. Наследовать использует настройки темы публичного сайта; сохраняется в layout блока.
`;}
function blockProps(b){return `
${esc(F[b.fragment].name)} ${esc(b.id)} / ${esc(b.fragment)}${b.visible?'Виден':'Скрыт'} ${F[b.fragment].fields.map(field=>fieldHTML(b,field)).join('')}${blockWidthControls(b)}${b.fragment==='richtext'?'Внимание: содержимое выводится из Markdown body текущей страницы. Изменить его можно во вкладке «Страница».
':''}${b.fragment==='image'&&b.props.asset==='assets/missing.webp'?'Asset не найден: assets/missing.webp. Проверьте ссылку.
':''}${b.fragment==='collection_list'&&b.props.collection==='missing_collection'?'Коллекция не найдена: missing_collection.
':''}
Anchor Заметка редактора Показывать блок на страницеУправление блоком
${button(icon('up')+' Выше','move-up','small')}${button(icon('down')+' Ниже','move-down','small')}
${button(icon('copy')+' Дублировать','duplicate','small')}${button(icon(b.visible?'hide':'eye')+' '+(b.visible?'Скрыть':'Показать'),'visibility','small')}${button(icon('trash')+' Удалить','delete','small danger')}
`}
function blockBindings(b){const p=page(),fields=F[b.fragment].fields;
const edges=fields.map(([key,label])=>{const res=resolveValue(b,key,p),issue=bindingIssue(b,key,p);let usage='';
if(res.kind==='query')usage=usageButton('collection',b.props.collection);
else if(res.kind==='ref')usage=usageButton('entry',b.props.entry);
else if(res.kind==='asset')usage=usageButton('asset',b.props.asset);
else if(res.kind==='link')usage=usageButton('page',b.props[key]);
else if(res.kind==='bind')usage=usageButton(res.source==='entry.title'?'entry':'data',res.source==='entry.title'?b.props.entry:res.source);
return `${esc(label)} ${esc(res.kind)}
props.${esc(key)} → ${esc(res.source)}
${icon(issue?'alert':'check')} ${esc(String(res.value).slice(0,120))}
${issue?`
${esc(issue.text)}
`:''}
${icon('search')} Сменить источник ${usage}
`;
}).join('');
return `
Маппинг источников ${esc(b.id)}${blockIssues(b,p).length?'Есть проблемы':'Связи корректны'} ${esc(p.id)} → ${esc(p.layout)} → main → ${esc(b.id)} → ${esc(b.fragment)}
${edges}
${icon('layers')} Каталог данных Источник выбирается из UI и сохраняется в props/bindings документа. Query DSL ограничен collection, sort и limit. Реальная проверка и права — за сервером.
`;
}
function pageDiagnostics(p){const list=[];const push=(key,text,level='warn')=>list.push({key,text,level});if(!p.title.trim())push('title','Название страницы обязательно','error');if(!p.url.startsWith('/')||p.url.includes(' '))push('url','URL должен начинаться с / и не содержать пробелов','error');if(s.pages.some(x=>x.id!==p.id&&x.url===p.url))push('url','Такой URL уже используется другой страницей','error');if(!p.seo.title.trim())push('seo.title','SEO title не задан');if(p.seo.title.length>70)push('seo.title','SEO title длиннее 70 символов');if(!p.seo.description.trim())push('seo.description','SEO description не задан');if(p.seo.description.length>160)push('seo.description','SEO description длиннее 160 символов');if(p.body.trim()&&!p.blocks.some(b=>b.fragment==='richtext'&&b.visible))push('body','Markdown body заполнен, но не выводится видимым richtext');return list;}
function fieldDiagnostic(p,key){const found=pageDiagnostics(p).filter(x=>x.key===key);return found.map(x=>`${icon('alert')} ${esc(x.text)}
`).join('')}
function markdownHTML(raw){const inline=x=>esc(x).replace(/\*\*(.+?)\*\*/g,'$1 ').replace(/`([^`]+)`/g,'$1').replace(/\*([^*]+)\*/g,'$1 ').replace(/\[([^\]]+)\]\((https?:\/\/[^\s)]+)\)/g,'$1 ');let inList=false;return String(raw||'').split(/\r?\n/).map(line=>{const t=line.trim();if(!t){if(inList){inList=false;return ''}return '';}if(/^#{1,3}\s/.test(t)){const n=t.match(/^#+/)[0].length;return `${inList?'':''}${inline(t.slice(n).trim())} `;}if(/^[-*]\s/.test(t)){const first=inList?'':'';inList=true;return `${first}${inline(t.slice(2))} `;}const close=inList?' ':'';inList=false;return close+`${inline(t)}
`;}).join('')+(inList?'':'');}
function pageTab(){let p=page(),diags=pageDiagnostics(p),hasBody=p.blocks.some(b=>b.fragment==='richtext'&&b.visible);return `
Свойства страницы pages/${p.id==='home'?'index':p.id}.md${diags.length?diags.length+' замечаний':'Проверено'}
Изменения — в workspace. Save draft ≠ Publish . Для публикации понадобится проверенный release candidate.
Название ${fieldDiagnostic(p,'title')}
URL / route ${fieldDiagnostic(p,'url')}
Layout landing standard
Статус файла published draft archived status: published не значит, что последняя правка уже в live.
SEO Search preview
SEO title ${p.seo.title.length}/70 ${fieldDiagnostic(p,'seo.title')}
SEO description ${p.seo.description.length}/160 ${fieldDiagnostic(p,'seo.description')}
studio.example${esc(p.url)}
${esc(p.seo.title||p.title||'Название страницы')}
${esc(p.seo.description||'Описание страницы пока не заполнено.')}
Markdown body pages/*.md
Содержимое страницы Markdown принадлежит Page, не полю Fragment. Вывод: ${hasBody?'видимый richtext':'richtext отсутствует / скрыт'}. ${fieldDiagnostic(p,'body')}
Markdown → preview (упрощённый, безопасный) ${markdownHTML(p.body)}
${!hasBody?button(icon('plus')+' Добавить richtext для body','add-richtext','small'):''}`;}
function renderInspector(){let blockSel=isFixed(),b=current();const tabs=[['props','Свойства'],['bindings','Связи'],['page','Страница']];$('#inspectpane').innerHTML=`Инспектор Схема полей Fragment
${icon('setting')}
${tabs.map(([id,label])=>`${label} `).join('')}
`;}
function renderAll(){if(s.mode==='expert'){renderExpert();return;}$('#builder')?.classList.remove('expert-layout');renderHead();renderTree();renderStage();renderInspector()}
const previewCss=`*{box-sizing:border-box}body{margin:0;background:#fbfaf7;color:#191e23;font:14px/1.6 Inter,Arial,sans-serif}a{color:inherit;text-decoration:none}.inner{max-width:1080px;padding:0 36px;margin:auto}.site-header{border-bottom:1px solid #e5e4e0;background:#fff;position:sticky;top:0;z-index:1}.site-header .inner{display:flex;align-items:center;height:62px;gap:24px;justify-content:space-between}.site-header b{font-size:15px;letter-spacing:-.05em}.brandmark{display:inline-grid;place-items:center;width:26px;height:26px;background:#141b25;color:white;margin-right:8px;border-radius:5px}.site-header nav{display:flex;gap:19px;color:#6f747c;font-size:12px}.site-header nav span{white-space:nowrap}.site-header .smallbtn{background:#1e2938;color:white;border-radius:5px;padding:6px 12px;font-size:11px}.hero{background:radial-gradient(circle at 90% 7%,#d9d2ff 0%,transparent 33%),linear-gradient(145deg,#1e2735 0%,#15202d 55%,#31344a 100%);color:white;padding:84px 0 90px;min-height:330px}.hero .tag{font-size:10px;color:#c5d1e8;letter-spacing:.13em;text-transform:uppercase}.hero h1{font-size:clamp(30px,4.2vw,54px);line-height:1.14;letter-spacing:-.065em;max-width:700px;margin:17px 0}.hero p{font-size:14px;color:#bbc6d6;max-width:560px}.hero a,.cta a{display:inline-block;background:#d4beff;color:#212438;font-weight:750;font-size:12px;padding:11px 18px;border-radius:5px;margin-top:21px}.section{padding:58px 0}.section.alt{background:#f0f1ef}.section h2{font-size:30px;letter-spacing:-.055em;margin:0 0 13px}.section p{max-width:720px;color:#5a6670;margin:0}.cards{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:15px;margin:25px 0 0}.card{border:1px solid #e0e1de;border-radius:7px;background:white;padding:22px 20px;min-height:122px}.card small{color:#9d92cf;font-weight:800}.card strong{font-size:16px;display:block;margin:14px 0 5px;line-height:1.3}.card p{font-size:12px}.steps{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:25px;margin-top:23px}.steps div{border-top:1px solid #ccd0d8;padding-top:13px}.steps span{display:block;color:#8e7cc9;font-size:11px;font-weight:700}.steps b{font-size:17px}.cta{padding:54px 0;background:#dfe3f2}.cta h2{font-size:35px;letter-spacing:-.06em;margin:0 0 8px}.cta a{background:#1d2432;color:white}.site-footer{background:#18202b;color:#bfc7d1;padding:25px 0;font-size:11px}.site-footer .inner{display:flex;justify-content:space-between}.section[data-bid],.hero[data-bid],.cta[data-bid]{position:relative;cursor:pointer;outline-offset:-3px}.section[data-bid]:hover,.hero[data-bid]:hover,.cta[data-bid]:hover{outline:2px dashed #a085ed}.sel{outline:3px solid #9a6cfa!important;outline-offset:-3px}.sel::after{content:'SELECTED';position:absolute;top:0;right:0;background:#925de0;color:white;font:10px monospace;padding:4px 8px;z-index:2}.hiddenblock{opacity:.48;filter:grayscale(.5)}.hiddenblock::before{content:'СКРЫТ — только в Конструкторе';position:absolute;inset:0 auto auto 0;background:#ad6b2c;color:white;font-size:10px;padding:2px 7px;z-index:2}.imgbox{background:linear-gradient(135deg,#d0d5e0,#a7aed1);height:180px;display:grid;place-items:center;color:#525f87;margin:20px 0;border-radius:7px}.markdown-content h1,.markdown-content h2,.markdown-content h3{font-size:22px;margin:13px 0 9px}.markdown-content p{margin:6px 0 10px;max-width:720px}.markdown-content ul{padding-left:21px;color:#566070}.markdown-content a{color:#5d52b6;text-decoration:underline}.faqcard{padding:15px 0;border-bottom:1px solid #d6d8dc}.faqcard b{display:block;font-size:15px;margin-bottom:5px}@media(max-width:600px){.inner{padding:0 20px}.site-header nav{display:none}.site-header .smallbtn{display:none}.hero{padding:57px 0}.hero h1{font-size:33px}.section{padding:38px 0}.section h2{font-size:25px}.cards,.steps{grid-template-columns:1fr}.card{min-height:0}.cta h2{font-size:29px}.site-footer .inner{display:block}}`;
function currentThemeContainer(){const fallback={mode:'boxed',max_width:1080,gutter:{desktop:32,tablet:24,mobile:16}};try{const stored=JSON.parse(localStorage.getItem('site-engine-theme-manager-v1')||'null');const c=stored?.tokens?.ui?.container;if(typeof c==='number')return {...fallback,max_width:c};if(!c||!['boxed','fluid','full'].includes(c.mode))return fallback;return {mode:c.mode,max_width:Number(c.max_width)||1080,gutter:{...fallback.gutter,...(c.gutter||{})}};}catch{return fallback;}}
const previewContainer=currentThemeContainer();
const layoutCss=`
:root{--preview-gutter:${previewContainer.gutter.desktop}px;--preview-container:${previewContainer.max_width}px;--preview-mode:${previewContainer.mode}}
[data-section-width=boxed]{width:calc(100% - 2 * var(--preview-gutter));max-width:var(--preview-container);margin-inline:auto}
[data-section-width=fluid]{width:calc(100% - 2 * var(--preview-gutter));max-width:none;margin-inline:auto}
[data-section-width=full]{width:100%;max-width:none;margin-inline:0}
[data-content-width=boxed] .inner{max-width:var(--preview-container);padding-inline:var(--preview-gutter)}
[data-content-width=fluid] .inner{max-width:none;padding-inline:var(--preview-gutter)}
[data-content-width=full] .inner{max-width:none;padding-inline:0}
[data-content-width=inherit] .inner{max-width:var(--preview-container);padding-inline:var(--preview-gutter)}
[data-section-width=inherit]{width:100%}
@media(max-width:1023px){:root{--preview-gutter:${previewContainer.gutter.tablet}px}}
@media(max-width:700px){:root{--preview-gutter:${previewContainer.gutter.mobile}px}}
`;
function previewSection(b,p){const v=k=>esc(effective(b,k,p));const sel=b.id===s.selected?'sel':'';const hidden=!b.visible?'hiddenblock':'';const layout=blockLayout(b);const outer=layout.section_width==='inherit'?previewContainer.mode:layout.section_width;const inner=layout.content_width==='inherit'?previewContainer.mode:layout.content_width;const att=`data-bid="${esc(b.id)}" data-section-width="${esc(outer)}" data-content-width="${esc(inner)}" class="${b.fragment==='hero'?'hero':b.fragment==='cta_banner'?'cta':'section'} ${sel} ${hidden}"`;let content='';
switch(b.fragment){
case'hero':content=``;break;
case'collection_list':{let records=visibleEntries(b.props.collection,b.props.sort||'order',b.props.limit);
content=`${v('heading')} Технологические решения для ваших процессов.
${records.map((r,i)=>`
0${i+1} / ${esc(r.collection.toUpperCase())}${r.status==='draft'?' · DRAFT':''} ${esc(r.title)} ${esc(r.desc)}
`).join('')||'
Коллекция не найдена / пустой результат.
'}
`;break;}
case'entry_card':{const r=entryById(b.props.entry);content=`${v('heading')} ${r?`
${esc(r.collection.toUpperCase())} / ${esc(r.status)} ${esc(r.title)} ${esc(r.desc)}
`:'
⚠ Связанная запись отсутствует
'}
`;break;}
case'section':content=`${v('heading')} ${v('text')}
`;break;
case'steps':content=`${v('heading')} ${['step1','step2','step3'].map((k,i)=>`
0${i+1} ${v(k)}
`).join('')}
`;break;
case'cta_banner':content=``;break;
case'richtext':content=`${v('heading')} ${markdownHTML(p.body)}
`;break;
case'faq':content=`${v('heading')} ${v('question')} ${v('answer')}
`;break;
case'image':content=`${!assetByPath(b.props.asset)?'⚠ Asset не найден':'◈ '+v('alt')}
`;break;
case'card_grid':content=`${v('heading')} ${['card1','card2','card3'].map((k,i)=>`
0${i+1} / VALUE ${v(k)} Практичный подход к реализации проекта.
`).join('')}
`;break;
}return content;}
function renderPreview(){const frame=$('#preview');if(!frame)return;const p=s.view==='live'?livePage():page();const mainHtml=p.blocks.filter(b=>b.visible||s.view==='draft').map(b=>previewSection(b,p)).join('');const html=`Preview ${mainHtml}