Category: JavaScript
Mar 4, 2019

I love using YUIDoc for my JavaScript projects because the setup is dead simple and the default theme has everything I need, including search and good markup for SEO. It’s no secret it’s a little outdated, though (does Yahoo! even still exist?). If you’re using more modern JavaScript practices like CommonJS modules, you’ll probably run into issues with its interpretation of a “module” versus a “class”–two concepts that have evolved wildly in their practical usage in JavaScript since YUIDoc was created.

Suffice to say, “module” in YUIDoc doesn’t mean “module” in the import/export/require sense, especially when you’re splitting your code out into smaller files or using something like Browserify to bundle your project. Classes didn’t even technically exist (at least in name) until ECMAScript 2015. So how do you document a module such that it shows up nicely in your documentation?

Static vs. Constructor Classes

What you’re probably looking for is a “static class.” YUIDoc’s syntax reference notes that whenever you define a @class you should include a @static or @constructor tag. The @constructor tag’s use is self-evident in the traditional sense of a class, whereas the @static tag “indicates that you should not instantiate the class with new. You can call all of the class’s methods statically.” That sounds kind of like what we’re doing when requiring a module!

Assuming you’re exporting an object with methods, you can document the module as a static class and then write up each of its methods with the @method tag. Place a block like so at the top of your module:

<pre class="CodeMirror cm-s-monokai" data-setting="%1$s">/**
 * Provides sorting tools for Posts instances
 *
 * @class sort
 * @static
 * @uses validatePostArray
 */</pre>

Then document each of the methods of the returned object like so:

<pre class="CodeMirror cm-s-monokai" data-setting="%1$s">/**
 * Sorts posts in a Posts instance by their
 * pubDate property, descending.
 *
 * @example
 * 	sort.pubDateNewest(Posts);
 *
 * @method pubDateNewest
 *
 * @param {Posts} posts Posts instance
 * @return {Posts} sorted Posts instance
 */</pre>
Methods indexed at same level of importance in module documentation

But what if you’re not exporting an object with methods?

Exporting a Function

If you’re exporting a single function (with or without @private methods in the module) you’ll need a workaround, though. A @class tag will not respect the usual @method tags like @param and @return.

In this case, what I recommend is placing your @class block, then immediately below it placing an @method block with the method name matching your module name. Document the function you’re returning as a normal method, then in your class block, write in the description that the class is a module that exports that method, and link to the method with an anchor tag.

<pre class="CodeMirror cm-s-monokai" data-setting="%1$s">/**
 * CommonJS module - exports <a href="#method_fetchXML">fetchXML</a>
 *
 * @class fetchXML
 * @static
 */

/**
 * Fetches an XMLDocument instance from a URL.
 * 
 * @example
 * 	let xmlDoc = await require("path/fetchXML.js")("https://example.com/feed");
 *
 * @method fetchXML
 * @async
 * @chainable
 * @param {String} url URL of feed to retrieve
 * @return {XMLDocument} traversable XMLDocument instance
 */</pre>

This ensures that the exported function has a clear, expected name and takes a place front-and-center in your module’s documentation. Clicking the link in the class description will immediately open the documentation for your exported function.

Exported function takes a priority spot in the “class” description

Using this formatting will allow you to document any range of CommonJS modules and point clearly to your exports while ensuring they show up in the index on the left.

The future of YUIDoc

YUIDoc has been around for a while and has a lot of competitors like JSDoc, ESDoc, Doxx, Docco, Document! X, and Natural Docs. While its functionality is probably not going anywhere any time soon, I’m interested to hear what documentation tools you use and how they address modern JavaScript. Feel free to leave a comment or send me an email on this topic!

Jan 5, 2017

Normally in web application development, clicks are a matter of listeners. Either a click hit a thing or it didn’t. When using the HTML5 canvas, this isn’t the case. Images and features are rendered onto it, but you can’t attach a listener to them. Instead, you monitor where these elements visually reside versus where clicks land.

If an object is rectangular and will never rotate, the solution is easy. If click X is between object start X and object end X, and click Y likewise, then it hit. If not, it didn’t.

In this post we’ll construct a simple series of functions for determining the same thing if the rectangle has rotated, then look at how the idea can apply to more complex shapes. Nothing new or groundbreaking, and nothing language-specific — consider this a StackOverflow answer.

Visualization

For a developer who hasn’t mathed in a while, this can seem tricky at first. Once you see a few images it’s perfectly sensible.

We’ll be drawing four triangles. Each one consists of the click point and two vertices of the object. We then compare the area of the object to the combined area of the triangles. If they’re the same, the click had to be in the object. If the triangles are larger, the click couldn’t have been in the object.

Rotated Rectangle - Click hit
If the click was inside, the areas are equal.
Rotated Rectangle - Click miss
If the click was outside, the combined area of the triangles is bigger than the area of the rectangle.

How much it’s rotated doesn’t matter. Where it’s at doesn’t matter. That’s literally all there is to this.

First things first

To figure out if the click hit, we’ll need four pieces of data:

  • The coordinates of the click
  • The position of the rectangle
  • The size of the rectangle
  • The angle of rotation of the rectangle

Those last three pieces we’re just putting together so we can find the vertices. Once we know the click position and the vertex positions, figuring out if the click hit is easy.

Finding the vertices

Since you’re probably not tracking the individual locations of the vertices and are instead tracking the position of the object, you’ll want to start with a function that can find these by the object’s size and position. How this will be done is hugely variable depending on where you’re measuring from (tracking left top? center?) and if/how the object has been scaled.

If we pretend like there’s no scaling or rotation and we’re measuring from left and top, the function may initially look like this:

<pre class="CodeMirror cm-s-monokai" data-setting="%1$s">// Find vertices before taking rotation into account
function findRectVertices(position, size) {
	var left = position[0];
	var right = position[0] + size[0];
	var top = position[1];
	var bottom = position[1] + size[1];
	
	return {
		LT: [ left, top ],
		RT: [ right, top ],
		RB: [ right, bottom ],
		LB: [ left, bottom ]
	};
}</pre>

Since this doesn’t take into account rotation yet, we’ll need a utility function to find a point’s new location after it’s been rotated by X degrees around another point:

<pre class="CodeMirror cm-s-monokai" data-setting="%1$s">/**
* Find point after rotation around another point by X degrees
*
* @param {Array} point The point to be rotated [X,Y]
* @param {Array} rotationCenterPoint The point that should be rotated around [X,Y]
* @param {Number} degrees The degrees to rotate the point
* @return {Array} Returns point after rotation [X,Y]
*/
function rotatePoint(point, rotationCenterPoint, degrees) {
	// Using radians for this formula
	var radians = degrees * Math.PI / 180;

	// Translate the plane on which rotation is occurring.
	// We want to rotate around 0,0. We'll add these back later.
	point[0] -= rotationCenterPoint[0];
	point[1] -= rotationCenterPoint[1];

	// Perform the rotation
	var newPoint = [];
	newPoint[0] = point[0] * Math.cos(radians) - point[1] * Math.sin(radians);
	newPoint[1] = point[0] * Math.sin(radians) + point[1] * Math.cos(radians);

	// Translate the plane back to where it was.
	newPoint[0] += rotationCenterPoint[0];
	newPoint[1] += rotationCenterPoint[1];

	return newPoint;
}</pre>

Modifying our previous findRectVertices  function to also use rotation may then look like this, assuming we’re rotating objects around their center:

<pre class="CodeMirror cm-s-monokai" data-setting="%1$s">/**
* Find the vertices of a rotating rectangle
*
* @param {Array} position From left, top [X,Y]
* @param {Array} size Lengths [X,Y]
* @param {Number} degrees Degrees rotated around center
* @return {Object} Arrays LT, RT, RB, LB [X,Y]
*/
function findRectVertices(position, size, degrees) {
	var left = position[0];
	var right = position[0] + size[0];
	var top = position[1];
	var bottom = position[1] + size[1];

	var center = [ right - left, bottom - top ];
	var LT = [ left, top ];
	var RT = [ right, top ];
	var RB = [ right, bottom ];
	var LB = [ left, bottom ];

	return {
		LT: rotatePoint(LT, center, degrees),
		RT: rotatePoint(RT, center, degrees),
		RB: rotatePoint(RB, center, degrees),
		LB: rotatePoint(LB, center, degrees)
	};
}</pre>

Calculating the areas

Now that we have all the necessary points, all that’s left are three things:

  • Calculate the area of the rectangle
  • Calculate the area of the triangles
  • Compare the two

If you recall high school geometry, point two is the loaded one there. To find the area of an unknown triangle we’d use Heron’s formula, but first the distances of each side will be needed. The two utility functions may look like this:

<pre class="CodeMirror cm-s-monokai" data-setting="%1$s">/**
* Distance formula
*
* @param {Array} p1 First point [X,Y]
* @param {Array} p2 Second point [X,Y]
* @return {Number} Returns distance between points
*/
function distance(p1, p2) {
	return Math.sqrt( Math.pow(p1[0] - p2[0], 2) + Math.pow(p1[1] - p2[1], 2) );
}

/**
* Heron's formula (triangle area)
*
* @param {Number} d1 Distance, side 1
* @param {Number} d2 Distance, side 2
* @param {Number} d3 Distance, side 3
* @return {Number} Returns area of triangle
*/
function triangleArea(d1, d2, d3) {
	// See https://en.wikipedia.org/wiki/Heron's_formula
	var s = (d1 + d2 + d3) / 2;
	return Math.sqrt(s * (s - d1) * (s - d2) * (s - d3));
}</pre>

With those functions ready, we can now write a complete function that performs the three bullet points and returns a simple True or False:

<pre class="CodeMirror cm-s-monokai" data-setting="%1$s">/**
* Determine if a click hit a rotated rectangle
*
* @param {Array} click Click position [X,Y]
* @param {Array} position Rect from left, top [X,Y]
* @param {Array} size Rect size as lengths [X,Y]
* @param {Number} degrees Degrees rotated around center
* @return {Boolean} Returns true if hit, false if miss
*/
function clickHit(click, position, size, degrees) {
	// Find the area of the rectangle
	// Round to avoid small JS math differences
	var rectArea = Math.round(size[0] * size[1]);

	// Find the vertices
	var vertices = findRectVertices(position, size, degrees);

	// Create an array of the areas of the four triangles
	var triArea = [
		// Click, LT, RT
		triangleArea(
			distance(click, vertices.LT),
			distance(vertices.LT, vertices.RT),
			distance(vertices.RT, click)
		),
		// Click, RT, RB
		triangleArea(
			distance(click, vertices.RT),
			distance(vertices.RT, vertices.RB),
			distance(vertices.RB, click)
		),
		// Click, RB, LB
		triangleArea(
			distance(click, vertices.RB),
			distance(vertices.RB, vertices.LB),
			distance(vertices.LB, click)
		),
		// Click, LB, LT
		triangleArea(
			distance(click, vertices.LB),
			distance(vertices.LB, vertices.LT),
			distance(vertices.LT, click)
		)
	];

	// Reduce this array with a sum function
	// Round to avoid small JS math differences
	triArea = Math.round(triArea.reduce(function(a,b) { return a + b; }, 0));

	// Finally do that simple thing we visualized earlier
	if (triArea > rectArea) {
		return true;
	}
	return false;
}</pre>

Common issues

By far the most frequent annoyance with this approach when working in the DOM is going to be getting good position numbers. So many variables can throw a wrench in how you’re measuring where the object is. If your reported object position doesn’t match up with the reported mouse or touch position, all of the above is useless.

Look for situations in which clicking near something instead of on it reports a hit, then try to identify elements that match the size of the inaccuracy. Everything from margins on the HTML or body elements, borders on divs, document scroll position, and box-sizing settings can play havoc on your ability to get clean measurements that match up with what’s plainly visible.

Going farther

This method isn’t just good for rectangles. It would be straightforward to apply to triangles, too, or for any other convex polygon. Consider how you might implement the ability to check if a click landed inside a hexagon. As a brain teaser, what would happen on a concave polygon?

Jan 4, 2017

My team does a holiday card promotion each year, which gives us a chance to create something unusual. This year we decided on a “create your own holiday card” image editor idea. We’d specify a couple of backgrounds and design a bunch of “sticker” graphics, then users could arrange these how they liked and print off a foldable […]

Continue reading...
Sep 15, 2016

Update:  Now with more style. The most important thing in life is to have your pokémon arranged neatly. That’s a fact. While I understand you can just rename boxes with numbers so that Box 1 is 1-30 and Box 2 is 31-60, etc., there’s still a tiny bit of basic arithmetic slowing down your sorting […]

Continue reading...
Fork me on GitHub