Skip to content

Commit

Permalink
add page functions to demos awaiting JavaScript from client (#3517)
Browse files Browse the repository at this point in the history
  • Loading branch information
falkoschindler authored Aug 15, 2024
1 parent 10c006d commit 7185449
Show file tree
Hide file tree
Showing 5 changed files with 102 additions and 79 deletions.
2 changes: 2 additions & 0 deletions nicegui/functions/javascript.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@ def run_javascript(code: str, *,
If the function is awaited, the result of the JavaScript code is returned.
Otherwise, the JavaScript code is executed without waiting for a response.
Note that requesting data from the client is only supported for page functions, not for the shared auto-index page.
:param code: JavaScript code to run
:param timeout: timeout in seconds (default: `1.0`)
Expand Down
25 changes: 15 additions & 10 deletions website/documentation/content/aggrid_documentation.py
Original file line number Diff line number Diff line change
Expand Up @@ -224,18 +224,23 @@ def aggrid_run_row_method():
@doc.demo('Filter return values', '''
You can filter the return values of method calls by passing string that defines a JavaScript function.
This demo runs the grid method "getDisplayedRowAtIndex" and returns the "data" property of the result.
Note that requesting data from the client is only supported for page functions, not for the shared auto-index page.
''')
def aggrid_filter_return_values():
grid = ui.aggrid({
'columnDefs': [{'field': 'name'}],
'rowData': [{'name': 'Alice'}, {'name': 'Bob'}],
})

async def get_first_name() -> None:
row = await grid.run_grid_method('(g) => g.getDisplayedRowAtIndex(0).data')
ui.notify(row['name'])

ui.button('Get First Name', on_click=get_first_name)
# @ui.page('/')
def page():
grid = ui.aggrid({
'columnDefs': [{'field': 'name'}],
'rowData': [{'name': 'Alice'}, {'name': 'Bob'}],
})

async def get_first_name() -> None:
row = await grid.run_grid_method('g => g.getDisplayedRowAtIndex(0).data')
ui.notify(row['name'])

ui.button('Get First Name', on_click=get_first_name)
page() # HIDE


doc.reference(ui.aggrid)
39 changes: 22 additions & 17 deletions website/documentation/content/echart_documentation.py
Original file line number Diff line number Diff line change
Expand Up @@ -79,25 +79,30 @@ def echart_from_pyecharts_demo():
The colon ":" in front of the method name "setOption" indicates that the argument is a JavaScript expression
that is evaluated on the client before it is passed to the method.
Note that requesting data from the client is only supported for page functions, not for the shared auto-index page.
''')
def methods_demo() -> None:
echart = ui.echart({
'xAxis': {'type': 'category', 'data': ['Mon', 'Tue', 'Wed', 'Thu', 'Fri']},
'yAxis': {'type': 'value'},
'series': [{'type': 'line', 'data': [150, 230, 224, 218, 135]}],
})

ui.button('Show Loading', on_click=lambda: echart.run_chart_method('showLoading'))
ui.button('Hide Loading', on_click=lambda: echart.run_chart_method('hideLoading'))

async def get_width():
width = await echart.run_chart_method('getWidth')
ui.notify(f'Width: {width}')
ui.button('Get Width', on_click=get_width)

ui.button('Set Tooltip', on_click=lambda: echart.run_chart_method(
':setOption', r'{tooltip: {formatter: params => "$" + params.value}}',
))
# @ui.page('/')
def page():
echart = ui.echart({
'xAxis': {'type': 'category', 'data': ['Mon', 'Tue', 'Wed', 'Thu', 'Fri']},
'yAxis': {'type': 'value'},
'series': [{'type': 'line', 'data': [150, 230, 224, 218, 135]}],
})

ui.button('Show Loading', on_click=lambda: echart.run_chart_method('showLoading'))
ui.button('Hide Loading', on_click=lambda: echart.run_chart_method('hideLoading'))

async def get_width():
width = await echart.run_chart_method('getWidth')
ui.notify(f'Width: {width}')
ui.button('Get Width', on_click=get_width)

ui.button('Set Tooltip', on_click=lambda: echart.run_chart_method(
':setOption', r'{tooltip: {formatter: params => "$" + params.value}}',
))
page() # HIDE


@doc.demo('Arbitrary chart events', '''
Expand Down
41 changes: 23 additions & 18 deletions website/documentation/content/json_editor_documentation.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,26 +29,31 @@ def main_demo() -> None:
The colon ":" in front of the method name "expand" indicates that the value "path => true" is a JavaScript expression
that is evaluated on the client before it is passed to the method.
Note that requesting data from the client is only supported for page functions, not for the shared auto-index page.
''')
def methods_demo() -> None:
json = {
'Name': 'Alice',
'Age': 42,
'Address': {
'Street': 'Main Street',
'City': 'Wonderland',
},
}
editor = ui.json_editor({'content': {'json': json}})

ui.button('Expand', on_click=lambda: editor.run_editor_method(':expand', 'path => true'))
ui.button('Collapse', on_click=lambda: editor.run_editor_method(':expand', 'path => false'))
ui.button('Readonly', on_click=lambda: editor.run_editor_method('updateProps', {'readOnly': True}))

async def get_data() -> None:
data = await editor.run_editor_method('get')
ui.notify(data)
ui.button('Get Data', on_click=get_data)
# @ui.page('/')
def page():
json = {
'Name': 'Alice',
'Age': 42,
'Address': {
'Street': 'Main Street',
'City': 'Wonderland',
},
}
editor = ui.json_editor({'content': {'json': json}})

ui.button('Expand', on_click=lambda: editor.run_editor_method(':expand', 'path => true'))
ui.button('Collapse', on_click=lambda: editor.run_editor_method(':expand', 'path => false'))
ui.button('Readonly', on_click=lambda: editor.run_editor_method('updateProps', {'readOnly': True}))

async def get_data() -> None:
data = await editor.run_editor_method('get')
ui.notify(data)
ui.button('Get Data', on_click=get_data)
page() # HIDE


doc.reference(ui.json_editor)
74 changes: 40 additions & 34 deletions website/documentation/content/run_javascript_documentation.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,47 +5,53 @@

@doc.demo(ui.run_javascript)
def main_demo() -> None:
def alert():
ui.run_javascript('alert("Hello!")')
# @ui.page('/')
def page():
def alert():
ui.run_javascript('alert("Hello!")')

async def get_date():
time = await ui.run_javascript('Date()')
ui.notify(f'Browser time: {time}')
async def get_date():
time = await ui.run_javascript('Date()')
ui.notify(f'Browser time: {time}')

def access_elements():
ui.run_javascript(f'getElement({label.id}).innerText += " Hello!"')
def access_elements():
ui.run_javascript(f'getElement({label.id}).innerText += " Hello!"')

ui.button('fire and forget', on_click=alert)
ui.button('receive result', on_click=get_date)
ui.button('access elements', on_click=access_elements)
label = ui.label()
ui.button('fire and forget', on_click=alert)
ui.button('receive result', on_click=get_date)
ui.button('access elements', on_click=access_elements)
label = ui.label()
page() # HIDE


@doc.demo('Run async JavaScript', '''
Using `run_javascript` you can also run asynchronous code in the browser.
The following demo shows how to get the current location of the user.
''')
def run_async_javascript():
async def show_location():
response = await ui.run_javascript('''
return await new Promise((resolve, reject) => {
if (!navigator.geolocation) {
reject(new Error('Geolocation is not supported by your browser'));
} else {
navigator.geolocation.getCurrentPosition(
(position) => {
resolve({
latitude: position.coords.latitude,
longitude: position.coords.longitude,
});
},
() => {
reject(new Error('Unable to retrieve your location'));
}
);
}
});
''', timeout=5.0)
ui.notify(f'Your location is {response["latitude"]}, {response["longitude"]}')

ui.button('Show location', on_click=show_location)
# @ui.page('/')
def page():
async def show_location():
response = await ui.run_javascript('''
return await new Promise((resolve, reject) => {
if (!navigator.geolocation) {
reject(new Error('Geolocation is not supported by your browser'));
} else {
navigator.geolocation.getCurrentPosition(
(position) => {
resolve({
latitude: position.coords.latitude,
longitude: position.coords.longitude,
});
},
() => {
reject(new Error('Unable to retrieve your location'));
}
);
}
});
''', timeout=5.0)
ui.notify(f'Your location is {response["latitude"]}, {response["longitude"]}')

ui.button('Show location', on_click=show_location)
page() # HIDE

0 comments on commit 7185449

Please sign in to comment.