How do you get around Cloned Templates losing Element References? - hyperhtml

I noticed that hyperHTML preserves references I make to elements:
let div = document.createElement("div");
div.textContent = "Before Update";
hyperHTML.bind(document.body)`static1 - ${div} - static2`;
div.textContent = "After Update";
Above will produce a page that says:
static1 - After Update - static2
It is my understanding that hyperHTML ultimately clones an HTML <tempate> element to render the final output. However, don't you typical lose references when cloning an HTML template (like the variable "div" in the example above)?
Therefore, on the initial render, does hyperHTML somehow replace cloned elements with their originals after cloning the HTML template?
Here's how I think it works:
Create an HTML Template of the original template literal while
replacing all interpolations with comments.
Clone the html template with comments left in.
Make elements or document fragments out of each interpolation originally recieved
Replace each comment in the clone with its processed interpolation.
Is this correct?

I am not sure what is the question here, but there is a documentation page, and various examples too to understand how to use hyperHTML, which is not exactly in the way you are using it.
In fact, there's no need to have any reference there because hyperHTML is declarative, so you'd rather write:
function update(text) {
var render = hyperHTML.bind(document.body);
render`static1 - <div>${text}</div> - static2`;
}
and call update("any text") any time you need.
Here's how I think it works ... Is this correct?
No, it's not. hyperHTML doesn't clone anything the way you described, it associates once per unique template tag a sanitized version to the output and finds out all interpolated holes in it.
The part of the library that does this is called domtagger, and the mapping per template literal is based on the standard fact that these are unique per scope:
const templates = [];
function addTemplate(template, value) {
templates.push(template);
return template.join(value);
}
function asTemplate(value) {
return addTemplate`number ${value}!`;
}
asTemplate(1);
asTemplate(2);
asTemplate(Math.random());
templates[0] === templates[1]; // true
templates[1] === templates[2]; // true
// it is always the same template object!
After that, any other element using once that very same tag template will have a clone of that fragment with a map to find holes once and some complex logic to avoid replacing anything that's already known, being that text, attributes, events, or any other kind of node.
hyperHTML never removes comments, it uses these as pin and then uses domdiff to eventually update nodes related to these pins whenever there's a need to update anything.
Domdiff is a vDOM-less implementation of the petit-dom algorithm, which in turns is based on E.W Myers' "An O(ND) Difference Algorithm and Its Variations" paper.
Whenever you have DOM nodes in the holes, hyperHTML understand that and fill these holes with those nodes. If you pass repeatedly the same node, hyperHTML won't do anything 'cause it's full of algorithm and smart decisions, all described in the documentation, to obtain best performance out of its abstraction.
All these things, and much more, normalized for any browser out there, makes hyperHTML weight roughly 7K once minified and gzipped, bit it also offers:
Custom Elements like hooks through onconnected/disconnected listeners
lightweight components through hyperHTML.Component
SVG manipulation as content or via wire
easy Custom Elements definition through HyperHTMLElement class
As summary, if you need these simplifications and you don't want to reinvent the wheel, I suggest you give it a better try.
If you instead are just trying to understand how it works, there's no need to assume anything because the project is fully open source.
So far, all I've read from your questions here and there, is that you just believe to understand how it works so I hope in this reply I've put together all the missing pieces you need to fully understand it.
Do you want to write your own lit/hyperHTML library? Go ahead, feel free to use the domtagger or the domdiff library too, few others are already doing the same.

Related

scala for mapbox vector tiles - getting an 'id' field into the Features written to vector tiles

I'm writing MapBox vector tiles using geotrellis vectorpipe.
see here for the basic flow: https://geotrellis.github.io/vectorpipe/usage.html
Typically GeoJson Features can have an id field, so that Features can be rolled up into FeatureCollections. I need to make use of this field, but vectorpipe doesn't (natively) have this capability.
This is the Feature type used, and you can see it only has space for 1) a Geometry and 2) a data object D (which ends up populating properties in the output). There is no spot for an id.
https://geotrellis.github.io/scaladocs/latest/index.html#geotrellis.vector.Feature
Upstream there's a method called writeFeatureJsonWithID() that does let you inject an id field into a Feature when writing GeoJson.
https://github.com/locationtech/geotrellis/blob/master/vector/src/main/scala/geotrellis/vector/io/json/FeatureFormats.scala#L41-L49
My question is this:
I have worked through the vectorpipe code (https://github.com/geotrellis/vectorpipe), and I can't figure out if/where the data ever exists as GeoJson in a way where I can override and inject the id, maybe using the writeFeatureJsonWithID() or something I write explicitly. A lot of conversions are implicit, but it also may never explicitly sit as json.
Any ideas for how to get an id field in the final GeoJson written to vector tiles?
EDIT
Right now I think the trick is going to be finding a way to override .unfeature() method here:
https://github.com/locationtech/geotrellis/blob/master/vectortile/src/main/scala/geotrellis/vectortile/Layer.scala
The problem is that the internal.vector_tile.Tile is private, so I can construct it without forking the project.
Ended up having to fork geotrellis, hard-code a metadata => id function in Layer.unfeature() and compile locally to include in my project. Not ideal, but it works fine.
Also opened an issue here: https://github.com/locationtech/geotrellis/issues/2884

Can I use Eclipse templates to insert methods and also call them?

I'm doing some competitions on a website called topcoder.com where the objective is to solve algorithmic problems. I'm using Eclipse for this purpose, and I code in Java, it would be help me to have some predefined templates or macros that I can use for common coding tasks. For example I would like to write methods to be able to find the max value in and int[] array, or the longest sequence in an int[] array, and so on (there should be quite many of these). Note I can't write these methods as libraries because as part of the competition I need to submit everything in one file.
Therefore ideally, I would like to have some shortcut available to generate code both as a method and as a calling statement at once. Any ideas if this is possible?
Sure you can - I think that's a nifty way to auto-insert boilerplate or helper code. To the point of commenters, you probably want to group the code as a helper class, but the general idea sounds good to me:
You can see it listed in your available templates:
Then as you code your solution, you can Control+Space, type the first few characters of the name you gave your template, and you can preview it:
And then you can insert it. Be sure if you use a class structure to position it as an inner class:
Lastly - if you want to have a template inserts a call to method from a template, I think you would just use two templates. One like shown above (to print the helper code) and another that might look like this, which calls a util method and drops the cursor after it (or between the parentheses if you'd like, etc):
MyUtils.myUtilMethod1();${cursor}

ExtJS: Component VS Element VS other

I've been working with ExtJS for a good few months now, but still don't have a perfectly clear map of what's going on behind the scenes there. I'm just talking about the building blocks of the framework and their most basic functionality.
Ext.Component
Ext.Element
DOM.Element
DOM.Node (?)
CompositeElement (?)
Whatever else (?)
For each of the abovementioned I would like to know:
How to select: by ID, by class, via parent, find (OR children OR query OR select? WTF), siblings, ComponentQuery, DOM-query, CSS-query, etc..
How to manipulate in the tree: create, append, prepend, insert after this sibling, move to that parent, remove, destroy, etc..
How to manipulate on the screen: show, hide, fade, slide, move up, down, change size, etc..
How to identify related to each other: find DOM.Element knowing its Ext.Component, find Ext.Component knowing its DOM.Element, etc..
What is the dependency between them: what happens to the DOM.Element if its Ext.Component is hidden / destroyed / changed / moved, what happens to the Ext.Component if its Ext.Element is hidden / destroyed / changed / moved, etc.
I'm looking for a methodical and logically clear layout of how each is supposed to be used and is expected to behave. I am also hoping that the described functionality can be grouped in corresponding categories, e.g. would be nice to see complement traversing methods .up() and .down() next to each other, rather than alphabetically pages apart. Of course links and examples (which the official documentation lacks so badly) are also welcome!
You can find out a whole lot about the building blocks of ExtJS (known as Ext Core) from the manual for this: http://docs.sencha.com/core/manual/. I will try to add some knowledge and highlight some key points, but you should definitely read through that for a very informative overview.
Ext.Component
The building block for the OOP paradigm within ExtJS. Essentially, this is an Object that contains inherited functionality to serve as the basis for a specialized component that will be transformed by the framework into DOM elements that are shown as HTML.
The Sencha documentation is excellent for this. Here are a couple good places to start:
http://docs.sencha.com/extjs/4.2.1/#!/guide/layouts_and_containers
http://docs.sencha.com/extjs/4.2.1/#!/guide/components
Ext.Element vs DOM Element
As an JavaScript develop knows, a DOM element is just a JS object that represents a tag in the document's HTML. Essentially, Ext.Element is a wrapper object for a DOM element that allows for ExtJS to manipulate the object. Any DOM element on the page can be wrapped as an Ext.Element to allow for this additional functionality.
For example, take this HTML tag:
<div id="myDiv">My content</div>
You can access this using
var el = document.getElementById('myDiv')
and use the basic, built-in JavaScript DOM functionality on el. You could also access this using
var el = Ext.get('myDiv')
and have a whole additional set of functionality available to apply to that element using the ExtJS library
The Sencha docs are also excellent for this. See all the available functionality for Ext.Element here: http://docs.sencha.com/extjs/4.2.1/#!/api/Ext.dom.Element
Misc
You can get an Ext.Element from a component using the getEl() method:
var myComponent = Ext.create('Ext.Component', { html: 'my component' });
var el = myComponent.getEl();
You would rarely need to go the other way, to determine a component from a DOM element. There isn't much of a use case there unless you are really hacking something. A major reason for using a framework like ExtJS is to prevent needing to do something like this; if should develop entirely within the JavaScript, you should be able to avoid having a reference to a DOM element where you need to get its containing ExtJS component.
Niklas answered pretty well about how to select components and elements. The only things I would really add is that you can use up() and down() to select relative to a component. In this way, you should use itemId on components rather than the global identifier id (using id can cause difficult-to-debug errors if you are reusing components with the same ID).
Also, to add to Niklas's answer about showing/hiding components, the framework does indeed add some CSS to the component's element, depending on what the hideMode for the component is. Learn more about that property here: http://docs.sencha.com/extjs/4.2.1/#!/api/Ext.AbstractComponent-cfg-hideMode
An excellent way to learn more is to look through all of the examples that come packaged with the framework. Open the examples in your browser, then look through the code to find out how things are done. You will find it way easier to learn this way, rather than reading it on paper or a website. Nothing beats experience when it comes to learning something new.
How to select: by ID, by class, via parent, find (OR children OR query OR select? WTF), siblings, ComponentQuery, DOM-query, CSS-query, etc..
Ext.ComponentQuery.query("*") // get all
Ext.ComponentQuery.query("button") // all buttons
Ext.ComponentQuery.query("#myid") // all controls / components myid
Ext.ComponentQuery.query("#myid", rootelement) // all controls / components myid with rootelement
Ext.ComponentQuery.query("#myid,button") // all buttons or controls / components myid
How to manipulate in the tree: create, append, prepend, insert after this sibling, move to that parent, remove, destroy, etc..
Adding button to a View:
Ext.ComponentQuery.query("#viewId")[0].add(new Ext.Button({ text: 'test'}));
There is also insert, remove and so on depending on the control you are querying.
How to manipulate on the screen: show, hide, fade, slide, move up, down, change size, etc..
Ext.ComponentQuery.query("button").forEach(function(button){ button.hide(); }) // hide all buttons
There is also show, disable, enable and so on depending on the control you are querying.
How to identify related to each other: find DOM.Element knowing its Ext.Component, find Ext.Component knowing its DOM.Element, etc..
Finding Ext.Component knowing its Dom.Element is pretty easy, you just take the ID from the DOM element and use Ext.ComponentQuery.query("#id").
There is also Ext.select('#id') for getting the object from an ID.
With the element property you can get the DOM:
var dom = Ext.ComponentQuery.query("button")[0].element.dom // Getting the DOM from the first button
var dom2 = component.element.dom // does also work as long as component is a valid sencha touch component
What is the dependency between them: what happens to the DOM.Element if its Ext.Component is hidden / destroyed / changed / moved, what happens to the Ext.Component if its Ext.Element is hidden / destroyed / changed / moved, etc.
I think, I'm not sure, that if you call .hide for instance there will be some CSS applied to the DOM for example: display: none. Internally they can use some framework like jQuery for that or the old school version document.getElementById('id').css and so one. If you call .show, it may change to display: block or whatever type it was before(this could be saved in the Sencha Touch class).
I don't know what happens if the DOM element gets destroyed. Probably the element too and then the garbage collector has some work to do.
If there are any more questions / something was unclear or not enough, don't hesitate to ask.
An attempt to answer the question myself.
Since there is no TABLE markup support on this website, I put my answer in this shared Spreadsheet. Note the comments on mouse rollover.
It's just a pattern for now. It needs work to get more legible and complete. Feel free to comment, or ask me if you would like to edit it.

Using table-of-contents in code?

Do you use table-of-contents for listing all the functions (and maybe variables) of a class in the beginning of big source code file? I know that alternative to that kind of listing would be to split up big files into smaller classes/files, so that their class declaration would be self-explanatory enough.. but some complex tasks require a lot of code. I'm not sure is it really worth it spending your time subdividing implementation into multiple of files? Or is it ok to create an index-listing additionally to the class/interface declaration?
EDIT:
To better illustrate how I use table-of-contents this is an example from my hobby project. It's actually not listing functions, but code blocks inside a function.. but you can probably get the idea anyway..
/*
CONTENTS
Order_mouse_from_to_points
Lines_intersecting_with_upper_point
Lines_intersecting_with_both_points
Lines_not_intersecting
Lines_intersecting_bottom_points
Update_intersection_range_indices
Rough_method
Normal_method
First_selected_item
Last_selected_item
Other_selected_item
*/
void SelectionManager::FindSelection()
{
// Order_mouse_from_to_points
...
// Lines_intersecting_with_upper_point
...
// Lines_intersecting_with_both_points
...
// Lines_not_intersecting
...
// Lines_intersecting_bottom_points
...
// Update_intersection_range_indices
for(...)
{
// Rough_method
....
// Normal_method
if(...)
{
// First_selected_item
...
// Last_selected_item
...
// Other_selected_item
...
}
}
}
Notice that index-items don't have spaces. Because of this I can click on one them and press F4 to jump to the item-usage, and F2 to jump back (simple visual studio find-next/prevous-shortcuts).
EDIT:
Another alternative solution to this indexing is using collapsed c# regions. You can configure visual studio to show only region names and hide all the code. Of course keyboard support for that source code navigation is pretty cumbersome...
I know that alternative to that kind of listing would be to split up big files into smaller classes/files, so that their class declaration would be self-explanatory enough.
Correct.
but some complex tasks require a lot of code
Incorrect. While a "lot" of code be required, long runs of code (over 25 lines) are a really bad idea.
actually not listing functions, but code blocks inside a function
Worse. A function that needs a table of contents must be decomposed into smaller functions.
I'm not sure is it really worth it spending your time subdividing implementation into multiple of files?
It is absolutely mandatory that you split things into smaller files. The folks that maintain, adapt and reuse your code need all the help they can get.
is it ok to create an index-listing additionally to the class/interface declaration?
No.
If you have to resort to this kind of trick, it's too big.
Also, many languages have tools to generate API docs from the code. Java, Python, C, C++ have documentation tools. Even with Javadoc, epydoc or Doxygen you still have to design things so that they are broken into intellectually manageable pieces.
Make things simpler.
Use a tool to create an index.
If you create a big index you'll have to maintain it as you change your code. Most modern IDEs create list of class members anyway. it seems like a waste of time to create such index.
I would never ever do this sort of busy-work in my code. The most I would do manually is insert a few lines at the top of the file/class explaining what this module did and how it is intended to be used.
If a list of methods and their interfaces would be useful, I generate them automatically, through a tool such as Doxygen.
I've done things like this. Not whole tables of contents, but a similar principle -- just ad-hoc links between comments and the exact piece of code in question. Also to link pieces of code that make the same simplifying assumptions that I suspect may need fixing up later.
You can use Visual Studio's task list to get a listing of certain types of comment. The format of the comments can be configured in Tools|Options, Environment\Task List. This isn't something I ended up using myself but it looks like it might help with navigating the code if you use this system a lot.
If you can split your method like that, you should probably write more methods. After this is done, you can use an IDE to give you the static call stack from the initial method.
EDIT: You can use Eclipse's 'Show Call Hierarchy' feature while programming.

Using YAML tags to denote types

I don't quite understand how to use application specific YAML tags, and maybe its because my desired use of them is purely wrong. I am using YAML for a configuration file and was hoping to use tags to provide my configuration loader with a hint as to what datatype it should parse the data into - application specific datatypes.
I'm also using libyaml with C.
So I'm trying to do something like...
shapes:
square: "0,4,8,16"
circle: "5,10"
In my app I'd like to use tags as hints so I can load the values of square into my square data structure, and the values of circle into my circle data structure (these values mean nothing in this example).
So I'm currently doing:
shapes:
square: !square "0,4,8,16"
circle: !circle "5,10"
Libyaml will provide a tag of "!square" when I'm passed the scalar "0,4,8,16". Is it valid to use this tag to provide my loader with a hint of how to process the scalar?
Since it does work for me, I'm more curious to know if its proper. And if not, how would I go about making this more proper.
Thanks.
I know that this is an ancient question, but anyway I've seen !int, etc being used in yaml files before so I went to look up the specs at Yaml 1.2 Spec # Tags
application specific tag: !something |
The semantics of the tag
above may be different for
different documents.
As per the document, it does look like your intended usage of tags is correct for application specific tag.