javascript¶
Domonic includes a JavaScript-like runtime surface for practical scripting and porting.
It’s useful for quickly porting familiar JS code to Python while staying close to web-platform concepts:
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, String, Number
# etc..
Alongside the global helpers, there are familiar String, Number, Array, Date, URL, and timing APIs.
Date class¶
The Date class is available…
from domonic.javascript import Date
print(Date.now())
Array methods¶
Many of the familiar JavaScript array methods are available in Python form:
myarr = Array("1", "2", 3, {"4": "four"}, 5, [6])
print(myarr.length)
print(myarr.includes("1"))
print(myarr.includes(3))
print(myarr.includes(10))
print(myarr.indexOf(10))
print(myarr.indexOf("1"))
print(myarr.indexOf([6]))
print(myarr[1])
print(len(myarr))
print(myarr.join('---'))
print(myarr.lastIndexOf("1"))
print(myarr.lastIndexOf(3))
print(myarr.reverse())
print(myarr.slice(0, 1))
print(myarr.splice(1))
# print(myarr.splice(2))
# print(myarr.splice(3))
# print(myarr.splice(4))
print(myarr.splice(3, 3, "a", "b", "c"))
print(myarr)
print(myarr.pop())
print(myarr)
myarr.push(7)
print(myarr)
print(myarr.unshift('z'))
print(myarr)
print(myarr.shift())
print(myarr)
# print(myarr.concat())
# myarr.sort()
# myarr.fill()
# myarr.isArray()?
# myarr.map()
# myarr.reduce()
# myarr.reduceRight()
# myarr.some()
String methods¶
A whole bunch of familiar string methods for you to enjoy…
mystr = String("Some String")
mystr.toLowerCase() # "some string"
mystr.toUpperCase() # "SOME STRING"
# print(mystr.length)
mystr.repeat(2) # "Some StringSome String"
print(mystr.startsWith('S'))
# mystr.endsWith('g'))
# javascript substr in python
mystr.substr(1) # 'ome String'
# javascript slice in python
# print(mystr.slice(1, 3))
mystr.slice(1, 3) # 'om')
# trim
mystr = String(" Some String ")
mystr.trim() # "Some String")
# charAt
mystr = String("Some String")
mystr.charAt(1) # 'o'
mystr.charAt(5) # 'S'
# charCodeAt
mystr.charCodeAt(1) # 111
mystr.fromCharCode(111) # 'o'
# test
# mystr.test('a') # True
# mystr.test('b') # False
# replace
# print(mystr.replace('S', 'X'))
mystr.replace('S', 'X') # "Xome String"
mystr.replace(' ', 'X') # "SomeXString"
mystr.replace('S', 'X') != "Xome Xtring"
# search
mystr = String("Some String")
mystr.search('a') # False
mystr.search('o') # True
# substr
print(mystr.substr(1, 2))
mystr.substr(1, 2) # 'om')
mystr.substr(1, 3) # 'ome')
mystr.substr(1, 4) # 'ome ')
mystr.substr(1, 5) # 'ome S')
# toLocaleLowerCase
mystr.toLocaleLowerCase() # 'some string'
mystr.toLocaleLowerCase() # 'some string'
# toLocaleUpperCase
# print(mystr.toLocaleUpperCase())
mystr.toLocaleUpperCase() # 'SOME STRING'
# lastIndex
# print(mystr.lastIndexOf('o'))
mystr.lastIndexOf('o') # 1
assert mystr.padEnd(13) # "Some String "
assert mystr.padStart(13) # " Some String"
assert mystr.padStart(13, '-') # "--Some String"
mystr.includes('a') # False
mystr.includes('Some') # True
Plus some obsolete friends to do fancy tricks with!!… i.e
>>> test = String("Hello Wolrd!")
>>> test.blink()
>>> test.sub()
>>> test.sup()
>>> test.div() # ?? hang on?
>>> test.webpage() # ??? err... wait what!!!
You can actually transform a type String into any tag.
Simply call `()` on a stringvar to transform it into a Node
>>> test = String("time to take a mo")
>>> test('div', _style="font-color:red;")
>>> str(test('div', _style="font-color:red;"))
passing it the tag and attributes…
Object methods¶
Object is useful for making dicts a bit more js-like…
o = Object()
o.prop = 'hi'
str(o)
But also contains a growing list of methods you may know from javascript.
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
keywords¶
If you `import *` you will get the js keywords… i.e.
print(true) # True
print(false) # False
print(undefined) # None
print(null) # None
As well as a function which evaluates python strings…
sup = function('''print("hi")''')
sup()
Typed arrays¶
js style typed arrays are even available
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.
- class domonic.javascript.Array(*args: Any)[source]
javascript array
- at(index: int) Any[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.]
- concat(*args: list[Any]) list[Any][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: Sequence[Any], start: int = 0, end: int | None = None) None[source]
Copies array elements within the array, from start to end
- entries() Iterator[list[Any]][source]
[Returns a key/value pair Array Iteration Object]
- Yields:
[type] – [key/value pair]
- fill(value: Any = None, start: int | None = None, end: int | None = None) list[Any][source]
[Fills elements of an array from a start index to an end index with a static value]
- filter(func: Callable[[Any], bool]) list[Any][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: Callable[[Any], bool]) Any[source]
Returns the value of the first element in an array that pass a test
- findIndex(value: Any) int[source]
Returns the index of the first element in an array that pass a test
- findLast(callback: Callable[[Any, int, list[Any]], bool]) Any[source]
[Returns the last element in an array that passes a test]
- findLastIndex(callback: Callable[[Any, int, list[Any]], bool]) int[source]
[Returns the last index of an element in an array that passes a test]
- flat(depth: int = 1) list[Any][source]
[Flattens an array into a single-dimensional array or a depth of arrays]
- flatMap(fn: Callable[[Any], Any]) Array[source]
[Maps a function over an array and flattens the result]
- static from_(obj: Any) Array[source]
Creates a new Array instance from an array-like or iterable object.
- groupBy(callback) dict[source]
[Groups the elements of an array according to the result of calling a callback function on each element]
- Parameters:
callback (callable) – [the callback recieves the following paramters(value, index, target)]
- Returns:
[a dictionary of arrays]
- Return type:
[dict]
- includes(value: Any) bool[source]
[Check if an array contains the specified item
- Parameters:
value ([any]) – [any value]
- Returns:
[a boolean]
- Return type:
[bool]
- keys() Iterator[Any][source]
Returns a Array Iteration Object, containing the keys of the original array
- lastIndexOf(value: Any) int | None[source]
Search the array for an element, starting at the end, and returns its position
- property length: int
Sets or returns the number of elements in an array
- map(func: Callable[[Any], Any]) list[Any][source]
[Creates a new array with the result of calling a function for each array element]
- static of(*args: Any) Array[source]
Creates a new Array instance with a variable number of arguments, regardless of number or type of the arguments.
- prototype
alias of
Array
- reduce(callback: Callable[[...], Any], initialValue: Any = None) Any[source]
Reduces the array to a single value (going left-to-right) callback recieve theses parameters: previousValue, currentValue, currentIndex, array
- reduceRight(callback: Callable[[...], Any], initialValue: Any = None) Any[source]
Reduces the array to a single value (going right-to-left) callback recieve theses parameters: previousValue, currentValue, currentIndex, array
- shift() Any[source]
[removes the first element from an array and returns that removed element]
- Returns:
[the removed array element]
- Return type:
[type]
- slice(start: int = 0, stop: int | None = None, step: int = 1) list[Any][source]
[Selects a part of an array, and returns the new array]
- some(func: Callable[[Any], bool]) bool[source]
Checks if any of the elements in an array pass a test
- class domonic.javascript.Boolean(value: Any = False)[source]
[Creates a Boolean Object. Warning this is NOT a boolean type. for that use Global.Boolean()]
- class domonic.javascript.Date(date: Any = None, *args: Any, formatter: str = 'python', **kwargs: Any)[source]
javascript date
- UTC() datetime[source]
Returns the number of milliseconds in a date since midnight of January 1, 1970, according to UTC time
- getDay() int[source]
Returns the day of the week (from 0-6 : Sunday-Saturday)
- Returns:
An integer number, between 0 and 6, corresponding to the day of the week for the given date, according to local time: 0 for Sunday, 1 for Monday, 2 for Tuesday, and so on
- Return type:
- getTime() int[source]
Returns A number representing the milliseconds elapsed between 1 January 1970 00:00:00 UTC and self.date
- getTimezoneOffset() int[source]
Returns the difference, in minutes, between a date as evaluated in the UTC time zone, and the same date as evaluated in the local time zone
- static parse(date_string: Any) int[source]
Parses a date string and returns the number of milliseconds since January 1, 1970
- setFullYear(yearValue: int, monthValue: int | None = None, dateValue: int | None = None) int[source]
Sets the year of a date object
- setHours(hoursValue: int, minutesValue: int | None = None, secondsValue: int | None = None, msValue: int | None = None) int[source]
Sets the hour of a date object
- Parameters:
- Returns:
milliseconds between epoch and updated date.
- Return type:
- setMilliseconds(milliseconds: int) None[source]
Sets the milliseconds of a date object
- Parameters:
milliseconds (int) – Milliseconds to set i.e 123
- setMinutes(minutesValue: int, secondsValue: int | None = None, msValue: int | None = None) int[source]
Set the minutes of a date object
- setSeconds(secondsValue: int, msValue: int | None = None) int[source]
Sets the seconds of a date object
- setTime(milliseconds: int | None = None, tz: Any = None) int | None[source]
Sets the date and time of a date object
- Parameters:
milliseconds (_type_, optional) – _description_. Defaults to None.
- Returns:
_description_
- Return type:
_type_
- setUTCDate(day: int) int[source]
Sets the day of the month of a date object, according to universal time
- setUTCMilliseconds(milliseconds: int) int[source]
Sets the milliseconds of a date object, according to universal time
- setUTCMinutes(minutes: int) int[source]
Set the minutes of a date object, according to universal time
- setUTCSeconds(seconds: int) int[source]
Set the seconds of a date object, according to universal time
- toLocaleDateString() str[source]
Returns the date portion of a Date object as a string, using locale conventions
- class domonic.javascript.Function(func: Callable[[...], Any], *args: Any, **kwargs: Any)[source]
a Function object
- apply(thisArg: Any = None, args: Sequence[Any] | None = None, **kwargs: Any) Any[source]
[calls a function with a given this value, and arguments provided as an array]
- bind(thisArg: Any, *args: Any, **kwargs: Any) Callable[[...], Any][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.]
- class domonic.javascript.Global[source]
javascript global methods
- static clearTimeout(timeoutID: int) None[source]
[cancels a timer set with setTimeout()]
- Parameters:
timeoutID ([str]) – [the identifier returned by setTimeout()]
- static eval(pythonstring: str) Any[source]
Evaluates a string and executes it as if it was script code
- class domonic.javascript.Job(interval: timedelta, execute: Callable[[...], Any], *args: Any, **kwargs: Any)[source]
- run() None[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: list[Any] | dict[str, Any])[source]
Map holds key-value pairs and remembers the original insertion order of the keys.
- delete(key: str) bool[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() list[tuple[str, Any]][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: str, default: Any = None) Any[source]
Returns the value associated to the key, or undefined if there is none.
- has(key: str) bool[source]
Returns a boolean asserting whether a value has been associated to the key in the Map object or not.
- keys() list[str][source]
Returns a new Iterator object that contains the keys for each element in the Map object in insertion order.
- class domonic.javascript.Math(obj: Any = None, *args: Mapping[str, Any], **kwargs: Any)[source]
Math class that mirrors javascript implementation.
i.e. you can pass strings and it will also work, Math.abs(‘-1’)
- static hypot(*args: float) float[source]
returns the square root of the sum of squares of its arguments
- class domonic.javascript.Number(x: Any = '', *args: Any, **kwargs: Any)[source]
javascript Number methods
- NEGATIVE_INFINITY = inf
Represents negative infinity (returned on overflow) Number
- POSITIVE_INFINITY = -inf
Represents infinity (returned on overflow) Number
- toPrecision(precision: int) str[source]
[returns a string representing the Number object to the specified precision.]
- exception domonic.javascript.ProgramKilled[source]
- class domonic.javascript.Reflect[source]
The Reflect object provides the following static functions which have the same names as the proxy handler methods. Some of these methods are also the same as corresponding methods on Object, although they do have some subtle differences between them.
- static apply(target: Callable[[...], Any], thisArgument: Any, argumentsList: Sequence[Any]) Any[source]
Calls a target function with arguments as specified by the argumentsList parameter. See also Function.prototype.apply().
- static construct(target: Any, argumentsList: Sequence[Any], newTarget: Any = None) Any[source]
The new operator as a function. Equivalent to calling new target(…argumentsList). Also provides the option to specify a different prototype.
- static defineProperty(target: Any, propertyKey: str, attributes: Any) Any[source]
Similar to Object.defineProperty(). Returns a Boolean that is true if the property was successfully defined.
- static deleteProperty(target: Any, propertyKey: str) Any[source]
The delete operator as a function. Equivalent to calling delete target[propertyKey].
- static get(target: Any, propertyKey: str, receiver: Any = None) Any[source]
Returns the value of the property. Works like getting a property from an object (target[propertyKey]) as a function.
- static getOwnPropertyDescriptor(target: Any, propertyKey: str) Any[source]
Similar to Object.getOwnPropertyDescriptor(). Returns a property descriptor of the given property if it exists on the object, undefined otherwise.
- getPrototypeOf() Any
Returns the prototype (internal [[Prototype]] property) of the specified object.
- static has(target: Any, propertyKey: str) Any[source]
Returns a Boolean indicating whether the target has the property. Either as own or inherited. Works like the in operator as a function.
- static ownKeys(target: Any) list[str][source]
Returns an array of the target object’s own (not inherited) property keys.
- static preventExtensions(target: Any) Any[source]
Similar to Object.preventExtensions(). Returns a Boolean that is true if the update was successful.
- class domonic.javascript.Screen[source]
screen
- class domonic.javascript.String(x: Any = '', *args: Any, **kwargs: Any)[source]
javascript String methods
- big() str[source]
[wraps the string in big tags]
- Returns:
[the string in big tags]
- Return type:
[str]
- blink() str[source]
[wraps the string in blink tags]
- Returns:
[the string in blink tags]
- Return type:
[str]
- bold() str[source]
[wraps the string in bold tags]
- Returns:
[the string in bold tags]
- Return type:
[str]
- codePointAt(index: int) int[source]
[Returns the Unicode code point at the specified index (position)]
- compile(pattern: str) Pattern[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.
- concat(*args, seperator: str = '') str[source]
[concatenates the string arguments to the calling string and returns a new string.]
- div(*args: Any, **kwargs: Any) Any[source]
[wraps the string in a div tag]
- Returns:
[the string in a div tag]
- Return type:
[str]
- endsWith(x: str, start: int = None, end: int = None) bool[source]
Checks whether a string ends with specified string/characters
- fixed() str[source]
[wraps the string in fixed tags]
- Returns:
[the string in fixed tags]
- Return type:
[str]
- fromCharCode(*codes: int) str[source]
returns a string created from the specified sequence of UTF-16 code units
- includes(searchValue: str, position: int = 0) bool[source]
[returns true if the specified string is found within the calling String object,]
- indexOf(searchValue: str, fromIndex: int = 0) int[source]
[returns the index within the calling String object of the first occurrence of the specified value, starting the search at fromIndex ]
- italics() str[source]
[wraps the string in italics tags]
- Returns:
[the string in italics tags]
- Return type:
[str]
- lastIndexOf(searchValue: str, fromIndex: int = 0) int[source]
returns the last index within the calling String object of the first occurrence of the specified value, starting the search at fromIndex
- localeCompare(comparisonString: str, locale: str = None, *args) int[source]
method returns a number indicating whether a reference string comes before, or after, or is the same as the given string in sort order
- match(pattern: str) Match[str] | None[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.
- matchAll(pattern: str) 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.
- padEnd(length: int, padChar: str = ' ') str[source]
[Pads the end of a string with a specified character (repeated, if needed) to create a new string.]
- padStart(length: int, padChar: str = ' ') str[source]
[Pads the start of a string with a specified character]
- repeat(count: int) str[source]
Returns a new string with a specified number of copies of an existing string
- replace(old: str, new: str | Callable[[...], str]) 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) str[source]
[returns a new string where the specified values are replaced. ES2021]
- search(searchValue: str, position: int = 0) bool[source]
[returns true if the specified string is found within the calling String object,] starting at the specified position. :param searchValue: [The string value to search for.] :type searchValue: str :param position: [the position to search from]. Defaults to 0. :type position: int, optional
- Returns:
[a boolean value indicating whether the search value was found.]
- Return type:
[type]
- slice(start: int = 0, end: int = None) str[source]
Selects a part of an string, and returns the new string
- small() str[source]
[wraps the string in small tags]
- Returns:
[the string in small tags]
- Return type:
[str]
- startsWith(x: str, start: int = None, end: int = None) bool[source]
Checks whether a string begins with specified characters
- strike() str[source]
[wraps the string in strike tags]
- Returns:
[the string in strike tags]
- Return type:
[str]
- sub() str[source]
[wraps the string in sub tags]
- Returns:
[the string in sub tags]
- Return type:
[str]
- substr(start: int = 0, end: int | None = None) str[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) str[source]
Extracts the characters from a string, between two specified indices
- sup() str[source]
[wraps the string in sup tags]
- Returns:
[the string in sup tags]
- Return type:
[str]
- toLocaleLowerCase() str[source]
Converts a string to lowercase letters, according to the host’s locale
- class domonic.javascript.Window(*args: Any, **kwargs: Any)[source]
window
- clearTimeout() None
[cancels a timer set with setTimeout()]
- Parameters:
timeoutID ([str]) – [the identifier returned by setTimeout()]
- static prompt(msg: Any, default_text: str = '') str[source]
Displays a dialog box that prompts the visitor for input
- static requestAnimationFrame(callback: Callable[[float], Any]) Any[source]
[requests a frame of an animation]
- Parameters:
callback (callable) – [the callback function]
- Returns:
[description]
- Return type:
[type]
- class domonic.javascript.Worker(script: str)[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]
- domonic.javascript.as_signed(value: int, bits: int) int[source]
Converts an unsigned integer to a signed integer.
- domonic.javascript.clearTimeout(timeoutID: int) None
[cancels a timer set with setTimeout()]
- Parameters:
timeoutID ([str]) – [the identifier returned by setTimeout()]
- domonic.javascript.function(python_str: str) Callable[[], Any][source]
[evals a string i.e.
sup = function(‘’’print(hi)’’’) sup()
]
- Parameters:
python_str ([str]) – [some valid python code as a string]
- domonic.javascript.setTimeout(callback: str | Callable[[...], Any], t: int | float, *args: Any, **kwargs: Any) int
[sets a timer which executes a function or evaluates an expression after a specified delay]
- domonic.javascript.window
alias of
Window