Jump to content

FieldLabel + svg icon


x11

Recommended Posts

1 hour ago, x11 said:

sewage.svg

Try this approach:

function painted(sender, eOpts)
{
    var svgHeight = sender.element.getHeight();
    sender.setLabelWidth(svgHeight + 3);
    sender.setLabel('<svg style="position:absolute; top:0; height:'+ svgHeight +'" viewBox="0 0 512 512" xmlns="http://www.w3.org/2000/svg"><path d="m512 462c0 11.046875-8.953125 20-20 20-51.363281 0-54.390625 30-118.003906 30-63.976563 0-66.335938-30-118-30-51.363282 0-54.386719 30-118 30-63.972656 0-66.332032-30-117.996094-30-11.046875 0-20-8.953125-20-20s8.953125-20 20-20c63.976562 0 66.332031 30 117.996094 30 51.910156 0 53.8125-30 118-30 63.976562 0 66.332031 30 118 30 51.910156 0 53.816406-30 118.003906-30 11.046875 0 20 8.953125 20 20zm-196-96.847656v-107.152344c0-26.074219-16.722656-48.304688-40-56.558594v54.558594c0 11.046875-8.953125 20-20 20s-20-8.953125-20-20v-18h-216c-11.046875 0-20-8.953125-20-20v-160c0-11.046875 8.953125-20 20-20h216v-18c0-11.046875 8.953125-20 20-20s20 8.953125 20 20v59.117188c89.875 9.980468 160 86.390624 160 178.882812v105.285156c13.40625-6.042968 30.003906-11.285156 56-11.285156 11.046875 0 20 8.953125 20 20s-8.953125 20-20 20c-51.363281 0-54.390625 30-118.003906 30-63.976563 0-66.335938-30-118-30-51.363282 0-54.386719 30-118 30-63.972656 0-66.332032-30-117.996094-30-11.046875 0-20-8.953125-20-20s8.953125-20 20-20c63.976562 0 66.332031 30 117.996094 30 51.910156 0 53.8125-30 118-30 28.644531 0 45.878906 6.367188 60.003906 13.152344zm-80.003906-287.152344h-195.996094v120h195.988281zm120.003906 180v122.746094c5.171875.804687 11.046875 1.253906 17.996094 1.253906 8.8125 0 15.894531-.722656 22.003906-1.976562v-122.023438c0-70.40625-52.246094-128.828125-120-138.566406v40.578125c45.589844 9.289062 80 49.695312 80 97.988281zm0 0"/></svg>');
}

 

Link to comment
Share on other sites

1. В какой-нибудь папке типа /files/img/svg

2. Я не знаю, подскажите, как правильно с точки зрения оптимизации, кэширования и быстрой работы приложения.

Link to comment
Share on other sites

function painted(sender, eOpts)
{
    var me=sender;
    if (me._fieldLabelIcon) {
        var svgHeight = me.element.getHeight();
        me.setLabelWidth(svgHeight + 3);
        sender.setLabel('<img style="position:absolute; top:0; height:'+ svgHeight + 'px" src="files/'+ me._fieldLabelIcon +'.svg"></img>');
    } 
}
procedure TMainmForm.UnimFormCreate(Sender: TObject);
begin
  UnimDBLookupComboBox1.JSInterface.JSConfig('_fieldLabelIcon', ['sewage']);
end;

 

  • Like 1
Link to comment
Share on other sites

        var svgHeight = me.element.getHeight();

 

это 41, а 41 слишком много

нужно брать не высоту элемента, а что=то другое, например, высоту "внутренней" части контейнера, чтобы было примерно 20-25 px

Link to comment
Share on other sites

Вот так хорошо:

function painted(sender, eOpts)
{
    var me=sender;
    if (me._fieldLabelIcon) {
        var svgHeight = me.element.getHeight() - 20;        
        sender.setLabel('<img style="position:absolute; top:auto; height:' + svgHeight + 'px" src="files/svg/'+ me._fieldLabelIcon + '"></img>');
    }
}

 

delphi-код

procedure SetIconSvg(combo: TUnimDBLookupComboBox; const IconFileName: string = '');
begin
  if IconFileName.IsEmpty then
    combo.JSInterface.JSConfig('_fieldLabelIcon', [combo.FieldLabel])
  else
    combo.JSInterface.JSConfig('_fieldLabelIcon', [IconFileName]);
end;

и не забыть указать fieldLabelWidth

 

Screenshot_2.jpg

  • Like 1
Link to comment
Share on other sites

Вопрос по наследованию. В документации не смог найти

 

вот код

procedure SetIconSvg(FormControl: TUniFormControl; const IconFileName: string = '');
begin
  if IconFileName.IsEmpty then
    FormControl.JSInterface.JSConfig('_fieldLabelIcon', [FormControl.FieldLabel])
  else
    FormControl.JSInterface.JSConfig('_fieldLabelIcon', [IconFileName]);
end;

само собой, что он не компилируется, т.к. у TUniFormControl отсутствует свойство FieldLabel.

Что подставить вместо TUniFormControl?

 

Link to comment
Share on other sites

3 minutes ago, x11 said:

Что подставить вместо TUniFormControl?

просто не хочется писать отдельно для каждого визуального класса (компоненты) отдельную процедуру

Link to comment
Share on other sites

Как вариант, можно использовать костыль в виде дополнительной проверки IsPublishedProp + GetPropValue. Но это не очень оптимально, особенно если на форме много компонент c такими SVG-иконками.

 

procedure SetIconSvg(FormControl: TUniFormControl; const IconFileName: string = '');
Var
  FieldLabel: string;
begin
  if IconFileName.IsEmpty then
  begin
    if IsPublishedProp(FormControl, 'FieldLabel') then
      FieldLabel := GetPropValue(FormControl, 'FieldLabel');

    FormControl.JSInterface.JSConfig('_fieldLabelIcon', [FieldLabel]);
  end
  else
    FormControl.JSInterface.JSConfig('_fieldLabelIcon', [IconFileName]);
end;

 

Link to comment
Share on other sites

  • 2 months later...

Может кому-то пригодится.

Сделал svg + текст подписи на примере TunimToggle.

Т.е. в данном примере в свойстве unimToggle1.FieldLabel будет не имя файла, а просто подпись.

И так.

В unimToggle1.ClientEvents.extEvents:

function painted(sender, eOpts)
{
    var me=sender;
    if (me.IconFileName) {
        var svgHeight = me.element.getHeight() - 30;        
        sender.setLabel('<p class="svgIconLabel"><img class="svgIcon" height="' + svgHeight + 'px" src="files/svg/'+ me.IconFileName + '"></img>' + me._label+'</p>');
    } 
}

 

unimToggle1.FieldLabel := ' Мікрохвильова піч';

 

в customCSS:

.svgIcon {
	vertical-align: sub;
}

/*чтоб обнулить margin, иначе расстояние между элементами формы будет слишком большое*/
.svgIconLabel{
	margin-block-start: 0;
	margin-block-end: 0;
}

 

//в событии onCreate или OnShow формы

  SetIconSvg2(checkMicrowave, 'microwave.svg');


procedure SetIconSvg2(FormControl: TUniFormControl; const IconFileName: string);
begin
  if IconFileName.IsEmpty then
    exit;
  FormControl.JSInterface.JSConfig('IconFileName', [IconFileName]);
end;


 

Screenshot_15.jpg

Link to comment
Share on other sites

23 hours ago, x11 said:

В unimToggle1.ClientEvents.extEvents:


function painted(sender, eOpts)

 

Подскажите, а как сделать, чтобы это событие не прописывать у каждой компоненты в ExvEvents, а написать один раз в function window.beforeInit, но чтобы оно срабатывало у конкретных (заранее) определенных компонент? Например, на форме где-то есть 3-4 компоненты и чтобы только для них это работало.

Спасибо.

Link to comment
Share on other sites

да, ведь зачем плодить 5 раз одну и ту же процедуру?

в соседней теме уже было что-то похожее с использованием "window.beforeInit", но я так и не смог адаптировать

Вот у меня уже есть код, который загружается при старте мобильного окна

function window.beforeInit(sender, config) 
{
	createToolTip = function(combo, tip) {
		combo.labelTip = Ext.create('Ext.tip.ToolTip', {
			closable: true,
			align: 'tl',
			focusOnToFront: true,
			autoHide: true,
			autoShow: true,
			autoScroll: true
		});

		combo.labelElement.addListener('click', function(e) {
			e.preventDefault();
			if (combo.labelTip) {
				if (combo.getPlaceholder()) {
					combo.labelTip.setHtml(combo.getPlaceholder());
				} else {
					combo.labelTip.setHtml(tip);
				}
				combo.labelTip.showByTarget(combo.inputElement);
			}
		});
	};
}

 

На форме есть 10 компонент типа TunimToggle, но "function painted(sender, eOpts)" нужно применить только к конкретным 3-4 компонентам.

 

 

Link to comment
Share on other sites

2 minutes ago, x11 said:

в соседней теме уже было что-то похожее с использованием "window.beforeInit"

Да я помню.

3 minutes ago, x11 said:

На форме есть 10 компонент типа TunimToggle, но "function painted(sender, eOpts)" нужно применить только к конкретным 3-4 компонентам.

Я проанализирую.

Конечно, есть много способов, как это можно сделать. Я рассмотрю способ, как минимизировать код, но все равно, будете назначать событие самостоятельно, для нужных Вам компонент...

  • Like 1
Link to comment
Share on other sites

19 minutes ago, x11 said:

На форме есть 10 компонент типа TunimToggle, но "function painted(sender, eOpts)" нужно применить только к конкретным 3-4 компонентам.

Попробуйте это решение:

1. 

function window.beforeInit(sender, config) 
{
    window.togglePainted = function() {
        var me = this;
        if (me.IconFileName) {
            var svgHeight = me.element.getHeight() - 30;
            sender.setLabel('<p class="svgIconLabel"><img class="svgIcon" height="' + svgHeight + 'px" src="files/svg/' + me.IconFileName + '"></img>' + me._label + '</p>');
        }
    }
}

2.

procedure TMainmForm.UnimFormCreate(Sender: TObject);
begin
  UnimToggle1.JSInterface.JSAddListener('painted', 'togglePainted');
  UnimToggle2.JSInterface.JSAddListener('painted', 'togglePainted');
end;

 

Link to comment
Share on other sites

Не получается. Что-то делаю не так?

1. UnimFormCreate

function window.beforeInit(sender, config) 
{
	createToolTip = function(combo, tip) {
		combo.labelTip = Ext.create('Ext.tip.ToolTip', {
			closable: true,
			align: 'tl',
			focusOnToFront: true,
			autoHide: true,
			autoShow: true,
			autoScroll: true
		});

		combo.labelElement.addListener('click', function(e) {
			e.preventDefault();
			if (combo.labelTip) {
				if (combo.getPlaceholder()) {
					combo.labelTip.setHtml(combo.getPlaceholder());
				} else {
					combo.labelTip.setHtml(tip);
				}
				combo.labelTip.showByTarget(combo.inputElement);
			}
		});
	};
	
	window.togglePainted = function() {
        var me = this;
        if (me.IconFileName) {
            var svgHeight = me.element.getHeight() - 30;
            sender.setLabel('<p class="svgIconLabel"><img class="svgIcon" height="' + svgHeight + 'px" src="files/svg/' + me.IconFileName + '"></img>' + me._label + '</p>');
        }
    };
	
}

 

2. UnimFormShow

procedure SetIconSvg2(FormControl: TUniFormControl; const IconFileName: string);
begin

  if IconFileName.IsEmpty then
  begin

    exit;
  end;

  FormControl.JSInterface.JSAddListener('pained', 'togglePainted');
  FormControl.JSInterface.JSConfig('IconFileName', [IconFileName]);
end;

 

 

 

 

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...