How do I dynamically load HTML and insert into my web page with Dart? - dart

How do I dynamically load a snippet of HTML and insert it into my web page? I am using Dart.

Glad you asked! Using Dart for this task isn't much different than JavaScript, except you get typing, code completion, and a slick editing experience.
First, create the snippet.html:
<p>This is the snippet</p>
Next, create the application. Notice the use of XMLHttpRequest to request the snippet. Also, use new Element.html(string) to create a block of HTML from a string.
import 'dart:html';
void main() {
var div = querySelector('#insert-here');
HttpRequest.getString("snippet.html").then((resp) {
div.append(new Element.html(resp));
});
}
Finally, here's the host HTML page:
<!DOCTYPE html>
<html>
<head>
<title>dynamicdiv</title>
</head>
<body>
<h1>dynamicdiv</h1>
<div id="insert-here"></div>
<script type="application/dart" src="dynamicdiv.dart"></script>
<script src="packages/browser/dart.js"></script>
</body>
</html>

main.dart:
import 'dart:html';
DivElement div = querySelector('div');
main() async {
String template = await HttpRequest.getString("template.html");
div.setInnerHtml(template, treeSanitizer: NodeTreeSanitizer.trusted);
}
template.html:
<h1>Hello world.</h1>
Check my bird... <em>it flies</em> !
<img src="https://www.dartlang.org/logos/dart-bird.svg">
For the full example, that runs out of the box, see:
https://gist.github.com/kasperpeulen/536b021ac1cf397d4e6d
Note that you need 1.12 to get NodeTreeSanitizer.trusted working.

You can try this example.
https://jsfiddle.net/kofwe39d/ (JS compiled from Dart source code.)
web/main.dart
import 'dart:async';
import 'dart:html';
import 'package:virtual_dom/components/component.dart';
import 'package:virtual_dom/features/state.dart';
import 'package:virtual_dom/helpers/h.dart';
import 'package:virtual_dom/helpers/mount.dart';
import 'package:virtual_dom/helpers/styles.dart';
import 'package:virtual_dom/helpers/vhtml.dart';
void main() {
final app = document.getElementById('app')!;
mount(app, _App());
}
class _App extends Component {
#override
Object render() {
final timer = State.get('timer', () => 3);
final setTimer = State.set<int>('timer');
if (timer > 0) {
Timer(Duration(seconds: 1), () {
setTimer(timer - 1);
});
}
final html = timer > 0
? ''
: '''
Hello, <strong>World!</strong>
''';
final style = styles({'padding': '6px'});
return h('div', {
'style': style
}, [
if (timer > 0) '$timer sec',
h('p', 'Your html:'),
vHtml('div', html),
]);
}
}
web/index.html
<!DOCTYPE html>
<html style="height: 100%;">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Example application</title>
<link rel="stylesheet" href="normalize.css">
<link rel="stylesheet" href="styles.css">
<script defer src="main.dart.js"></script>
</head>
<body style="height: 100%; font-family: Verdana,sans-serif; font-size:15px; line-height:1.5">
<div id="app" style="height: 100%;"></div>
</body>
</html>

Related

Polymer Dart $[] selector in an autobinding model

Since polymer-body has been removed, we need to use an auto-binded template to use polymer binding features outside of a PolymerElement:
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Sample app</title>
<script src="packages/web_components/platform.js"></script>
<script src="packages/web_components/dart_support.js"></script>
<link rel="import" href="packages/polymer/polymer.html">
<script src="packages/browser/dart.js"></script>
</head>
<body>
<template is="auto-binding-dart">
<div>Say something: <input value="{{value}}"></div>
<div>You said: {{value}}</div>
<button id="mybutton" on-tap="{{buttonTap}}">Tap me!</button>
</template>
<script type="application/dart">
import 'dart:html';
import 'package:polymer/polymer.dart';
import 'package:template_binding/template_binding.dart';
main() {
initPolymer().run(() {
Polymer.onReady.then((_) {
var template = document.querySelector('template');
templateBind(template).model = new MyModel();
});
});
}
class MyModel extends Observable {
//$['mybutton'] wont works there
#observable String value = 'something';
buttonTap() => print('tap!');
}
</script>
</body>
</html>
Unfortunately, the whole model now extends Observable, every binding seems to work, but the PolymerElement array selector $['foo'] cant be used anymore...
Is there any easy way to implement this $['id'] selector into an Observable model?
I would suggest to use a normal Polymer element instead of auto-binding-dart.
Then you don't have to care about differences and you need no 'main'.
I always start a Polymer project with an <app-element> Polymer element that acts as main() and container for the entire app.
I also would suggest to not use inline code.
As far as I know it has some limitations especially debugging is not supported (might be fixed already, I don't know because I never use it).
To make $ work you need a small and simple workaround;
import 'dart:html';
import 'package:polymer/polymer.dart';
import 'package:template_binding/template_binding.dart';
Map<String, dynamic> $; // we define our own '$'
main() {
initPolymer().run(() {
Polymer.onReady.then((_) {
var template = document.querySelector('template') as Polymer;
$ = template.$; // we assign template.$ to our own '$' so we can omit the 'template' part
templateBind(template).model = new MyModel();
});
});
}
class MyModel extends Observable {
//$['mybutton'] wont work there - it can't because this is outside of a method
#observable String value = 'something';
buttonTap() {
print($['mybutton'].id); // here it works
print('tap!');
}
}

Databinding not working in Polymer Dart

The subject line of the question is a bit ambiguous. I have an main entry file to load (entry.html) which uses a entry.dart script. In the entry.html, I use a custom polymer element card-table. cardtable.html is a simple list. When I load the entry.html first time, everything is good.. I see multiple rows of text printed with static data in my model list. My entry.html has a button, clicking which changes the data model (through entry.dart, I invoke the cardtable.dart). I see the right methods being called and data model change is confirmed, but UI is not updated.
entry.html
<link rel="import" href="cardtable.html">
<link rel="import" href="packages/paper_elements/paper_button.html">
<script async src="packages/browser/dart.js"></script>
<script async type="application/dart" src="entry.dart"></script>
<link rel="stylesheet" href="entry.css">
</head>
<body>
<paper-button id="inc_btn" label="+" raisedButton></paper-button>
<paper-button id="dec_btn" label="-" raisedButton></paper-button>
<card-table></card-table>
</body>
entry.dart
var tablec;
void main() {
initPolymer().run(() {
Polymer.onReady.then((_) {
tablec = new Element.tag('card-table');
var incBtn = querySelector('#inc_btn');
incBtn.onClick.listen(increment);
});
}
void increment(Event e) {
new Future(() {
tablec.increment();
});
}
}
card-table.html
<link rel="import" href="packages/polymer/polymer.html">
<polymer-element name="card-table">
<template>
<style>
:host {
display: block;
color: green;
}
</style>
<content>
<div id="dynamic_area">
<template repeat="{{item in list}}">
<span>ABCD : {{item}}</span>
</template>
</div>
</content>
</template>
<script type="application/dart" src="cardtable.dart"></script>
</polymer-element>
cardtable.dart
#CustomTag('card-table')
class CardTable extends PolymerElement {
#observable List list = toObservable(['a', 'b', 'c']);
CardTable.created() : super.created() {
polymerCreated();
}
void increment() {
print('INCREMENT'); //is called on clicking + button on entry.html
list.add('d');
}
}
You call increment on a new <card-table> you reference using a variable, not the one inside your <body> tag.
Instead of
tablec = new Element.tag('card-table');
you use use
tablec = querySelector('card-table');

How to Use Dart Route API

I have created a sample app to test the Dart Route API. I have the following code:
urls.dart
library urls;
import 'package:route/url_pattern.dart';
final homeUrl = new UrlPattern(r'/');
final otherScreenUrl = new UrlPattern(r'/other_screen/');
main.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Test</title>
</head>
<body>
<div id="sample_container_id">
<p id="sample_text_id"></p>
</div>
<script type="application/dart" src="main.dart"></script>
<script src="packages/browser/dart.js"></script>
</body>
</html>
main.dart
import 'dart:html';
import 'package:route/client.dart';
import 'urls.dart';
void main() {
var router = new Router()
..addHandler(homeUrl, _showHome)
..addHandler(otherScreenUrl, _showOtherScreen)
..listen();
querySelector("#sample_text_id")
..text = "Click me!"
..onClick.listen(_gotoOtherScreen);
}
_gotoOtherScreen(MouseEvent event) {
// I am trying to navigate to the "other screen" by using history.pushState here
window.history.pushState({'url' : otherScreenUrl}, "other screen", otherScreenUrl);
}
_showHome(String path) {
querySelector("#other_element")
..remove();
}
_showOtherScreen(String path) {
querySelector("#sample_container_id")
..append(new SpanElement()
..innerHtml = "now in other screen"
..id = "other_element");
}
I am getting the following errors when running the app and then clicking on the <p> tag:
Breaking on exception: Illegal argument(s): No handler found for
/test/web/main.html
Exception: Illegal argument(s): No handler found for
/test/web/main.html Router._getUrl (package:route/client.dart:53:7)
Router.handle (package:route/client.dart:71:22)
Router.listen. (package:route/client.dart:102:15)
Breaking on exception: type 'UrlPattern' is not a subtype of type
'String' of 'url'.
Exception: type 'UrlPattern' is not a subtype of type 'String' of
'url'. _gotoOtherScreen
(http://127.0.0.1:3030/test/web/main.dart:18:27)
How is the Route API supposed to be used? What am I doing wrong?
The following is the updated code that solves the above issues:
urls.dart
library urls;
import 'package:route/url_pattern.dart';
final homeUrl = new UrlPattern(r'(.*)/');
final homeUrlWithFile = new UrlPattern(r'(.*)/main.html');
final otherScreenUrl = new UrlPattern(r'(.*)/other_screen');
main.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Test</title>
</head>
<body>
<div id="sample_container_id">
click me!!
</div>
<script type="application/dart" src="main.dart"></script>
<script src="packages/browser/dart.js"></script>
</body>
</html>
main.dart
import 'dart:html';
import 'package:route/client.dart';
import 'urls.dart';
void main() {
var router = new Router()
..addHandler(homeUrl, _showHome)
..addHandler(homeUrlWithFile, _showHome)
..addHandler(otherScreenUrl, _showOtherScreen)
..listen();
}
_showHome(String path) {
var e = querySelector("#other_element");
if (e != null) e.remove();
}
_showOtherScreen(String path) {
querySelector("#sample_container_id")
..append(new SpanElement()
..innerHtml = "now in other screen"
..id = "other_element");
}

When dynamically adding dart polymer elements, how do I get observable variables to on DOM

I am trying to change the default web application that uses the polymer library so that the polymer element is created and added to the DOM from DART code rather than including in the HTML. I have succeeded in adding the element to the DOM, but my observable variable are not being updated on the DOM. The events are being fired, and the values are changing. I have got the DOM to update using Observable.dirtyCheck(), however, this is apparently expensive, so am trying to figure out how to get polymer to update dom without dirtyCheck().
So, In short, how to I get rid of Observable.dirtyCheck()???
dynamiccreate.dart
library dynamiccreate;
import 'dart:html';
import 'package:polymer/polymer.dart';
main() {
initPolymer();
//create click-counter element at runtime from DART, not HTML
var NewElement = new Element.tag('click-counter');
NewElement.setAttribute("count", "5");
//Add to DOM
querySelector('#sample_container_id').children.add(NewElement);
}
dynamiccreate.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Sample app</title>
<link rel="stylesheet" href="dynamiccreate.css">
<!-- import the click-counter -->
<link rel="import" href="clickcounter.html">
<!-- <script type="application/dart">export 'package:polymer/init.dart';</script> -->
<script src="packages/browser/dart.js"></script>
</head>
<body>
<h1>DynamicCreate</h1>
<p>Hello world from Dart!</p>
<div id="sample_container_id">
<!-- <click-counter count="5"></click-counter> -->
</div>
<script src="dynamiccreate.dart" type="application/dart"></script>
</body>
</html>
clickcounter.dart
import 'package:polymer/polymer.dart';
/**
* A Polymer click counter element.
*/
#CustomTag('click-counter')
class ClickCounter extends PolymerElement {
#published int count = 0;
ClickCounter.created() : super.created() {
}
//increment gets called when dynamically adding object at runtime
//But does not update count on DOM
void increment() {
count++;
//Have to add this to update count in DOM
Observable.dirtyCheck(); //<<<---How do I get rid of this???
}
}
clickcounter.html
<polymer-element name="click-counter" attributes="count">
<template>
<style>
div {
font-size: 24pt;
text-align: center;
margin-top: 140px;
}
button {
font-size: 24pt;
margin-bottom: 20px;
}
</style>
<div>
<button on-click="{{increment}}">Click me</button><br>
<span>(click count: {{count}})</span>
</div>
</template>
<script type="application/dart" src="clickcounter.dart"></script>
</polymer-element>
Change your dynamiccreate.dart file to look like this, and the counter starts incrementing in the UI:
library dynamiccreate;
import 'dart:html';
import 'package:polymer/polymer.dart';
main() {
initPolymer().run(() {
var newElement = new Element.tag('click-counter');
newElement.setAttribute("count", "15");
querySelector('#sample_container_id').children.add(newElement);
});
}
Nit: name your variable newElement, not NewElement. Fixed here.

Dynamically add a web component to a div

I started with the generating click-counter example. I made the click-counter into a library which I then imported into my main file. The click-counter component can be added manually by putting the appropriate HTML into the web page before running the program. However, I've been unable to find a way to dynamically add the click-counter web component to a div. My attempts have either ended in "Aw, snap!" errors or simply with nothing happening.
The click-counter (xclickcounter.dart):
library clickcounter;
import 'package:web_ui/web_ui.dart';
class CounterComponent extends WebComponent {
int count = 0;
void increment() {
count++;
}
}
The main HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Sample app</title>
<link rel="stylesheet" href="test1.css">
<!-- import the click-counter -->
<link rel="components" href="xclickcounter.html">
</head>
<body>
<h1>Test1</h1>
<p>Hello world from Dart!</p>
<div id="sample_container_id">
<div is="x-click-counter" id="click_counter" count="{{startingCount}}"></div>
</div>
<script type="application/dart" src="test1.dart"></script>
<script src="packages/browser/dart.js"></script>
</body>
</html>
main file:
import 'dart:html';
import 'package:web_ui/web_ui.dart';
import 'xclickcounter.dart';
// initial value for click-counter
int startingCount = 5;
void main() {
// no error for adding an empty button
var button = new ButtonElement();
query('#sample_container_id').append(button);
// doesn't work (gives "Aw, snap!" in Dartium)
query('#sample_container_id').append(new CounterComponent());
// Nothing happens with this code. Nothing appears.
// But I promise this same thing was giving Aw, Snap
// for a very similar program
final newComponentHtml = '<div is="x-click-counter"></div>';
query('#sample_container_id').appendHtml(newComponentHtml);
}
I tried added an empty constructor to click-counter but it still crashes.
I had the same issue.
See the example (not mine) at https://github.com/dart-lang/web-ui/blob/master/test/data/input/component_created_in_code_test.html and let me know if it works for you.
TL;DR:
void main() {
var element = query('#sample_container_id');
appendComponentToElement(element, new CounterComponent() );
}
void appendComponentToElement(Element element, WebComponent component) {
component.host = new DivElement();
var lifecycleCaller = new ComponentItem(component)..create();
element.append(component.host);
lifecycleCaller.insert();
}
There's more info at my web-ui#dartlang.org post: https://groups.google.com/a/dartlang.org/d/topic/web-ui/hACXh69UqG4/discussion
Hope that helps.

Resources