README
@datawrapper/shared
a set of shared methods that can be used throughout Datawrapper
Import single functions:
import purifyHtml from '@datawrapper/shared/purifyHtml';
Import entire package:
import shared from '@datawrapper/shared';
shared.purifyHtml();
shared.httpReq();
API reference
- __(key, scope) ⇒
string
- area(vertices) ⇒
number
- arrayToObject(o) ⇒
object
- autoTickFormat(column) ⇒
string
- autoTickFormatDate(range, precision) ⇒
string
- autoTickFormatNumber(range) ⇒
string
- clone(object) ⇒
*
- colorLightness(hexColor) ⇒
number
- columnFormatter(numeral, column, metadata, axis) ⇒
function
- columnNameToVariable(name) ⇒
string
- combinations(input) ⇒
Array.<array>
- dateColumnFormatter(column) ⇒
function
- decodeHtml(input) ⇒
string
- defaultColors(theme) ⇒
*
- defaultOverlayTitle(vis, colName) ⇒
string
deleteJSON(url, callback) ⇒Promise
- drawPattern(parameters)
- equalish(a, b) ⇒
boolean
- escapeHtml(unsafe) ⇒
string
- estimateTextWidth(text, fontSize) ⇒
number
fetchJSON(url, method, credentials, body, callback) ⇒Promise
- formatNumber(numeral, value, options) ⇒
string
- get(object, key, _default) ⇒
getJSON(url, credentials, callback) ⇒Promise
- highlightTimer(action, delay) ⇒
object
- httpReq(path, options) ⇒
Promise
- isValidUrl(input) ⇒
boolean
- kMeans(values, numCluster) ⇒
array.<Array.<number>>
- loadScript(src, callback)
- loadStylesheet(src, callback)
- normalizeAlphaNumKey(key) ⇒
string
- normalizeNumKey(key) ⇒
number
- numberColumnFormatter(numeral, config) ⇒
function
- observeFonts(fontsJSON, typographyJSON) ⇒
Promise
- opts :
object
patchJSON(url, body, callback) ⇒Promise
- postEvent(chartId) ⇒
function
postJSON(url, body, callback) ⇒Promise
- purifyHTML(input, allowed) ⇒
string
putJSON(url, body, callback) ⇒Promise
- round(value, decimals) ⇒
number
- set(object, key, value) ⇒
- significantDimension(values, tolerance) ⇒
number
- smartRound(values, addPrecision, tolerance) ⇒
- tailLength(value) ⇒
number
- toFixed(value) ⇒
string
- trackEvent(category, category, category, category)
- trackPageView(loadTime)
- truncate(str, start, end) ⇒
string
string
__(key, scope) ⇒ translates a message key. translations are originally stored in a
Google spreadsheet that we're pulling into Datawrapper using the
scripts/update-translations
script, which stores them as :locale.json
files in the /locale folders (both in core as well as inside plugin folders)
for the client-side translation to work we are also storing the translations
in the global window.dw.backend.__messages
object. plugins that need
client-side translations must set "svelte": true
in their plugin.json
Returns: string
- -- the translated text
Param | Type | Default | Description |
---|---|---|---|
key | string |
- the key to be translated, e.g. "signup / hed" | |
scope | string |
"core" |
- the translation scope, e.g. "core" or a plugin name |
number
area(vertices) ⇒ Computes the area of a polygon
Returns: number
- -- polygon area, might be negative
Param | Type | Description |
---|---|---|
vertices | Array.<array> |
- polygon vertices as [[x,y], [x,y], ...] array |
object
arrayToObject(o) ⇒ This function fixes an uglyness when working with PHP backends.
in PHP, there is no distiction between arrays and objects, so
PHP converts an empty object {} to a empty array [].
When this empty array then ends up in client-side JS functions which
might start to assign values to the array using arr.foo = "bar"
which results in a data structure like this:
Param | Type | Description |
---|---|---|
o | array |
the input |
Example
console.log(arr);
[]
foo: "bar"
length: 0
<prototype>: Array []
console.log(arrayToObject(arr));
Object { foo: "bar" }
string
autoTickFormat(column) ⇒ Convenient wrapper around autoTickFormatNumber and autoTickFormatDate. Returns either a numeral.js or day.js format, depending on the column type.
Returns: string
- -- a numeral|dayjs format string
Param | Type | Description |
---|---|---|
column | object |
- dw.column instance that is displayed on the axis |
string
autoTickFormatDate(range, precision) ⇒ auto-detects a nice default axis tick format for date columns based on the input range and precision
Returns: string
- - day.js compatible format string
Param | Type | Description |
---|---|---|
range | array |
[min, max] of the data |
precision | string |
the input data precision (year |
Example
import {autoTickFormatDate} from '@datawrapper/shared/autoTickFormat';
autoTickFormatDate([new Date(2000,0,1), new Date(2002,0,1)], 'quarter'); // 'YYYY|[Q]Q'
string
autoTickFormatNumber(range) ⇒ auto-detects a nice default axis tick format for numeric columns based on the input range
Returns: string
- - numeral.js compatible format string
Param | Type | Description |
---|---|---|
range | array |
[min, max] of the data |
Example
import {autoTickFormatNumber} from '@datawrapper/shared/autoTickFormat';
autoTickFormatNumber([0,100]); // '0,0.[00]'
autoTickFormatNumber([0.2,0.7]); // '0,0.00[00]'
*
clone(object) ⇒ Clones an object
Returns: *
- - the cloned thing
Param | Type | Description |
---|---|---|
object | * |
the thing that should be cloned |
number
colorLightness(hexColor) ⇒ Returns the Lab lightness value of a given hexidecimal RGB color. Uses chroma-js to convert from Hex to Lab, but only adds a few hundreds bytes to your build.
To use this function, you have to manually install chroma-js using
npm install chroma-js
.
Returns: number
- - the Lab lightness, between 0 (black) and 100 (white)
Param | Type | Description |
---|---|---|
hexColor | string |
the RGB color as hexadecimal string, e.g. "#330066" |
Example
import colorLightness from '@datawrapper/shared/colorLightness';
colorLightness('#ff3399') // 57.9
function
columnFormatter(numeral, column, metadata, axis) ⇒ This function returns a formatting function based, given a column object, a metadata object and the axis column name.
Param | Type | Description |
---|---|---|
numeral | object |
Numeral.js instance |
column | object |
the date column object |
metadata | object |
the full metadata object |
axis | string |
the column name of the axis |
string
columnNameToVariable(name) ⇒ converts a column name to a variable name that can be used in the custom column editor. variable names can't contain spaces and special characters and are also converted to lowercase.
Returns: string
- -- variable name
Param | Type | Description |
---|---|---|
name | string |
- name of the column |
Example
import columnNameToVariable from '@datawrapper/shared/columnNameToVariable';
columnNameToVariable('GDP (per cap.)') // gdp_per_cap
Array.<array>
combinations(input) ⇒ computes all combinations of input elements
Returns: Array.<array>
- -- array of combinations
Param | Type | Description |
---|---|---|
input | Array.<array> |
- array of input objects, could be numbers, strings, etc |
Example
// returns [['a','b'], ['a'], ['b']]
combinations(['a', 'b']);
Example
// returns [[1,2,3], [1,2], [1,3], [1], [2,3], [2], [3]]
combinations([1,2,3])
function
dateColumnFormatter(column) ⇒ This function returns a date formatting function based on a dw column object. The implementation is backwards-compatible with our old Globalize-based date formatting, but uses dayjs under the hood.
Param | Type | Description |
---|---|---|
column | object |
the date column object |
string
decodeHtml(input) ⇒ Removes all html tags and decodes html entities like
Param | Type |
---|---|
input | string |
*
defaultColors(theme) ⇒ defines colors for the various chart elements like axis text, gridlines, bar background etc. based on the theme background color, and some other optional theme parameters
Returns: *
- -- object with color definitions
Param | Type | Description |
---|---|---|
theme | * |
- theme data for a chart |
Example
// returns {"tickText":{"secondary":"#9d9d9d","primary":"#d9d9d9"},"series":"#f1f1f1","value":"#d9d9d9","axis":"#f1f1f1","gridline":"#707070","fallbackBaseColor":"#f1f1f1"}
defaultColors({"colors": {"background": "#333333"}});
Example
// returns {"tickText":{"secondary":"#ffffff","primary":"#ffffff"},"series":"#ffffff","value":"#fef2e4","axis":"#ffffff","gridline":"#fedeb5","fallbackBaseColor":"#ffffff"}
defaultColors({"colors": {"bgBlendRatios": {"gridline": 0.5,"tickText": {"primary": 0,"secondary": 0}},"chartContentBaseColor": "#ffffff","background": "#FCB716"}});
string
defaultOverlayTitle(vis, colName) ⇒ returns the overlays column title
Param | Type |
---|---|
vis | object |
colName | string |
Promise
deleteJSON(url, callback) ⇒
Promise
Deprecated
Download and parse a remote JSON endpoint via DELETE. credentials are included automatically Use httpReq or delete instead.
Param | Type |
---|---|
url | string |
callback | function |
Example
import { deleteJSON } from '@datawrapper/shared/fetch';
deleteJSON('http://api.example.org/chart/123').then(() => {
console.log('deleted!')
});
drawPattern(parameters)
draws a configurable pattern into an svg pattern def, so that it can be used as a fill
Param | Type | Description |
---|---|---|
parameters | * |
- style parameters for the pattern |
boolean
equalish(a, b) ⇒ returns true if two numeric values are close enough
Param | Type |
---|---|
a | number |
b | number |
Example
// returns true
equalish(0.333333, 1/3)
Example
// returns false
equalish(0.333, 1/3)
string
escapeHtml(unsafe) ⇒ returns escaped HTML that can be used to display untrusted content
Param | Type |
---|---|
unsafe | string |
number
estimateTextWidth(text, fontSize) ⇒ returns the estimated width of a given text in Roboto. this method has proven to be a good compromise between pixel-perfect but expensive text measuring methods using canvas or getClientBoundingRect and just multiplying the number of characters with a fixed width.
be warned that this is just a rough estimate of the text width. the character widths will vary from typeface to typeface and may be off quite a bit for some fonts (like monospace fonts).
Param | Type | Description |
---|---|---|
text | string |
the text to measure |
fontSize | number |
the output font size (optional, default is 14) |
Example
import estimateTextWidth from '@datawrapper/shared/estimateTextWidth';
// or import {estimateTextWidth} from '@datawrapper/shared';
const width = estimateTextWidth('my text', 12);
Promise
fetchJSON(url, method, credentials, body, callback) ⇒
Promise
Deprecated
Download and parse a remote JSON document. Use httpReq instead
Param | Type | Description |
---|---|---|
url | string |
|
method | string |
HTTP method, either GET, POST or PUT |
credentials | string | undefined |
set to "include" if cookies should be passed along CORS requests |
body | string |
|
callback | function |
Example
import { fetchJSON } from '@datawrapper/shared/fetch';
fetchJSON('http://api.example.org', 'GET', 'include');
string
formatNumber(numeral, value, options) ⇒ special number formatting that can deal with microtypography and "prepend currencies" (e.g., −$1234.57)
Returns: string
- - the formatted number
Param | Type | Description |
---|---|---|
numeral | object |
Numeral.js instance |
value | number |
the number to format |
options | object |
options, see below |
options.format | string |
numeral.js compatible number format |
options.prepend | string |
string to prepend to number |
options.append | string |
string to append to number |
options.minusChar | string |
custom character to use for minus |
options.multiply | number |
multiply number before applying format |
Example
// returns '1234.57'
formatNumber(numeral, 1234.567)
Example
// returns '−$1234.57'
formatNumber(numeral, -1234.567, { prepend: '