• This repository has been archived on 22/Feb/2018
  • Stars
    star
    114
  • Rank 298,520 (Top 7 %)
  • Language
    Dart
  • License
    BSD 3-Clause "New...
  • Created over 11 years ago
  • Updated almost 9 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Deprecated: code is now in the SDK repo

Dart-JavaScript Interop (paused)

Note: Development on this package has paused. We encourage every developer to use dart:js for Dart-JavaScript interop. Further work on a higher-level interop with JavaScript will be explored along with new experimental approaches to compiling to JavaScript.

package:js provides high-level, typed interopability between Dart and JavaScript. It allows developers to export Dart APIs to JavaScript and define well-typed interfaces for JavaScript objects.

Status

Paused

Version 0.4.0 is a complete rewrite of package:js as described in the package:js 1.0 design document.

Usage

Warning: The API is still changing rapidly. Not for the faint of heart

Defining Typed JavaScript Proxies

Typed JavaScript Proxies are classes that represent a JavaScript object and have a well-defined Dart API, complete with type annotations, constructors, even optional and named parameters. They are defined in two parts:

  1. An abstract class that defines the interface
  2. A concrete class that implements the interface (automatically, either via mirrors or the js transformer)

The abstract class is defined as follows:

  1. It must extend JsInterface
  2. It must have a constructor with the signature C.created(JsObject o).
  3. Any abstract methods or accessors on the class are automatically implemented for you to call into JavaScript. Becuase only abstract class members are proxied to JavaScript, fields must be represented as abstract getter/setter pairs.
  4. Ideally, all parameters and returns should have type annotations. The generator adds casts based on the type annotations which help dart2js produce smaller, faster output.
  5. Add a factory constructor if you want to create new instances from Dart. The constructor must redirect to a factory constructor on the implementation class.
  6. Maps and Lists need to be copied to be usable in JavaScript. Add a @jsify annotation to any parameter that takes a Map or List. Note that modification from JS won't be visible in Dart, unless you send the copied collection back later.

The concrete implementation class is defined as follows:

  1. It must extend the interface class.
  2. It must have a created constructor.
  3. It must have a @JsProxy annotation. This tells package:js that the class is a proxy, and which JavaScript prototype it should proxy.
  4. It should have a noSuchMethod that forwards to the super class to suppress warnings.

Example - Proxying JavaScript to Dart

JavaScript
function Foo(name) {
  this.name = name;
}

Foo.prototype.sayHello = function() {
  return "Hello " + name;
}
Dart
import 'package:js/js.dart';

abstract class Foo extends JsInterface {
  Foo.created(JsObject o) : super.created(o);
  
  factory Foo(String name) => new FooImpl(name);
  
  String get name;
  void set name(String n);
  
  String sayHello();
}

@JsProxy(constructor: 'Foo')
class FooImpl extends Foo {
  FooImpl.created(JsObject o) : super.created(o);
  
  factory FooImpl(String name) => new JsInterface(FooImpl, [name]);
  
  noSuchMethod(i) => super.noSuchMethod(i);
}

This may seem a bit verbose, and it is, but it's because of a few constraints we have:

  • The proxy methods should be abstract.
  • Abstract members cause warnings on non-abstract classes, which can't be silenced by adding a noSuchMethod(), so the proxy class must be abstract.
  • Abstract classes can't be instantiated, so we need a separate implementation class.
  • The abstract methods are implemented via noSuchMethod() in JsInterface, which doesn't silence the warnings cause be "unimplemented" methods, so we must add a noSuchMethod() to the implementation class.
  • The only way to express an "abstract field" is with a getter/setter pair.
  • JsInterface needs a reference to the raw JsObject, so must have a generative constructor.
  • We want to create new instances with expressions like new Foo(), not new FooImpl(), so we need a factory constructor on the interface class.

We will try to see what changes we can make in the future to this package or the language to alleviate the boilerplate. The good news is that once the boilerplate for the class is set up, the interesting parts - the methods and fields - are quite simple to write and maintain. We will also look into generators for proxies from various sources like TypeScript, Closure, JSHint annotations, Polymer, etc.

Exporting Dart APIs to JavaScript

You can export classes, functions, variables, and even whole libraries to JavaScript by using the @Export annotation.

Example

a.dart:
library a;

import 'package:js/js.dart';

@Export()
class A {
  String name;

  A();

  A.withName(this.name);
}
JavaScript
var a1 = new dart.a.A();
a1 instanceof dart.a.A; // true
a1.name; // null
a1.name = 'red'; // sets the value in Dart

// Named constructors are supported
var a2 = new dart.a.A.withName('blue');
a2 instanceof dart.a.A;
a2.name; // 'blue'

All of the types referenced by exported functions and methods must either be "primitives" as defined by dart:js (bool, num, String, DateTime), JsInterfaces, or other exported classes.

As with parameters for JsInterfaces, the return values of exported methods are Dart objects being passed to JavaScript. If these are Maps or Lists, they too must be copied to work in JavaScript, so add @jsify to the method, field or getter.

Configuration and Initialization

Adding the dependency

Version 0.4.0 is not published to pub.dartlang.org yet, so you must use a Git dependency to install it.

Add the following to your pubspec.yaml:

dependencies:
  js:
    git:
      url: git://github.com/dart-lang/js-interop.git

Configuring the transformers

package:js requires two transformers to be installed, a transformer that works on packages that directly use package:js to generate implementations of JavaScript proxy classes, and another transformer that works on entry-points that generates the necessary setup code.

If your packages uses package:js to export APIs or define JavaScript proxies, add this to your pubspec.yaml:

transformers:
- js

If your packages defines an entry-point in web/, add this to your pubspec.yaml:

transformers:
- js/intializer

If your package both defines proxies or exports, and has an HTML entry-point in web/, then add both transformers:

transformers:
- js
- js/intializer

Loading the generated JavaScript

The JavaScript prototypes for exported APIs must be loaded in a page for them to be available to other JavaScript code. This code is loaded by including packages/js/interop.js in your HTML. When your application is built that script is replaced by the generated JavaScript. The interop script must be loaded before your main Dart script.

main.html
<html>
  <head>
    <script src="packages/js/interop.js"></script>
  </head>
  <body>
    <script type="application/dart" src="main.dart"></script>
  </body>
</html>

Initializing Interop

Your main() method must call initializeJavaScript() in order to export Dart classes and register proxies. This call should be made as early as possible, ideally first.

main.dart
library main;

import 'package:js/js.dart';

main() {
  initializeJavaScript();
}

Contributing and Filing Bugs

Please file bugs and features requests on the Github issue tracker: https://github.com/dart-lang/js-interop/issues

We also love and accept community contributions, from API suggestions to pull requests. Please file an issue before beginning work so we can discuss the design and implementation. We are trying to create issues for all current and future work, so if something there intrigues you (or you need it!) join in on the discussion.

All we require is that you sign the Google Individual Contributor License Agreement https://developers.google.com/open-source/cla/individual?csw=1

More Repositories

1

angular.dart

Legacy source repository. See github.com/dart-lang/angular
1,250
star
2

stagehand

Dart project generator - web apps, console apps, servers, and more.
Dart
660
star
3

intl

Internationalization and localization support
Dart
527
star
4

dart-samples

Various samples and examples in Dart
Dart
468
star
5

sdk

The Dartino project was an experiment seeking to improve productivity when writing application code for embedded devices.
Dart
325
star
6

dart-services

The server backend for a web based interactive Dart service
Dart
312
star
7

angular.dart.tutorial

AngularDart tutorial
Dart
236
star
8

pub_server

Reusable components for making a pub package server
Dart
215
star
9

bleeding_edge-DEPRECATED-USE-SDK-INSTEAD

NO LONGER SYNCING. use dart-lang/sdk
Dart
210
star
10

www.dartlang.org

DEPRECATED - OLD SITE for DART
HTML
197
star
11

dart-tutorials-samples

Sample code for "A Game of Darts" tutorial
Dart
187
star
12

polymer-dart

Polymer support for Dart
Dart
181
star
13

ts2dart

ts2dart TypeScript to Dart transpiler
TypeScript
177
star
14

js_facade_gen

Generates package:js Javascript interop facades for arbitrary TypeScript libraries
TypeScript
159
star
15

dev_compiler

DEPRECATED - Moved to main SDK
JavaScript
136
star
16

intl_translation

Message extraction and code generation from translated messages for the intl package
Dart
128
star
17

tflite_native

A Dart interface to TensorFlow Lite (tflite) through dart:ffi
Dart
125
star
18

rpc

RPC package for building server-side RESTful Dart APIs.
Dart
117
star
19

one-hour-codelab

Learn how to build a webapp with Dart in one hour.
Dart
104
star
20

dart-up-and-running-book

ARCHIVE - The DocBook (XML) and code that make up the O'Reilly book Dart: Up and Running
Dart
98
star
21

isolate

Makes working with Dart isolates easier.
Dart
90
star
22

dart_docker

Docker images for Dart
Shell
85
star
23

dart_enhancement_proposals

This repo contains info on DEP - Dart Enhancement Proposal
Dart
81
star
24

dart-protoc-plugin

Dart plugin for protobuf compiler (protoc)
79
star
25

discoveryapis_generator

Create API Client libraries based on the API's Discovery documentation
Dart
77
star
26

graphs

Graph algorithms
Dart
74
star
27

angular_analyzer_plugin

WORK MOVED TO dart-lang/angular repository
69
star
28

di.dart

DEPRECATED
Dart
66
star
29

googleapis_examples

Examples for accessing Google APIs with Dart
Dart
66
star
30

angular_components_example

A sample usage of https://github.com/dart-lang/angular_components
Dart
66
star
31

polymer-dart-patterns

Small, useful, snippets/samples that show how to do things the Polymer.dart way.
HTML
63
star
32

conference_app

Dart
56
star
33

paper-elements

Polymer.dart <=0.17.0 wrappers for Polymer's paper-elements
HTML
52
star
34

pub-dartlang

DEPRECATED - old pub.dartlang.org site in Python
Python
43
star
35

dump-info-visualizer

A visualizer for the JSON data produced by the dart2js --dump-info command
Dart
43
star
36

googleapis_auth

Obtain OAuth 2.0 credentials to access Google APIs
Dart
38
star
37

http_server

Utility classes for HTTP server
Dart
37
star
38

bazel

Bazel support for Dart projects [EXPERIMENTAL]
Dart
34
star
39

appengine_samples

Dart App Engine samples
Dart
33
star
40

core-elements

Polymer core-* elements wrapped or ported for Dart
HTML
33
star
41

route.dart

MOVE to https://github.com/dart-lang/angular/tree/master/angular_router
Dart
29
star
42

ton80

A benchmark suite for Dart
Dart
25
star
43

polymer_elements

JavaScript
24
star
44

shelf_static

archived repo
Dart
24
star
45

shelf_proxy

A shelf handler for proxying requests to another server.
Dart
23
star
46

dartdoc-viewer

deprecated. Use dartdoc instead.
Dart
23
star
47

sample-todomvc-polymer

todomvc example built with polymer.dart
Dart
22
star
48

shelf_web_socket

A WebSocket handler for Shelf.
Dart
22
star
49

kernel

Dart IR (Intermediate Representation) -- moved to dart-lang/sdk
Dart
21
star
50

web-components

Dart package providing the web components platform polyfills
JavaScript
18
star
51

polymer-core-and-paper-examples

This repo contains examples for the core and paper polymer elements, from Dart
HTML
16
star
52

resource

Resource loading library.
Dart
16
star
53

http_io

Dart
15
star
54

http_retry

HTTP client middleware that automatically retries requests
Dart
15
star
55

angular_ast

DEPRECATED - development moved to share angular repo
Dart
15
star
56

dart2js_info

Model of the data produced by dart2js with --dump-info, and tools that process the information.
Dart
14
star
57

polymer-and-dart-codelab

Polymer Dart codelab sample code
HTML
14
star
58

custom-element-apigen

Tool to generate Dart APIs for polymer custom elements written in Javascript
Dart
13
star
59

old_ghpages_server_docs

Documentation for Dart on the server
HTML
13
star
60

observe

Support for marking objects as observable, and getting notifications when those objects are mutated
Dart
13
star
61

angular_test

**MOVED**: Repository has moved to https://github.com/dart-lang/angular
13
star
62

vm_service_client

A Darty client for the VM service protocol
Dart
12
star
63

smoke

Smoke is a Dart package that exposes a reduced reflective system API. This API includes accessing objects in a dynamic fashion (read properties, write properties, and call methods), inspecting types (for example, whether a method exists), and symbol/string convention.
Dart
12
star
64

rules_dart

Dart rules for Bazel
Python
11
star
65

polymer-spa-example

A sample "Single Page App" for Polymer.dart <=0.17.0
Dart
11
star
66

vm_service_drivers

[DEPRECATED] Libraries to access the Dart VM Service Protocol
Dart
11
star
67

barback

An asset build system for Dart.
Dart
11
star
68

angulardart.org

Website for AngularDart, a web framework for Dart
HTML
10
star
69

utf

Provides common operations for manipulating Unicode sequences
Dart
10
star
70

rpc-examples

Dart
9
star
71

expected_output

Dart
9
star
72

memcache

Memcache interface for the Dart appengine package
Dart
9
star
73

atom-dartino

Atom Plug-in for Dartino
JavaScript
8
star
74

angular2_api_examples

DEPRECATED - content moved
8
star
75

shelf_rpc

shelf_rpc is a Shelf Handler for the Dart rpc package.
Dart
7
star
76

webcore

Web DOM IDL files and support files copied from Blink
Python
7
star
77

eclipse3

DEPRECATED - NO LONGER maintained/supported - Eclipse plugins and Dart Editor
Java
7
star
78

package_resolver

First-class package resolution strategy classes.
Dart
7
star
79

polymer_interop

Repackaging of the original polymer js source.
HTML
7
star
80

dart2_fix

A tool to migrate API usage to Dart 2
Dart
7
star
81

plugin

Dart
7
star
82

observatory

The website for Dart VM's Observatory
CSS
7
star
83

initialize

Provides a common interface for initialization annotations on top level methods, classes, and libraries in Dart
Dart
7
star
84

dart2es6

Dart to ECMAScript 6 transpiler
JavaScript
6
star
85

dart-doc-syncer

A utility for syncing Dart examples for the public docs
Dart
6
star
86

http_throttle

HTTP client middleware that throttles requests.
Dart
6
star
87

io_2017_components_codelab

Dart
6
star
88

code_transformers

Package to help with code transformers in barback
Dart
5
star
89

discoveryapis_commons

A package used by client libraries generated from discovery documents.
Dart
5
star
90

shelf_test_handler

A Shelf handler that makes it easy to test HTTP interactions
Dart
5
star
91

shelf_appengine

A set helpers to make it easy to use Shelf on App Engine.
Dart
5
star
92

csslib-test-suite

Suite of CSS tests (originating from the W3C) used to validate CSS parsing.
HTML
4
star
93

site-events

Source of events.dartlang.org
CSS
3
star
94

test_reflectable

tests for the reflectable package
Dart
3
star
95

polymer-expressions

Polymer.dart <=0.17.0 support for polymer expressions in Dart
Dart
3
star
96

shelf_packages_handler

A shelf handler for serving a `packages/` directory
Dart
3
star
97

gulp-ts2dart

Gulp task to transpile TypeScript code to Dart
JavaScript
3
star
98

func

Repository for the func package containing convenience typedefs for specifying function types.
Dart
3
star
99

scheduled_test

A package for writing readable tests of asynchronous behavior.
Dart
3
star
100

multi_server_socket

An implementation of dart:io's ServerSocket that wraps multiple servers and forwards methods to all of them
Dart
3
star