Domonic: Javascript

There’s a javascript package that mimics the js API.

It’s useful for things like porting javascript code to python but also if you already know javascript:

from domonic.javascript import Math
print(Math.random())

from domonic.javascript import Array
myArr=Array(1,2,3)
print(myArr.splice(1))

from domonic.javascript import URL
url = URL('https://somesite.com/blog/article-one#some-hash')
print(url.protocol)
print(url.host)
print(url.pathname)
print(url.hash)

# from domonic.javascript import Global
# Global.decodeURIComponent(...
# Global.encodeComponent(...

# from domonic.javascript import Date
# etc..

setInterval

You can use setInterval and clearInterval with params

x=0

def hi(inc):
    global x
    x = x+inc
    print(x)

test = window.setInterval(hi, 1000, 2)
import time
time.sleep(5)
window.clearInterval(test)
print(f"Final value of x:{x}")

fetch

There’s a fetch implementation that uses promises. With additional mulithreaded and pooled versions.

from domonic.javascript import *

urls = ['http://google.com', 'http://linkedin.com', 'http://eventual.technology']  # use your own domains

print('run 1')
results = window.fetch(urls[0])
results.then(lambda r: print(r.text))
print('run 1 FINISHED')

def somefunc(response):
        print("I'm a callback", response.ok)
        return response

mydata = window.fetch(urls[0]).then(somefunc)
print(mydata)
print(mydata.data)
print(mydata.data.text)

# fetch more than one
results = window.fetch_set(urls)
print(results)
print(list(results))
for r in results:
        if r is not None:
                print(r.ok)
                # print(r.text)

# multi-threaded
results = window.fetch_threaded(urls)
print(results)
print(list(results))
for r in results:
        if r is not None:
                print(r.ok)
                # print(r.text)

# pooled
results = window.fetch_pooled(urls, timeout=2)
print(results)
for r in results:
        if r is not None:
                print(r.ok)
                # print(r.text)

print('run 4')
results = window.fetch(urls[0])
print(results)
results.then(lambda r: print(r.text) if r is not None else None)

All fetch methods use requests and will pass all the kwargs along should you need to modify

Styling

Styling gets passed to the style tag on render.

mytag = div("hi", _id="test")
mytag.style.backgroundColor = "black"
mytag.style.fontSize = "12px"
print(mytag)
# <div id="test" style="background-color:black;font-size:12px;">hi</div>

Many other undocumented features. Take a look at the code.

domonic.javascript

class domonic.javascript.Array(*args)[source]

javascript array

at(index: int)[source]

[takes an integer value and returns the item at that index, allowing for positive and negative integers. Negative integers count back from the last item in the array.]

Parameters:index ([type]) – [position of item]
Returns:[item at the given position]
Return type:[type]
concat(*args)[source]

[Joins two or more arrays, and returns a copy of the joined arrays]

Returns:[returns a copy of the joined arrays]
Return type:[list]
copyWithin(target, start=0, end=None)[source]

Copies array elements within the array, from start to end

entries()[source]

[Returns a key/value pair Array Iteration Object]

Yields:[type] – [key/value pair]
every(func)[source]

[Checks if every element in an array pass a test]

Parameters:func ([type]) – [test function]
Returns:[if every array elemnt passed the test]
Return type:[bool]
fill()[source]

Fill the elements in an array with a static value

filter(func)[source]

Creates a new array with every element in an array that pass a test i.e. even_numbers = someArr.filter( lambda x: x % 2 == 0 )

find(func)[source]

Returns the value of the first element in an array that pass a test

findIndex(value)[source]

Returns the index of the first element in an array that pass a test

forEach(func)[source]

Calls a function for each array element

includes(value)[source]

Check if an array contains the specified element

indexOf(value)[source]

Search the array for an element and returns its position

static isArray(self, thing)[source]

[Checks whether an object is an array]

Parameters:thing ([type]) – [thing to check]
Returns:[True if the object is list, tuple or Array]
Return type:[bool]
join(value)[source]

Joins all elements of an array into a string

keys()[source]

Returns a Array Iteration Object, containing the keys of the original array

lastIndexOf(value)[source]

Search the array for an element, starting at the end, and returns its position

length

Sets or returns the number of elements in an array

map(func)[source]

[Creates a new array with the result of calling a function for each array element]

Parameters:func ([type]) – [a function to call on each array element]
Returns:[a new array]
Return type:[list]
pop()[source]

Removes the last element of an array, and returns that element

push(value)[source]

Adds new elements to the end of an array, and returns the new length

reduce(func, value=None)[source]

Reduce the values of an array to a single value (going left-to-right)

reduceRight(func, value=None)[source]

Reduce the values of an array to a single value (going right-to-left)

reverse()[source]

Reverses the order of the elements in an array

shift()[source]

[removes the first element from an array and returns that removed element]

Returns:[the removed array element]
Return type:[type]
slice(start=0, stop=None, step=1)[source]

[Selects a part of an array, and returns the new array]

Parameters:
  • start ([int]) – [index to slice from]
  • stop ([int], optional) – [index to slice to]. Defaults to end of the array.
  • step (int, optional) – [description]. Defaults to 1.
Returns:

[new array]

Return type:

[type]

some(func)[source]

Checks if any of the elements in an array pass a test

sort(func=None)[source]

Sorts the elements of an array

splice(start, delete_count=None, *items)[source]

Selects a part of an array, and returns the new array

toString()[source]

Converts an array to a string, and returns the result

unshift(*args)[source]

[Adds new elements to the beginning of an array, and returns the new length]

Returns:[the length of the array]
Return type:[int]
class domonic.javascript.Date(date: str = None, formatter='python')[source]

javascript date

UTC()[source]

Returns the number of milliseconds in a date since midnight of January 1, 1970, according to UTC time

getDate()[source]

Returns the day of the month (from 1-31)

getDay()[source]

Returns the day of the week (from 0-6)

getFullYear()[source]

Returns the year

getHours()[source]

Returns the hour (from 0-23)

getMilliseconds()[source]

Returns the milliseconds (from 0-999)

getMinutes()[source]

Returns the minutes (from 0-59)

getMonth()[source]

Returns the month (from 0-11)

getSeconds()[source]

Returns the seconds (from 0-59)

getTime()[source]

Returns the number of milliseconds since midnight Jan 1 1970, and a specified date

getTimezoneOffset()[source]

Returns the time difference between UTC time and local time, in minutes

getUTCDate()[source]

Returns the day of the month, according to universal time (from 1-31)

getUTCDay()[source]

Returns the day of the week, according to universal time (from 0-6)

getUTCFullYear()[source]

Returns the year, according to universal time

getUTCHours()[source]

Returns the hour, according to universal time (from 0-23)

getUTCMilliseconds()[source]

Returns the milliseconds, according to universal time (from 0-999)

getUTCMinutes()[source]

Returns the minutes, according to universal time (from 0-59)

getUTCMonth()[source]

Returns the month, according to universal time (from 0-11)

getUTCSeconds()[source]

Returns the seconds, according to universal time (from 0-59)

getYear()[source]

Deprecated. Use the getFullYear() method instead

static now()[source]

Returns the number of milliseconds since midnight Jan 1, 1970

parse(date_string)[source]

Parses a date string and returns the number of milliseconds since January 1, 1970

setDate(day)[source]

Sets the day of the month of a date object

setFullYear(year)[source]

Sets the year of a date object

setHours(hours)[source]

Sets the hour of a date object

setMilliseconds(milliseconds)[source]

Sets the milliseconds of a date object

setMinutes(minutes)[source]

Set the minutes of a date object

setMonth(month)[source]

Sets the month of a date object

setSeconds(seconds)[source]

Sets the seconds of a date object

setTime(milliseconds=None)[source]

Sets the number of milliseconds since January 1, 1970

setUTCDate(day)[source]

Sets the day of the month of a date object, according to universal time

setUTCFullYear(year)[source]

Sets the year of a date object, according to universal time

setUTCHours(hour)[source]

Sets the hour of a date object, according to universal time

setUTCMilliseconds(milliseconds)[source]

Sets the milliseconds of a date object, according to universal time

setUTCMinutes(minutes)[source]

Set the minutes of a date object, according to universal time

setUTCMonth(month)[source]

Sets the month of a date object, according to universal time

setUTCSeconds(seconds)[source]

Set the seconds of a date object, according to universal time

setYear(year)[source]

Deprecated. Use the setFullYear() method instead

toDateString()[source]

Converts the date portion of a Date object into a readable string

toGMTString()[source]

Deprecated. Use the toUTCString() method instead

toISOString()[source]

Returns the date as a string, using the ISO standard

toJSON()[source]

Returns the date as a string, formatted as a JSON date

toLocaleDateString()[source]

Returns the date portion of a Date object as a string, using locale conventions

toLocaleString()[source]

Converts a Date object to a string, using locale conventions

toLocaleTimeString()[source]

Returns the time portion of a Date object as a string, using locale conventions

toTimeString()[source]

Converts the time portion of a Date object to a string

toUTCString()[source]

Converts a Date object to a string, according to universal time

exception domonic.javascript.Error(message, *args, **kwargs)[source]

Raise Errors

class domonic.javascript.FormData(form)[source]

[utils for a form]

Parameters:object ([str]) – [takes a string or pyml object and returns a FormData]
append(name, value, filename)[source]

Appends a new value onto an existing key inside a FormData object, or adds the key if it does not already exist.

delete(name)[source]

Deletes a key/value pair from a FormData object.

entries()[source]

Returns an iterator allowing to go through all key/value pairs contained in this object.

get(name)[source]

Returns the first value associated with a given key from within a FormData object.

getAll(name)[source]

Returns an array of all the values associated with a given key from within a FormData

has(name)[source]

Returns a boolean stating whether a FormData object contains a certain key.

keys()[source]

Returns an iterator allowing to go through all keys of the key/value pairs contained in this object.

set(name, value, filename)[source]

Sets a new value for an existing key inside a FormData object, or adds the key/value if it does not already exist.

values()[source]

Returns an iterator allowing to go through all values contained in this object.

class domonic.javascript.Function(func)[source]

a Function object

apply(thisArg=None, *args, **kwargs)[source]

[calls a function with a given this value, and arguments provided as an array]

Parameters:thisArg ([type]) – [The value of this provided for the call to func.]
Returns:[result of calling the function.]
Return type:[type]
bind(thisArg, *args, **kwargs)[source]

[creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called.]

Parameters:
  • thisArg ([type]) – [The value to be passed as the this parameter to the target
  • func when the bound function is called.] (function) –
Returns:

[A copy of the given function with the specified this value, and initial arguments (if provided).]

Return type:

[type]

call(thisArg=None, *args, **kwargs)[source]

[calls a function with a given this value and arguments provided individually.]

Parameters:thisArg ([type]) – [description]
Returns:[result of calling the function.]
Return type:[type]
toString()[source]

[Returns a string representing the source code of the function. Overrides the]

class domonic.javascript.Global[source]

javascript global methods

NaN()[source]

“Not-a-Number” value

static Number(x)[source]

Converts an object’s value to a number

static String(x)[source]

Converts an object’s value to a string

static decodeURI(x)[source]

Decodes a URI

static decodeURIComponent(x)[source]

Decodes a URI component

static encodeURI(x)[source]

Encodes a URI

static encodeURIComponent(x)[source]

Encodes a URI component

static eval(pythonstring)[source]

Evaluates a string and executes it as if it was script code

static isFinite(x)[source]

Returns true if x is a finite number

static isNaN(x)[source]

Determines whether a value is an illegal number

static parseFloat(x: str)[source]

Parses a string and returns a floating point number

static parseInt(x: str)[source]

Parses a string and returns an integer

static require(path: str)[source]

Loads a script from a file

static setTimeout(callback, t, *args, **kwargs)[source]

use threads to create a timeout method

undefined()[source]

Indicates that a variable has not been assigned a value

class domonic.javascript.Job(interval, execute, *args, **kwargs)[source]
run()[source]

Method representing the thread’s activity.

You may override this method in a subclass. The standard run() method invokes the callable object passed to the object’s constructor as the target argument, if any, with sequential and keyword arguments taken from the args and kwargs arguments, respectively.

class domonic.javascript.Map(collection)[source]

Map holds key-value pairs and remembers the original insertion order of the keys.

clear()[source]

Removes all key-value pairs from the Map object.

delete(key)[source]

Returns true if an element in the Map object existed and has been removed, or false if the element does not exist. Map.prototype.has(key) will return false afterwards.

entries()[source]

Returns a new Iterator object that contains an array of [key, value] for each element in the Map object in insertion order.

get(key, default=None)[source]

Returns the value associated to the key, or undefined if there is none.

has(key)[source]

Returns a boolean asserting whether a value has been associated to the key in the Map object or not.

keys()[source]

Returns a new Iterator object that contains the keys for each element in the Map object in insertion order.

set(key, value)[source]

Sets the value for the key in the Map object. Returns the Map object.

values()[source]

Returns a new Iterator object that contains the values for each element in the Map object in insertion order.

class domonic.javascript.Math(obj={}, *args, **kwargs)[source]

Math class that mirrors javascript implementation.

i.e. you can pass strings and it will also work Math.abs(‘-1’)

static hypot(*args)[source]

returns the square root of the sum of squares of its arguments

static log2(*args)[source]

returns the square root of the sum of squares of its arguments

static loglp(*args)[source]

returns the natural logarithm (base e) of 1 + a number, that is

class domonic.javascript.Navigator(*args, **kwargs)[source]

navigator

class domonic.javascript.Number(x='', *args, **kwargs)[source]

javascript Number methods

NEGATIVE_INFINITY = inf

Represents negative infinity (returned on overflow) Number

POSITIVE_INFINITY = -inf

Represents infinity (returned on overflow) Number

isInteger()[source]

Checks whether a value is an integer

isSafeInteger()[source]

Checks whether a value is a safe integer

toExponential(num=None)[source]

Converts a number into an exponential notation

toFixed(digits: int)[source]

[formats a number using fixed-point notation.]

Parameters:digits ([int]) – [The number of digits to appear after the decimal point
Returns:[A string representing the given number using fixed-point notation.]
Return type:[str]
toPrecision(precision)[source]

[returns a string representing the Number object to the specified precision.]

Parameters:precision ([int]) – [An integer specifying the number of significant digits.]
Returns:[A string representing a Number object in fixed-point or exponential notation rounded to precision significant digits]
Return type:[str]
toString(base: int)[source]

[returns a string representing the specified Number object.]

Parameters:base (int) – [An integer in the range 2 through 36 specifying the base to use for representing numeric values.]
Returns:[a string representing the specified Number object]
Return type:[str]
class domonic.javascript.Object(obj={}, *args, **kwargs)[source]

Creates a Mock Javascript Object in python

static defineProperty(obj, prop, descriptor)[source]

Adds the named property described by a given descriptor to an object.

static entries(obj)[source]

Returns an array containing all of the [key, value] pairs in the object.

static fromEntries(entries)[source]

transforms a list of lists containing key and value into an object.

@param entries: a list containing key and value tuples. The key and value
are separated by ‘:’

@type entries: list of tuple(string, string) @returns: a { dict } object.

>>> fromEntries(entries)
{'a': 1, 'b': 2, 'c': 3}
static getOwnPropertyDescriptor(obj, prop)[source]

Returns a property descriptor for a named property on an object.

static getOwnPropertyNames(obj)[source]

Returns an array containing the names of all of the given object’s own enumerable and non-enumerable properties.

static getOwnPropertySymbols(obj)[source]

Returns an array of all symbol properties found directly upon a given object.

static getPrototypeOf(obj)[source]

Returns the prototype (internal [[Prototype]] property) of the specified object.

hasOwnProperty(prop)[source]

Returns a boolean indicating whether an object contains the specified property as a direct property of that object and not inherited through the prototype chain.

isPrototypeOf(obj)[source]

Returns a boolean indicating whether an object is a copy of this object.

static keys(obj)[source]

Returns an array containing the names of all of the given object’s own enumerable string properties.

prototype(obj)[source]

prototype and allows you to add properties and methods to this object

toLocaleString()[source]

Calls toString()

toString()[source]

Returns a string representation of the object.

valueOf()[source]

Returns the value of the object.

static values(obj)[source]

Returns an array containing the values that correspond to all of a given object’s own enumerable string properties.

exception domonic.javascript.ProgramKilled[source]
class domonic.javascript.Screen[source]

screen

availHeight()[source]

Returns the height of the screen (excluding the Windows Taskbar)

availWidth()[source]

Returns the width of the screen (excluding the Windows Taskbar)

colorDepth()[source]

Returns the colorDepth

height()[source]

Returns the total height of the screen

pixelDepth()[source]

Returns the pixelDepth

width()[source]

Returns the total width of the screen

class domonic.javascript.String(x='', *args, **kwargs)[source]

javascript String methods

charAt(index: int)[source]

[Returns the character at the specified index (position)]

Parameters:index (int) – [index position]
Returns:[character]
Return type:[str]
charCodeAt(index: int)[source]

Returns the Unicode of the character at the specified index

concat(*args, seperator='')[source]

[concatenates the string arguments to the calling string and returns a new string.]

Parameters:seperator (str, optional) – []. Defaults to “”.
Returns:[A new string containing the combined text of the strings provided.]
Return type:[type]
endsWith(x: str, start: int = None, end: int = None)[source]

Checks whether a string ends with specified string/characters

fromCharCode(*codes)[source]

returns a string created from the specified sequence of UTF-16 code units

indexOf(searchValue: str, fromIndex: int = 0)[source]

[returns the index within the calling String object of the first occurrence of the specified value, starting the search at fromIndex ]

Parameters:
  • searchValue (str) – [The string value to search for.]
  • fromIndex (int) – [An integer representing the index at which to start the search]
Returns:

[The index of the first occurrence of searchValue, or -1 if not found.]

Return type:

[type]

repeat(count: int)[source]

Returns a new string with a specified number of copies of an existing string

replace(old: str, new: str)[source]

Searches a string for a specified value, or a regular expression, and returns a new string where the specified values are replaced. only replaces first one.

replaceAll(old: str, new: str)[source]

[returns a new string where the specified values are replaced. ES2021]

Parameters:
  • old ([str]) – [word to remove]
  • new ([str]) – [word to replace it with]
Returns:

[new string with all occurences of old word replaced]

Return type:

[str]

slice(start: int = 0, end: int = None)[source]

Selects a part of an string, and returns the new string

split(expr)[source]

[can split a string based on a regex]

Parameters:expr ([str]) – [valid regex or string to split on]
Returns:[list of str]
Return type:[list]
startsWith(x: str, start: int = None, end: int = None)[source]

Checks whether a string begins with specified characters

substr(start: int = 0, end: int = None)[source]

Extracts the characters from a string, beginning at a specified start position, and through the specified number of character

substring(start: int, end: int = None)[source]

Extracts the characters from a string, between two specified indices

toLocaleLowerCase()[source]

Converts a string to lowercase letters, according to the host’s locale

toLocaleUpperCase()[source]

Converts a string to uppercase letters, according to the host’s locale

toLowerCase()[source]

Converts a string to lowercase letters

toUpperCase()[source]

Converts a string to uppercase letters

trim()[source]

Removes whitespace from both ends of a string

class domonic.javascript.URL(url: str = '', *args, **kwargs)[source]

a-tag extends from URL

hash

” hash Sets or returns the anchor part (#) of a URL

class domonic.javascript.URLSearchParams(paramString)[source]

[utility methods to work with the query string of a URL]

created with help of https://6b.eleuther.ai/

append(key, value)[source]

Appends a specified key/value pair as a new search parameter

delete(key)[source]

Deletes the given search parameter, and its associated value, from the list of all search parameters.

entries()[source]

Returns an iterator allowing iteration through all key/value pairs contained in this object.

forEach(func)[source]

Allows iteration through all values contained in this object via a callback function.

get(key)[source]

Returns the first value associated with the given search parameter.

getAll(key)[source]

Returns all the values associated with a given search parameter.

has(key)[source]

Returns a Boolean indicating if such a given parameter exists.

keys()[source]

Returns an iterator allowing iteration through all keys of the key/value pairs contained in this object.

set(key, value)[source]

Sets the value associated with a given search parameter to the given value. If there are several values, the others are deleted.

sort()[source]

Sorts all key/value pairs, if any, by their keys.

toString()[source]

Returns a string containing a query string suitable for use in a URL.

values()[source]

Returns an iterator allowing iteration through all values of the key/value pairs contained in this object.

class domonic.javascript.Window(*args, **kwargs)[source]

window

static alert(msg)[source]

Displays an alert box with a message and an OK button

static atob(dataString)[source]

Decodes a base-64 encoded string

static btoa(dataString)[source]

Encodes a string in base-64

static prompt(msg, default_text='')[source]

Displays a dialog box that prompts the visitor for input

static requestAnimationFrame(callback)[source]

[requests a frame of an animation]

Parameters:callback (callable) – [the callback function]
Returns:[description]
Return type:[type]
static setTimeout(function, t, *args, **kwargs)[source]

Calls a function or evaluates an expression after a specified number of milliseconds

class domonic.javascript.Worker(script)[source]

[A background task that can be created via script, which can send messages back to its creator. Creating a worker is done by calling the Worker(“path/to/worker/script”) constructor.] TODO - JSWorker - Node :param object: [takes a path to a python script] :type object: [str]

postMessage()[source]

Sends a message — consisting of any object — to the worker’s inner scope.

terminate()[source]

Immediately terminates the worker. This does not let worker finish its operations; it is halted at once. ServiceWorker instances do not support this method.

domonic.javascript.window

alias of domonic.javascript.Window