How to use adoptedStyleSheets in lit - lit

Refer to this document,
https://lit.dev/docs/api/styles/#adoptStyles
I am not able to figure out the way to use it.

Seems like I can use following way to do the import.
import styleSheet from '#material/data-table/dist/mdc.data-table.css' assert { type: 'css' };
connectedCallback() {
super.connectedCallback();
this.renderRoot.adoptedStyleSheets = [styleSheet];
}

you can use static get styles inside your class
import { adoptStyles, LitElement } from 'lit';
class youComp extends LitElement {
static get styles(){
return [adoptStyles] /* you can return array of styles */
}
}
This should do the job

Related

I can't pass parameters to the component Wire Elements Modal

I can't pass parameters to the component.
I have 3 files:
Inside Livewire/test.blade.php
...............
onclick='Livewire.emit("openModal", "test-modal", {{ json_encode(["id_code" => $client->id_code]) }})'>
Inside /Http/Livewire/TestModal.php
namespace App\Http\Livewire;
use LivewireUI\Modal\ModalComponent;
use App\Models\Client;
class TestModal extends ModalComponent
{
public $id_code;
public function render($id_code)
{
dd($id_code);
return view('livewire.test-modal');
}
}
And livewire.test-modal which displays the content of the modal window.
But I can't get the id_code.
Let's see if someone can help me with this. Thanks.
So I had the same issue pretty much.
I solved it by adding the $id_code to the mount method. I hope it helps
namespace App\Http\Livewire;
use LivewireUI\Modal\ModalComponent;
use App\Models\Client;
class TestModal extends ModalComponent
{
public $id_code;
public function mount($id_code){
$this->id_code = $id_code
}
public function render()
{
$elCliente = Client::where("erp_code", $this->id_code)->first();
dd($elCliente);
return view('livewire.test-modal');
}
}
Livewire.emit("openModal") will emit an event that you can listen to in your components. The render() method in Livewire does not accept a parameter, so instead you need to listen to that event, and do your actions in a separate method instead.
By adding
protected $listeners = ['openModal' => 'openModal'];
the component will now listen to the event openModal (key in the array) being dispatched, and then fire the method openModal() (value in the array). Since you pass in two parameters, "test-modal" and a JSON parameter, you can accept those in that method.
namespace App\Http\Livewire;
use LivewireUI\Modal\ModalComponent;
use App\Models\Client;
class TestModal extends ModalComponent
{
public $id_code;
protected $listeners = ['openModal' => 'openModal'];
public function openModal($name, $data)
{
$this->id_code = $data['id_code'];
}
public function render()
{
return view('livewire.test-modal');
}
}

Javafx: Can't import custom control into Scene Builder

I tried to import my gui control (jar file) into the scene builder but without success. The file was created using eclipse export -> jar. When it was selected in scene builder "import JAR/FXML File", there was nothing inside the Import Dialog.
My control is a TextField with TextFormatter:
import java.text.NumberFormat;
import java.text.ParseException;
import javafx.scene.control.TextField;
import javafx.scene.control.TextFormatter;
import javafx.util.StringConverter;
public class CustomTextField extends TextField {
public CustomTextField() {
setText("Custom");
NumberTextFormatter formatter = new NumberTextFormatter(new StringConverter<Number>() {
#Override
public String toString(Number object) {
return object.toString();
}
#Override
public Number fromString(String string) {
try {
return NumberFormat.getInstance().parse(string);
} catch (ParseException e) {
e.printStackTrace();
return null;
}
}
});
setTextFormatter(formatter);
}
public static class NumberTextFormatter extends TextFormatter<Number> {
public NumberTextFormatter(StringConverter<Number> valueConverter) {
super(valueConverter);
}
}
}
I am sure that the culprit is the usage of TextFormatter. Because the control will works (appear in Import Dialog) if I removed the TextFormatter from the codes.
Whats wrong?
Update: Even if I simplified my constructor to exclude setTextFormatter(), as long as it still have a line of TextFormatter declaration the problem still persist. Such as:
public CustomTextField() {
setText("Custom");
TextFormatter<Integer> formatter = new TextFormatter<Integer>(new IntegerStringConverter());
}
Found the solution. The oracle scene builder 2.0 is too old/ too dumb to work with TextFormatter. Need to upgrade to Gluon scene builder 8.5.0.

Using Custom Pipes in services in angular2

I want to call the my custom pipe inside Injectable service. I checked many threads in stackoverflow. But they talk about using custom pipes inside a component. Can u please help me here, any helpful link will be fine. Below is my custom pipe file:
import { Pipe, PipeTransform } from '#angular/core';
#Pipe({ name: 'unit' })
export class UnitPipe implements PipeTransform {
transform(val,unit, args) {
if(unit=='Metric') {
return val * 2;
}
else {
return val * 4;
}
}
}
And Iam trying to access this pipe in my service:
import { Injectable } from '#angular/core';
import { Http, Response, Headers, RequestOptions } from '#angular/http';
import { UnitPipe } from '../pipes/UnitPipe';
#Injectable()
export class SomeService {
constructor(http: Http, unitPipe: UnitPipe) {
this.http = http;
this.unitPipe = unitPipe;
}
transformUnit() {
return this.unitPipe.transform('10', 'Metric');
}
}
I have specified this in app.module.js
declarations: [UnitPipe],
providers: [UnitPipe]
And in my component.js, I am calling this service method & just checking the output in console:
import { Component, OnInit, EventEmitter, Input } from '#angular/core';
import { SomeService } from '../../services/SomeService';
#Component({
})
export class SomeClass implements OnInit {
constructor(someService: SomeService) {
this.someService = someService;
}
ngOnInit(): void {
console.log(this.someService.transformUnit());
}
}
But Iam getting below error
One more thing is, my plan is to call transformUnit method inside my service file 'SomeService', may be onload, where the function definition is present. Any thought on this?
Thank you.
Your pipe transform function expects 3 parameters:
transform(val,unit, args) {
...
}
You're providing only 2 parameters to it:
transformUnit() {
return this.unitPipe.transform('10', 'Metric');
}
Best solutions I can suggest is using an Optional/Default parameter:
Optional parameter - Change args to args?
OR
Default parameter - Change args to args = null // or some other default value
This will allow you to call the pipe function with 2 params, so no need for code changing in your service.
You can see in this TypeScirpt-Functions link, section called Optional and Default Parameters for more details.
Created a simple StackBlitz DEMO with your code to this in action. Initially you will see the error in SomeService file. Just change the pipe args param accordingly. refresh the page. The error is gone in SomeService.

Checking if build macro already processed ancestor node

Assume you have type-building macro, interface invoking #:autoBuild using aforementioned macro, class implementing the interface and class extending it. Macro will fail if the class doesn't contain specific method.
Like so:
Macro.hx
package;
import haxe.macro.Context;
import haxe.macro.Expr;
import haxe.macro.Type;
class Macro
{
macro public function build():Array<Field>
{
var fields = Context.getBuildFields();
for (field in fields) {
if (field.name == "hello") {
//Do some modifications
return fields;
}
}
Context.error('${Context.getLocalClass().toString()} doesn\'t contain a method `hello`', Context.currentPos());
return null;
}
}
I.hx
package;
#:autoBuild(Macro.build())
interface I {}
Foobar.hx
package;
class Foobar implements I
{
public function new() {}
public function hello(person:String)
{
return 'Hello $person!';
}
}
Foo.hx
package;
#:keep
class Foo extends Foobar {}
As you can see, we're checking if field "hello" exists. However, Context.getBuildFields contains only fields of current class, and build will fail for Foo.
This is where my idea comes in: Why not just check if any ancestor was already processed? We'll change Macro.hx to reflect just that:
Macro.hx
package;
import haxe.macro.Context;
import haxe.macro.Expr;
import haxe.macro.Type;
class Macro
{
macro public function build():Array<Field>
{
var c = Context.getLocalClass().get();
if(isAncestorAlreadyProcessed(c)) {
return null;
}
var fields = Context.getBuildFields();
for (field in fields) {
if (field.name == "hello") {
//Do some modifications
c.meta.add(":processed", [], c.pos);
return fields;
}
}
Context.error('${Context.getLocalClass().toString()} doesn\'t contain a method `hello`', Context.currentPos());
return null;
}
private static function isAncestorAlreadyProcessed(c:ClassType)
{
if (c.meta.has(":processed")) return true;
if (c.superClass == null) return false;
return isAncestorAlreadyProcessed(c.superClass.t.get());
}
}
And for the main questions: Do I misunderstand haxe macro type building? Is there a more viable way of making this work? Does my code fail in specific scenarios? Are there any harmful side-effects caused by this code?
I'm trying to resolve this issue.
No, this is the way to go, use metadata to store information of the classes you processed (source).
Another way, if you don't need this information at runtime, is to use a static array on a dedicated class like here. Afterwards, you can even push this information in your compiled code, see here.
Hope that helps.

How to register factory of part in Dart

I have a lot of part of library. But all of the same type (extends Part)
part1.dart
part of Parts;
class Part1 extends Part { /* ... */ }
parts.add((varOfSomeClass){ return new Part1(varOfSomeClass + 1); });
part2.dart
part of Parts;
class Part2 extends Part { /* ... */ }
parts.add((varOfSomeClass){ return new Part2(varOfSomeClass - 1); });
parts.dart
library Parts;
part "Part1.dart";
part "Part2.dart";
List<Function> parts = new List<Function>();
class Parts {
getPart(int index) {
if (parts.contains(index)) {
return parts[index](someVarOfThisClass);
}
}
}
OUTPUT: error: unexpected token 'parts'
How to get all included factories without create instance all the Part classes?
For example need to do:
BMW.dart
part of Auto;
class BMW {
String color;
BMW(this.color);
}
list.add((color){
return new BMW(color);
});
Lada.dart
part of Auto;
class Lada {
List<int> color;
}
list.add((color){
var auto = new Lada();
auto.color = hex2rgb(color);
return auto;
});
Auto.dart
library Auto;
class Auto {
getByIndex(int index) {
if (list.contains(index)) {
return list[index](color);
}
return null;
}
}
Looks like your problem is that you have code outside of a class or function definition. If I'm guessing what you want to do correctly, you want BMW.dart to look something like
part of Auto;
class BMW {
String color;
BMW(this.color);
}
and then in your main() method have code like
main() {
List list = [];
list.add((color) => new BMW(color));
}
This will get the code above running. It's probably not the best way to structure your program though. You may want to do some more reading on Dart factory constructors. https://www.dartlang.org/dart-tips/dart-tips-ep-11.html is a good place to start.
I don't know what you need it for but how about using mirrors:
main.dart
library cars;
import 'dart:mirrors';
part 'bmw.dart';
part 'audi.dart';
abstract class Car {
}
void main() {
List<Car> cars = new List<Car>();
Map libraries = currentMirrorSystem().libraries;
LibraryMirror mirror = libraries[libraries.keys.last];
mirror.declarations.forEach((Symbol s, DeclarationMirror mirror) {
if(mirror is ClassMirror) {
if(!mirror.isAbstract && mirror.isAssignableTo(reflectType(Car))) {
// new Symbol(mirror.reflectedType.toString()))
cars.add(mirror.newInstance(#Car, []).reflectee);
}
}
});
print(cars);
}
bmw.dart
part of cars;
class Bmw extends Car {
Bmw.Car() {
}
}
audi.dart
part of cars;
class Audi extends Car {
Audi.Car() {
}
}