Initial commit: Tkinter Designer extension

This commit is contained in:
Popov_Grigorii committed 2025-12-22 14:39:20 +03:00
1 parent d3e8798c2a
commit b79c15c8ae
24 files changed
+4387

No files matched your search

Binary file not shown.
+1
View File
@@ -0,0 +1 @@
.CodeMirror{font-family:monospace;height:300px;color:black;direction:ltr}.CodeMirror-lines{padding:4px 0}.CodeMirror pre.CodeMirror-line,.CodeMirror pre.CodeMirror-line-like{padding:0 4px}.CodeMirror-scrollbar-filler,.CodeMirror-gutter-filler{background-color:white}.CodeMirror-gutters{border-right:1px solid #ddd;background-color:#f7f7f7;white-space:nowrap}.CodeMirror-linenumber{padding:0 3px 0 5px;min-width:20px;text-align:right;color:#999;white-space:nowrap}.CodeMirror-guttermarker{color:black}.CodeMirror-guttermarker-subtle{color:#999}.CodeMirror-cursor{border-left:1px solid black;border-right:none;width:0}.CodeMirror div.CodeMirror-secondarycursor{border-left:1px solid silver}.cm-fat-cursor .CodeMirror-cursor{width:auto;border:0 !important;background:#7e7}.cm-fat-cursor div.CodeMirror-cursors{z-index:1}.cm-fat-cursor-mark{background-color:rgba(20, 255, 20, 0.5);-webkit-animation:blink 1.06s steps(1) infinite;-moz-animation:blink 1.06s steps(1) infinite;animation:blink 1.06s steps(1) infinite}.cm-animate-fat-cursor{width:auto;-webkit-animation:blink 1.06s steps(1) infinite;-moz-animation:blink 1.06s steps(1) infinite;animation:blink 1.06s steps(1) infinite;background-color:#7e7}@-moz-keyframes blink{50%{background-color:transparent}}@-webkit-keyframes blink{50%{background-color:transparent}}@keyframes blink{50%{background-color:transparent}}.cm-tab{display:inline-block;text-decoration:inherit}.CodeMirror-rulers{position:absolute;left:0;right:0;top:-50px;bottom:0;overflow:hidden}.CodeMirror-ruler{border-left:1px solid #ccc;top:0;bottom:0;position:absolute}.cm-s-default .cm-header{color:blue}.cm-s-default .cm-quote{color:#090}.cm-negative{color:#d44}.cm-positive{color:#292}.cm-header,.cm-strong{font-weight:bold}.cm-em{font-style:italic}.cm-link{text-decoration:underline}.cm-strikethrough{text-decoration:line-through}.cm-s-default .cm-keyword{color:#708}.cm-s-default .cm-atom{color:#219}.cm-s-default .cm-number{color:#164}.cm-s-default .cm-def{color:blue}.cm-s-default .cm-variable-2{color:#05a}.cm-s-default .cm-variable-3,.cm-s-default .cm-type{color:#085}.cm-s-default .cm-comment{color:#a50}.cm-s-default .cm-string{color:#a11}.cm-s-default .cm-string-2{color:#f50}.cm-s-default .cm-meta{color:#555}.cm-s-default .cm-qualifier{color:#555}.cm-s-default .cm-builtin{color:#30a}.cm-s-default .cm-bracket{color:#997}.cm-s-default .cm-tag{color:#170}.cm-s-default .cm-attribute{color:#00c}.cm-s-default .cm-hr{color:#999}.cm-s-default .cm-link{color:#00c}.cm-s-default .cm-error{color:red}.cm-invalidchar{color:red}.CodeMirror-composing{border-bottom:2px solid}div.CodeMirror span.CodeMirror-matchingbracket{color:#0b0}div.CodeMirror span.CodeMirror-nonmatchingbracket{color:#a22}.CodeMirror-matchingtag{background:rgba(255, 150, 0, 0.3)}.CodeMirror-activeline-background{background:#e8f2ff}.CodeMirror{position:relative;overflow:hidden;background:white}.CodeMirror-scroll{overflow:scroll !important;margin-bottom:-50px;margin-right:-50px;padding-bottom:50px;height:100%;outline:none;position:relative}.CodeMirror-sizer{position:relative;border-right:50px solid transparent}.CodeMirror-vscrollbar,.CodeMirror-hscrollbar,.CodeMirror-scrollbar-filler,.CodeMirror-gutter-filler{position:absolute;z-index:6;display:none;outline:none}.CodeMirror-vscrollbar{right:0;top:0;overflow-x:hidden;overflow-y:scroll}.CodeMirror-hscrollbar{bottom:0;left:0;overflow-y:hidden;overflow-x:scroll}.CodeMirror-scrollbar-filler{right:0;bottom:0}.CodeMirror-gutter-filler{left:0;bottom:0}.CodeMirror-gutters{position:absolute;left:0;top:0;min-height:100%;z-index:3}.CodeMirror-gutter{white-space:normal;height:100%;display:inline-block;vertical-align:top;margin-bottom:-50px}.CodeMirror-gutter-wrapper{position:absolute;z-index:4;background:none !important;border:none !important}.CodeMirror-gutter-background{position:absolute;top:0;bottom:0;z-index:4}.CodeMirror-gutter-elt{position:absolute;cursor:default;z-index:4}.CodeMirror-gutter-wrapper ::selection{background-color:transparent}.CodeMirror-gutter-wrapper ::-moz-selection{background-color:transparent}.CodeMirror-lines{cursor:text;min-height:1px}.CodeMirror pre.CodeMirror-line,.CodeMirror pre.CodeMirror-line-like{-moz-border-radius:0;-webkit-border-radius:0;border-radius:0;border-width:0;background:transparent;font-family:inherit;font-size:inherit;margin:0;white-space:pre;word-wrap:normal;line-height:inherit;color:inherit;z-index:2;position:relative;overflow:visible;-webkit-tap-highlight-color:transparent;-webkit-font-variant-ligatures:contextual;font-variant-ligatures:contextual}.CodeMirror-wrap pre.CodeMirror-line,.CodeMirror-wrap pre.CodeMirror-line-like{word-wrap:break-word;white-space:pre-wrap;word-break:normal}.CodeMirror-linebackground{position:absolute;left:0;right:0;top:0;bottom:0;z-index:0}.CodeMirror-linewidget{position:relative;z-index:2;padding:.1px}.CodeMirror-rtl pre{direction:rtl}.CodeMirror-code{outline:none}.CodeMirror-scroll,.CodeMirror-sizer,.CodeMirror-gutter,.CodeMirror-gutters,.CodeMirrorLine truncated
+3
View File
@@ -0,0 +1,3 @@
/*! grapesjs - 0.22.14 */
!function(t,e){'object'==typeof exports&&'object'==typeof module?module.exports=e():'function'==typeof define&&define.amd?define([],e):'object'==typeof exports?exports["grapesjs"]=e():t["grapesjs"]=e()}('undefined'!=typeof globalThis?globalThis:'undefined'!=typeof window?window:this,(()=>(()=>{var t={4729:(t,e,n)=>{var o,r,i;1&&(r=[n(5706),n(4193)],void 0===(i='function'==typeof(o=function(t,e){var n=Array.prototype.slice;function o(t,e,n){return n.length<=4?t.call(e,n[0],n[1],n[2],n[3]):t.apply(e,n)}function r(t,e){return n.call(t,e)}function i(e,n){return null!=e&&(t.isArray(n)||(n=r(arguments,1)),t.all(n,(function(t){return t in e})))}var a=function(){var e=!1,n=-1;function o(){n++,e=!0,t.defer((function(){e=!1}))}return function(){return e||o(),n}}();function s(){this.registeredObjects=[],this.cidIndexes=[]}function l(e,n,o,r){for(var i,a=0,s=n.length;a<s;a++)if(i=n[a]){if("on"===e){if(!r.objectRegistry.register(i))continue}else if(!r.objectRegistry.unregister(i))continue;t.isFunction(i[e])&&i[e]("all",o,r)}}function c(e,n){var o=n.type,r=n.undoTypes,i=!r[o]||r[o][e];t.isFunction(i)&&i(n.object,n.before,n.after,n.options)}function u(e,o,r,i,a){if(!(r.isCurrentlyUndoRedoing||"undo"===e&&-1===r.pointer||"redo"===e&&r.pointer===r.length-1)){r.isCurrentlyUndoRedoing=!0;var s,l,c="undo"===e;for(a?l=c&&r.pointer===r.length-1||!c&&-1===r.pointer?t.clone(r.models):n.apply(r.models,c?[0,r.pointer]:[r.pointer,r.length-1]):(s=r.at(c?r.pointer:r.pointer+1),l=i?r.where({magicFusionIndex:s.get("magicFusionIndex")}):[s]),r.pointer+=(c?-1:1)*l.length;s=c?l.pop():l.shift();)s[e]();r.isCurrentlyUndoRedoing=!1,o.trigger(e,o)}}function p(t,e){var n=t.condition,r=typeof n;return"function"===r?!!o(n,t,e):"boolean"!==r||n}function d(t,e,n,r){if(t.track&&!t.isCurrentlyUndoRedoing&&e in r&&p(r[e],n)){var s=o(r[e]["on"],r[e],n);if(i(s,"object","before","after")){if(s.type=e,s.magicFusionIndex=a(),s.undoTypes=r,t.pointer<t.length-1)for(var l=t.length-t.pointer-1;l--;)t.pop();t.pointer=t.length,t.add(s),t.length>t.maximumStackLength&&(t.shift(),t.pointer--)}}}s.prototype={isRegistered:function(e){return e&&e.cid?this.registeredObjects[e.cid]:t.contains(this.registeredObjects,e)},register:function(t){return!this.isRegistered(t)&&(t&&t.cid?(this.registeredObjects[t.cid]=t,this.cidIndexes.push(t.cid)):this.registeredObjects.push(t),!0)},unregister:function(e){if(this.isRegistered(e)){if(e&&e.cid)delete this.registeredObjects[e.cid],this.cidIndexes.splice(t.indexOf(this.cidIndexes,e.cid),1);else{var n=t.indexOf(this.registeredObjects,e);this.registeredObjects.splice(n,1)}return!0}return!1},get:function(){return t.map(this.cidIndexes,(function(t){return this.registeredObjects[t]}),this).concat(this.registeredObjects)}};var f={add:{undo:function(t,e,n,o){t.remove(n,o)},redo:function(t,e,n,o){o.index&&(o.at=o.index),t.add(n,o)},on:function(e,n,o){return{object:n,before:void 0,after:e,options:t.clone(o)}}},remove:{undo:function(t,e,n,o){"index"in o&&(o.at=o.index),t.add(e,o)},redo:function(t,e,n,o){t.remove(e,o)},on:function(e,n,o){return{object:n,before:e,after:void 0,options:t.clone(o)}}},change:{undo:function(e,n,o,r){t.isEmpty(n)?t.each(t.keys(o),e.unset,e):(e.set(n),r&&r.unsetData&&r.unsetData.before&&r.unsetData.before.length&&t.each(r.unsetData.before,e.unset,e))},redo:function(e,n,o,r){t.isEmpty(o)?t.each(t.keys(n),e.unset,e):(e.set(o),r&&r.unsetData&&r.unsetData.after&&r.unsetData.after.length&&t.each(r.unsetData.after,e.unset,e))},on:function(e,n){var o=e.changedAttributes(),r=t.keys(o),i=t.pick(e.previousAttributes(),r),a=t.keys(i),s=(n||(n={})).unsetData={after:[],before:[]};return r.length!=a.length&&(r.length>a.length?t.each(r,(function(t){t in i||s.before.push(t)}),this):t.each(a,(function(t){t in o||s.after.push(t)}))),{object:e,before:i,after:o,options:t.clone(n)}}},reset:{undo:function(t,e,n){t.reset(e)},redo:function(t,e,n){t.reset(n)},on:function(e,n){return{object:e,before:n.previousModels,after:t.clone(e.models)}}}};function h(){}function v(e,n,o,r){if("object"==typeof n)return t.each(n,(function(t,n){2===e?v(e,t,o,r):v(e,n,t,o)}));switch(e){case 0:i(o,"undo","redo","on")&&t.all(t.pick(o,"undo","redo","on"),t.isFunction)&&(r[n]=o);break;case 1:r[n]&&t.isObject(o)&&(r[n]=t.extend({},r[n],o));break;case 2:delete r[n]}return this}h.prototype=f;var g=e.Model.extend({defaults:{type:null,object:null,before:null,after:null,magicFusionIndex:null},undo:function(t){c("undo",this.attributes)},redo:function(t){c("redo",this.attributes)}}),y=e.Collection.extend({model:g,pointer:-1,track:!1,isCurrentlyUndoRedoing:!1,maximumStackLength:1/0,setMaxLength:function(t){this.maximumStackLength=t}}),m=e.Model.extend({defaults:{maximumStackLength:1/0,track:!1},initialize:function(e){this.stack=new y,this.objectRegistry=new s,this.undoTypes=new h,this.stack.setMaxLength(this.get("maximumStackLength")),this.on("change:maximumStackLength",(function(t,e){this.stack.setMaxLength(e)}),this),e&&e.track&&this.startTracking(),e&&e.register&&(t.isALine truncated
//# sourceMappingURL=grapes.min.js.map
+378
View File
@@ -0,0 +1,378 @@
const vscode = acquireVsCodeApi();
// ============================================
// 1. Инициализация
// ============================================
const editor = grapesjs.init({
container: '#editor',
height: '100%',
storageManager: false,
dragMode: 'absolute',
selectorManager: { componentFirst: true },
undoManager: { trackSelection: false },
styleManager: { sectors: [{ name: 'Geometry', buildProps: ['left', 'top', 'width', 'height'] }] },
canvas: {
styles: [
'body { background-color: #444444; margin: 0; padding: 0; display: flex; justify-content: center; align-items: center; min-height: 100vh; }',
'::-webkit-scrollbar { width: 10px; height: 10px; }',
'::-webkit-scrollbar-track { background: #333; }',
'::-webkit-scrollbar-thumb { background: #666; border-radius: 5px; }'
]
}
});
// ============================================
// 2. Панель и Кнопки
// ============================================
editor.Panels.getButton('views', 'open-blocks').set('active', true);
editor.Panels.addButton('options', {
id: 'import-python-btn', className: 'fa fa-upload', command: 'import-python-cmd',
attributes: { title: 'Import from Python File' }
});
editor.Commands.add('import-python-cmd', { run: () => { vscode.postMessage({ type: 'request-import' }); } });
editor.Panels.addButton('options', {
id: 'window-settings-btn', className: 'fa fa-cog', command: 'window-settings-cmd',
attributes: { title: 'Window Settings' }
});
editor.Commands.add('window-settings-cmd', {
run: (editor, sender) => {
sender.set('active', 0);
const wrapper = editor.getWrapper();
const attrs = wrapper.getAttributes();
const currW = attrs['data-width'] || 500;
const currH = attrs['data-height'] || 400;
const currTitle = attrs['data-title'] || 'Form';
const content = `
<div style="padding: 10px; font-family: sans-serif; color: #333;">
<div style="margin-bottom: 10px;">
<label>Window Title:</label>
<input type="text" id="win-title" value="${currTitle}" style="width: 100%; padding: 5px;">
</div>
<div style="display: flex; gap: 10px; margin-bottom: 20px;">
<div style="flex: 1;"><label>Width:</label><input type="number" id="win-width" value="${currW}" style="width: 100%; padding: 5px;"></div>
<div style="flex: 1;"><label>Height:</label><input type="number" id="win-height" value="${currH}" style="width: 100%; padding: 5px;"></div>
</div>
<button id="win-save" style="background: #444; color: #fff; border: none; padding: 8px 15px; cursor: pointer;">Apply</button>
</div>
`;
const modal = editor.Modal;
modal.setTitle('Window Settings');
modal.setContent(content);
modal.open();
document.getElementById('win-save').onclick = () => {
const newTitle = document.getElementById('win-title').value;
const newW = parseInt(document.getElementById('win-width').value) || 500;
const newH = parseInt(document.getElementById('win-height').value) || 400;
// Применяем размеры
wrapper.addStyle({ width: newW + 'px', height: newH + 'px' });
const newAttrs = { ...wrapper.getAttributes() };
newAttrs['data-title'] = newTitle;
newAttrs['data-width'] = newW;
newAttrs['data-height'] = newH;
wrapper.setAttributes(newAttrs);
modal.close();
sendDataToExtension();
};
}
});
// ============================================
// 3. Загрузка (Настройка Wrapper)
// ============================================
editor.on('load', () => {
editor.Keymaps.add('redo-custom', 'ctrl+y', 'core:redo');
editor.Keymaps.add('undo-custom', 'ctrl+z', 'core:undo');
const wrapper = editor.getWrapper();
wrapper.addStyle({
'position': 'relative',
'background-color': '#ffffff',
'overflow': 'hidden',
'border': '2px solid #333',
'box-shadow': '0 0 30px rgba(0,0,0,0.5)',
'width': '500px',
'height': '400px',
'margin': '0'
});
const attrs = wrapper.getAttributes();
if (!attrs['data-width']) {
wrapper.setAttributes({ 'data-width': 500, 'data-height': 400, 'data-title': 'My App' });
} else {
wrapper.addStyle({
width: attrs['data-width'] + 'px',
height: attrs['data-height'] + 'px'
});
}
});
const geoTraits = [
{ type: 'number', name: 'x', label: 'X' }, { type: 'number', name: 'y', label: 'Y' },
{ type: 'number', name: 'width', label: 'W' }, { type: 'number', name: 'height', label: 'H' },
{ type: 'color', name: 'bg', label: 'Bg' }, { type: 'color', name: 'fg', label: 'Fg' }
];
// ============================================
// 4. Компоненты
// ============================================
function addTkComponent(type, tkType, label, defaultContent = '', defW = 80, defH = 30) {
editor.DomComponents.addType(type, {
model: {
defaults: {
tagName: 'div', draggable: true, droppable: false,
attributes: { 'data-tk-type': tkType },
traits: [ { type: 'text', name: 'text', label: 'Text', default: defaultContent }, ...geoTraits ],
style: {
position: 'absolute', left: '0px', top: '0px', width: defW + 'px', height: defH + 'px',
padding: '5px', border: '1px solid #999', background: '#f0f0f0',
display: 'flex', 'align-items': 'center', 'justify-content': 'center', 'overflow': 'hidden',
...(tkType === 'Entry' || tkType === 'Text' ? { background: '#ffffff', border: '2px inset #ccc', 'align-items': 'start', 'justify-content': 'start', 'white-space': 'pre-wrap' } : {})
},
content: defaultContent || label
},
updated(p) { if(p==='traits') { const text = this.getTrait('text')?.getValue(); if(text!==undefined && tkType!=='Entry') this.components(text); updateStylesAndSync(this); sendDataToExtension(); } }
}
});
editor.BlockManager.add(type, { label: label, category: 'Tkinter', content: { type: type } });
}
addTkComponent('tk-label', 'Label', 'Label', 'Label', 100, 30);
addTkComponent('tk-button', 'Button', 'Button', 'Button', 100, 40);
addTkComponent('tk-entry', 'Entry', 'Entry', 'Input here', 120, 30);
addTkComponent('tk-check', 'Checkbutton', 'Checkbox', 'Check', 100, 30);
addTkComponent('tk-radio', 'Radiobutton', 'Radio', 'Radio', 100, 30);
addTkComponent('tk-text', 'Text', 'Text', 'Multiline\nText', 150, 100);
editor.DomComponents.addType('tk-listbox', {
model: {
defaults: {
tagName: 'div', draggable: true, droppable: false,
attributes: { 'data-tk-type': 'Listbox', 'line_count': 3 },
style: { position: 'absolute', left: '0', top: '0', width: '120px', height: '100px', background: '#fff', border: '2px inset #ccc', overflow: 'hidden', padding: '0' },
traits: [{ type: 'number', name: 'line_count', label: 'Rows Count', default: 3, changeProp: 1 }, ...geoTraits]
},
init() { this.on('change:line_count', this.updateTraits); this.updateTraits(); this.renderList(); },
updateTraits() {
const count = parseInt(this.get('line_count') || 0);
const newTraits = [{ type: 'number', name: 'line_count', label: 'Rows Count', changeProp: 1 }];
for (let i = 0; i < count; i++) newTraits.push({ type: 'text', name: `line_${i}`, label: `Line ${i + 1}`, changeProp: 1 });
newTraits.push(...geoTraits);
this.set('traits', newTraits);
},
renderList() {
const count = parseInt(this.get('line_count') || 0);
let htmlItems = '', dataItems = [];
for (let i = 0; i < count; i++) {
let val = this.get(`line_${i}`);
if (val === undefined) { val = `Item ${i + 1}`; this.set(`line_${i}`, val); }
htmlItems += `<div style="border-bottom:1px solid #eee; padding:2px;">${val}</div>`;
dataItems.push(val);
}
this.components(htmlItems);
const attrs = { ...this.getAttributes() };
attrs['data-items'] = dataItems.join('\n');
this.setAttributes(attrs);
},
updated(p) {
if (p==='traits' || p.startsWith('line_') || p==='line_count') {
this.renderList();
updateStylesAndSync(this);
sendDataToExtension();
}
}
}
});
editor.BlockManager.add('tk-listbox', { label: 'Listbox', category: 'Tkinter', content: { type: 'tk-listbox' } });
editor.DomComponents.addType('tk-canvas', { extend: 'tk-label', model: { defaults: { attributes: { 'data-tk-type': 'Canvas' }, traits: geoTraits, style: { position: 'absolute', left:'0', top:'0', border: '1px solid black', width: '150px', height: '150px', background: '#fff' } }, updated(p){ if(p==='traits') { updateStylesAndSync(this); sendDataToExtension(); } } } });
editor.BlockManager.add('tk-canvas', { label: 'Canvas', category: 'Tkinter', content: { type: 'tk-canvas' } });
editor.DomComponents.addType('tk-frame', {
model: {
defaults: {
tagName: 'div', draggable: true, droppable: true,
attributes: { 'data-tk-type': 'Frame' },
traits: geoTraits,
style: { position: 'absolute', left:'0', top:'0', width: '200px', height: '200px', border: '2px dashed #666', background: 'rgba(0,0,0,0.05)' }
},
updated(p) { if(p==='traits') { updateStylesAndSync(this); sendDataToExtension(); } }
}
});
editor.BlockManager.add('tk-frame', { label: 'Frame', category: 'Tkinter', content: { type: 'tk-frame' } });
// ============================================
// 5. Вложенность и Синхронизация
// ============================================
editor.on('component:drag:end', (model) => {
const target = model.target;
if (!target) return;
if (target.getAttributes()['data-tk-type'] === 'Frame') { syncCoordinates(target); sendDataToExtension(); return; }
const targetEl = target.getEl();
if (!targetEl) return;
const currentStyle = target.getStyle();
let safeWidth = currentStyle.width;
let safeHeight = currentStyle.height;
if (!safeWidth || safeWidth === 'auto') safeWidth = targetEl.offsetWidth + 'px';
if (!safeHeight || safeHeight === 'auto') safeHeight = targetEl.offsetHeight + 'px';
const targetRect = targetEl.getBoundingClientRect();
const zoom = editor.Canvas.getZoom() / 100 * 100;
const wrapper = editor.getWrapper();
const frames = wrapper.find('[data-tk-type="Frame"]');
// Центр
const tCx = targetRect.left + targetRect.width / 2;
const tCy = targetRect.top + targetRect.height / 2;
let bestParent = wrapper;
let parentRect = wrapper.getEl().getBoundingClientRect();
// Если кинули в фрейм
for (let frame of frames) {
if (frame === target) continue;
const fRect = frame.getEl().getBoundingClientRect();
if (tCx > fRect.left && tCx < fRect.right && tCy > fRect.top && tCy < fRect.bottom) {
bestParent = frame;
parentRect = fRect;
break;
}
}
const currentParent = target.parent();
if (bestParent === currentParent) {
syncCoordinates(target);
sendDataToExtension();
return;
}
// Расчет новых координат
let borderOffset = 0;
let newX = (targetRect.left - parentRect.left - borderOffset) / zoom;
let newY = (targetRect.top - parentRect.top - borderOffset) / zoom;
newX = Math.round(newX); newY = Math.round(newY);
bestParent.append(target);
target.addStyle({ position: 'absolute', left: newX + 'px', top: newY + 'px', width: safeWidth, height: safeHeight, margin: '0' });
syncCoordinates(target);
sendDataToExtension();
});
function updateStylesAndSync(component) {
if (!component.getTrait) return;
const x = component.getTrait('x')?.getValue();
const y = component.getTrait('y')?.getValue();
const w = component.getTrait('width')?.getValue();
const h = component.getTrait('height')?.getValue();
const bg = component.getTrait('bg')?.getValue();
const fg = component.getTrait('fg')?.getValue();
if (x !== undefined && x !== "") component.addStyle({ left: x + 'px' });
if (y !== undefined && y !== "") component.addStyle({ top: y + 'px' });
if (w !== undefined && w !== "") component.addStyle({ width: w + 'px' });
if (h !== undefined && h !== "") component.addStyle({ height: h + 'px' });
if (bg) component.addStyle({ background: bg });
if (fg) component.addStyle({ color: fg });
syncCoordinates(component);
}
function syncCoordinates(component) {
if (!component || !component.getStyle) return;
const style = component.getStyle();
const attrs = { ...component.getAttributes() };
attrs['data-x'] = parseInt(style.left || 0);
attrs['data-y'] = parseInt(style.top || 0);
attrs['data-width'] = parseInt(style.width);
attrs['data-height'] = parseInt(style.height);
const bg = component.getTrait('bg')?.getValue();
const fg = component.getTrait('fg')?.getValue();
if(bg) attrs['data-bg'] = bg;
if(fg) attrs['data-fg'] = fg;
if (attrs['data-tk-type'] !== 'Listbox') {
const text = component.getTrait('text')?.getValue();
if (text) attrs['data-text'] = text;
}
component.setAttributes(attrs);
}
function syncAllComponents() {
const wrapper = editor.getWrapper();
const syncRecursive = (comp) => {
if(comp.getAttributes()['data-tk-type']) syncCoordinates(comp);
comp.components().each(child => syncRecursive(child));
}
syncRecursive(wrapper);
}
let isReadyToSave = false;
function sendDataToExtension() {
if (!isReadyToSave) return;
vscode.postMessage({ type: 'update-code', payload: editor.getProjectData() });
}
editor.on('component:add', (c) => { setTimeout(() => { syncCoordinates(c); sendDataToExtension(); }, 50); });
editor.on('component:remove', () => { sendDataToExtension(); });
function handleUndoRedo() {
editor.select(null);
setTimeout(() => {
const currentData = editor.getProjectData();
editor.loadProjectData(currentData);
syncAllComponents();
sendDataToExtension();
}, 150);
}
editor.on('run:undo', handleUndoRedo);
editor.on('run:redo', handleUndoRedo);
window.addEventListener('message', e => {
const d = e.data;
if (d.type === 'load-data' || d.type === 'import-data') {
try {
if(d.payload && Object.keys(d.payload).length > 0) {
if (d.type === 'import-data') editor.DomComponents.clear();
editor.loadProjectData(d.payload);
editor.UndoManager.clear();
// ВОССТАНОВЛЕНИЕ РАЗМЕРОВ ОКНА
const wrapper = editor.getWrapper();
const wAttrs = wrapper.getAttributes();
if (wAttrs['data-width']) {
wrapper.addStyle({
width: wAttrs['data-width'] + 'px',
height: wAttrs['data-height'] + 'px'
});
}
if (d.type === 'import-data') {
setTimeout(() => { syncAllComponents(); sendDataToExtension(); }, 200);
}
}
} catch(err){ console.error(err); }
setTimeout(() => isReadyToSave = true, 500);
}
});
setTimeout(() => { vscode.postMessage({ type: 'request-load' }); }, 100);
+8
View File
@@ -0,0 +1,8 @@
html, body {
height: 100%;
margin: 0;
overflow: hidden;
}
#editor {
height: 100%;
}