js¶
Submodules¶
js/api¶
API definitions for communication with back-end.
- class Api()¶
Being web API.
- Api.create_curve(name, curve)¶
Create a new curve.
- Arguments
name (
string()
) – Curve name.curve (
Curve()
) – Curve instance.
- Returns
Promise – Empty JSON object to signalize success.
- Api.delete_curve(name, curve)¶
Delete a curve.
- Arguments
name (
string()
) – Curve name.curve (
Curve()
) – Curve instance.
- Returns
Promise – Empty JSON object to signalize success.
- Api.disable_motors()¶
Disable all motors in backend for motion recording.
- Returns
Promise.<Array.<Motor>> – Array of updated motor infos.
- Api.download_all_curves_as_zip()¶
Download all curves as Zip.
- Returns
Promise – Zip file response
- Api.enable_motors()¶
Enable all motors in backend after motion recording.
- Returns
Promise.<Array.<Motor>> – Array of updated motor infos.
- Api.find_free_name(wishName)¶
Find a free name for a new curve.
- Arguments
wishName (
string()
) – Wish name (if any). If undefined backend will use default new-curve-name “Untitled” and append ascending numbers to it if necessary.
- Returns
Promise.<string> – Next free curve name.
- Api.fit_curve(trajectory)¶
Fit curve from trajectory data.
- Arguments
trajectory (
array()
) – Recorded trajectory. Row direction is time and column timestamp and position values [timestamp, x, y, …].
- Returns
Promise.<Curve> – Fitted curve with smoothing splines.
- Api.get_config()¶
Get being configurations.
- Returns
Promise.<object> – Being CONFIG dictionary.
- Api.get_curve(name)¶
Get curve by name.
- Arguments
name (
string()
) – Curve name.
- Returns
Curve – Curve instance.
- Api.get_curves()¶
Get all motion curves. Returned a motion message with curves as [name, curve] tuples (most recently modified order).
- Returns
object – Motions message object.
Examples:
{ type: "motions", curves: [ ["some name", {"type": "Curve", ...}], ["other name", {"type": "Curve", ...}], // ... ] }
- Api.get_graph()¶
Get graph of block network (ELK style object).
- Returns
Promise.<object> – Graph object.
- Api.get_index_of_value_outputs(id)¶
Get output block ids for a given block id. All blocks that are connected via value output connection.
- Arguments
id (
number()
) – Block id.
- Returns
Promise.<Array.<number>> – List of connected block ids. Empty list if no outgoing connections.
- Api.get_motion_player_infos()¶
Get motion player infos.
- Returns
Promise.<Array.<MotionPlayer>> – Array of motion player dictionaries.
- Api.get_motor_infos()¶
Get motor infos.
- Returns
Promise.<Array.<Motor>> – Array of motor objects.
- Api.home_motors()¶
Trigger homing in all motors.
- Returns
Promise – Standard HTTP response.
- Api.live_preview(position, id, channel=0)¶
Move motion player / motor to position.
- Arguments
position (
number()
) – Position value in SI units.id (
number()
) – Motion player id.channel (
number()
) – Motion player output channel.
- Returns
Promise – Empty JSON object to signalize success.
- Api.play_multiple_curves(armed, loop=false, offset=0)¶
Play multiple motion curves in backend.
- Arguments
armed (
object()
) – Armed motion curves per motion player id.loop (
bool()
) – If to loop motions.offset (
number()
) – Start time offset in motion curves.
- Returns
number – Start timestamp of motion playback.
- Api.rename_curve(oldName, newName)¶
Rename a curve.
- Arguments
oldName (
string()
) – Old curve name.newName (
string()
) – New curve name.
- Returns
Promise – Empty JSON object to signalize success.
- Api.stop_spline_playback()¶
Stop all spline playback in backend.
- Returns
Promise – Standard HTTP response.
js/array¶
Numpy style array helpers. Most of these functions operate on standard and nested JS arrays (like [0, 1, 2, 3] or [[0, 1, 2], [3, 4, 5]]).
- array.array_shape(arr)¶
Determine array shape.
- Arguments
arr (
array()
) – Input array.
- Returns
array – array shape.
- array.array_ndims(arr)¶
Number of array dimensions.
- Arguments
arr (
array()
) – Input array.
- Returns
Number of array
- array.array_reshape(arr, shape)¶
Reshape an array. (Taken from _reshape function from the math.js library).
- Arguments
arr (
array()
) – Input array.shape (
array()
) – New array shape.
- Returns
Reshaped array.
- array.array_min(arr)¶
Minimum value in array.
- Arguments
arr (
array()
) – Input array.
- Returns
Minimum value.
- array.array_max(arr)¶
Maximum value in array.
- Arguments
arr (
array()
) – Input array.
- Returns
Maximum value.
- array.zeros(shape)¶
Create a new array filled with zeros.
- Arguments
shape (
array()
) – Input shape
- Returns
array – Zero array of given shape
- array.arange(start, stop, step=1)¶
Ascending integer array.
- Arguments
start (
number()
) – Start index.stop (
number|undefined()
) – Stop index (not included).step (
number()
) – Step size.
- Returns
Range array.
Examples:
// returns [0, 1, 2, 3, 4] arange(5)
// returns [2, 3, 4] arange(2, 5)
// returns [0, 2, 4] arange(0, 5, 2)
- array.linspace(start=0.0, stop=1.0, num=50)¶
Ascending linspace array.
- Arguments
start (
number()
) – Start value.stop (
number()
) – End value.num (
number()
) – Number of entries.
- Returns
array – Linspace array.
- array.add_arrays(augend, addend)¶
Element wise add two arrays together.
- Arguments
augend (
array()
) – First operand.addend (
array()
) – Second operand.
- Returns
array – Added array.
Examples:
// returns [3, 6] add_arrays([1, 2], [2, 4]);
- array.multiply_scalar(factor, arr)¶
Multiply scalar factor with array.
- Arguments
factor (
number()
) – Scalar factor.arr (
array()
) – Array to multiply.
- Returns
array – Multiplied array.
Examples:
// returns [3, 6, 9] multiply_scalar(3, [1, 2, 3]);
- array.divide_arrays(dividend, divisor)¶
Element wise divide two arrays.
- Arguments
dividend (
array()
) – Left operand.divisor (
array()
) – Right operand.
- Returns
array – Divided array.
- array.subtract_arrays(minuend, subtrahend)¶
Element wise subtract two array from each other.
- Arguments
minuend (
array()
) – Left operand.subtrahend (
array()
) – Right operand.
- Returns
array – Difference array.
- array.transpose_array(arr)¶
Transpose array. Works only for 2d arrays.
- Arguments
arr (
array()
) – Array to transpose.
- Returns
array – Transposed array.
Examples:
// returns [[1, 2, 3]] transpose_array([[1], [2], [3]])
- array.array_full(shape, fillValue)¶
Return a new array of given shape filled with fillValue.
- Arguments
shape (
array()
) – Desired shape.fillValue (
number()
) – Fill value.
- Returns
array – Output array.
- array.diff_array(arr)¶
Discrete difference along first axis. Only for 1D arrays.
- Arguments
arr (
array()
) – Input array.
- Returns
array – Difference. One shorter than input array!
Examples:
// returns [1, 1] diff_array([1, 2, 3])
js/bbox¶
Bounding box. Progressively expand a 2D region.
- class BBox(ll=[Infinity, Infinity, ur=[-Infinity, -Infinity)¶
Two dimensional bounding box.
- Arguments
ll (
array()
) – Lower left point.ur (
array()
) – Upper right point.
Examples:
bbox = new BBox(); bbox.expand_by_point([1, 1]); bbox.expand_by_point([3, 2]); // outputs [2, 1] console.log(bbox.size);
- BBox.height¶
type: number
Bounding box height.
- BBox.left¶
type: number
Get / set leftmost x value.
- BBox.right¶
type: number
Get / set rightmost x value.
- BBox.size¶
type: array
Bounding box size.
- BBox.width¶
type: number
Bounding box width.
- BBox.clip_point(pt)¶
Clip point inside bounding box.
- Arguments
pt (
Array()
) – 2D point to clip.
- Returns
Array – Clipped point.
- BBox.copy()¶
Copy bounding box.
- Returns
BBox – New bounding box copy.
- BBox.expand_by_bbox(bbox)¶
Expand bounding box region for another bounding box.
- Arguments
bbox (
BBox()
) – Bounding box to expand this bounding box with.
- BBox.expand_by_point(pt)¶
Expand bounding box region.
- Arguments
pt (
array()
) – Point to add to bounding box.
- BBox.expand_by_points(pts)¶
Expand bounding box region for some point.
- Arguments
pts (
array()
) – Points to add to bounding box.
- BBox.is_finite()¶
Check if bounding box is finite.
- Returns
boolean – If finite.
- BBox.reset()¶
Reset to infinite bounding box.
js/color_map¶
Color maps. Currently only batlowK color map is available (see website of Fabio Crameri).
- color_map.get_color(alpha, name="batlowK")¶
Lookup color value for some alpha in [0.0, 1.0]. Returned color value is not interpolated! Simply the next lower color value is picked.
- Arguments
alpha (
number()
) – Normalized number value.name (
string()
) – Color map name.
- Returns
string – Color value.
Examples:
// returns "#8e7f32" get_color(.5);
js/config¶
Some configuration values / definitions.
- INTERVAL¶
Note
Deprecated: Should be loaded from backend via API.
type: number
Main loop interval of being block network.
- API¶
type: string
API url base address.
- WS_ADDRESS¶
type: string
Websocket address.
js/constants¶
All kind of constants.
- MS¶
type: number
Milliseconds constants
- PI¶
type: number
One PI
- TAU¶
type: number
Two PI
- LEFT_MOUSE_BUTTON¶
type: number
Left mouse button (evt.which)
- ONE_D¶
type: number
One dimension.
- TWO_D¶
type: number
Two dimension.
js/curve¶
Curve container.
- ALL_CHANNELS¶
type: object
Targeting all channels literal.
- class Curve(splines)¶
Curve container. A curve contains multiple individual splines (channels).
- Arguments
splines (
array()
) – Individual curve splines.
- Curve.duration¶
type: number
Get curve duration. Initial delay is not considered.
- Curve.end¶
type: number
Get end time of curve.
- Curve.n_channels¶
type: number
Get number of channels.
- Curve.n_splines¶
type: number
Get number of splines.
- Curve.start¶
type: number
Get start time of curve.
- Curve.bbox()¶
Calculate bounding box of curve.
- Returns
BBox – Curve bounding box.
- Curve.copy()¶
Copy curve.
- Returns
Curve – - New curve copy.
- Curve.flip_horizontally(channel=ALL_CHANNELS)¶
Flip curve horizontally (in place). Mirrored along time axis.
- Arguments
channel (
number()
) – Target channel.
- Curve.flip_vertically(channel=ALL_CHANNELS)¶
Flip curve vertically (in place). Retrograde.
- Arguments
channel (
number()
) – Target channel.
- Curve.restrict_to_bbox(bbox)¶
Restrict curve to bounding box (in place).
- Arguments
bbox (
BBox()
) – Restricting bounding box.
- Curve.scale(factor, channel=ALL_CHANNELS)¶
Scale curve position values by some scalar factor (in place).
- Arguments
factor (
number()
) – Scale factor.channel (
number()
) – Target channel.
- Curve.shift(offset, channel=ALL_CHANNELS)¶
Shift curve in time by some offset (in place).
- Arguments
offset (
number()
) – Shift offset.channel (
number()
) – Target channel.
- Curve.stretch(factor, channel=ALL_CHANNELS)¶
Stretch curve in time by some factor (in place).
- Arguments
factor (
number()
) – Stretch factor.channel (
number()
) – Target channel.
- Curve.to_dict()¶
Convert curve to JSON object representation (for serialization).
- Returns
object – - JSON object.
- Curve.from_dict(dct)¶
Build curve from JSON object (deserialization). No checks are performed.
- Arguments
dct (
object()
) – JSON object.
- Returns
Curve – - Deserialized curve instance.
- curve.Curve.from_dict(dct)¶
Build curve from JSON object (deserialization). No checks are performed.
- Arguments
dct (
object()
) – JSON object.
- Returns
Curve – - Deserialized curve instance.
js/deque¶
Double ended queue.
- class Deque(iterable=0, maxlen=Infinity)¶
Deque array type with maxlen and better clearer naming (similar Pythons collections.deque). Note that maxlen only takes effect when using the extra methods but not the build in Array ones!
- Arguments
iterable (
number()
) – Number of initial empty elements.maxlen (
number()
) – Maximum length of deque.
Examples:
maxlen = 3 queue = new Deque(0, maxlen); queue.append(0, 1, 2, 3, 4); // returns Deque(3) [2, 3, 4, _maxlen: 3] console.log(queue);
- Deque.maxlen¶
type: number
Get / set maximum length.
- Deque._purge_left()¶
Pop from left side until maxlen.
- Deque._purge_right()¶
Pop from right side until maxlen.
- Deque.append(items)¶
Append items to the right side.
- Returns
number – New deque length.
- Deque.appendleft(items)¶
Append items to the left side.
- Returns
number – New deque length.
- Deque.clear()¶
Clear all items.
- Deque.popleft()¶
Pop item from the left side.
- Returns
object – Popped item.
js/draggable¶
Make something draggable.
- draggable.make_draggable(ele, callbacks, options)¶
Make some element react to click and drag movements. User can provide his / her own event listeners for:
Start of the drag motion (start_drag)
During the drag motion (drag)
End of drag motion (end_drag)
Further options are:
mouseButton {number}: Which mouse button to react to. Default is left mouse button.
escapable {boolean}: End drag by pressing ESC key. Default is true.
suppressClicks {boolean}: Suppress normal mouse clicks when dragging (only normal and double clicks). Default is true.
- Arguments
ele (
HTMLElement()
) – HTML element to make draggable.callbacks (
Object()
) – Drag event callbacks (start_drag, drag and end_drag).options (
Object()
) – Additional options.
js/editable_text¶
Editable text field.
- editable_text.make_editable(ele, on_change, validator=null, newLines=false)¶
Make text field editable by double clicking it. On change callback is called when user leaves editing mode by hitting enter key. Additionally a validator function can be provided to validate newly generated input text. This validator function can either reformat the text or throw an error. For the latter all changes will be reverted.
- Arguments
ele (
HTMLElement()
) – Element to make editable.on_change (
function()
) – On change event callback.validator (
function|null()
) – Text content validator function.newLines (
boolean()
) – If to accept new lines or not.
js/fetching¶
Wrapper verbs around standard JS fetch.
- fetching.get(url)¶
HTTP GET request.
- Arguments
url (
string()
) – URL parameter.
- Returns
Promise – HTTP response.
- fetching.put(url)¶
HTTP PUT request.
- Arguments
url (
string()
) – URL parameter.
- Returns
Promise – HTTP response.
- fetching.post(url)¶
HTTP POST request.
- Arguments
url (
string()
) – URL parameter.
- Returns
Promise – HTTP response.
- fetching.delete_fetch(url)¶
HTTP DELETE request. The odd one out since delete is a reserved JS keyword…
- Arguments
url (
string()
) – URL parameter.
- Returns
Promise – HTTP response.
- fetching.fetch_json(url, method, data)¶
Fetch JSON data from or to url.
- Arguments
url (
string()
) – URL parameter.method (
string()
) – HTTP method to use.data (
Object()
) – JSON data (for PUT and POST methods).
- fetching.get_json(url)¶
Get JSON data from url.
- Arguments
url (
string()
) – URL parameter.
- Returns
object – JSON payload.
- fetching.post_json(url, data)¶
Post JSON data to url.
- Arguments
url (
string()
) – URL parameter.data (
object()
) – Payload.
- fetching.put_json(url, data)¶
Put JSON data to url.
- Arguments
url (
string()
) – URL parameter.data (
object()
) – Payload.
js/history¶
Editing history.
- class History(maxlen)¶
Editing history container. Keeps track of changes in a past and future queue. Allows for capturing new states and retrieving the current one. An editing state can be an arbitrary JS object.
- Arguments
maxlen (
number()
) – Maximum lengths of past and future queues.
- History.length¶
type: number
History length. Total number of states in past and future.
- History.redoable¶
type: boolean
Can the wheel of time be turned back?
- History.savable¶
type: boolean
Are there unsaved changes?
- History.undoable¶
type: boolean
Can history be made undone?
- History.capture(state)¶
Capture a new state and add it to the history. This will clear the future.
- Arguments
state (
object()
) – State to capture / add to history.
- History.clear()¶
Clear entire history.
- History.redo()¶
Fast forward one state.
- Returns
object – Newly current state.
- History.retrieve()¶
Retrieve current state.
- Returns
object|null – current state (if any).
- History.undo()¶
Wind back one state.
- Returns
object – Newly current state.
js/layout¶
Graphical layout helpers. Only finding nice tick labels for now. Taken from here: Nice label Algorithm For Charts With Minimum Ticks.
- layout.nice_number(range, round)¶
Find nice number for data range.
- Arguments
range (
number()
) – Data space width.round (
boolean()
) – Perform number rounding.
- Returns
number – Nice number.
- layout.tick_space(lower, upper, maxTicks)¶
Nice tick numbers for a given data range.
- Arguments
lower (
number()
) – Lower limit of data range.upper (
number()
) – Upper limit of data range.maxTicks (
number()
) – Maximum number of ticks.
- Returns
array – Tick number candidates.
js/math¶
All kinds of math helpers.
- math.clip(value, lower=0, upper=1)¶
Clip value to [lower, upper] boundaries. Note: No lower < upper validation!
- Arguments
value (
number()
) – Number to clip.lower (
number()
) – Lower bound.upper (
number()
) – Upper bound.
- Returns
number – Clipped number.
- math.round(number, ndigits=0)¶
Round number to given decimal places.
- Arguments
number (
number()
) – Input number to round.ndigits (
number()
) – Digit number.
- Returns
number – Rounded number.
- math.normal(mean=0, std=1)¶
Normal Gaussian random distribution. See Box-Muller Transform.
- Arguments
mean (
number()
) – Mean value of distribution.std (
number()
) – Standard deviation of distribution.
- Returns
number – Random number.
- math.mod(dividend, divisor)¶
Positive numbers only modulo operation. Euclidean modulo operation (?).
- Arguments
dividend. (
number()
) –divisor. (
number()
) –
- Returns
number – Remainder.
- math.floor_division(number, divisor)¶
Perform floor division between two number.
- Arguments
number (
number()
) – Number to divide.divisor. (
number()
) –
- Returns
number – Quotient.
- math.isclose(a, b, rel_tol=1e-9, abs_tol=0)¶
Check if two values are reasonably close to each other. Adapted from pythons math.isclose() function.
- Arguments
a (
number()
) – First number.b (
number()
) – Second number.rel_tol (
number()
) – Relative tolerance.abs_tol (
number()
) – Absolute tolerance.
- Returns
boolean – If the two numbers are close.
js/notification_center¶
Notification central. Puts notifications to the upper right of the screen. Builds on top of AlertifyJS.
- notification_center.remodel_notification(noti, msg="null", type="null", wait=null)¶
Remodel alertify notification object after it was created.
- Arguments
noti (
object()
) – AlertifyJS notificaiton object.msg (
string|null()
) – New notification message text. Leave as is by default.type (
string|null()
) – New notification type. Either “”, “message”, “success”, “error” or “warning”. Leave as is by default.wait (
number|null()
) – New notification wait time. Leave as is by default.
- class NotificationCenter(alertify)¶
Notification central. Allows for persistent notifications which can be resolved (with new message, type, wait time) at a later time. Also processes motor information messages.
- Arguments
alertify (
object()
) – AlertifyJS instance / module.
- NotificationCenter.new_motor_message(msg)¶
Process motor update messages.
- Arguments
msg (
object()
) – Motor update message object.
- NotificationCenter.notify(msg, type="message", wait=2)¶
Notify message.
- Arguments
msg (
string()
) – Message text.type (
string()
) – Notification type. Either “”, “message”, “success”, “error” or “warning”.wait (
number()
) – Auto-dismiss wait time.
- Returns
object – Notification object.
- NotificationCenter.notify_persistent(msg, type="message", wait=2, id=0)¶
Notify persistent message.
- Arguments
msg (
string()
) – Message text.type (
string()
) – Notification type. Either “”, “message”, “success”, “error” or “warning”.wait (
number()
) – Auto-dismiss wait time.id (
number()
) – Wish id. Will get auto created by default.
- Returns
number – Internal id of notification object.
- NotificationCenter.update_motor_notification(motor)¶
Process single motor and update notifications.
- Arguments
motor (
object()
) – Motor object.
js/serialization¶
Serializing and deserializing splines and curve objects.
- serialization.objectify(dct)¶
Create being object from JS dictionary object.
- Arguments
dct (
object()
) – Dictionary representation.
- Returns
Being object.
- serialization.anthropomorphify(obj)¶
Convert being object to object representation.
- Arguments
obj (
object()
) – Being object.
- Returns
object – Dictionary representation.
js/spline¶
Spline stuff. Some constants and BPoly wrapper. Spline data container. No spline evaluation. Sampling splines for plotting is handled by SVG. Helpers for manipulating the shape of the spline:
Moving control points around
Changing the derivative at a given knot
Inserting / removing knots
- KNOT¶
type: number
First knot index for BPoly coefficent matrix.
- FIRST_CP¶
type: number
First control point index for BPoly coefficent matrix.
- SECOND_CP¶
type: number
Second control point index for BPoly coefficent matrix.
- Order¶
type: object
Spline order enum.
- Degree¶
type: object
Spline degree enum.
- LEFT¶
type: string
Left side of knot string literal.
- RIGHT¶
type: string
Right side of knot string literal.
- COEFFICIENTS_DEPTH¶
type: number
Depth of coefficients tensor.
- spline.spline_order(spline)¶
Determine spline polynom order.
- Arguments
spline (
BPoly()
) – Input spline.
- Returns
number – Spline order.
- spline.spline_degree(spline)¶
Determine spline polynom degree.
- Arguments
spline (
BPoly()
) – Input spline.
- Returns
number – Spline degree.
- spline.zero_spline(ndim=1)¶
Create all zero spline for a given number of dimensions.
- Arguments
ndim (
number()
) – Number of spline dimensions
- Returns
BPoly – Zero spline.
- class BPoly(c, x, extrapolate, axis)¶
JS BPoly wrapper.
BPoly is used by scipys interpolate package in Python. We do not need to sample the spline but rather the extract the Bézier control points. And we need a data structure for storing and manipulating the spline.
- Arguments
c (
array()
) – Spline coefficients.x (
array()
) – Spline knots.extrapolate (
boolean()
) – Extrapolation flag (not really used here but for completeness).axis (
number()
) – Spline axis (for completeness but not in use).
- BPoly.duration¶
type: number
Duration of the spline.
- BPoly.end¶
type: number
End time of spline.
- BPoly.max¶
type: number
Maximum value of the spline. Not the global minimum!
- BPoly.min¶
type: number
Minimum value of the spline. Not the global maximum!
- BPoly.n_segments¶
type: number
Number of segments in the spline.
- BPoly.start¶
type: number
Start time of spline.
- BPoly._dx(seg)¶
Spline segment width.
- Arguments
seg (
number()
) – Spline segment number.
- Returns
number – Segment width.
- BPoly._is_last_knot(knotNr)¶
Check if we are dealing with the last spline knot.
- Arguments
knotNr (
number()
) – Knot number.
- Returns
boolean – If we are dealing with the last knot of the spline.
- BPoly._x(seg, nr=0)¶
Time value of a given Bézier control point. Along first axis. The intermediate points are distributed equally between two knots.
- Arguments
seg (
number()
) – Segment number.nr (
number()
) – Control point number. E.g. for a cubic spline 0 -> left knot, 1 -> first control point, 2 -> second control point and 3 -> right control point.
- Returns
number – Control point time or x value.
- BPoly.bbox()¶
Calculate bounding box of spline (approximately).
- Returns
BBox – Spline bounding box.
- BPoly.copy()¶
Create a deep copy of the spline.
- BPoly.flip_horizontally()¶
Flip horizontally (in place). Mirrored along time axis.
- BPoly.flip_vertically()¶
Flip vertically (in place). Retrograde.
- BPoly.get_derivative_at_knot(nr, side="right", dim=0)¶
Get first derivative of spline at a knot.
- Arguments
nr (
number()
) – Knot number.side (
string()
) – Which side of the knot. Right side by default.dim (
number()
) – Target spline dimension.
- Returns
number – Derivative value.
- BPoly.insert_knot(pos)¶
Insert new knot into the spline.
- Arguments
pos (
array()
) – [x, y] position.
- BPoly.point(seg, nr=0, dim=0)¶
Get Bézier control point for SVG paths.
- Arguments
seg (
number()
) – Segment number.nr (
number()
) – Knot / control point number.dim (
number()
) – Spline dimension.
- Returns
array – 2D [x, y] point.
- BPoly.position_control_point(seg, nr, y, c1=false, dim=0)¶
Move control point around (only vertically).
- Arguments
seg (
number()
) – Segment number.nr (
number()
) – Knot / control point number.y (
number()
) – Target vertical y position.c1 (
boolean()
) – Ensure C1 continuity.dim (
number()
) – Target spline dimension.
- BPoly.position_knot(nr, pos, c1=false, dim=0)¶
Move knot around.
- Arguments
nr (
number()
) – Knot number.pos (
array()
) – Target position.c1 (
boolean()
) – C1 continuity. If true move surrounding control points as well.dim (
number()
) – Target spline dimension.
- BPoly.remove_knot(knotNr)¶
Remove knot from spline.
- Arguments
knotNr (
number()
) – Knot number to remove.
- BPoly.restrict_to_bbox(bbox)¶
Restrict all knots and control points to a bounding box.
- Arguments
bbox (
Bbox()
) – Limiting bounding box.
- BPoly.scale(factor)¶
Scale position values by some scalar factor (in place).
- Arguments
factor (
number()
) – Scale factor.
- BPoly.set_derivative_at_knot(nr, value, side="right", dim=0)¶
Set derivative value at a knot. This will affect adjacent coefficient values.
- Arguments
nr (
number()
) – Knot number.value (
number()
) – Desired derivative value at knot.side (
string()
) – Which side of the knot. Right side by default.dim (
number()
) – Target spline dimension.
- BPoly.shift(offset)¶
Shift in time by some offset (in place).
- Arguments
offset (
number()
) – Shift offset.
- BPoly.stretch(factor)¶
Stretch in time by some factor (in place).
- Arguments
factor (
number()
) – Stretch factor.
- BPoly.to_dict()¶
Convert BPoly instance to dict representation.
- Returns
object – Dictionary representation for serialization.
- BPoly.from_dict(dct)¶
Construct from BPoly object.
- Returns
BPoly – New spline instance.
- spline.BPoly.from_dict(dct)¶
Construct from BPoly object.
- Returns
BPoly – New spline instance.
js/svg¶
Working with SVG elements.
- svg.create_element(tag)¶
Create SVG element.
- Arguments
tag (
string()
) – SVG element tag name.
- Returns
SVGElement – Freshly created SVG element.
- svg.setattr(ele, name, value)¶
Set attribute of SVG element.
- Arguments
ele (
SVGElement()
) – SVG element.name (
string()
) – Attribute name.value (
number|string()
) – Attribute value.
- svg.getattr(ele, name)¶
Get attribute of SVG element.
- Arguments
ele (
SVGElement()
) – SVG element.name (
String()
) – Attribute name.
- Returns
number|string – Attribute value.
- svg.path_d(cps)¶
SVG path d attribute string from array of 2d control points.
- Arguments
cps (
array()
) – Bézier control points for one segment. Number of control points defines the curve degree.
- Returns
string – SVG path d attribute string.
Examples:
// returns "M0 1 C2 3 4 5 6 7" path_d([[0, 1], [2, 3], [4, 5], [6, 7]]);
- svg.draw_path(svg, cps, strokeWidth=1, color="black")¶
Draw control points as path onto SVG.
- Arguments
svg (
SVGElement()
) – Target SVG element.cps (
array()
) – Control points.strokeWidth (
number()
) – Stroke width.color (
string()
) – Stroke color.
- Returns
SVGPathElement – New SVG path element.
- svg.draw_circle(svg, center, radius=1, color="red")¶
Draw circle onto SVG.
- Arguments
svg (
SVGElement()
) – Target SVG element.center (
array()
) – Circle center.radius (
number()
) – Circle radius.color (
string()
) – Fill color.
- Returns
SVGCircleElement – New SVG circle element.
- svg.draw_line(svg, start, end, strokeWidth=1, color="black")¶
Draw line onto SVG.
- Arguments
svg (
SVGElement()
) – Target SVG element.start (
array()
) – Start point.end (
array()
) – End point.strokeWidth (
number()
) – Stroke width.color (
string()
) – Stroke color.
- Returns
SVGLineElement – New SVG circle element.
js/utils¶
This and that.
- utils.ready(fn)¶
Wait until DOM ready (from http://youmightnotneedjquery.com).
- Arguments
fn (
function()
) – Callback.
- utils.remove_all_children(el)¶
Remove all children from HTML element (from http://youmightnotneedjquery.com).
- Arguments
el (
HTMLElement()
) – HTML element to remove all children from.
- utils.clear_array(arr)¶
Clear array in place.
- Arguments
arr (
array()
) – Array to clear.
- utils.last_element(arr)¶
Get last element of array.
- Arguments
arr (
array()
) – Input array.
- Returns
object – Last element.
- utils.deep_copy(obj)¶
Deep copy JS array / object. Uses JSON. Not really performant and does not work for Infinity and NaN (get mapped to null).
- Arguments
obj (
object()
) – Input object.
- Returns
object – Object copy.
- utils.cycle(sequence)¶
Cycle through sequence iterator.
- Arguments
sequence (
array()
) – Input sequence.
- Returns
object – Next-able object.
- utils.arrays_equal(a, b)¶
Check if two arrays are equal (deep comparison).
- Arguments
a (
array()
) – First array.b (
array()
) – Second array.
- Returns
boolean – If the two arrays are equal.
- utils.assert(condition, message="\"\"")¶
Assert something and throw an error if condition does not hold up.
- Arguments
condition (
boolean()
) – Condition to assert.message (
string()
) – Message to alert.
- utils.searchsorted(arr, val)¶
Find index to insert item into sorted array so that it stays sorted.
- Arguments
arr (
array()
) – Sorted input array.val (
number()
) – Value to insert.
- Returns
number – Index to insert val to preserve array ordering.
- utils.add_option(select, name, after)¶
Add option to select.
- Arguments
select (
HTMLElement()
) – Select element to append option to.name (
string()
) – Option name.after (
HTMLElement()
) – Optional after reference element to insert new option after.
- Returns
HTMLOptionElement – Newly created option element.
- utils.is_valid_filename(fnm)¶
Test if the filename is valid on different operating systems
- Arguments
fnm (
string()
) – Filename to validate.
- Returns
boolean – If valid filename.
- utils.insert_in_array(array, index, item)¶
Insert item in array at index.
- Arguments
array (
array()
) – Input array.index (
number()
) – Target index.item (
object()
) – Object to insert.
- utils.remove_from_array(array, index)¶
Remove item from array at index.
- Arguments
array (
array()
) – Input array.index (
number()
) – Index to remove.
- utils.defaultdict(default_factory)¶
Python like defaultdict.
- Arguments
default_factory (
function()
) – Default factory for missing entries.
- Returns
Proxy – Default dict proxy object.
- utils.sleep(duration)¶
Sleep for some time (async).
- Arguments
duration (
number()
) – Sleep duration in seconds.
- Returns
Promise – Awaitable setTimeout promis;
- utils.rename_map_key(map, oldKey, newKey)¶
Rename map entry to a new key. No error checking whatsoever, overwrites existing entries.
- Arguments
map (
Map()
) – Targeted map instance.oldKey (
object()
) – Old key.newKey (
object()
) – New key.
- utils.find_map_key_for_value(map, value)¶
Find key for a value inside a map.
- Arguments
map (
Map()
) – Map to search.value (
object()
) – Value to find.
- Returns
object|undefined – Found value (if any). undefined otherwise.
- utils.insert_after(newNode, referenceNode)¶
Insert HTML node after an existing node (needs to have a parentNode!).
- Arguments
newNode (
HTMLElement()
) – New node to insert.referenceNode (
HTMLElement()
) – Reference node.
- Returns
HTMLElement – Inserted HTML node.
- utils.emit_event(ele, typeArg, bubbles=false, cancelable=false, composed=false)¶
Emit event for HTML element.
- Arguments
ele (
HTMLElement()
) – HTML element to emit event from.typeArg (
string()
) – Event type.bubbles (
boolean()
) – If to bubble.cancelable (
boolean()
) – If possible to cancel event.composed (
boolean()
) – If composed event.
- utils.emit_custom_event(ele, typeArg, detail)¶
Emit custom event for HTML element.
- Arguments
ele (
HTMLElement()
) – HTML element to emit event from.typeArg (
string()
) – Event type.detail (
object|null()
) – Optional detail object.
js/web_socket¶
- class WebSocketCentral(url, reconnectTimeout=1.0)¶
Web socket central. Relays received JSON messages to callback functions. Automatic reconnect. Also possible to subscribe to web socket events (open and close).
- Arguments
url (
string()
) – Web socket url to fetch data from.reconnectTimeout (
number()
) – Reconnect timeout duration in seconds.
- WebSocketCentral.connect()¶
Try to connect. If reconnectTimeout is set will continuously try to reconnect.
- WebSocketCentral.subscribe(eventType, callback)¶
Subscribe callback to WebSocket event.
- Arguments
eventType (
string()
) – Event name."open"
or"close"
.callback (
function()
) – Notificaiton callback function.
- WebSocketCentral.subscribe_to_message(msgType, callback)¶
Subscribe callback for messages of a given type.
- Arguments
msgType (
string()
) – Message type to get notifications for.callback (
function()
) – Notification callback function.
js/widget¶
Widget base class for being HTML web components. Simple HTMLElement with an additional toolbar div.
- widget.append_template_to(template, target)¶
Render template, clone it and append it to a target HTMLElement.
- Arguments
template (
HTMLTemplateElement|string()
) – Template element or string.target (
HTMLElement()
) – Target element to append rendered template to.
- widget.append_link_to(href, target)¶
Append CSS link node to target.
- Arguments
href (
string()
) – Href link.target (
HTMLElement()
) – Target element to append link to.
- widget.create_select(options, name)¶
Create select HTML element.
- Arguments
options (
array()
) – Name of initial options to add.name (
string()
) – Optional label string (not supported at the moment).
- Returns
HTMLSelectElement – New select element.
- class WidgetBase()¶
Base class for Being widget.
Simple web component with open shadow root. No toolbar.
- WidgetBase.append_link(href)¶
Add CSS stylesheet link to shadowroot.
- Arguments
href (
string()
) – Path to CSS stylesheet.
- WidgetBase.append_template(template)¶
Append HTML template to shadow root.
- Arguments
template (
HTMLTemplateElement|string()
) – Template to add.
- class Widget()¶
Custom component being widget. With toolbar.
- Widget.add_button_to_toolbar(innerHTML, title=)¶
Add a new material icon button to toolbar.
- Arguments
innerHTML (
string()
) – Inner HTML texttitle= (
string()
) – Button tooltip.
- Returns
HTMLButton – Button element.
- Widget.add_select_to_toolbar(options, name=)¶
Add a select element to the toolbar.
- Arguments
options (
string()
) – Select options.name= (
string()
) – Select name and label.
- Returns
HTMLSelectElement – Select element.
- Widget.add_space_to_toolbar()¶
Add a spacing element to the toolbar.
- Returns
HTMLSpanElement – Span element.