//- UNCLASSIFIED

extends base
append base_parms
	- tech = "d3"

append base_help
	:markdown
		Display d3 us map chart using parameters:

			src = source url returning map [ { name: "...", code: "", doc: "", lat: N, lon: N, ... }, ... ]
			name = "name" || "name%..." || "" of source record(s)
			pivots = "key,key,..." || "" source record grouping keys
			w = drawing width
			h = drawing height
			debug = level of debugging alerts
			node,nodes,value,size,parent,doc = tree keys

append base_head
	style.
		.states :hover {
			fill: red;
		}

		.state-borders {
			fill: none;
			stroke: #fff;
			stroke-width: 1px;
			stroke-linejoin: round;
			stroke-linecap: round;
			pointer-events: none;
		}

		.state-counties {
			stroke-width: 0.5px;
			stroke: #aaa;
		}
											
	script.
		var opts = {
			ds: "#{query.pivots}"
				? "!{query.src}.tree?name=#{query[NAME]}&_sort=#{query.pivots}"
				: "#{query[NAME]}"
							? "!{query.src}.schema?name=#{query[NAME]}"
							: "!{query.src}" || "/mapdata.json",

			url: "#{url}",
			family: "usmap,worldmap",

			dims: {
				margin: {top: 20, right: 90, bottom: 30, left: 90},
				width: parseInt("#{query.w}") || 1200,
				height: parseInt("#{query.h}") || 500
			},
			debug: parseInt("#{query.debug}"),

			keys: {
				NODE: "#{query.node}" || "name",
				NODES: "#{query.nodes}" || "children",
				VALUE: "#{query.value}" || "value",
				PARENT: "#{query.parent}" || "parent",
				SIZE: "#{query.size}" || "size",
				DOC: "#{query.doc}" || "doc"
			}
		};
		
		const {NODE, NODES, VALUE, SIZE, PARENT, DOC} = opts.keys;

append base_body
	script(src="/clients/topojson.min.js")
	script.
		// https://observablehq.com/@d3/u-s-map-canvas
		// https://bl.ocks.org/mbostock/1073373
		Fetch( "/stores/usatlas.json" , usatlas => {
			Fetch( opts, (data,svg) => {
				var
					width = svg.attr("width"),
					height = svg.attr("height"),
					path = d3.geoPath(),
					us = usatlas[0];

				svg.append("g")
						.attr("class", "states")
						.selectAll("path")
						.data(topojson.feature(us, us.objects.states).features)
						.enter().append("path")
							.attr("d", path);

				svg.append("path")
						.attr("class", "state-borders")
						.attr("d", path(topojson.mesh(us, us.objects.states, (a, b) => a !== b )));
											
				svg.append("path")
						.attr("class", "state-counties")
						.attr("d", path(topojson.mesh(us, us.objects.counties, (a, b) => a !== b && (a.id / 1000 | 0) === (b.id / 1000 | 0))) );
			});
		});

// UNCLASSIFIED
		
