JS docs
animation.js
- animationMain()
Any animation called here. Runs on Browser refresh rate.
background.js
Starter script for browser extension
constants.js
global constants
canvasAntiClock.js
- createTernaryPlot(options)
Eventually draw the SVG triangle to canvas.
- Arguments:
options (*) – options = {}
options.injectorId (string) – div id
options.url (string) – local path to SVG
- fetchAnimationSVG(options)
Load an SVG image and inject it into a div. Now we can access all of the internal paths and groups. This is not fully used in this app. Else cartoon style animation.
- Arguments:
options (Object) – options = {}
options.injectorId (string) – div id
options.url (string) – local path to SVG
- Returns:
Promise – the injected SVG ‘text’ as DOM elem with an id
Examples:
fetchAnimationSVG({ injectorId: "divTriangleAntiClock", url: "images/Ternary-plot-anti.svg" })
- drawSvgCanvas(options)
SVG image converted to base64 drawn on canvas.
- Arguments:
options (*) – options = {}
options.scale (*) – to adapt to device display size
options.canvas (*) – named display area
- Returns:
Object – choosen canvas and context
- svg2img64(svg)
SVG to base64. (avoids PNG) One shot conversion to paint complicated SVG content. Needs an animation “overlay”. If any. SVGtoCanvas class, on the other hand, can edit the paths without the need to convert to base64. SVGtoCanvas direct draw. But fails to paint blur and gradients. GhettoRecorder has Python base64 conversion for background image in browser.
- Arguments:
svg (SVGImageElement)
- Returns:
Promise – base64 image as background for the calculated triangle.
- grabPngCanvas()
Print a translucent image to the user download folder.
- resizePage(options)
Adapt screen size to different devices.
- Arguments:
options (Object) – options = {}
options.fromLayoutLarge (boolean) – y/n
- updateScreen()
Dispatcher small, big screen.
dataFetch.js
- pullStoreJson()
Menu bar full download. Async.
- getApiData(options)
Pull via proxy, node.js npm packet. Then, POST the URL string to the node.js express proxy. Pull via Browser exension. Then, GET request directly to API.
- Arguments:
options (Object) – options = {}
options.useProxy (boolean) – true or false
options.country (string) – for JSON data set
options.yNum (string) – date data set
options.year (Object) – dict with strings of years
options.parentId (string) – div elem to attach log div
- getData(options)
GET request via Browser to get JSON from Fraunhofer Institut.
- Arguments:
options.start (string) – date data set
options.end (string) – date data set
options.url (string) – for JSON data set
options.endPoint (string) – API for JSON data set
options.country (string) – for JSON data set
- Returns:
JSON – if ok, undefined if fail
- postData(options)
POST request to local proxy express server. Browser to Node.js express server proxy -> 3rd party API, back.
- Arguments:
options.start (string) – date data set
options.end (string) – date data set
options.url (string) – for JSON data set
options.endPoint (string) – API for JSON data set
options.country (string) – for JSON data set
- Returns:
Object – with JSON and custom meta data to store it in IndexedDB
- prepIndexedDbStorage(options)
Construct the object for IndexDb feed. Proxy XHR returns {data: json}, one more “data” key
- Arguments:
options.country (string) – country code
options.start (string) – start date in DB
options.data (string) – JSON data from API
- Returns:
Object – JSON data and meta data
- adaptDataColHeader(bubbleObj)
Adapt the API data to browser IndexedDb column names. Get rid of obj.name and obj.data key names (original db table col remnants)
- Arguments:
bubbleObj (Object) – JSON and meta data
- Returns:
Object – JSON data and meta data
- updateIndexDbCountry(bubbleObj)
Update the country IndexedDb.
- Arguments:
bubbleObj (Object) – JSON and meta data
dataIdbCreate.js
- initIndexDb(options)
Create the objectStore and DB indicies for a named database. Also a template for the upgrade fun. Go ‘DBOpenRequest.onsuccess’ not ‘DBOpenRequest.onupgradeneeded’.
- Arguments:
options (Object) – = {}
options.dbName (string) – 2 char country code
options.dbVersion (string) – DB schema
options.objectStoreName (string) – DB table
options.primaryKey (string) – table row identifier column
options.indexNames (string) – not used here but, search key: or val
- Returns:
Promise – true, done or error
- createCountryDB()
Just create a DB, not add any data.
- createUserSettingsDB()
App state restrore after reload or page closed. Create DB if not existing, init restore of settings.
dataIdbRestoreUserState.js
- restoreUserSettings(stateDict)
Restore setting if other than default.
- Arguments:
stateDict (Object)
dataIdbSetGet.js
- setIdbValue(options)
Write data to IndexedDB.
- Arguments:
options.dbName – dbName
options.dbVersion – dbVersion
options.objectStoreName – objectStoreName
options.data – dictionary with data row to update, whole row
options.updFields – dictionary with data, selective update fields
- Returns:
Promise – true or error object
Examples:
setIdbValue({ // db transaction, update if country is done dbName: bubbleObj.logDbFetched, dbVersion: 1, objectStoreName: bubbleObj.objectStoreName, data: { id: bubbleObj.year, country: [...result.country, bubbleObj.country], }, }); setIdbValue({ dbName: "prokif_user_settings", dbVersion: 1, objectStoreName: "state", id: "user_settings", updFields: { sliderFps: sliderFps.value }, });
- getIdbValue(options)
Get the data row with a given ‘id’.
- Arguments:
options.dbName – dbName
options.dbVersion – dbVersion
options.objectStoreName – objectStoreName
options.id – primary key for a paricular row, i.e. “2022”
options.callback – fun to transport value out of promise
- Returns:
Promise.resolve(data) – .then((data) => …) data{id:2022,power:true,band:3,…}
Examples:
getIdbValue({ dbName: "de", dbVersion: 1, objectStoreName: "production_types", id: "2023", callback: (data) => dataCall.set(data, "de", "2023"), });
dataPlayground.js
- createInfocards()
HTML elements to an info card of selected data (online) and claculated data (we).
dataTernaryPlotCalc.js
- getIntersection(options)
Calc component distribution intersection point p(x,y) in the ternary plot. (A) Get the start and end of a line representing a component in the diagram. (B) Get the line intersection points p(x,y) with the triangle at a certain percent number. As if you would read it on the diagram. (C) Calc intersection with a second component line inside of the triangle. That is the point p(x,y) to draw on the plot. (D) Calc the same for two other possible line intersections. They all must come to the same result, if data sets are complete and valid. Else we get at least (hopefully) one valid calculation. Filter it out. Line intersection of percent scales on triangle rulers reading. 63% noCO2 line left to right start: left[63], end: bottom[100-63]
- prodTypeValues(options)
Accumulate all data into one number for one of three production types. Later we set the brutto of all three to 100% and calc each proportion. { Solar: (17756) […], Wind_onshore: (17756) […], Wind_offshore: (17756) […] }
- Arguments:
options.prodType (Object) – dict with belonging production rows
options.idx (Object) – current row index
- Returns:
Number – result of summed rows
- adjustPlotTrails(options)
Show only desired amount of data as trails.
- Arguments:
options.numTrails (Number) – max. amount of points in the dict
options.plotPoints (Object) – { 0: {x,y}, 1:{x,y}, 2:{x,y} }
- Returns:
Object – dict with only the newest, reduced plot points
- updateInfoCardMeta(options)
Country info card metadata put on DOM elements for user.
- Arguments:
options.prodYear (Number) – year of downloaded dataset
options.teamColor (array) – country color rgb values for rgb string
options.teamNumber (Number) – to distinguish country instances
options.countryCode (String) – two char country code
options.hour (Number) – calced from Unix timestamp
options.minute (Number) – calced from Unix timestamp
options.monthDayDigit (Number) – calced from Unix timestamp
options.monthName (String) – calced from Unix timestamp
options.dayName (String) – calced from Unix timestamp
- updateInfoCardData(options)
Country info card data put on DOM elements for user.
- Arguments:
options.teamNumber (Number) – to distinguish country instances
options.noCO2Sum (Number) – sum of all non co2 productions
options.lowCO2Sum (Number) – sum of all low co2 productions
options.isCO2Sum (Number) – sum of all fossil co2 productions
options.Load (Number) – giga watt sum from dl dataset, all energy
options.Residual_load (Number) – sum from dl dataset, non renewable production
options.Cross_border_electricity_trading (Number) – gain or loss in trading
- getPositionAlongTheLine(x1, y1, x2, y2, percentage)
Imaginary straight line between p1(x1,y1) and p2(x2,y2) is cut at percent x.
- Arguments:
x1 (Number) – p1 x origin
y1 (Number) – p1 y origin
x2 (Number) – p2 x destination
y2 (Number) – p2 y destination
percentage (Number) – between 0 and 1, where to cut the line
- Returns:
Object – point(x,y) intersection at percent
- lineIntersection(pointA, pointB, pointC, pointD)
Calc line intersection point.
- Arguments:
pointA (Object) – start point line1
pointB (Object) – end point line1
pointC (Object) – start point line2
pointD (Object) – end point line2
- Returns:
Object – point(x,y) intersection
- class EnergyStorage()
Helper class for EnergyMix class. To limit instances, they pop a number from a list. Color palette and canvas, ctx assignment.
- class EnergyMix(options)
Calculates the distribution of three components inside of a system of 100%. Regardless of the overall performance of the system. {Percent: sum of sub components}, {noCO2:20,lowCO2:40,isCO2:40}
How it works? Pulled data for one timestamp from all keys of the country IndexedDB. Instantiate class. Can calc, show multiple countries in one plot. Data assigned to the correct object key. Calc all values = 100%. Calc individual object % of 100%. {no:20,low:45,is:35}
Examples:
frameControl[countryCode + year]["instance"] = new EnergyMix({ prodCountry: countryCode, prodYear: year, cData: dataobj.cData, // dataset of country, year noCO2: dataobj.trinity.noCO2, // grouped arrays lowCO2: dataobj.trinity.lowCO2, isCO2: dataobj.trinity.isCO2, unix_seconds: dataobj.timestamps.unix_seconds, clockwise: false, ctx: eStore.antiClockCtx, triangleName: "ternaryPlotAntiClock", trianglePoints: eStore.triangleResize, // pull current triangle data });
- class EnergyMix.update()
This is the driver to move through the data sets.
- Returns:
undefined – prevent next cycle if array ends
- class EnergyMix.isDataValid(badData)
Valid if data is feasible for calc or display.
- Arguments:
badData (Object) – any datastructure
- Returns:
boolean – true if valid
- class EnergyMix.tradeColors(number)
Assign colors to trade volumes.
- Arguments:
number (number) – trade volume
- Returns:
string – hsl numbers color code
- class EnergyMix.syncWeekday()
Remove first days of year from data sets to sync years and weekdays for all countries.
- Returns:
undefined – exit fun if not useable
- class EnergyMix.setPercentDist(options)
Set the feeder object to calc line intersection in the triangle. Percent calc is used to position a point inside the triangle.
- Arguments:
options (*)
dataTernaryPlotSetup.js
- datahome(set, countryCode, year, get)
Storage, cache for country data sets. Show a closure in action in my repo. Not a fan boy. Just for the sake of my art.
Function expression closure with setter and getter. Not hoisted. Set, get values may not be arrow functions.
Save/add the result of a DB request promise via callback into a closure.
- Arguments:
set – callback result, object of an IndexDB get() request,
countryCode – second arg setter, “fr”, “bg”
year – of data set
get – get stored object from this closure
- Returns:
Object – {countryCode: {year: Data}}
Examples:
const dataCall = datahome(); // instantiate first fun expression dataCall.set(data, "fr", "2023") dataCall.get(); // print {"fr": {2023: {Nuclear:...}, {Coal:...}}}
- createTrinityFromClosure(options)
Assign the production types to one of three objects. [noCO2] pv wind; [lowCO2] nukes water bio geo; [isCO2] coal oil gas
- Arguments:
options.countryCode (string) – country
options.year (number) – year
options.call (function) – fun call result of getting data out of the closure
- Returns:
Object – {trinity: Data, timestamps: Number, countryCode: String}
Examples:
const trinity = createTrinityFromClosure({ countryCode: "de", year: "2023", call: () => dataCall.get(), });
- buildManualSliderFromMax()
Set manual slider max. value. Problem is to filter out quarter hours, if demanded. Means there are much more data rows than hourly. Try to display synced days and hours for different countries.
- getMinDataSet()
Hourly switch is set.
- Returns:
number – of lowest row count of a country data set
- getMaxDataSet()
Hourly is not set. Display quarter hours possible. frameControl in animation.js hosts the instances that calcs and draws
- Returns:
number – of biggest row count of a country data set
- createManualSlider(maxLen)
Set max value and event listener to manually move through the data sets. Problem seems to be step keyword related. Jumps over some data sets. Seen if data num is set high.
- Arguments:
maxLen (number) – for the slider
dataTime.js
- getDateParts(unixTimestamp)
Convert unix time in JS time.
- Arguments:
unixTimestamp (number) – unix time format
- Returns:
Object – date components in human readable format
- getYesterday()
JS time from yesterday.
- Returns:
Object – date components
description.js
- textColumnOne()
Text for introduction.
- textColumnTwo()
Text HowTo section.
- textColumnTwoDotOne()
Text more description.
index.js
Vanilla JS draws invisible paths to calc the intersection in a triangle for three data results from DB queries or arrays.
There are two opposite ways to read the ternary diagram.
Should implement clockwise, anti-clockwise.
Anti-clock, https://www.youtube.com/watch?v=fyJOEGTcHSM
Clockwise, https://www.youtube.com/watch?v=SG_8u6_UMTA,
plot.js
- plotter(options)
Print data points of multiple EnergyMix instances. Must clear canvas before multiple draws on top.
- Arguments:
options (*) – options = {}
options.cx (Object) – center point x
options.cycenter (Object) – point y
options.ctx (HTMLCanvasElement) – canvas context
options.canvas (HTMLCanvasElement) – canvas
options.instancesData (Object) – team num, color …
options.plotIdx (number) – current number of plots
selectRun.js
- runShow(options)
Create country instance and adjust it onto the user selected options.
- Arguments:
options (Object) – options = {}
options.cCode (string) – two char country code
options.year (number) – of the data set in DB
- pickDataSet(options)
Checks our local DB if data already exists. GET request the Fraunhofer API data via browser, as extension. POST request the local express API data, as node.js package.
- Arguments:
options (Object) – options = {}
options.cCode (string) – country code
options.year (number) – of data set
options.useProxy (boolean) – node.js express
- Returns:
Promise – true or false if failed
- getIndexStepHourly(options)
Provide each instance with index step to sync if demanded. How many steps to skip to get only full hours displayed. If countryA got full hours and countryB 0,15,30,45 quarters. Find first data set with 0, count next as long not 0 again.
- Arguments:
options (Object) – options = {}
options.instance (instance) – country instance
- Returns:
number – of index steps to next data set to read
setEventListener.js
- setPageEventHandler()
A ‘x’ knob to hide the settings buttons.
- setMenuEventHandler()
Top nav menu.
- setBtnEventHandler()
Buttons event handler.
- setCheckboxEventHandler()
All checkboxes.
triangleCalc.js
- reseizeTriangle(options)
Have to reconstruct the triangle if screen resizes.
- Arguments:
options.id (string) – triangle visible in dev mode drawTriangle()
options.side (number) – boundaries of the diagram spots/intersection points
options.precision (number) – for option drawing show, how many parts one side consists of
options.clockwise (boolean) – clock or antiClock readable ternary plot; where spots are drawn
- Returns:
Object – dict with description where to draw and how big
- getCoords(side, coords, precision)
Feeder for triangle drawer. Can draw in mini steps. User show. Not needed to calc line start/end, intersections anymore. Class EnergyMix, method getIntersection does it on the fly with pure math. Origin->target; Is clockwise? Coords list will be [{2,4}, {4,7}] or [{4,7}, {2,4}].
- Arguments:
side (Number) – len of triangle side
coords (Object) – triangle object describes (x,y) coords/points for A,B,C edges
precision (Number) – 100 means, ‘side’ is split in 100 segments/points; 1.000 -> 1.000
- Returns:
Object – or same with “antiClock” key to prepare a diagram with rulers in opposite direction %, clockwise diagram reading or not
See also
:any:`ptr (global) default input object for triangle coords param
{antiClock:{{1: {x: 1,2,y:3,6}}, 2: {x: 4,3,y:5,1}}} use percent scale -> ruler points`
- createSideRuler(options)
Create the side rulers (points objects) for the diagram. Wrap the fun request with dependency injector to keep the reading cleaner.
- Arguments:
options.origin (Object) – {x: Number, y: Number} triangle edge point
options.target (Object) – {x: Number, y: Number} triangle edge point
options.percent (number) – precision of ‘ruler marks’, amount of points on the ruler
- Returns:
Object – } target coords for next ruler mark
trianglePlot.js
- intersect(x1, y1, x2, y2, x3, y3, x4, y4)
- Arguments:
x1 (number) – point x coordinate
y1 (number) – point y coordinate
x2 (number) – point x coordinate
y2 (number) – point y coordinate
x3 (number) – point x coordinate
y3 (number) – point y coordinate
x4 (number) – point x coordinate
y4 (number) – point y coordinate
- Returns:
Object – X and Y coordinates of intersection point.
utils.js
- appendDiv(opt)
Stack div and use it as a list.
- Arguments:
opt (Object) – dictionary
Examples:
appendDiv({ parentId: 'div0ne', childId: 'c1', innerText: 'low', elemClass: 'logger' });