Skip to content

Commit

Permalink
Fixed double quotes
Browse files Browse the repository at this point in the history
  • Loading branch information
Alyxion committed Apr 6, 2024
1 parent 87e83b5 commit 2cf5058
Show file tree
Hide file tree
Showing 5 changed files with 62 additions and 62 deletions.
46 changes: 23 additions & 23 deletions examples/single_page_router/advanced.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,43 +9,43 @@

def setup_page_layout(content: Callable):
with ui.header():
ui.label("My Company").classes("text-2xl")
ui.label('My Company').classes('text-2xl')
with ui.left_drawer():
ui.button("Home", on_click=lambda: ui.navigate.to("/"))
ui.button("About", on_click=lambda: ui.navigate.to("/about"))
ui.button("Contact", on_click=lambda: ui.navigate.to("/contact"))
ui.button('Home', on_click=lambda: ui.navigate.to('/'))
ui.button('About', on_click=lambda: ui.navigate.to('/about'))
ui.button('Contact', on_click=lambda: ui.navigate.to('/contact'))
content() # <-- The individual pages will be rendered here
with ui.footer() as footer:
ui.label("Copyright 2023 by My Company")
ui.label('Copyright 2023 by My Company')


@page('/', title="Welcome!")
@page('/', title='Welcome!')
def index():
ui.label("Welcome to the single page router example!").classes("text-2xl")
ui.label('Welcome to the single page router example!').classes('text-2xl')


@page('/about', title="About")
@page('/about', title='About')
def about():
ui.label("This is the about page testing local references").classes("text-2xl")
ui.label("Top").classes("text-lg").props("id=ltop")
ui.link("Bottom", "#lbottom")
ui.link("Center", "#lcenter")
ui.label('This is the about page testing local references').classes('text-2xl')
ui.label('Top').classes('text-lg').props('id=ltop')
ui.link('Bottom', '#lbottom')
ui.link('Center', '#lcenter')
for i in range(30):
ui.label(f"Lorem ipsum dolor sit amet, consectetur adipiscing elit. {i}")
ui.label("Center").classes("text-lg").props("id=lcenter")
ui.link("Top", "#ltop")
ui.link("Bottom", "#lbottom")
ui.label(f'Lorem ipsum dolor sit amet, consectetur adipiscing elit. {i}')
ui.label('Center').classes('text-lg').props('id=lcenter')
ui.link('Top', '#ltop')
ui.link('Bottom', '#lbottom')
for i in range(30):
ui.label(f"Lorem ipsum dolor sit amet, consectetur adipiscing elit. {i}")
ui.label("Bottom").classes("text-lg").props("id=lbottom")
ui.link("Top", "#ltop")
ui.link("Center", "#lcenter")
ui.label(f'Lorem ipsum dolor sit amet, consectetur adipiscing elit. {i}')
ui.label('Bottom').classes('text-lg').props('id=lbottom')
ui.link('Top', '#ltop')
ui.link('Center', '#lcenter')


@page('/contact', title="Contact") # this page will not be hosted as SPA
@page('/contact', title='Contact') # this page will not be hosted as SPA
def contact():
def custom_content_area():
ui.label("This is the contact page").classes("text-2xl")
ui.label('This is the contact page').classes('text-2xl')

setup_page_layout(content=custom_content_area)

Expand All @@ -55,6 +55,6 @@ def setup_root_page(self, **kwargs):
setup_page_layout(content=self.setup_content_area)


router = CustomRouter("/", included=[index, about], excluded=[contact])
router = CustomRouter('/', included=[index, about], excluded=[contact])
router.setup_page_routes()
ui.run()
14 changes: 7 additions & 7 deletions examples/single_page_router/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,17 +5,17 @@
from nicegui.single_page import SinglePageRouter


@page('/', title="Welcome!")
@page('/', title='Welcome!')
def index():
ui.label("Welcome to the single page router example!")
ui.link("About", "/about")
ui.label('Welcome to the single page router example!')
ui.link('About', '/about')


@page('/about', title="About")
@page('/about', title='About')
def about():
ui.label("This is the about page")
ui.link("Index", "/")
ui.label('This is the about page')
ui.link('Index', '/')


router = SinglePageRouter("/").setup_page_routes()
router = SinglePageRouter('/').setup_page_routes()
ui.run()
18 changes: 9 additions & 9 deletions nicegui/single_page.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
export default {
template: "<slot></slot>",
template: '<slot></slot>',
mounted() {
let router = this;
document.addEventListener('click', function (e) {
Expand All @@ -8,30 +8,30 @@ export default {
let href = e.target.getAttribute('href'); // Get the link's href value
// remove query and anchor
const org_href = href;
href = href.split("?")[0].split("#")[0]
href = href.split('?')[0].split('#')[0]
// check if the link ends with / and remove it
if (href.endsWith("/")) href = href.slice(0, -1);
if (href.endsWith('/')) href = href.slice(0, -1);
// for all valid path masks
for (let mask of router.valid_path_masks) {
// apply filename matching with * and ? wildcards
let regex = new RegExp(mask.replace(/\?/g, ".").replace(/\*/g, ".*"));
let regex = new RegExp(mask.replace(/\?/g, '.').replace(/\*/g, '.*'));
if (!regex.test(href)) continue;
e.preventDefault(); // Prevent the default link behavior
if (router.use_browser_history) window.history.pushState({page: org_href}, '', org_href);
router.$emit("open", org_href, false);
router.$emit('open', org_href, false);
return
}
}
});
window.addEventListener("popstate", (event) => {
window.addEventListener('popstate', (event) => {
let new_page = window.location.pathname;
this.$emit("open", new_page, false);
this.$emit('open', new_page, false);
});
const connectInterval = setInterval(async () => {
if (window.socket.id === undefined) return;
let target = window.location.pathname;
if (window.location.hash !== "") target += window.location.hash;
this.$emit("open", target, false);
if (window.location.hash !== '') target += window.location.hash;
this.$emit('open', target, false);
clearInterval(connectInterval);
}, 10);
},
Expand Down
32 changes: 16 additions & 16 deletions nicegui/single_page.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,8 @@ def __init__(self, valid_path_masks: list[str], use_browser_history: bool = True
:param use_browser_history: Optional flag to enable or disable the browser history management. Default is True.
"""
super().__init__()
self._props["valid_path_masks"] = valid_path_masks
self._props["browser_history"] = use_browser_history
self._props['valid_path_masks'] = valid_path_masks
self._props['browser_history'] = use_browser_history


class SinglePageRouterEntry:
Expand All @@ -39,15 +39,15 @@ def __init__(self, path: str, builder: Callable, title: Union[str, None] = None)
def verify(self) -> Self:
"""Verifies a SinglePageRouterEntry for correctness. Raises a ValueError if the entry is invalid."""
path = self.path
if "{" in path:
if '{' in path:
# verify only a single open and close curly bracket is present
elements = path.split("/")
elements = path.split('/')
for cur_element in elements:
if "{" in cur_element:
if cur_element.count("{") != 1 or cur_element.count("}") != 1 or len(cur_element) < 3 or \
not (cur_element.startswith("{") and cur_element.endswith("}")):
raise ValueError("Only simple path parameters are supported. /path/{value}/{another_value}\n"
f"failed for path: {path}")
if '{' in cur_element:
if cur_element.count('{') != 1 or cur_element.count('}') != 1 or len(cur_element) < 3 or \
not (cur_element.startswith('{') and cur_element.endswith('}')):
raise ValueError('Only simple path parameters are supported. /path/{value}/{another_value}\n'
f'failed for path: {path}')
return self


Expand All @@ -64,8 +64,8 @@ class SinglePageRouter:
def __init__(self,
path: str,
browser_history: bool = True,
included: Union[List[Union[Callable, str]], str, Callable] = "/*",
excluded: Union[List[Union[Callable, str]], str, Callable] = "",
included: Union[List[Union[Callable, str]], str, Callable] = '/*',
excluded: Union[List[Union[Callable, str]], str, Callable] = '',
on_instance_created: Optional[Callable] = None) -> None:
"""
:param path: the base path of the single page router.
Expand All @@ -87,7 +87,7 @@ def __init__(self,
# list of masks and callables of paths to exclude
self.excluded: List[Union[Callable, str]] = [excluded] if not isinstance(excluded, list) else excluded
# low level system paths which are excluded by default
self.system_excluded = ["/docs", "/redoc", "/openapi.json", "_*"]
self.system_excluded = ['/docs', '/redoc', '/openapi.json', '_*']
# set of all registered paths which were finally included for verification w/ mask matching in the browser
self.included_paths: Set[str] = set()
self.content_area_class = SinglePageRouterFrame
Expand All @@ -101,7 +101,7 @@ def setup_page_routes(self, **kwargs):
:param kwargs: Additional arguments for the @page decorators
"""
if self._setup_configured:
raise ValueError("The SinglePageRouter is already configured")
raise ValueError('The SinglePageRouter is already configured')
self._setup_configured = True
self._update_masks()
self._find_api_routes()
Expand Down Expand Up @@ -153,7 +153,7 @@ def add_page(self, path: str, builder: Callable, title: Optional[str] = None) ->
:param builder: The builder function
:param title: Optional title of the page
"""
self.routes[path] = SinglePageRouterEntry(path.rstrip("/"), builder, title).verify()
self.routes[path] = SinglePageRouterEntry(path.rstrip('/'), builder, title).verify()

def add_router_entry(self, entry: SinglePageRouterEntry) -> None:
"""Adds a fully configured SinglePageRouterEntry to the router
Expand Down Expand Up @@ -234,7 +234,7 @@ def _update_masks(self) -> None:
cur_list[index] = Client.page_routes[element]
else:
raise ValueError(
f"Invalid target page in inclusion/exclusion list, no @page assigned to element")
f'Invalid target page in inclusion/exclusion list, no @page assigned to element')

def _find_api_routes(self) -> None:
"""Find all API routes already defined via the @page decorator, remove them and redirect them to the
Expand All @@ -247,7 +247,7 @@ def _find_api_routes(self) -> None:
title = None
if key in Client.page_configs:
title = Client.page_configs[key].title
route = route.rstrip("/")
route = route.rstrip('/')
self.add_router_entry(SinglePageRouterEntry(route, builder=key, title=title))
# /site/{value}/{other_value} --> /site/*/* for easy matching in JavaScript
route_mask = re.sub(r'{[^}]+}', '*', route)
Expand Down
14 changes: 7 additions & 7 deletions nicegui/single_page_url.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ class SinglePageUrl:
"""Aa helper class which is used to parse the path and query parameters of an URL to find the matching
SinglePageRouterEntry and convert the parameters to the expected types of the builder function"""

def __init__(self, path: Optional[str] = None, entry: Optional["SinglePageRouterEntry"] = None,
def __init__(self, path: Optional[str] = None, entry: Optional['SinglePageRouterEntry'] = None,
fragment: Optional[str] = None, query_string: Optional[str] = None):
"""
:param path: The path of the URL
Expand All @@ -25,7 +25,7 @@ def __init__(self, path: Optional[str] = None, entry: Optional["SinglePageRouter
self.query_args = urllib.parse.parse_qs(self.query_string)
self.entry = entry

def parse_single_page_route(self, routes: Dict[str, "SinglePageRouterEntry"], path: str) -> Self:
def parse_single_page_route(self, routes: Dict[str, 'SinglePageRouterEntry'], path: str) -> Self:
"""
:param routes: All routes of the single page router
:param path: The path of the URL
Expand All @@ -44,18 +44,18 @@ def parse_single_page_route(self, routes: Dict[str, "SinglePageRouterEntry"], pa
self.convert_arguments()
return self

def parse_path(self) -> Optional["SinglePageRouterEntry"]:
def parse_path(self) -> Optional['SinglePageRouterEntry']:
"""Splits the path into its components, tries to match it with the routes and extracts the path arguments
into their corresponding variables.
"""
for route, entry in self.routes.items():
route_elements = route.lstrip('/').split("/")
path_elements = self.path.lstrip('/').rstrip("/").split("/")
route_elements = route.lstrip('/').split('/')
path_elements = self.path.lstrip('/').rstrip('/').split('/')
if len(route_elements) != len(path_elements): # can't match
continue
match = True
for i, route_element_path in enumerate(route_elements):
if route_element_path.startswith("{") and route_element_path.endswith("}") and len(
if route_element_path.startswith('{') and route_element_path.endswith('}') and len(
route_element_path) > 2:
self.path_args[route_element_path[1:-1]] = path_elements[i]
elif path_elements[i] != route_element_path:
Expand All @@ -75,4 +75,4 @@ def convert_arguments(self):
params[func_param_name] = func_param_info.annotation(
params[func_param_name]) # Convert parameter to the expected type
except ValueError as e:
raise ValueError(f"Could not convert parameter {func_param_name}: {e}")
raise ValueError(f'Could not convert parameter {func_param_name}: {e}')

0 comments on commit 2cf5058

Please sign in to comment.