Commit f064c792 authored by Muddsair Sharif's avatar Muddsair Sharif
Browse files

Initial commit

parents
Pipeline #8 canceled with stages
export {default as drag} from "./src/drag";
export {default as dragDisable, yesdrag as dragEnable} from "./src/nodrag";
{
"_args": [
[
{
"raw": "d3-drag@1.1.0",
"scope": null,
"escapedName": "d3-drag",
"name": "d3-drag",
"rawSpec": "1.1.0",
"spec": "1.1.0",
"type": "version"
},
"C:\\Users\\Giuliano\\worldwind\\nasaworldwind\\node\\node_modules\\d3"
]
],
"_from": "d3-drag@1.1.0",
"_id": "d3-drag@1.1.0",
"_inCache": true,
"_location": "/d3-drag",
"_nodeVersion": "7.3.0",
"_npmOperationalInternal": {
"host": "packages-18-east.internal.npmjs.com",
"tmp": "tmp/d3-drag-1.1.0.tgz_1494519148552_0.4138396279886365"
},
"_npmUser": {
"name": "mbostock",
"email": "mike@ocks.org"
},
"_npmVersion": "3.10.10",
"_phantomChildren": {},
"_requested": {
"raw": "d3-drag@1.1.0",
"scope": null,
"escapedName": "d3-drag",
"name": "d3-drag",
"rawSpec": "1.1.0",
"spec": "1.1.0",
"type": "version"
},
"_requiredBy": [
"/d3",
"/d3-brush",
"/d3-zoom"
],
"_resolved": "https://registry.npmjs.org/d3-drag/-/d3-drag-1.1.0.tgz",
"_shasum": "4a49b4d77a42e9e3d5a0ef3b492b14aaa2e5a733",
"_shrinkwrap": null,
"_spec": "d3-drag@1.1.0",
"_where": "C:\\Users\\Giuliano\\worldwind\\nasaworldwind\\node\\node_modules\\d3",
"author": {
"name": "Mike Bostock",
"url": "http://bost.ocks.org/mike"
},
"bugs": {
"url": "https://github.com/d3/d3-drag/issues"
},
"dependencies": {
"d3-dispatch": "1",
"d3-selection": "1"
},
"description": "Drag and drop SVG, HTML or Canvas using mouse or touch input.",
"devDependencies": {
"eslint": "3",
"package-preamble": "0.1",
"rollup": "0.41",
"tape": "4",
"uglify-js": "^2.8.11"
},
"directories": {},
"dist": {
"shasum": "4a49b4d77a42e9e3d5a0ef3b492b14aaa2e5a733",
"tarball": "https://registry.npmjs.org/d3-drag/-/d3-drag-1.1.0.tgz"
},
"gitHead": "c4104ced87f59e5e7b3eb52fde9c3701fa8a4c33",
"homepage": "https://d3js.org/d3-drag/",
"jsnext:main": "index",
"keywords": [
"d3",
"d3-module",
"drag",
"behavior",
"interaction"
],
"license": "BSD-3-Clause",
"main": "build/d3-drag.js",
"maintainers": [
{
"name": "mbostock",
"email": "mike@ocks.org"
}
],
"module": "index",
"name": "d3-drag",
"optionalDependencies": {},
"readme": "# d3-drag\n\n[Drag-and-drop](https://en.wikipedia.org/wiki/Drag_and_drop) is a popular and easy-to-learn pointing gesture: move the pointer to an object, press and hold to grab it, “drag” the object to a new location, and release to “drop”. D3’s [drag behavior](#api-reference) provides a convenient but flexible abstraction for enabling drag-and-drop interaction on [selections](https://github.com/d3/d3-selection). For example, you can use d3-drag to facilitate interaction with a [force-directed graph](https://github.com/d3/d3-force), or a simulation of colliding circles:\n\n[<img alt=\"Force Dragging III\" src=\"https://raw.githubusercontent.com/d3/d3-drag/master/img/force-graph.png\" width=\"420\" height=\"219\">](http://bl.ocks.org/mbostock/ad70335eeef6d167bc36fd3c04378048)[<img alt=\"Force Dragging II\" src=\"https://raw.githubusercontent.com/d3/d3-drag/master/img/force-collide.png\" width=\"420\" height=\"219\">](http://bl.ocks.org/mbostock/2990a882e007f8384b04827617752738)\n\nYou can also use d3-drag to implement custom user interface elements, such as a slider. But the drag behavior isn’t just for moving elements around; there are a variety of ways to respond to a drag gesture. For example, you can use it to lasso elements in a scatterplot, or to paint lines on a canvas:\n\n[<img alt=\"Line Drawing\" src=\"https://raw.githubusercontent.com/d3/d3-drag/master/img/drawing.png\" width=\"420\" height=\"219\">](http://bl.ocks.org/mbostock/f705fc55e6f26df29354)\n\nThe drag behavior can be combined with other behaviors, such as [d3-zoom](https://github.com/d3/d3-zoom) for zooming.\n\n[<img alt=\"Drag & Zoom II\" src=\"https://raw.githubusercontent.com/d3/d3-drag/master/img/dots.png\" width=\"420\" height=\"219\">](http://bl.ocks.org/mbostock/3127661b6f13f9316be745e77fdfb084)\n\nThe drag behavior is agnostic about the DOM, so you can use it with SVG, HTML or even Canvas! And you can extend it with advanced selection techniques, such as a Voronoi overlay or a closest-target search:\n\n[<img alt=\"Circle Dragging IV\" src=\"https://raw.githubusercontent.com/d3/d3-drag/master/img/voronoi.png\" width=\"420\" height=\"219\">](http://bl.ocks.org/mbostock/ec10387f24c1fad2acac3bc11eb218a5)[<img alt=\"Circle Dragging II\" src=\"https://raw.githubusercontent.com/d3/d3-drag/master/img/canvas.png\" width=\"420\" height=\"219\">](http://bl.ocks.org/mbostock/c206c20294258c18832ff80d8fd395c3)\n\nBest of all, the drag behavior automatically unifies mouse and touch input, and avoids browser idiosyncrasies. When [Pointer Events](https://www.w3.org/TR/pointerevents/) are more widely available, the drag behavior will support those, too.\n\n## Installing\n\nIf you use NPM, `npm install d3-drag`. Otherwise, download the [latest release](https://github.com/d3/d3-drag/releases/latest). You can also load directly from [d3js.org](https://d3js.org), either as a [standalone library](https://d3js.org/d3-drag.v1.min.js) or as part of [D3 4.0](https://github.com/d3/d3). AMD, CommonJS, and vanilla environments are supported. In vanilla, a `d3` global is exported:\n\n```html\n<script src=\"https://d3js.org/d3-dispatch.v1.min.js\"></script>\n<script src=\"https://d3js.org/d3-selection.v1.min.js\"></script>\n<script src=\"https://d3js.org/d3-drag.v1.min.js\"></script>\n<script>\n\nvar drag = d3.drag();\n\n</script>\n```\n\n[Try d3-drag in your browser.](https://tonicdev.com/npm/d3-drag)\n\n## API Reference\n\nThis table describes how the drag behavior interprets native events:\n\n| Event | Listening Element | Drag Event | Default Prevented? |\n| ------------ | ----------------- | ---------- | ------------------ |\n| mousedown⁵ | selection | start | no¹ |\n| mousemove² | window¹ | drag | yes |\n| mouseup² | window¹ | end | yes |\n| dragstart² | window | - | yes |\n| selectstart² | window | - | yes |\n| click³ | window | - | yes |\n| touchstart | selection | start | no⁴ |\n| touchmove | selection | drag | yes |\n| touchend | selection | end | no⁴ |\n| touchcancel | selection | end | no⁴ |\n\nThe propagation of all consumed events is [immediately stopped](https://dom.spec.whatwg.org/#dom-event-stopimmediatepropagation). If you want to prevent some events from initiating a drag gesture, use [*drag*.filter](#drag_filter).\n\n¹ Necessary to capture events outside an iframe; see [#9](https://github.com/d3/d3-drag/issues/9).\n<br>² Only applies during an active, mouse-based gesture; see [#9](https://github.com/d3/d3-drag/issues/9).\n<br>³ Only applies immediately after some mouse-based gestures; see [*drag*.clickDistance](#drag_clickDistance).\n<br>⁴ Necessary to allow [click emulation](https://developer.apple.com/library/ios/documentation/AppleApplications/Reference/SafariWebContent/HandlingEvents/HandlingEvents.html#//apple_ref/doc/uid/TP40006511-SW7) on touch input; see [#9](https://github.com/d3/d3-drag/issues/9).\n<br>⁵ Ignored if within 500ms of a touch gesture ending; assumes [click emulation](https://developer.apple.com/library/ios/documentation/AppleApplications/Reference/SafariWebContent/HandlingEvents/HandlingEvents.html#//apple_ref/doc/uid/TP40006511-SW7).\n\n<a href=\"#drag\" name=\"drag\">#</a> d3.<b>drag</b>() [<>](https://github.com/d3/d3-drag/blob/master/src/drag.js \"Source\")\n\nCreates a new drag behavior. The returned behavior, [*drag*](#_drag), is both an object and a function, and is typically applied to selected elements via [*selection*.call](https://github.com/d3/d3-selection#selection_call).\n\n<a href=\"#_drag\" name=\"_drag\">#</a> <i>drag</i>(<i>selection</i>) [<>](https://github.com/d3/d3-drag/blob/master/src/drag.js#L31 \"Source\")\n\nApplies this drag behavior to the specified [*selection*](https://github.com/d3/d3-selection). This function is typically not invoked directly, and is instead invoked via [*selection*.call](https://github.com/d3/d3-selection#selection_call). For example, to instantiate a drag behavior and apply it to a selection:\n\n```js\nd3.selectAll(\".node\").call(d3.drag().on(\"start\", started));\n```\n\nInternally, the drag behavior uses [*selection*.on](https://github.com/d3/d3-selection#selection_on) to bind the necessary event listeners for dragging. The listeners use the name `.drag`, so you can subsequently unbind the drag behavior as follows:\n\n```js\nselection.on(\".drag\", null);\n```\n\nApplying the drag behavior also sets the [-webkit-tap-highlight-color](https://developer.apple.com/library/mac/documentation/AppleApplications/Reference/SafariWebContent/AdjustingtheTextSize/AdjustingtheTextSize.html#//apple_ref/doc/uid/TP40006510-SW5) style to transparent, disabling the tap highlight on iOS. If you want a different tap highlight color, remove or re-apply this style after applying the drag behavior.\n\n<a href=\"#drag_container\" name=\"drag_container\">#</a> <i>drag</i>.<b>container</b>([<i>container</i>]) [<>](https://github.com/d3/d3-drag/blob/master/src/drag.js#L31 \"Source\")\n\nIf *container* is specified, sets the container accessor to the specified object or function and returns the drag behavior. If *container* is not specified, returns the current container accessor, which defaults to:\n\n```js\nfunction container() {\n return this.parentNode;\n}\n```\n\nThe *container* of a drag gesture determines the coordinate system of subsequent [drag events](#drag-events), affecting *event*.x and *event*.y. The element returned by the container accessor is subsequently passed to [d3.mouse](https://github.com/d3/d3-selection#mouse) or [d3.touch](https://github.com/d3/d3-selection#touch), as appropriate, to determine the local coordinates of the pointer.\n\nThe default container accessor returns the parent node of the element in the originating selection (see [*drag*](#_drag)) that received the initiating input event. This is often appropriate when dragging SVG or HTML elements, since those elements are typically positioned relative to a parent. For dragging graphical elements with a Canvas, however, you may want to redefine the container as the initiating element itself:\n\n```js\nfunction container() {\n return this;\n}\n```\n\nAlternatively, the container may be specified as the element directly, such as `drag.container(canvas)`.\n\n<a href=\"#drag_filter\" href=\"drag_filter\">#</a> <i>drag</i>.<b>filter</b>([<i>filter</i>]) [<>](https://github.com/d3/d3-drag/blob/master/src/drag.js#L126 \"Source\")\n\nIf *filter* is specified, sets the filter to the specified function and returns the drag behavior. If *filter* is not specified, returns the current filter, which defaults to:\n\n```js\nfunction filter() {\n return !d3.event.button;\n}\n```\n\nIf the filter returns falsey, the initiating event is ignored and no drag gestures are started. Thus, the filter determines which input events are ignored; the default filter ignores mousedown events on secondary buttons, since those buttons are typically intended for other purposes, such as the context menu.\n\n<a href=\"#drag_subject\" name=\"drag_subject\">#</a> <i>drag</i>.<b>subject</b>([<i>subject</i>]) [<>](https://github.com/d3/d3-drag/blob/master/src/drag.js#L134 \"Source\")\n\nIf *subject* is specified, sets the subject accessor to the specified object or function and returns the drag behavior. If *subject* is not specified, returns the current subject accessor, which defaults to:\n\n```js\nfunction subject(d) {\n return d == null ? {x: d3.event.x, y: d3.event.y} : d;\n}\n```\n\nThe *subject* of a drag gesture represents *the thing being dragged*. It is computed when an initiating input event is received, such as a mousedown or touchstart, immediately before the drag gesture starts. The subject is then exposed as *event*.subject on subsequent [drag events](#drag-events) for this gesture.\n\nThe default subject is the [datum](https://github.com/d3/d3-selection#selection_datum) of the element in the originating selection (see [*drag*](#_drag)) that received the initiating input event; if this datum is undefined, an object representing the coordinates of the pointer is created. When dragging circle elements in SVG, the default subject is thus the datum of the circle being dragged. With [Canvas](https://html.spec.whatwg.org/multipage/scripting.html#the-canvas-element), the default subject is the canvas element’s datum (regardless of where on the canvas you click). In this case, a custom subject accessor would be more appropriate, such as one that picks the closest circle to the mouse within a given search *radius*:\n\n```js\nfunction subject() {\n var n = circles.length,\n i,\n dx,\n dy,\n d2,\n s2 = radius * radius,\n circle,\n subject;\n\n for (i = 0; i < n; ++i) {\n circle = circles[i];\n dx = d3.event.x - circle.x;\n dy = d3.event.y - circle.y;\n d2 = dx * dx + dy * dy;\n if (d2 < s2) subject = circle, s2 = d2;\n }\n\n return subject;\n}\n```\n\n(If necessary, the above can be accelerated using [*quadtree*.find](https://github.com/d3/d3-quadtree#quadtree_find).)\n\nThe returned subject should be an object that exposes `x` and `y` properties, so that the relative position of the subject and the pointer can be preserved during the drag gesture. If the subject is null or undefined, no drag gesture is started for this pointer; however, other starting touches may yet start drag gestures. See also [*drag*.filter](#drag_filter).\n\nThe subject of a drag gesture may not be changed after the gesture starts. The subject accessor is invoked with the same context and arguments as [*selection*.on](https://github.com/d3/d3-selection#selection_on) listeners: the current datum `d` and index `i`, with the `this` context as the current DOM element. During the evaluation of the subject accessor, [d3.event](https://github.com/d3/d3-selection#event) is a beforestart [drag event](#drag-events). Use *event*.sourceEvent to access the initiating input event and *event*.identifier to access the touch identifier. The *event*.x and *event*.y are relative to the [container](#drag_container), and are computed using [d3.mouse](https://github.com/d3/d3-selection#mouse) or [d3.touch](https://github.com/d3/d3-selection#touch) as appropriate.\n\n<a href=\"#drag_clickDistance\" name=\"drag_clickDistance\">#</a> <i>drag</i>.<b>clickDistance</b>([<i>distance</i>]) [<>](https://github.com/d3/d3-drag/blob/master/src/drag.js#L387 \"Source\")\n\nIf *distance* is specified, sets the maximum distance that the mouse can move between mousedown and mouseup that will trigger a subsequent click event. If at any point between mousedown and mouseup the mouse is greater than or equal to *distance* from its position on mousedown, the click event follwing mouseup will be suppressed. If *distance* is not specified, returns the current distance threshold, which defaults to zero. The distance threshold is measured in client coordinates ([*event*.clientX](https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/clientX) and [*event*.clientY](https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/clientY)).\n\n<a href=\"#drag_on\" name=\"drag_on\">#</a> <i>drag</i>.<b>on</b>(<i>typenames</i>, [<i>listener</i>]) [<>](https://github.com/d3/d3-drag/blob/master/src/drag.js#L138 \"Source\")\n\nIf *listener* is specified, sets the event *listener* for the specified *typenames* and returns the drag behavior. If an event listener was already registered for the same type and name, the existing listener is removed before the new listener is added. If *listener* is null, removes the current event listeners for the specified *typenames*, if any. If *listener* is not specified, returns the first currently-assigned listener matching the specified *typenames*, if any. When a specified event is dispatched, each *listener* will be invoked with the same context and arguments as [*selection*.on](https://github.com/d3/d3-selection#selection_on) listeners: the current datum `d` and index `i`, with the `this` context as the current DOM element.\n\nThe *typenames* is a string containing one or more *typename* separated by whitespace. Each *typename* is a *type*, optionally followed by a period (`.`) and a *name*, such as `drag.foo` and `drag.bar`; the name allows multiple listeners to be registered for the same *type*. The *type* must be one of the following:\n\n* `start` - after a new pointer becomes active (on mousedown or touchstart).\n* `drag` - after an active pointer moves (on mousemove or touchmove).\n* `end` - after an active pointer becomes inactive (on mouseup, touchend or touchcancel).\n\nSee [*dispatch*.on](https://github.com/d3/d3-dispatch#dispatch_on) for more.\n\nChanges to registered listeners via *drag*.on during a drag gesture *do not affect* the current drag gesture. Instead, you must use [*event*.on](#event_on), which also allows you to register temporary event listeners for the current drag gesture. **Separate events are dispatched for each active pointer** during a drag gesture. For example, if simultaneously dragging multiple subjects with multiple fingers, a start event is dispatched for each finger, even if both fingers start touching simultaneously. See [Drag Events](#drag-events) for more.\n\n<a href=\"#dragDisable\" name=\"dragDisable\">#</a> d3.<b>dragDisable</b>(<i>window</i>) [<>](https://github.com/d3/d3-drag/blob/master/src/nodrag.js#L4 \"Source\")\n\nPrevents native drag-and-drop and text selection on the specified *window*. As an alternative to preventing the default action of mousedown events (see [#9](https://github.com/d3/d3-drag/issues/9)), this method prevents undesirable default actions following mousedown. In supported browsers, this means capturing dragstart and selectstart events, preventing the associated default actions, and immediately stopping their propagation. In browsers that do not support selection events, the user-select CSS property is set to none on the document element. This method is intended to be called on mousedown, followed by [d3.dragEnable](#dragEnable) on mouseup.\n\n<a href=\"#dragEnable\" name=\"dragEnable\">#</a> d3.<b>dragEnable</b>(<i>window</i>[, <i>noclick</i>]) [<>](https://github.com/d3/d3-drag/blob/master/src/nodrag.js#L15 \"Source\")\n\nAllows native drag-and-drop and text selection on the specified *window*; undoes the effect of [d3.dragDisable](#dragDisable). This method is intended to be called on mouseup, preceded by [d3.dragDisable](#dragDisable) on mousedown. If *noclick* is true, this method also temporarily suppresses click events. The suppression of click events expires after a zero-millisecond timeout, such that it only suppress the click event that would immediately follow the current mouseup event, if any.\n\n### Drag Events\n\nWhen a [drag event listener](#drag_on) is invoked, [d3.event](https://github.com/d3/d3-selection#event) is set to the current drag event. The *event* object exposes several fields:\n\n* `target` - the associated [drag behavior](#drag).\n* `type` - the string “start”, “drag” or “end”; see [*drag*.on](#drag_on).\n* `subject` - the drag subject, defined by [*drag*.subject](#drag_subject).\n* `x` - the new *x*-coordinate of the subject; see [*drag*.container](#drag_container).\n* `y` - the new *y*-coordinate of the subject; see [*drag*.container](#drag_container).\n* `dx` - the change in *x*-coordinate since the previous drag event.\n* `dy` - the change in *y*-coordinate since the previous drag event.\n* `identifier` - the string “mouse”, or a numeric [touch identifier](https://www.w3.org/TR/touch-events/#widl-Touch-identifier).\n* `active` - the number of currently active drag gestures (on start and end, not including this one).\n* `sourceEvent` - the underlying input event, such as mousemove or touchmove.\n\nThe *event*.active field is useful for detecting the first start event and the last end event in a sequence of concurrent drag gestures: it is zero when the first drag gesture starts, and zero when the last drag gesture ends.\n\nThe *event* object also exposes the [*event*.on](#event_on) method.\n\n<a href=\"#event_on\" name=\"event_on\">#</a> <i>event</i>.<b>on</b>(<i>typenames</i>, [<i>listener</i>]) [<>](https://github.com/d3/d3-drag/blob/master/src/event.js \"Source\")\n\nEquivalent to [*drag*.on](#drag_on), but only applies to the current drag gesture. Before the drag gesture starts, a [copy](https://github.com/d3/d3-dispatch#dispatch_copy) of the current drag [event listeners](#drag_on) is made. This copy is bound to the current drag gesture and modified by *event*.on. This is useful for temporary listeners that only receive events for the current drag gesture. For example, this start event listener registers temporary drag and end event listeners as closures:\n\n```js\nfunction started() {\n var circle = d3.select(this).classed(\"dragging\", true);\n\n d3.event.on(\"drag\", dragged).on(\"end\", ended);\n\n function dragged(d) {\n circle.raise().attr(\"cx\", d.x = d3.event.x).attr(\"cy\", d.y = d3.event.y);\n }\n\n function ended() {\n circle.classed(\"dragging\", false);\n }\n}\n```\n",
"readmeFilename": "README.md",
"repository": {
"type": "git",
"url": "git+https://github.com/d3/d3-drag.git"
},
"scripts": {
"postpublish": "git push && git push --tags && cd ../d3.github.com && git pull && cp ../d3-drag/build/d3-drag.js d3-drag.v1.js && cp ../d3-drag/build/d3-drag.min.js d3-drag.v1.min.js && git add d3-drag.v1.js d3-drag.v1.min.js && git commit -m \"d3-drag ${npm_package_version}\" && git push && cd - && zip -j build/d3-drag.zip -- LICENSE README.md build/d3-drag.js build/d3-drag.min.js",
"prepublish": "npm run test && uglifyjs --preamble \"$(preamble)\" build/d3-drag.js -c -m -o build/d3-drag.min.js",
"pretest": "rm -rf build && mkdir build && rollup --banner \"$(preamble)\" -g d3-dispatch:d3,d3-selection:d3 -f umd -n d3 -o build/d3-drag.js -- index.js",
"test": "tape 'test/**/*-test.js' && eslint index.js src"
},
"version": "1.1.0"
}
export default function(x) {
return function() {
return x;
};
}
import {dispatch} from "d3-dispatch";
import {event, customEvent, select, mouse, touch} from "d3-selection";
import nodrag, {yesdrag} from "./nodrag";
import noevent, {nopropagation} from "./noevent";
import constant from "./constant";
import DragEvent from "./event";
// Ignore right-click, since that should open the context menu.
function defaultFilter() {
return !event.button;
}
function defaultContainer() {
return this.parentNode;
}
function defaultSubject(d) {
return d == null ? {x: event.x, y: event.y} : d;
}
export default function() {
var filter = defaultFilter,
container = defaultContainer,
subject = defaultSubject,
gestures = {},
listeners = dispatch("start", "drag", "end"),
active = 0,
mousedownx,
mousedowny,
mousemoving,
touchending,
clickDistance2 = 0;
function drag(selection) {
selection
.on("mousedown.drag", mousedowned)
.on("touchstart.drag", touchstarted)
.on("touchmove.drag", touchmoved)
.on("touchend.drag touchcancel.drag", touchended)
.style("-webkit-tap-highlight-color", "rgba(0,0,0,0)");
}
function mousedowned() {
if (touchending || !filter.apply(this, arguments)) return;
var gesture = beforestart("mouse", container.apply(this, arguments), mouse, this, arguments);
if (!gesture) return;
select(event.view).on("mousemove.drag", mousemoved, true).on("mouseup.drag", mouseupped, true);
nodrag(event.view);
nopropagation();
mousemoving = false;
mousedownx = event.clientX;
mousedowny = event.clientY;
gesture("start");
}
function mousemoved() {
noevent();
if (!mousemoving) {
var dx = event.clientX - mousedownx, dy = event.clientY - mousedowny;
mousemoving = dx * dx + dy * dy > clickDistance2;
}
gestures.mouse("drag");
}
function mouseupped() {
select(event.view).on("mousemove.drag mouseup.drag", null);
yesdrag(event.view, mousemoving);
noevent();
gestures.mouse("end");
}
function touchstarted() {
if (!filter.apply(this, arguments)) return;
var touches = event.changedTouches,
c = container.apply(this, arguments),
n = touches.length, i, gesture;
for (i = 0; i < n; ++i) {
if (gesture = beforestart(touches[i].identifier, c, touch, this, arguments)) {
nopropagation();
gesture("start");
}
}
}
function touchmoved() {
var touches = event.changedTouches,
n = touches.length, i, gesture;
for (i = 0; i < n; ++i) {
if (gesture = gestures[touches[i].identifier]) {
noevent();
gesture("drag");
}
}
}
function touchended() {
var touches = event.changedTouches,
n = touches.length, i, gesture;
if (touchending) clearTimeout(touchending);
touchending = setTimeout(function() { touchending = null; }, 500); // Ghost clicks are delayed!
for (i = 0; i < n; ++i) {
if (gesture = gestures[touches[i].identifier]) {
nopropagation();
gesture("end");
}
}
}
function beforestart(id, container, point, that, args) {
var p = point(container, id), s, dx, dy,
sublisteners = listeners.copy();
if (!customEvent(new DragEvent(drag, "beforestart", s, id, active, p[0], p[1], 0, 0, sublisteners), function() {
if ((event.subject = s = subject.apply(that, args)) == null) return false;
dx = s.x - p[0] || 0;
dy = s.y - p[1] || 0;
return true;
})) return;
return function gesture(type) {
var p0 = p, n;
switch (type) {
case "start": gestures[id] = gesture, n = active++; break;
case "end": delete gestures[id], --active; // nobreak
case "drag": p = point(container, id), n = active; break;
}
customEvent(new DragEvent(drag, type, s, id, n, p[0] + dx, p[1] + dy, p[0] - p0[0], p[1] - p0[1], sublisteners), sublisteners.apply, sublisteners, [type, that, args]);
};
}
drag.filter = function(_) {
return arguments.length ? (filter = typeof _ === "function" ? _ : constant(!!_), drag) : filter;
};
drag.container = function(_) {
return arguments.length ? (container = typeof _ === "function" ? _ : constant(_), drag) : container;
};
drag.subject = function(_) {
return arguments.length ? (subject = typeof _ === "function" ? _ : constant(_), drag) : subject;
};
drag.on = function() {
var value = listeners.on.apply(listeners, arguments);
return value === listeners ? drag : value;
};
drag.clickDistance = function(_) {
return arguments.length ? (clickDistance2 = (_ = +_) * _, drag) : Math.sqrt(clickDistance2);
};
return drag;
}
export default function DragEvent(target, type, subject, id, active, x, y, dx, dy, dispatch) {
this.target = target;
this.type = type;
this.subject = subject;
this.identifier = id;
this.active = active;
this.x = x;
this.y = y;
this.dx = dx;
this.dy = dy;
this._ = dispatch;
}
DragEvent.prototype.on = function() {
var value = this._.on.apply(this._, arguments);
return value === this._ ? this : value;
};
import {select} from "d3-selection";
import noevent from "./noevent";
export default function(view) {
var root = view.document.documentElement,
selection = select(view).on("dragstart.drag", noevent, true);
if ("onselectstart" in root) {
selection.on("selectstart.drag", noevent, true);
} else {
root.__noselect = root.style.MozUserSelect;
root.style.MozUserSelect = "none";
}
}
export function yesdrag(view, noclick) {
var root = view.document.documentElement,
selection = select(view).on("dragstart.drag", null);
if (noclick) {
selection.on("click.drag", noevent, true);
setTimeout(function() { selection.on("click.drag", null); }, 0);
}
if ("onselectstart" in root) {
selection.on("selectstart.drag", null);
} else {
root.style.MozUserSelect = root.__noselect;
delete root.__noselect;
}
}
import {event} from "d3-selection";
export function nopropagation() {
event.stopImmediatePropagation();
}
export default function() {
event.preventDefault();
event.stopImmediatePropagation();
}
parserOptions:
sourceType: module
env:
browser: true
extends:
"eslint:recommended"
rules:
no-cond-assign: 0
*.sublime-*
build/*.zip
test/
Copyright 2013-2016 Mike Bostock
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the author nor the names of contributors may be used to
endorse or promote products derived from this software without specific prior
written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
# d3-dsv
This module provides a parser and formatter for delimiter-separated values, most commonly [comma-](https://en.wikipedia.org/wiki/Comma-separated_values) (CSV) or tab-separated values (TSV). These tabular formats are popular with spreadsheet programs such as Microsoft Excel, and are often more space-efficient than JSON. This implementation is based on [RFC 4180](http://tools.ietf.org/html/rfc4180).
Comma (CSV) and tab (TSV) delimiters are built-in. For example, to parse:
```js
d3.csvParse("foo,bar\n1,2"); // [{foo: "1", bar: "2"}, columns: ["foo", "bar"]]
d3.tsvParse("foo\tbar\n1\t2"); // [{foo: "1", bar: "2"}, columns: ["foo", "bar"]]
```
Or to format:
```js
d3.csvFormat([{foo: "1", bar: "2"}]); // "foo,bar\n1,2"
d3.tsvFormat([{foo: "1", bar: "2"}]); // "foo\tbar\n1\t2"
```
To use a different delimiter, such as “|” for pipe-separated values, use [d3.dsvFormat](#dsvFormat):
```js
var psv = d3.dsvFormat("|");
console.log(psv.parse("foo|bar\n1|2")); // [{foo: "1", bar: "2"}, columns: ["foo", "bar"]]
```
For easy loading of DSV files in a browser, see [d3-request](https://github.com/d3/d3-request)’s [d3.csv](https://github.com/d3/d3-request#csv) and [d3.tsv](https://github.com/d3/d3-request#tsv) methods.
## Installing
If you use NPM, `npm install d3-dsv`. Otherwise, download the [latest release](https://github.com/d3/d3-dsv/releases/latest). You can also load directly from [d3js.org](https://d3js.org), either as a [standalone library](https://d3js.org/d3-dsv.v1.min.js) or as part of [D3 4.0](https://github.com/d3/d3). AMD, CommonJS, and vanilla environments are supported. In vanilla, a `d3` global is exported:
```html
<script src="https://d3js.org/d3-dsv.v1.min.js"></script>
<script>
var data = d3.csvParse(string);
</script>
```
[Try d3-dsv in your browser.](https://tonicdev.com/npm/d3-dsv)
## API Reference
<a name="csvParse" href="#csvParse">#</a> d3.<b>csvParse</b>(<i>string</i>[, <i>row</i>]) [<>](https://github.com/d3/d3-dsv/blob/master/src/csv.js#L5 "Source")
Equivalent to [dsvFormat](#dsvFormat)(",").[parse](#dsv_parse).
<a name="csvParseRows" href="#csvParseRows">#</a> d3.<b>csvParseRows</b>(<i>string</i>[, <i>row</i>]) [<>](https://github.com/d3/d3-dsv/blob/master/src/csv.js#L6 "Source")
Equivalent to [dsvFormat](#dsvFormat)(",").[parseRows](#dsv_parseRows).
<a name="csvFormat" href="#csvFormat">#</a> d3.<b>csvFormat</b>(<i>rows</i>[, <i>columns</i>]) [<>](https://github.com/d3/d3-dsv/blob/master/src/csv.js#L7 "Source")
Equivalent to [dsvFormat](#dsvFormat)(",").[format](#dsv_format).
<a name="csvFormatRows" href="#csvFormatRows">#</a> d3.<b>csvFormatRows</b>(<i>rows</i>) [<>](https://github.com/d3/d3-dsv/blob/master/src/csv.js#L8 "Source")
Equivalent to [dsvFormat](#dsvFormat)(",").[formatRows](#dsv_formatRows).
<a name="tsvParse" href="#tsvParse">#</a> d3.<b>tsvParse</b>(<i>string</i>[, <i>row</i>]) [<>](https://github.com/d3/d3-dsv/blob/master/src/tsv.js#L5 "Source")
Equivalent to [dsvFormat](#dsvFormat)("\t").[parse](#dsv_parse).
<a name="tsvParseRows" href="#tsvParseRows">#</a> d3.<b>tsvParseRows</b>(<i>string</i>[, <i>row</i>]) [<>](https://github.com/d3/d3-dsv/blob/master/src/tsv.js#L6 "Source")
Equivalent to [dsvFormat](#dsvFormat)("\t").[parseRows](#dsv_parseRows).
<a name="tsvFormat" href="#tsvFormat">#</a> d3.<b>tsvFormat</b>(<i>rows</i>[, <i>columns</i>]) [<>](https://github.com/d3/d3-dsv/blob/master/src/tsv.js#L7 "Source")
Equivalent to [dsvFormat](#dsvFormat)("\t").[format](#dsv_format).
<a name="tsvFormatRows" href="#tsvFormatRows">#</a> d3.<b>tsvFormatRows</b>(<i>rows</i>) [<>](https://github.com/d3/d3-dsv/blob/master/src/tsv.js#L8 "Source")
Equivalent to [dsvFormat](#dsvFormat)("\t").[formatRows](#dsv_formatRows).
<a name="dsvFormat" href="#dsvFormat">#</a> d3.<b>dsvFormat</b>(<i>delimiter</i>) [<>](https://github.com/d3/d3-dsv/blob/master/src/dsv.js#L30)
Constructs a new DSV parser and formatter for the specified *delimiter*. The *delimiter* must be a single character (*i.e.*, a single 16-bit code unit); so, ASCII delimiters are fine, but emoji delimiters are not.
<a name="dsv_parse" href="#dsv_parse">#</a> *dsv*.<b>parse</b>(<i>string</i>[, <i>row</i>]) [<>](https://github.com/d3/d3-dsv/blob/master/src/dsv.js#L34 "Source")
Parses the specified *string*, which must be in the delimiter-separated values format with the appropriate delimiter, returning an array of objects representing the parsed rows.
Unlike [*dsv*.parseRows](#dsv_parseRows), this method requires that the first line of the DSV content contains a delimiter-separated list of column names; these column names become the attributes on the returned objects. For example, consider the following CSV file:
```
Year,Make,Model,Length
1997,Ford,E350,2.34
2000,Mercury,Cougar,2.38
```
The resulting JavaScript array is:
```js
[
{"Year": "1997", "Make": "Ford", "Model": "E350", "Length": "2.34"},
{"Year": "2000", "Make": "Mercury", "Model": "Cougar", "Length": "2.38"}
]
```
The returned array also exposes a `columns` property containing the column names in input order (in contrast to Object.keys, whose iteration order is arbitrary). For example:
```js
data.columns; // ["Year", "Make", "Model", "Length"]
```
If a *row* conversion function is not specified, field values are strings. For safety, there is no automatic conversion to numbers, dates, or other types. In some cases, JavaScript may coerce strings to numbers for you automatically (for example, using the `+` operator), but better is to specify a *row* conversion function.
If a *row* conversion function is specified, the specified function is invoked for each row, being passed an object representing the current row (`d`), the index (`i`) starting at zero for the first non-header row, and the array of column names. If the returned value is null or undefined, the row is skipped and will be ommitted from the array returned by *dsv*.parse; otherwise, the returned value defines the corresponding row object. For example:
```js
var data = d3.csvParse(string, function(d) {
return {
year: new Date(+d.Year, 0, 1), // lowercase and convert "Year" to Date
make: d.Make, // lowercase
model: d.Model, // lowercase
length: +d.Length // lowercase and convert "Length" to number
};
});
```
Note: using `+` rather than [parseInt](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/parseInt) or [parseFloat](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/parseFloat) is typically faster, though more restrictive. For example, `"30px"` when coerced using `+` returns `NaN`, while parseInt and parseFloat return `30`.
<a name="dsv_parseRows" href="#dsv_parseRows">#</a> <i>dsv</i>.<b>parseRows</b>(<i>string</i>[, <i>row</i>]) [<>](https://github.com/d3/d3-dsv/blob/master/src/dsv.js#L43 "Source")
Parses the specified *string*, which must be in the delimiter-separated values format with the appropriate delimiter, returning an array of arrays representing the parsed rows.
Unlike [*dsv*.parse](#dsv_parse), this method treats the header line as a standard row, and should be used whenever DSV content does not contain a header. Each row is represented as an array rather than an object. Rows may have variable length. For example, consider the following CSV file, which notably lacks a header line:
```
1997,Ford,E350,2.34
2000,Mercury,Cougar,2.38
```
The resulting JavaScript array is:
```js
[
["1997", "Ford", "E350", "2.34"],
["2000", "Mercury", "Cougar", "2.38"]
]
```
If a *row* conversion function is not specified, field values are strings. For safety, there is no automatic conversion to numbers, dates, or other types. In some cases, JavaScript may coerce strings to numbers for you automatically (for example, using the `+` operator), but better is to specify a *row* conversion function.
If a *row* conversion function is specified, the specified function is invoked for each row, being passed an array representing the current row (`d`), the index (`i`) starting at zero for the first row, and the array of column names. If the returned value is null or undefined, the row is skipped and will be ommitted from the array returned by *dsv*.parse; otherwise, the returned value defines the corresponding row object. For example:
```js
var data = d3.csvParseRows(string, function(d, i) {
return {
year: new Date(+d[0], 0, 1), // convert first colum column to Date
make: d[1],
model: d[2],
length: +d[3] // convert fourth column to number
};
});
```
In effect, *row* is similar to applying a [map](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/map) and [filter](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/filter) operator to the returned rows.
<a name="dsv_format" href="#dsv_format">#</a> <i>dsv</i>.<b>format</b>(<i>rows</i>[, <i>columns</i>]) [<>](https://github.com/d3/d3-dsv/blob/master/src/dsv.js#L105 "Source")
Formats the specified array of object *rows* as delimiter-separated values, returning a string. This operation is the inverse of [*dsv*.parse](#dsv_parse). Each row will be separated by a newline (`\n`), and each column within each row will be separated by the delimiter (such as a comma, `,`). Values that contain either the delimiter, a double-quote (`"`) or a newline will be escaped using double-quotes.
If *columns* is not specified, the list of column names that forms the header row is determined by the union of all properties on all objects in *rows*; the order of columns is nondeterministic. If *columns* is specified, it is an array of strings representing the column names. For example:
```js
var string = d3.csvFormat(data, ["year", "make", "model", "length"]);
```
All fields on each row object will be coerced to strings. For more control over which and how fields are formatted, first map *rows* to an array of array of string, and then use [*dsv*.formatRows](#dsv_formatRows).
<a name="dsv_formatRows" href="#dsv_formatRows">#</a> <i>dsv</i>.<b>formatRows</b>(<i>rows</i>) [<>](https://github.com/d3/d3-dsv/blob/master/src/dsv.js#L114 "Source")
Formats the specified array of array of string *rows* as delimiter-separated values, returning a string. This operation is the reverse of [*dsv*.parseRows](#dsv_parseRows). Each row will be separated by a newline (`\n`), and each column within each row will be separated by the delimiter (such as a comma, `,`). Values that contain either the delimiter, a double-quote (") or a newline will be escaped using double-quotes.
To convert an array of objects to an array of arrays while explicitly specifying the columns, use [*array*.map](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map). For example:
```js
var string = d3.csvFormatRows(data.map(function(d, i) {
return [
d.year.getFullYear(), // Assuming d.year is a Date object.
d.make,
d.model,
d.length
];
}));
```
If you like, you can also [*array*.concat](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/concat) this result with an array of column names to generate the first row:
```js
var string = d3.csvFormatRows([[
"year",
"make",
"model",
"length"
]].concat(data.map(function(d, i) {
return [
d.year.getFullYear(), // Assuming d.year is a Date object.
d.make,
d.model,
d.length
];
})));
```
### Content Security Policy
If a [content security policy](http://www.w3.org/TR/CSP/) is in place, note that [*dsv*.parse](#dsv_parse) requires `unsafe-eval` in the `script-src` directive, due to the (safe) use of dynamic code generation for fast parsing. (See [source](https://github.com/d3/d3-dsv/blob/master/src/dsv.js).) Alternatively, use [*dsv*.parseRows](#dsv_parseRows).
## Command Line Reference
### dsv2dsv
<a name="dsv2dsv" href="#dsv2dsv">#</a> <b>dsv2dsv</b> [<i>options…</i>] [<i>file</i>]
Converts the specified DSV input *file* to DSV (typically with a different delimiter or encoding). If *file* is not specified, defaults to reading from stdin. For example, to convert to CSV to TSV:
```
csv2tsv < example.csv > example.tsv
```
To convert windows-1252 CSV to utf-8 CSV:
```
dsv2dsv --input-encoding windows-1252 < latin1.csv > utf8.csv
```
<a name="dsv2dsv_help" href="dsv2dsv_help">#</a> dsv2dsv <b>-h</b>
<br><a href="dsv2dsv_help">#</a> dsv2dsv <b>--help</b>
Output usage information.
<a name="dsv2dsv_version" href="dsv2dsv_version">#</a> dsv2dsv <b>-V</b>
<br><a href="dsv2dsv_version">#</a> dsv2dsv <b>--version</b>
Output the version number.
<a name="dsv2dsv_out" href="dsv2dsv_out">#</a> dsv2dsv <b>-o</b> <i>file</i>
<br><a href="dsv2dsv_out">#</a> dsv2dsv <b>--out</b> <i>file</i>
Specify the output file name. Defaults to “-” for stdout.
<a name="dsv2dsv_input_delimiter" href="dsv2dsv_input_delimiter">#</a> dsv2dsv <b>-r</b> <i>delimiter</i>
<br><a href="dsv2dsv_input_delimiter">#</a> dsv2dsv <b>--input-delimiter</b> <i>delimiter</i>
Specify the input delimiter character. Defaults to “,” for reading CSV. (You can enter a tab on the command line by typing ⌃V.)
<a name="dsv2dsv_input_encoding" href="dsv2dsv_input_encoding">#</a> dsv2dsv <b>--input-encoding</b> <i>encoding</i>
Specify the input character encoding. Defaults to “utf8”.
<a name="dsv2dsv_output_delimiter" href="dsv2dsv_output_delimiter">#</a> dsv2dsv <b>-w</b> <i>delimiter</i>
<br><a href="dsv2dsv_output_delimiter">#</a> dsv2dsv <b>--output-delimiter</b> <i>delimiter</i>
Specify the output delimiter character. Defaults to “,” for writing CSV. (You can enter a tab on the command line by typing ⌃V.)
<a name="dsv2dsv_output_encoding" href="dsv2dsv_output_encoding">#</a> dsv2dsv <b>--output-encoding</b> <i>encoding</i>
Specify the output character encoding. Defaults to “utf8”.
<a name="csv2tsv" href="#csv2tsv">#</a> <b>csv2tsv</b> [<i>options…</i>] [<i>file</i>]
Equivalent to [dsv2dsv](#dsv2dsv), but the [output delimiter](#dsv2dsv_output_delimiter) defaults to the tab character (\t).
<a name="tsv2csv" href="#tsv2csv">#</a> <b>tsv2csv</b> [<i>options…</i>] [<i>file</i>]
Equivalent to [dsv2dsv](#dsv2dsv), but the [input delimiter](#dsv2dsv_output_delimiter) defaults to the tab character (\t).
### dsv2json
<a name="dsv2json" href="#dsv2json">#</a> <b>dsv2json</b> [<i>options…</i>] [<i>file</i>]
Converts the specified DSV input *file* to JSON. If *file* is not specified, defaults to reading from stdin. For example, to convert to CSV to JSON:
```
csv2json < example.csv > example.json
```
Or to convert CSV to a newline-delimited JSON stream:
```
csv2json -n < example.csv > example.ndjson
```
<a name="dsv2json_help" href="dsv2json_help">#</a> dsv2json <b>-h</b>
<br><a href="dsv2json_help">#</a> dsv2json <b>--help</b>
Output usage information.
<a name="dsv2json_version" href="dsv2json_version">#</a> dsv2json <b>-V</b>
<br><a href="dsv2json_version">#</a> dsv2json <b>--version</b>
Output the version number.
<a name="dsv2json_out" href="dsv2json_out">#</a> dsv2json <b>-o</b> <i>file</i>
<br><a href="dsv2json_out">#</a> dsv2json <b>--out</b> <i>file</i>
Specify the output file name. Defaults to “-” for stdout.
<a name="dsv2json_input_delimiter" href="dsv2json_input_delimiter">#</a> dsv2json <b>-r</b> <i>delimiter</i>
<br><a href="dsv2json_input_delimiter">#</a> dsv2json <b>--input-delimiter</b> <i>delimiter</i>
Specify the input delimiter character. Defaults to “,” for reading CSV. (You can enter a tab on the command line by typing ⌃V.)
<a name="dsv2json_input_encoding" href="dsv2json_input_encoding">#</a> dsv2json <b>--input-encoding</b> <i>encoding</i>
Specify the input character encoding. Defaults to “utf8”.
<a name="dsv2json_output_encoding" href="dsv2json_output_encoding">#</a> dsv2json <b>-r</b> <i>encoding</i>
<br><a href="dsv2json_output_encoding">#</a> dsv2json <b>--output-encoding</b> <i>encoding</i>
Specify the output character encoding. Defaults to “utf8”.
<a name="dsv2json_newline_delimited" href="dsv2json_newline_delimited">#</a> dsv2json <b>-n</b>
<br><a href="dsv2json_newline_delimited">#</a> dsv2json <b>--newline-delimited</b>
Output [newline-delimited JSON](https://github.com/mbostock/ndjson-cli) instead of a single JSON array.
<a name="csv2json" href="#csv2json">#</a> <b>csv2json</b> [<i>options…</i>] [<i>file</i>]
Equivalent to [dsv2json](#dsv2json).
<a name="tsv2json" href="#csv2json">#</a> <b>tsv2json</b> [<i>options…</i>] [<i>file</i>]
Equivalent to [dsv2json](#dsv2json), but the [input delimiter](#dsv2json_input_delimiter) defaults to the tab character (\t).
### json2dsv
<a name="json2dsv" href="#json2dsv">#</a> <b>json2dsv</b> [<i>options…</i>] [<i>file</i>]
Converts the specified JSON input *file* to DSV. If *file* is not specified, defaults to reading from stdin. For example, to convert to JSON to CSV:
```
json2csv < example.json > example.csv
```
Or to convert a newline-delimited JSON stream to CSV:
```
json2csv -n < example.ndjson > example.csv
```
<a name="json2dsv_help" href="json2dsv_help">#</a> json2dsv <b>-h</b>
<br><a href="json2dsv_help">#</a> json2dsv <b>--help</b>
Output usage information.
<a name="json2dsv_version" href="json2dsv_version">#</a> json2dsv <b>-V</b>
<br><a href="json2dsv_version">#</a> json2dsv <b>--version</b>
Output the version number.
<a name="json2dsv_out" href="json2dsv_out">#</a> json2dsv <b>-o</b> <i>file</i>
<br><a href="json2dsv_out">#</a> json2dsv <b>--out</b> <i>file</i>
Specify the output file name. Defaults to “-” for stdout.
<a name="json2dsv_input_encoding" href="json2dsv_input_encoding">#</a> json2dsv <b>--input-encoding</b> <i>encoding</i>
Specify the input character encoding. Defaults to “utf8”.
<a name="json2dsv_output_delimiter" href="json2dsv_output_delimiter">#</a> json2dsv <b>-w</b> <i>delimiter</i>
<br><a href="json2dsv_output_delimiter">#</a> json2dsv <b>--output-delimiter</b> <i>delimiter</i>
Specify the output delimiter character. Defaults to “,” for writing CSV. (You can enter a tab on the command line by typing ⌃V.)
<a name="json2dsv_output_encoding" href="json2dsv_output_encoding">#</a> json2dsv <b>--output-encoding</b> <i>encoding</i>
Specify the output character encoding. Defaults to “utf8”.
<a name="json2dsv_newline_delimited" href="json2dsv_newline_delimited">#</a> json2dsv <b>-n</b>
<br><a href="json2dsv_newline_delimited">#</a> json2dsv <b>--newline-delimited</b>
Read [newline-delimited JSON](https://github.com/mbostock/ndjson-cli) instead of a single JSON array.
<a name="csv2json" href="#csv2json">#</a> <b>csv2json</b> [<i>options…</i>] [<i>file</i>]
Equivalent to [json2dsv](#json2dsv).
<a name="tsv2json" href="#csv2json">#</a> <b>tsv2json</b> [<i>options…</i>] [<i>file</i>]
Equivalent to [json2dsv](#json2dsv), but the [output delimiter](#json2dsv_output_delimiter) defaults to the tab character (\t).
#!/usr/bin/env node
var os = require("os"),
rw = require("rw").dash,
path = require("path"),
iconv = require("iconv-lite"),
commander = require("commander"),
dsv = require("../");
var program = path.basename(process.argv[1]),
defaultInDelimiter = program.slice(0, 3) === "tsv" ? "\t" : ",",
defaultOutDelimiter = program.slice(-3) === "tsv" ? "\t" : ",";
commander
.version(require("../package.json").version)
.usage("[options] [file]")
.option("-o, --out <file>", "output file name; defaults to “-” for stdout", "-")
.option("-r, --input-delimiter <character>", "input delimiter character", defaultInDelimiter)
.option("-w, --output-delimiter <character>", "output delimiter character", defaultOutDelimiter)
.option("--input-encoding <encoding>", "input character encoding; defaults to “utf8”", "utf8")
.option("--output-encoding <encoding>", "output character encoding; defaults to “utf8”", "utf8")
.parse(process.argv);
var inFormat = dsv.dsvFormat(commander.inputDelimiter),
outFormat = dsv.dsvFormat(commander.outputDelimiter);
rw.readFile(commander.args[0] || "-", function(error, text) {
if (error) throw error;
rw.writeFile("-", iconv.encode(outFormat.format(inFormat.parse(iconv.decode(text, commander.inputEncoding))) + os.EOL, commander.outputEncoding), function(error) {
if (error) throw error;
});
});
#!/usr/bin/env node
var os = require("os"),
rw = require("rw").dash,
path = require("path"),
iconv = require("iconv-lite"),
commander = require("commander"),
dsv = require("../");
var program = path.basename(process.argv[1]),
defaultInDelimiter = program.slice(0, 3) === "tsv" ? "\t" : ",";
commander
.version(require("../package.json").version)
.usage("[options] [file]")
.option("-o, --out <file>", "output file name; defaults to “-” for stdout", "-")
.option("-r, --input-delimiter <character>", "input delimiter character", defaultInDelimiter)
.option("-n, --newline-delimited", "output newline-delimited JSON")
.option("--input-encoding <encoding>", "input character encoding; defaults to “utf8”", "utf8")
.option("--output-encoding <encoding>", "output character encoding; defaults to “utf8”", "utf8")
.parse(process.argv);
var inFormat = dsv.dsvFormat(commander.inputDelimiter);
rw.readFile(commander.args[0] || "-", function(error, text) {
if (error) throw error;
var rows = inFormat.parse(iconv.decode(text, commander.inputEncoding));
rw.writeFile(commander.out, iconv.encode(commander.newlineDelimited
? rows.map(function(row) { return JSON.stringify(row); }).join("\n") + "\n"
: JSON.stringify(rows) + os.EOL, commander.outputEncoding), function(error) {
if (error) throw error;
});
});
#!/usr/bin/env node
var os = require("os"),
rw = require("rw").dash,
path = require("path"),
iconv = require("iconv-lite"),
commander = require("commander"),
dsv = require("../");
var program = path.basename(process.argv[1]),
defaultOutDelimiter = program.slice(-3) === "tsv" ? "\t" : ",";
commander
.version(require("../package.json").version)
.usage("[options] [file]")
.option("-o, --out <file>", "output file name; defaults to “-” for stdout", "-")
.option("-w, --output-delimiter <character>", "output delimiter character", defaultOutDelimiter)
.option("-n, --newline-delimited", "accept newline-delimited JSON")
.option("--input-encoding <encoding>", "input character encoding; defaults to “utf8”", "utf8")
.option("--output-encoding <encoding>", "output character encoding; defaults to “utf8”", "utf8")
.parse(process.argv);
var outFormat = dsv.dsvFormat(commander.outputDelimiter);
rw.readFile(commander.args[0] || "-", function(error, text) {
if (error) throw error;
text = iconv.decode(text, commander.inputEncoding);
rw.writeFile(commander.out, iconv.encode(outFormat.format(commander.newlineDelimited
? text.trim().split(/\r?\n/g).map(function(line) { return JSON.parse(line); })
: JSON.parse(text)) + os.EOL, commander.outputEncoding), function(error) {
if (error) throw error;
});
});
// https://d3js.org/d3-dsv/ Version 1.0.5. Copyright 2017 Mike Bostock.
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
typeof define === 'function' && define.amd ? define(['exports'], factory) :
(factory((global.d3 = global.d3 || {})));
}(this, (function (exports) { 'use strict';
function objectConverter(columns) {
return new Function("d", "return {" + columns.map(function(name, i) {
return JSON.stringify(name) + ": d[" + i + "]";
}).join(",") + "}");
}
function customConverter(columns, f) {
var object = objectConverter(columns);
return function(row, i) {
return f(object(row), i, columns);
};
}
// Compute unique columns in order of discovery.
function inferColumns(rows) {
var columnSet = Object.create(null),
columns = [];
rows.forEach(function(row) {
for (var column in row) {
if (!(column in columnSet)) {
columns.push(columnSet[column] = column);
}
}
});
return columns;
}
var dsv = function(delimiter) {
var reFormat = new RegExp("[\"" + delimiter + "\n\r]"),
delimiterCode = delimiter.charCodeAt(0);
function parse(text, f) {
var convert, columns, rows = parseRows(text, function(row, i) {
if (convert) return convert(row, i - 1);
columns = row, convert = f ? customConverter(row, f) : objectConverter(row);
});
rows.columns = columns;
return rows;
}
function parseRows(text, f) {
var EOL = {}, // sentinel value for end-of-line
EOF = {}, // sentinel value for end-of-file
rows = [], // output rows
N = text.length,
I = 0, // current character index
n = 0, // the current line number
t, // the current token
eol; // is the current token followed by EOL?
function token() {
if (I >= N) return EOF; // special case: end of file
if (eol) return eol = false, EOL; // special case: end of line
// special case: quotes
var j = I, c;
if (text.charCodeAt(j) === 34) {
var i = j;
while (i++ < N) {
if (text.charCodeAt(i) === 34) {
if (text.charCodeAt(i + 1) !== 34) break;
++i;
}
}
I = i + 2;
c = text.charCodeAt(i + 1);
if (c === 13) {
eol = true;
if (text.charCodeAt(i + 2) === 10) ++I;
} else if (c === 10) {
eol = true;
}
return text.slice(j + 1, i).replace(/""/g, "\"");
}
// common case: find next delimiter or newline
while (I < N) {
var k = 1;
c = text.charCodeAt(I++);
if (c === 10) eol = true; // \n
else if (c === 13) { eol = true; if (text.charCodeAt(I) === 10) ++I, ++k; } // \r|\r\n
else if (c !== delimiterCode) continue;
return text.slice(j, I - k);
}
// special case: last token before EOF
return text.slice(j);
}
while ((t = token()) !== EOF) {
var a = [];
while (t !== EOL && t !== EOF) {
a.push(t);
t = token();
}
if (f && (a = f(a, n++)) == null) continue;
rows.push(a);
}
return rows;
}
function format(rows, columns) {
if (columns == null) columns = inferColumns(rows);
return [columns.map(formatValue).join(delimiter)].concat(rows.map(function(row) {
return columns.map(function(column) {
return formatValue(row[column]);
}).join(delimiter);
})).join("\n");
}
function formatRows(rows) {
return rows.map(formatRow).join("\n");
}
function formatRow(row) {
return row.map(formatValue).join(delimiter);
}
function formatValue(text) {
return text == null ? ""
: reFormat.test(text += "") ? "\"" + text.replace(/\"/g, "\"\"") + "\""
: text;
}
return {
parse: parse,
parseRows: parseRows,
format: format,
formatRows: formatRows
};
};
var csv = dsv(",");
var csvParse = csv.parse;
var csvParseRows = csv.parseRows;
var csvFormat = csv.format;
var csvFormatRows = csv.formatRows;
var tsv = dsv("\t");
var tsvParse = tsv.parse;
var tsvParseRows = tsv.parseRows;
var tsvFormat = tsv.format;
var tsvFormatRows = tsv.formatRows;
exports.dsvFormat = dsv;
exports.csvParse = csvParse;
exports.csvParseRows = csvParseRows;
exports.csvFormat = csvFormat;
exports.csvFormatRows = csvFormatRows;
exports.tsvParse = tsvParse;
exports.tsvParseRows = tsvParseRows;
exports.tsvFormat = tsvFormat;
exports.tsvFormatRows = tsvFormatRows;
Object.defineProperty(exports, '__esModule', { value: true });
})));
// https://d3js.org/d3-dsv/ Version 1.0.5. Copyright 2017 Mike Bostock.
!function(r,n){"object"==typeof exports&&"undefined"!=typeof module?n(exports):"function"==typeof define&&define.amd?define(["exports"],n):n(r.d3=r.d3||{})}(this,function(r){"use strict";function n(r){return new Function("d","return {"+r.map(function(r,n){return JSON.stringify(r)+": d["+n+"]"}).join(",")+"}")}function t(r,t){var e=n(r);return function(n,o){return t(e(n),o,r)}}function e(r){var n=Object.create(null),t=[];return r.forEach(function(r){for(var e in r)e in n||t.push(n[e]=e)}),t}var o=function(r){function o(r,e){var o,a,i=u(r,function(r,u){if(o)return o(r,u-1);a=r,o=e?t(r,e):n(r)});return i.columns=a,i}function u(r,n){function t(){if(c>=f)return a;if(o)return o=!1,u;var n,t=c;if(34===r.charCodeAt(t)){for(var e=t;e++<f;)if(34===r.charCodeAt(e)){if(34!==r.charCodeAt(e+1))break;++e}return c=e+2,n=r.charCodeAt(e+1),13===n?(o=!0,10===r.charCodeAt(e+2)&&++c):10===n&&(o=!0),r.slice(t+1,e).replace(/""/g,'"')}for(;c<f;){var i=1;if(10===(n=r.charCodeAt(c++)))o=!0;else if(13===n)o=!0,10===r.charCodeAt(c)&&(++c,++i);else if(n!==p)continue;return r.slice(t,c-i)}return r.slice(t)}for(var e,o,u={},a={},i=[],f=r.length,c=0,s=0;(e=t())!==a;){for(var d=[];e!==u&&e!==a;)d.push(e),e=t();n&&null==(d=n(d,s++))||i.push(d)}return i}function a(n,t){return null==t&&(t=e(n)),[t.map(c).join(r)].concat(n.map(function(n){return t.map(function(r){return c(n[r])}).join(r)})).join("\n")}function i(r){return r.map(f).join("\n")}function f(n){return n.map(c).join(r)}function c(r){return null==r?"":s.test(r+="")?'"'+r.replace(/\"/g,'""')+'"':r}var s=new RegExp('["'+r+"\n\r]"),p=r.charCodeAt(0);return{parse:o,parseRows:u,format:a,formatRows:i}},u=o(","),a=u.parse,i=u.parseRows,f=u.format,c=u.formatRows,s=o("\t"),p=s.parse,d=s.parseRows,v=s.format,l=s.formatRows;r.dsvFormat=o,r.csvParse=a,r.csvParseRows=i,r.csvFormat=f,r.csvFormatRows=c,r.tsvParse=p,r.tsvParseRows=d,r.tsvFormat=v,r.tsvFormatRows=l,Object.defineProperty(r,"__esModule",{value:!0})});
\ No newline at end of file
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment